-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
1712 lines (1533 loc) · 57.4 KB
/
app.go
File metadata and controls
1712 lines (1533 loc) · 57.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"io"
"math"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/host"
"github.com/shirou/gopsutil/v3/mem"
"github.com/showwin/speedtest-go/speedtest"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
//go:embed tweaks.json
var tweaksJSON []byte
//go:embed assets/OOSU10.exe
var oosu10Bytes []byte
type Category struct {
ID string `json:"id"`
Icon string `json:"icon"`
Name map[string]string `json:"name"`
Tweaks []Tweak `json:"tweaks"`
}
type Tweak struct {
ID string `json:"id"`
Name map[string]string `json:"name"`
Description map[string]string `json:"description"`
Benefit map[string]string `json:"benefit"`
Impact string `json:"impact"`
Commands []string `json:"commands"`
Warnings map[string][]string `json:"warnings"`
}
type App struct {
ctx context.Context
categories []Category
tweakMap map[string]*Tweak
tweaksErr error
opMu sync.Mutex
lastOp time.Time
cancelMu sync.Mutex
cancelFunc context.CancelFunc
}
const (
appVersion = "1.2.1"
githubRepo = "oscarcodedev/CodeWinOptimizer-App"
minOpInterval = 2 * time.Second
)
func (a *App) startOp() context.Context {
a.cancelMu.Lock()
defer a.cancelMu.Unlock()
if a.cancelFunc != nil {
a.cancelFunc()
}
ctx, cancel := context.WithCancel(context.Background())
a.cancelFunc = cancel
return ctx
}
func (a *App) CancelOperation() {
a.cancelMu.Lock()
defer a.cancelMu.Unlock()
if a.cancelFunc != nil {
a.cancelFunc()
a.cancelFunc = nil
a.emitLog("[WARN] Operation cancelled by user")
}
}
func (a *App) rateLimit(op string) error {
a.opMu.Lock()
defer a.opMu.Unlock()
if time.Since(a.lastOp) < minOpInterval {
return fmt.Errorf("rate limited: please wait before running %s again", op)
}
a.lastOp = time.Now()
return nil
}
func NewApp() *App {
a := &App{}
a.tweaksErr = a.loadTweaks()
return a
}
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
wailsRuntime.LogInfo(ctx, "CodeWinOptimizer started")
if a.tweaksErr != nil {
wailsRuntime.LogError(ctx, a.tweaksErr.Error())
wailsRuntime.EventsEmit(ctx, "log", "[ERR] "+a.tweaksErr.Error()+" — tweaks will be unavailable")
}
a.ensureDefaultProfiles()
}
func (a *App) GetSystemLang() string {
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command",
`try{(Get-WinUserLanguageList)[0].LanguageTag.Substring(0,2)}catch{(Get-UICulture).TwoLetterISOLanguageName}`)
cmd.SysProcAttr = getSysProcAttr()
out, err := cmd.CombinedOutput()
if err != nil {
return "en"
}
result := strings.TrimSpace(string(out))
// Log for debugging
if a.ctx != nil {
wailsRuntime.LogInfo(a.ctx, fmt.Sprintf("Detected system language: %q", result))
}
if strings.HasPrefix(result, "es") {
return "es"
}
return "en"
}
func (a *App) runPS(script string) string {
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.CombinedOutput()
out := strings.TrimSpace(string(output))
if err != nil {
if out != "" {
a.emitLog(out)
}
a.emitLog(fmt.Sprintf("[ERR] %v", err))
} else if out != "" {
a.emitLog(out)
} else {
a.emitLog("[OK] Command completed")
}
return out
}
func (a *App) loadTweaks() error {
if err := json.Unmarshal(tweaksJSON, &a.categories); err != nil {
a.categories = []Category{}
a.tweakMap = map[string]*Tweak{}
return fmt.Errorf("failed to load tweaks.json: %w", err)
}
a.tweakMap = make(map[string]*Tweak, 256)
for i := range a.categories {
for j := range a.categories[i].Tweaks {
a.tweakMap[a.categories[i].Tweaks[j].ID] = &a.categories[i].Tweaks[j]
}
}
return nil
}
// sanitizeLog removes control characters and ANSI escape sequences from log output
// to prevent potential UI manipulation if log rendering ever changes from textContent.
func sanitizeLog(s string) string {
// Strip ANSI escape sequences (colors, cursor movement, etc.)
s = regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`).ReplaceAllString(s, "")
// Strip other control characters except newline, carriage return, tab
var b strings.Builder
b.Grow(len(s))
for _, r := range s {
if r == '\n' || r == '\r' || r == '\t' || r >= 32 {
b.WriteRune(r)
}
}
return b.String()
}
func (a *App) emitLog(msg string) {
wailsRuntime.EventsEmit(a.ctx, "log", sanitizeLog(msg))
}
func (a *App) GetCategories() []Category {
return a.categories
}
func (a *App) GetVersion() string {
return appVersion
}
// RestartSystem schedules a Windows restart in 10 seconds.
// Returns an error string (empty on success).
func (a *App) RestartSystem() string {
cmd := exec.Command("shutdown.exe", "/r", "/t", "10", "/c", "CodeWinOptimizer: restarting to apply tweaks")
cmd.SysProcAttr = getSysProcAttr()
if err := cmd.Run(); err != nil {
return err.Error()
}
return ""
}
// CancelRestart cancels a pending restart scheduled by RestartSystem.
func (a *App) CancelRestart() string {
cmd := exec.Command("shutdown.exe", "/a")
cmd.SysProcAttr = getSysProcAttr()
if err := cmd.Run(); err != nil {
return err.Error()
}
return ""
}
func (a *App) CheckForUpdate() string {
type assetInfo struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
}
type releaseInfo struct {
TagName string `json:"tag_name"`
HTMLURL string `json:"html_url"`
Assets []assetInfo `json:"assets"`
}
type updateResult struct {
Current string `json:"current"`
Latest string `json:"latest"`
UpdateURL string `json:"updateUrl"`
DownloadURL string `json:"downloadUrl"`
HasUpdate bool `json:"hasUpdate"`
}
client := &http.Client{Timeout: 10 * time.Second}
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", githubRepo)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return "{}"
}
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("User-Agent", "CodeWinOptimizer/"+appVersion)
resp, err := client.Do(req)
if err != nil {
return "{}"
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "{}"
}
var release releaseInfo
if err := json.Unmarshal(body, &release); err != nil {
return "{}"
}
latest := strings.TrimPrefix(release.TagName, "v")
// Find .exe asset download URL
var downloadURL string
for _, asset := range release.Assets {
if strings.HasSuffix(strings.ToLower(asset.Name), ".exe") {
downloadURL = asset.BrowserDownloadURL
break
}
}
result := updateResult{
Current: appVersion,
Latest: latest,
UpdateURL: release.HTMLURL,
DownloadURL: downloadURL,
HasUpdate: latest != appVersion && latest > appVersion,
}
b, _ := json.Marshal(result)
return string(b)
}
func (a *App) DownloadUpdate(downloadURL string) string {
if downloadURL == "" {
return `{"ok":false,"error":"no download URL"}`
}
a.emitLog("[UPDATE] Downloading update...")
// Get current executable path
exePath, err := os.Executable()
if err != nil {
return fmt.Sprintf(`{"ok":false,"error":"%s"}`, err.Error())
}
exePath, _ = filepath.EvalSymlinks(exePath)
// Download to temp file next to current exe
tmpPath := exePath + ".update"
client := &http.Client{Timeout: 5 * time.Minute}
resp, err := client.Get(downloadURL)
if err != nil {
return fmt.Sprintf(`{"ok":false,"error":"download failed: %s"}`, err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Sprintf(`{"ok":false,"error":"HTTP %d"}`, resp.StatusCode)
}
out, err := os.Create(tmpPath)
if err != nil {
return fmt.Sprintf(`{"ok":false,"error":"create temp: %s"}`, err.Error())
}
written, err := io.Copy(out, resp.Body)
out.Close()
if err != nil {
os.Remove(tmpPath)
return fmt.Sprintf(`{"ok":false,"error":"write failed: %s"}`, err.Error())
}
a.emitLog(fmt.Sprintf("[UPDATE] Downloaded %.2f MB", float64(written)/(1024*1024)))
// Create PowerShell updater script
scriptPath := filepath.Join(os.TempDir(), "cwo-updater.ps1")
pid := os.Getpid()
script := fmt.Sprintf(`
$ErrorActionPreference = 'Stop'
Start-Sleep -Milliseconds 500
$proc = Get-Process -Id %d -ErrorAction SilentlyContinue
if ($proc) {
$proc.WaitForExit(10000) | Out-Null
}
Start-Sleep -Milliseconds 500
$old = '%s'
$tmp = '%s'
Remove-Item -Path $old -Force -ErrorAction SilentlyContinue
Move-Item -Path $tmp -Destination $old -Force
Start-Process -FilePath $old
Remove-Item -Path '%s' -Force -ErrorAction SilentlyContinue
`, pid, exePath, tmpPath, scriptPath)
if err := os.WriteFile(scriptPath, []byte(script), 0644); err != nil {
os.Remove(tmpPath)
return fmt.Sprintf(`{"ok":false,"error":"script: %s"}`, err.Error())
}
// Launch updater and quit
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive",
"-WindowStyle", "Hidden", "-ExecutionPolicy", "Bypass", "-File", scriptPath)
cmd.SysProcAttr = getSysProcAttr()
if err := cmd.Start(); err != nil {
os.Remove(tmpPath)
os.Remove(scriptPath)
return fmt.Sprintf(`{"ok":false,"error":"launch updater: %s"}`, err.Error())
}
a.emitLog("[UPDATE] Restarting...")
// Quit the app
go func() {
time.Sleep(300 * time.Millisecond)
wailsRuntime.Quit(a.ctx)
}()
return `{"ok":true}`
}
func (a *App) CreateRestorePoint(description string) string {
if err := a.rateLimit("CreateRestorePoint"); err != nil {
return err.Error()
}
// Sanitize description for PowerShell double-quoted string
desc := strings.NewReplacer(
"`", "``",
"$", "`$",
"\"", "\"\"",
).Replace(description)
psCmd := fmt.Sprintf(`[Console]::OutputEncoding = [Text.Encoding]::UTF8
$desc = "%s"
# Enable System Restore if needed
try { Enable-ComputerRestore -Drive "$env:SystemDrive\" -ErrorAction SilentlyContinue } catch {}
# Bypass the 24h limit — use reg.exe (works on all Windows versions)
$freqPath = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SystemRestore"
$freqName = "SystemRestorePointCreationFrequency"
# Save old value
$oldVal = (reg query $freqPath /v $freqName 2>$null | Select-String "0x" | ForEach-Object { $_.Line.Split()[2] }) -replace "0x",""
# Set to 0
reg add "$freqPath" /v $freqName /t REG_DWORD /d 0 /f 2>$null | Out-Null
try {
Checkpoint-Computer -Description $desc -RestorePointType MODIFY_SETTINGS -ErrorAction Stop
$created = Get-ComputerRestorePoint | Where-Object { $_.Description -eq $desc } | Select-Object -First 1
if ($created) {
Write-Host "OK - Restore point created: $desc"
} else {
Write-Host "ERR: created but not found in list"
exit 1
}
} catch {
Write-Host "ERR: $($_.Exception.Message)"
exit 1
} finally {
# Restore old frequency
if ($oldVal) {
reg add "$freqPath" /v $freqName /t REG_DWORD /d $oldVal /f 2>$null | Out-Null
} else {
reg delete "$freqPath" /v $freqName /f 2>$null | Out-Null
}
}`, desc)
a.emitLog("[CMD] Creating restore point")
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", psCmd)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.CombinedOutput()
if err != nil {
msg := fmt.Sprintf("[ERR] Restore point failed: %v", err)
a.emitLog(msg)
if len(output) > 0 {
a.emitLog(strings.TrimSpace(string(output)))
}
return string(output)
}
a.emitLog("[OK] Restore point created")
return strings.TrimSpace(string(output))
}
func (a *App) RunCommands(tweakIDs []string, lang string) string {
if err := a.rateLimit("RunCommands"); err != nil {
return err.Error()
}
opCtx := a.startOp()
total := len(tweakIDs)
for i, tweakID := range tweakIDs {
if opCtx.Err() != nil {
a.emitLog("[WARN] Operation cancelled")
return "cancelled"
}
tweak := a.findTweak(tweakID)
if tweak == nil || len(tweak.Commands) == 0 {
continue
}
name := tweak.Name["en"]
if lang == "es" {
name = tweak.Name["es"]
}
a.emitLog(fmt.Sprintf("--- [%d/%d] %s ---", i+1, total, name))
joinedCmd := "[Console]::OutputEncoding = [Text.Encoding]::UTF8; " + strings.Join(tweak.Commands, "; ")
cmd := exec.CommandContext(opCtx, "powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", joinedCmd)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.CombinedOutput()
if err != nil {
a.emitLog(fmt.Sprintf("[ERR] %v", err))
a.emitLog(strings.TrimSpace(string(output)))
} else {
out := strings.TrimSpace(string(output))
if out != "" {
a.emitLog(out)
} else {
a.emitLog("[OK] Applied successfully")
}
}
}
a.emitLog("=== Complete ===")
return ""
}
func ensureChoco(a *App) {
check := exec.Command("powershell", "-NoProfile", "-Command",
`if (Get-Command choco -ErrorAction SilentlyContinue) { exit 0 }; if (Get-Command "C:\ProgramData\chocolatey\bin\choco.exe" -ErrorAction SilentlyContinue) { exit 0 }; exit 1`)
check.SysProcAttr = getSysProcAttr()
if check.Run() == nil {
return
}
a.emitLog("[CMD] Chocolatey not found — installing...")
install := exec.Command("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",
`Write-Host "Downloading Chocolatey..."; Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))`)
install.SysProcAttr = getSysProcAttr()
out, err := install.CombinedOutput()
if err != nil {
a.emitLog(fmt.Sprintf("[ERR] Chocolatey install failed: %v", err))
}
outStr := strings.TrimSpace(string(out))
if outStr != "" {
for _, line := range strings.Split(outStr, "\n") {
line = strings.TrimSpace(line)
if line != "" {
a.emitLog(line)
}
}
} else {
a.emitLog("[OK] Chocolatey installed")
}
verify := exec.Command("powershell", "-NoProfile", "-Command",
`if (Get-Command choco -ErrorAction SilentlyContinue) { exit 0 }; if (Get-Command "C:\ProgramData\chocolatey\bin\choco.exe" -ErrorAction SilentlyContinue) { exit 0 }; exit 1`)
verify.SysProcAttr = getSysProcAttr()
if verify.Run() != nil {
a.emitLog("[ERR] Chocolatey installation could not be verified — choco command not found after install")
}
}
func (a *App) InstallApps(ids []string, lang string, pkgMgr string) string {
if err := a.rateLimit("InstallApps"); err != nil {
return err.Error()
}
opCtx := a.startOp()
total := len(ids)
if pkgMgr == "choco" {
ensureChoco(a)
}
for i, id := range ids {
if opCtx.Err() != nil {
a.emitLog("[WARN] Operation cancelled")
return "cancelled"
}
if !safePackageID.MatchString(id) {
a.emitLog(fmt.Sprintf("[ERR] Invalid package ID: %s", id))
continue
}
a.emitLog(fmt.Sprintf("--- [%d/%d] Installing: %s ---", i+1, total, id))
var psCmd string
if pkgMgr == "choco" {
psCmd = fmt.Sprintf(`[Console]::OutputEncoding = [Text.Encoding]::UTF8
$choco = Get-Command choco -ErrorAction SilentlyContinue
if (-not $choco) { $choco = Get-Command "C:\ProgramData\chocolatey\bin\choco.exe" -ErrorAction SilentlyContinue }
if (-not $choco) { Write-Host "[ERR] Chocolatey not available — restart app and try again"; exit 1 }
& $choco install %s -y --no-progress`, id)
} else {
psCmd = fmt.Sprintf("[Console]::OutputEncoding = [Text.Encoding]::UTF8; winget install --id %s --silent --accept-package-agreements --accept-source-agreements", id)
}
cmd := exec.CommandContext(opCtx, "powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", psCmd)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.CombinedOutput()
if err != nil {
a.emitLog(fmt.Sprintf("[ERR] %v", err))
a.emitLog(strings.TrimSpace(string(output)))
} else {
out := strings.TrimSpace(string(output))
if out != "" {
a.emitLog(out)
} else {
a.emitLog("[OK] Installed successfully")
}
}
}
a.emitLog("=== Complete ===")
return ""
}
func (a *App) UninstallApp(id string, pkgMgr string) string {
if !safePackageID.MatchString(id) {
a.emitLog(fmt.Sprintf("[ERR] Invalid package ID: %s", id))
return "[ERR] Invalid package ID"
}
var psCmd string
if pkgMgr == "choco" {
ensureChoco(a)
psCmd = fmt.Sprintf(`[Console]::OutputEncoding = [Text.Encoding]::UTF8
$choco = Get-Command choco -ErrorAction SilentlyContinue
if (-not $choco) { $choco = Get-Command "C:\ProgramData\chocolatey\bin\choco.exe" -ErrorAction SilentlyContinue }
if (-not $choco) { Write-Host "[ERR] Chocolatey not available — restart app and try again"; exit 1 }
& $choco uninstall %s -y --no-progress`, id)
} else {
psCmd = fmt.Sprintf("[Console]::OutputEncoding = [Text.Encoding]::UTF8; winget uninstall --id %s --silent --accept-source-agreements", id)
}
a.emitLog(fmt.Sprintf("[CMD] Uninstalling: %s via %s", id, pkgMgr))
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", psCmd)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.CombinedOutput()
if err != nil {
a.emitLog(fmt.Sprintf("[ERR] %v", err))
a.emitLog(strings.TrimSpace(string(output)))
} else {
out := strings.TrimSpace(string(output))
if out != "" {
a.emitLog(out)
} else {
a.emitLog("[OK] Uninstalled successfully")
}
}
return ""
}
func (a *App) OpenURL(url string) {
if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
a.emitLog(fmt.Sprintf("[ERR] Blocked URL with unsafe scheme: %s", url))
return
}
wailsRuntime.BrowserOpenURL(a.ctx, url)
}
// LaunchShutUp10 extracts the embedded O&O ShutUp10++ portable binary
// (cached under %LOCALAPPDATA%\CodeWinOptimizer\OOSU10.exe) and launches it.
// Returns "" on success or an error string.
func (a *App) LaunchShutUp10() string {
cacheDir := os.Getenv("LOCALAPPDATA")
if cacheDir == "" {
home, _ := os.UserHomeDir()
cacheDir = filepath.Join(home, "AppData", "Local")
}
cacheDir = filepath.Join(cacheDir, "CodeWinOptimizer")
if err := os.MkdirAll(cacheDir, 0755); err != nil {
a.emitLog(fmt.Sprintf("[ERR] Cannot create cache dir: %s", err.Error()))
return err.Error()
}
target := filepath.Join(cacheDir, "OOSU10.exe")
// Extract only if missing or size differs from embedded
needsExtract := true
if st, err := os.Stat(target); err == nil {
if st.Size() == int64(len(oosu10Bytes)) {
needsExtract = false
}
}
if needsExtract {
a.emitLog(fmt.Sprintf("[INFO] Extracting bundled ShutUp10++ (%d MB) to cache...", len(oosu10Bytes)/(1024*1024)))
if err := os.WriteFile(target, oosu10Bytes, 0755); err != nil {
a.emitLog(fmt.Sprintf("[ERR] Failed to write ShutUp10++: %s", err.Error()))
return err.Error()
}
a.emitLog(fmt.Sprintf("[OK] Cached at %s", target))
}
a.emitLog(fmt.Sprintf("[OK] Launching O&O ShutUp10++: %s", target))
cmd := exec.Command(target)
cmd.SysProcAttr = getSysProcAttr()
if err := cmd.Start(); err != nil {
a.emitLog(fmt.Sprintf("[ERR] Failed to launch ShutUp10++: %s", err.Error()))
return err.Error()
}
return ""
}
func openExplorerAt(dir string) {
os.MkdirAll(dir, 0755)
cmd := exec.Command("explorer", dir)
if err := cmd.Start(); err == nil {
cmd.Process.Release()
}
}
func (a *App) OpenFolder() {
openExplorerAt(filepath.Join(os.Getenv("USERPROFILE"), "CodeWinOptimizer", "registry-backups"))
}
func (a *App) OpenDriverFolder() {
openExplorerAt(filepath.Join(os.Getenv("USERPROFILE"), "CodeWinOptimizer", "driver-backups"))
}
var featureCommands = map[string]string{
"netfx": `dism /online /enable-feature /featurename:NetFx3 /all /quiet /norestart; Write-Host "[OK] .NET Framework enabled"`,
"hyperv": `dism /online /enable-feature /featurename:Microsoft-Hyper-V-All /all /quiet /norestart; Write-Host "[OK] Hyper-V enabled"`,
"f8disable": `bcdedit /set {default} bootmenupolicy standard; Write-Host "[OK] F8 legacy disabled"`,
"f8enable": `bcdedit /set {default} bootmenupolicy legacy; Write-Host "[OK] F8 legacy enabled"`,
"legacymedia": `dism /online /enable-feature /featurename:WindowsMediaPlayer /all /quiet /norestart; dism /online /enable-feature /featurename:DirectPlay /all /quiet /norestart; Write-Host "[OK] Legacy media enabled"`,
"nfs": `dism /online /enable-feature /featurename:ServicesForNFS-ClientOnly /all /quiet /norestart; dism /online /enable-feature /featurename:ClientForNFS-Infrastructure /all /quiet /norestart; Write-Host "[OK] NFS enabled"`,
"regbackupsched": `$dir = "$env:SystemDrive\RegistryBackup"; New-Item -ItemType Directory -Path $dir -Force -ErrorAction SilentlyContinue | Out-Null; $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-Command reg export HKLM '$dir\HKLM_$(Get-Date -Format yyyyMMdd_HHmmss).reg' /y"; $trigger = New-ScheduledTaskTrigger -Daily -At 00:30; Register-ScheduledTask -TaskName "CodeWinOptimizer_RegistryBackup" -Action $action -Trigger $trigger -Force -ErrorAction Stop | Out-Null; Write-Host "[OK] Daily registry backup scheduled at 00:30"`,
"sandbox": `dism /online /enable-feature /featurename:Containers-DisposableClientVM /all /quiet /norestart; Write-Host "[OK] Windows Sandbox enabled"`,
"wsl": `dism /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /quiet /norestart; dism /online /enable-feature /featurename:VirtualMachinePlatform /all /quiet /norestart; Write-Host "[OK] WSL enabled"`,
}
var fixCommands = map[string]string{
"autologin": `$regPath = "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"; $user = (Get-CimInstance -Class Win32_ComputerSystem | Select-Object -ExpandProperty Username); Set-ItemProperty -Path $regPath -Name "AutoAdminLogon" -Value "1" -Force; Set-ItemProperty -Path $regPath -Name "DefaultUserName" -Value $user -Force; Set-ItemProperty -Path $regPath -Name "DefaultPassword" -Value "" -Force; Write-Host "Autologin enabled for $user"`,
"netreset": `netsh int ip reset; netsh winsock reset; ipconfig /flushdns; Write-Host "Network stack reset complete"`,
"ntp": `w32tm /config /syncfromflags:manual /manualpeerlist:"time.windows.com" /reliable:YES /update; net stop w32time; net start w32time; w32tm /resync /force; Write-Host "NTP sync enabled"`,
"sfc": `DISM /Online /Cleanup-Image /RestoreHealth; sfc /scannow; Write-Host "System scan complete"`,
"wureset": `net stop wuauserv; net stop cryptSvc; net stop bits; net stop msiserver; Remove-Item -Recurse -Force "$env:windir\SoftwareDistribution" -ErrorAction SilentlyContinue; net start wuauserv; net start cryptSvc; net start bits; net start msiserver; Write-Host "Windows Update cache reset"`,
"wingetre": `Write-Host "Reinstalling WinGet..."; try{Add-AppxPackage -RegisterByFamilyName -MainPackage Microsoft.DesktopAppInstaller_8wekyb3d8bbwe -ErrorAction Stop; Write-Host "WinGet reinstalled successfully"}catch{Write-Host "ERR: WinGet reinstall failed -- $($_.Exception.Message)"}`,
}
func (a *App) RunFeature(id string) string {
script, ok := featureCommands[id]
if !ok {
a.emitLog(fmt.Sprintf("[ERR] Unknown feature: %s", id))
return "[ERR] Unknown feature"
}
return a.runPS(script)
}
func (a *App) RunFix(id string) string {
script, ok := fixCommands[id]
if !ok {
a.emitLog(fmt.Sprintf("[ERR] Unknown fix: %s", id))
return "[ERR] Unknown fix"
}
return a.runPS(script)
}
func (a *App) Quit() {
wailsRuntime.Quit(a.ctx)
}
func (a *App) BackupRegistry() string {
if err := a.rateLimit("BackupRegistry"); err != nil {
return err.Error()
}
backupDir := fmt.Sprintf("%s\\CodeWinOptimizer\\registry-backups", os.Getenv("USERPROFILE"))
ts := time.Now().Format("2006-01-02_150405")
dir := fmt.Sprintf("%s\\%s", backupDir, ts)
psCmd := fmt.Sprintf(`[Console]::OutputEncoding = [Text.Encoding]::UTF8
$dir = "%s"
New-Item -ItemType Directory -Path $dir -Force | Out-Null
$hives = @("HKLM","HKCU","HKCR","HKU","HKCC")
$total = $hives.Count; $ok = 0
foreach ($h in $hives) {
try {
$out = Join-Path $dir "$h.reg"
reg export $h $out /y 2>$null
if ($LASTEXITCODE -eq 0) { $ok++; Write-Host "OK: $h exported" }
else { Write-Host "WARN: $h had warnings (partial export)" }
} catch {
Write-Host "ERR: $h - $($_.Exception.Message)"
}
}
Write-Host "--- Full registry backup: $ok/$total hives -> $dir ---"
# Open folder in Explorer
Start-Process explorer.exe -ArgumentList $dir`, dir)
a.emitLog("[CMD] Backing up full registry (5 hives: HKLM, HKCU, HKCR, HKU, HKCC)...")
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", psCmd)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.CombinedOutput()
if err != nil {
a.emitLog(fmt.Sprintf("[ERR] Registry backup failed: %v", err))
} else {
a.emitLog(fmt.Sprintf("[OK] Full registry backup saved to: %s", dir))
}
return strings.TrimSpace(string(output))
}
func (a *App) findTweak(id string) *Tweak {
return a.tweakMap[id]
}
func (a *App) CheckAdmin() bool {
cmd := exec.Command("powershell", "-NoProfile", "-Command",
"(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)")
output, err := cmd.Output()
if err != nil {
return false
}
return strings.TrimSpace(string(output)) == "True"
}
func (a *App) GetInstalledPackages() string {
psCmd := `$out = winget list --accept-source-agreements 2>$null | Out-String -Width 4096; $lines = $out -split '\r?\n' | Where-Object { $_ -match '\S' }; $collect = $false; $ids = @(); foreach ($l in $lines) { if ($l -match '^-{2,}') { $collect = $true; continue }; if (-not $collect) { continue }; $p = @($l -split '\s{2,}'); if ($p.Count -ge 2 -and $p[1] -match '\.') { $ids += $p[1].Trim() } }; $ids | ConvertTo-Json -Compress; if (-not $?) { '[]' }`
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", psCmd)
cmd.SysProcAttr = getSysProcAttr()
output, err := cmd.Output()
if err != nil {
return "[]"
}
result := strings.TrimSpace(string(output))
if result == "" || result == "null" {
return "[]"
}
return result
}
func (a *App) GetSystemInfo() string {
// --- CPU % (gopsutil — native, reliable) ---
cpuPercent := 0.0
if percents, err := cpu.Percent(0, false); err == nil && len(percents) > 0 {
cpuPercent = math.Round(percents[0]*10) / 10
}
// CPU info via CIM (one-shot, no polling needed)
cpuInfo, _ := cpu.Info()
cpuName := ""
cpuCores := 0
cpuThreads := 0
if len(cpuInfo) > 0 {
cpuName = cpuInfo[0].ModelName
cpuCores = int(cpuInfo[0].Cores)
}
// Logical (thread) count
if n, err := cpu.Counts(true); err == nil {
cpuThreads = n
}
// --- RAM (gopsutil) ---
ramTotal := 0.0
ramFree := 0.0
ramUsed := 0.0
ramPct := 0.0
if vmem, err := mem.VirtualMemory(); err == nil {
ramTotal = math.Round(float64(vmem.Total)/bytesPerGiB*10) / 10
ramFree = math.Round(float64(vmem.Available)/bytesPerGiB*10) / 10
ramUsed = math.Round(float64(vmem.Used)/bytesPerGiB*10) / 10
ramPct = math.Round(vmem.UsedPercent*10) / 10
}
// --- Uptime (gopsutil) ---
uptimeStr := ""
if up, err := host.Uptime(); err == nil {
uptimeSec := uint64(up)
days := uptimeSec / secondsPerDay
hours := (uptimeSec % secondsPerDay) / secondsPerHour
minutes := (uptimeSec % secondsPerHour) / secondsPerMinute
uptimeStr = fmt.Sprintf("%dd %dh %dm", days, hours, minutes)
}
// --- GPU, Disks, Temps via PowerShell ---
psCmd := `[Console]::OutputEncoding = [Text.Encoding]::UTF8
$gpuList = @()
$gpus = Get-CimInstance Win32_VideoController
foreach ($g in $gpus) {
$name = $g.Name; if (-not $name) { $name = 'Unknown' }
if ($name.Length -gt 50) { $name = $name.Substring(0,47)+'...' }
$vram = 0
if ($g.AdapterRAM -and $g.AdapterRAM -gt 0) { $vram = [math]::Round($g.AdapterRAM/1GB, 1) }
$gpuList += [PSCustomObject]@{ name = $name; driver = $g.DriverVersion; ramGB = $vram; usage = 0; temp = 0 }
}
$nvidiaIdx = -1
for ($i=0; $i -lt $gpuList.Count; $i++) {
if ($gpuList[$i].name -match '(?i)nvidia|geforce|rtx|quadro|tesla') { $nvidiaIdx = $i; break }
}
if ($nvidiaIdx -ge 0) {
try {
$smi = & nvidia-smi --query-gpu=utilization.gpu,temperature.gpu,memory.total --format=csv,noheader,nounits 2>$null
if ($smi) {
$parts = $smi.Trim() -split ',\s*'
if ($parts.Count -ge 2) {
$gpuList[$nvidiaIdx].usage = [double]$parts[0]
$gpuList[$nvidiaIdx].temp = [double]$parts[1]
if ($parts.Count -ge 3 -and [double]$parts[2] -gt 0) {
$gpuList[$nvidiaIdx].ramGB = [math]::Round([double]$parts[2]/1024, 1)
}
}
}
} catch {}
}
$diskList = @()
$disks = Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3"
foreach ($d in $disks) {
$t = [math]::Round($d.Size/1GB, 1)
$f = [math]::Round($d.FreeSpace/1GB, 1)
$u = [math]::Round($t - $f, 1)
$p = if($t -gt 0){[math]::Round(($t-$f)/$t*100,1)}else{0}
$diskList += [PSCustomObject]@{ drive = $d.DeviceID; total = $t; free = $f; used = $u; pct = $p }
}
$tempList = @()
if ($nvidiaIdx -ge 0 -and $gpuList[$nvidiaIdx].temp -gt 0) {
$tempList += [PSCustomObject]@{ name = 'GPU'; temp = $gpuList[$nvidiaIdx].temp }
}
# CPU temp: try multiple sources, prefer the one that returns a sensible value.
# AMD Ryzen rarely exposes via MSAcpi; LibreHardwareMonitor/OpenHardwareMonitor
# expose it if running. Perf counter sometimes works on AMD.
$cpuTemp = -1
# 1. OpenHardwareMonitor / LibreHardwareMonitor WMI namespaces (if their service is running)
foreach ($ns in @('root/OpenHardwareMonitor', 'root/LibreHardwareMonitor')) {
if ($cpuTemp -ge 0) { break }
try {
$sensors = Get-CimInstance -Namespace $ns -ClassName Sensor -ErrorAction Stop
$cpuSensor = $sensors | Where-Object { $_.SensorType -eq 'Temperature' -and ($_.Name -match 'CPU Package|CPU Core|Core \(Tctl|Tdie' -or $_.Parent -match 'cpu') } | Select-Object -First 1
if ($cpuSensor -and $cpuSensor.Value -gt 0 -and $cpuSensor.Value -le 125) {
$cpuTemp = [math]::Round($cpuSensor.Value, 1)
}
} catch {}
}
# 2. Perf counter (works on some AMD systems)
if ($cpuTemp -lt 0) {
try {
$counters = (Get-Counter '\Thermal Zone Information(*)\High Precision Temperature' -ErrorAction Stop).CounterSamples
foreach ($c in $counters) {
$t = [math]::Round(($c.CookedValue / 10.0) - 273.15, 1)
if ($t -gt 20 -and $t -lt 125 -and ($cpuTemp -lt 0 -or $t -gt $cpuTemp)) { $cpuTemp = $t }
}
} catch {}
}
# 3. MSAcpi thermal zones (Intel-friendly fallback)
try {
$wmiTemps = Get-CimInstance -Namespace root/wmi MSAcpi_ThermalZoneTemperature -ErrorAction Stop
foreach ($tz in $wmiTemps) {
$t = [math]::Round(($tz.CurrentTemperature - 2732) / 10.0, 1)
if ($t -ge 20 -and $t -le 125 -and ($cpuTemp -lt 0 -or $t -gt $cpuTemp)) { $cpuTemp = $t }
}
} catch {}
if ($cpuTemp -gt 0) {
$tempList += [PSCustomObject]@{ name = 'CPU'; temp = $cpuTemp }
}
[PSCustomObject]@{
gpus = @($gpuList);
disks = @($diskList);
temps = @($tempList);
} | ConvertTo-Json -Compress -Depth 4
`
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", psCmd)
cmd.SysProcAttr = getSysProcAttr()
psOutput, psErr := cmd.Output()
// Build final JSON
psJSON := `{"gpus":[],"disks":[],"temps":[]}`
if psErr == nil && len(psOutput) > 0 {
psJSON = strings.TrimSpace(string(psOutput))
}
// Parse PS output and inject Go-computed values
type CPUOut struct {
Pct float64 `json:"pct"`
Name string `json:"name"`
Cores int `json:"cores"`
Threads int `json:"threads"`
}
type RAMOut struct {
TotalGB float64 `json:"totalGB"`
FreeGB float64 `json:"freeGB"`
UsedGB float64 `json:"usedGB"`
Pct float64 `json:"pct"`
}
type FullOut struct {
CPU CPUOut `json:"cpu"`
RAM RAMOut `json:"ram"`
Uptime string `json:"uptime"`
}
fo := FullOut{
CPU: CPUOut{Pct: cpuPercent, Name: cpuName, Cores: cpuCores, Threads: cpuThreads},
RAM: RAMOut{TotalGB: ramTotal, FreeGB: ramFree, UsedGB: ramUsed, Pct: ramPct},
Uptime: uptimeStr,
}
merged := map[string]interface{}{
"cpu": fo.CPU,
"ram": fo.RAM,
"uptime": fo.Uptime,
}
var psData map[string]interface{}
if err := json.Unmarshal([]byte(psJSON), &psData); err == nil {
for k, v := range psData {
merged[k] = v
}
}
result, _ := json.Marshal(merged)
return string(result)
}
func (a *App) GetHealthScore() string {
type HealthResult struct {
Score int `json:"score"`
Grade string `json:"grade"`
Breakdown map[string]int `json:"breakdown"`
Tips []string `json:"tips"`
}
score := 100
breakdown := map[string]int{}
var tips []string
// RAM usage (30 points max) — finer granularity so 100/A+ is genuinely rare
ramScore := 30
if vmem, err := mem.VirtualMemory(); err == nil {
pct := vmem.UsedPercent
switch {
case pct > 90:
ramScore = 5
tips = append(tips, "RAM usage critical (>90%)")
case pct > 80:
ramScore = 15
tips = append(tips, "RAM usage high (>80%)")
case pct > 70:
ramScore = 22
case pct > 50:
ramScore = 27
case pct > 30:
ramScore = 29
}
} else {