-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameTaskPlugin.cs
More file actions
968 lines (785 loc) · 37.3 KB
/
GameTaskPlugin.cs
File metadata and controls
968 lines (785 loc) · 37.3 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using Playnite.SDK;
using Playnite.SDK.Events;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
namespace GameTaskPlugin
{
public class GameTaskPlugin : GenericPlugin
{
public override Guid Id { get; } =
Guid.Parse("d6d798db-6a1f-4c6e-9b1d-000000000001");
private const string TagName = "[GT] UAC-skip";
private const string ActionName = "Play Without UAC";
private readonly IPlayniteAPI api;
private readonly string pluginDataPath;
private readonly Logger logger;
private readonly SettingsManager settingsManager;
private readonly GameTaskSettings gameTaskSettings;
private readonly TaskManager taskManager;
private readonly LauncherManager launcherManager;
private readonly ActionManager actionManager;
private readonly HiddenLauncherManager hiddenLauncherManager;
private readonly NotificationManager notificationManager;
private readonly TrackerManager trackerManager;
private readonly PathManager pathManager;
// Cooldown: tracks last launch time to prevent double-launch
private DateTime lastLaunchTime = DateTime.MinValue;
private const int LaunchCooldownMs = 3000;
public GameTaskPlugin(IPlayniteAPI api) : base(api)
{
this.api = api;
Properties = new GenericPluginProperties { HasSettings = true };
pluginDataPath = GetPluginUserDataPath();
Directory.CreateDirectory(pluginDataPath);
logger = new Logger(pluginDataPath);
settingsManager = new SettingsManager(logger, pluginDataPath);
gameTaskSettings = new GameTaskSettings(this, settingsManager);
taskManager = new TaskManager(logger, pluginDataPath);
launcherManager = new LauncherManager(logger, pluginDataPath, settingsManager);
actionManager = new ActionManager(logger, launcherManager);
hiddenLauncherManager = new HiddenLauncherManager(logger, pluginDataPath);
trackerManager = new TrackerManager(logger);
pathManager = new PathManager(logger, pluginDataPath, taskManager);
notificationManager = new NotificationManager(api, RunPendingTasks, pluginDataPath);
logger.Log("GameTask plugin started.");
}
// =====================================================
// SETTINGS PAGE
// =====================================================
public override ISettings GetSettings(bool firstRunSettings) => gameTaskSettings;
public override UserControl GetSettingsView(bool firstRunSettings)
=> new SettingsView { DataContext = gameTaskSettings };
// =====================================================
// STARTUP
// =====================================================
public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
{
base.OnApplicationStarted(args);
// Trim logs if they exceed 1 MB
TrimLog(Path.Combine(pluginDataPath, "Logs", "FocusGuard.log"), maxBytes: 1024 * 1024);
TrimLog(Path.Combine(pluginDataPath, "Logs", "PS1.log"), maxBytes: 1024 * 1024);
// Run startup tasks in background to avoid blocking Playnite UI
// and prevent the "serious error" crash on slow PCs with many tagged games
System.Threading.Tasks.Task.Run(() =>
{
try
{
ScanLibrary();
if (settingsManager.Current.DetectOrphanTasks)
CheckForOrphanTasks();
if (settingsManager.Current.DetectCorruptedTasks)
CheckForCorruptedTasks();
// ShowPendingNotification must run on UI thread
api.MainView.UIDispatcher.Invoke(() =>
notificationManager.ShowPendingNotification());
}
catch (Exception ex)
{
logger.Log($"ERROR in background startup: {ex.Message}");
}
});
}
// =====================================================
// LIBRARY SCAN
// =====================================================
private void TrimLog(string logPath, long maxBytes)
{
try
{
if (!File.Exists(logPath)) return;
var info = new FileInfo(logPath);
if (info.Length <= maxBytes) return;
var content = File.ReadAllText(logPath);
var trimmed = content.Substring(content.Length / 2);
var firstLine = trimmed.IndexOf('\n');
if (firstLine >= 0) trimmed = trimmed.Substring(firstLine + 1);
File.WriteAllText(logPath,
$"[Log trimmed at {DateTime.Now:yyyy-MM-dd HH:mm:ss} — older entries removed]\r\n" + trimmed);
logger.Log($"Log trimmed: {Path.GetFileName(logPath)}");
}
catch (Exception ex) { logger.Log($"ERROR trimming log: {ex.Message}"); }
}
private void ScanLibrary()
{
taskManager.ResetPendingFile();
foreach (var game in api.Database.Games)
{
if (!HasGameTaskTag(game)) continue;
RepairGameTask(game);
}
}
// =====================================================
// ORPHAN TASK DETECTION
// =====================================================
private void CheckForOrphanTasks()
{
try
{
var knownNames = api.Database.Games
.Where(HasGameTaskTag)
.Select(g => TaskManager.GetTaskName(g))
.ToList();
taskManager.WriteKnownTasks(knownNames);
var orphans = new List<string>();
using (var proc = new Process())
{
proc.StartInfo.FileName = "schtasks.exe";
proc.StartInfo.Arguments = "/query /fo CSV /nh /tn \"\\GameTask\\\"";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
foreach (var line in output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
{
string cell = line.Split(',')[0].Trim('"');
string name = Path.GetFileName(cell);
if (!string.IsNullOrWhiteSpace(name) &&
!knownNames.Contains(name, StringComparer.OrdinalIgnoreCase))
orphans.Add(name);
}
}
if (orphans.Count == 0) { logger.Log("Orphan check: none found."); return; }
logger.Log($"Orphan check: {orphans.Count} orphan(s) found.");
api.Notifications.Add(new NotificationMessage(
"GameTaskOrphans",
$"GameTask: {orphans.Count} orphan task(s) found in Task Scheduler. Click to clean up.",
NotificationType.Info,
() => CleanOrphanTasks()));
}
catch (Exception ex) { logger.Log($"ERROR in orphan check: {ex.Message}"); }
}
// =====================================================
// CORRUPTED TASK DETECTION
// =====================================================
private void CheckForCorruptedTasks()
{
try
{
var taggedGames = api.Database.Games.Where(HasGameTaskTag).ToList();
var corrupted = new List<Game>();
foreach (var game in taggedGames)
{
string customExe = pathManager.GetCustomPath(game);
if (!string.IsNullOrWhiteSpace(customExe))
{
if (!File.Exists(customExe)) corrupted.Add(game);
continue;
}
var action = game.GameActions?.FirstOrDefault(a =>
a != null && a.Name != ActionName && !string.IsNullOrWhiteSpace(a.Path));
if (action == null) continue;
string exePath = taskManager.ResolveExecutable(game, action);
if (!string.IsNullOrWhiteSpace(exePath) && !File.Exists(exePath))
corrupted.Add(game);
}
if (corrupted.Count == 0) { logger.Log("Corrupted task check: none found."); return; }
logger.Log($"Corrupted task check: {corrupted.Count} found.");
foreach (var game in corrupted)
notificationManager.ShowExecutableFixNotification(game, () => FixExecutablePath(game));
}
catch (Exception ex) { logger.Log($"ERROR in corrupted task check: {ex.Message}"); }
}
// =====================================================
// UNKNOWN EXE DETECTION
// Games tagged with GameTask but whose exe can't be
// resolved — FocusGuard won't work for these games.
// =====================================================
private void CheckForUnknownExecutables()
{
var unknown = api.Database.Games
.Where(HasGameTaskTag)
.Where(g => string.IsNullOrWhiteSpace(ResolveExePathForGame(g)))
.ToList();
if (unknown.Count == 0)
{
api.Dialogs.ShowMessage("All tagged games have a detected executable.", "GameTask");
return;
}
logger.Log($"Unknown exe check: {unknown.Count} game(s) need attention.");
api.Notifications.Add(new NotificationMessage(
"GameTaskUnknownExe",
$"GameTask: {unknown.Count} game(s) have no detected executable. Click to fix them.",
NotificationType.Info,
() => FixAllUnknownExecutables()));
}
// =====================================================
// FIX ALL UNKNOWN EXECUTABLES
// =====================================================
private void FixAllUnknownExecutables()
{
var unknown = api.Database.Games
.Where(HasGameTaskTag)
.Where(g => string.IsNullOrWhiteSpace(ResolveExePathForGame(g)))
.ToList();
if (unknown.Count == 0)
{
api.Dialogs.ShowMessage("All tagged games have a detected executable.", "GameTask");
return;
}
int fixed_count = 0;
foreach (var game in unknown)
{
var result = api.Dialogs.ShowMessage(
$"Game \"{game.Name}\" has no detected executable.\n\nDo you want to select it now?",
"GameTask — Fix Executable",
System.Windows.MessageBoxButton.YesNoCancel);
if (result == System.Windows.MessageBoxResult.Cancel) break;
if (result == System.Windows.MessageBoxResult.No) continue;
bool fixed_path = pathManager.PromptForExecutable(game);
if (!fixed_path) continue;
fixed_count++;
string customExe = pathManager.GetCustomPath(game);
taskManager.RemovePendingEntry(game);
taskManager.AddPendingTask(game, ActionName, customExe);
launcherManager.CreateOrUpdateLauncher(game, customExe);
actionManager.CreateOrUpdatePlayAction(game, api);
notificationManager.RemoveExecutableFixNotification(game);
logger.Log($"Executable fixed via Fix All: {game.Name} -> {customExe}");
}
api.Notifications.Remove("GameTaskUnknownExe");
if (fixed_count > 0)
{
notificationManager.ShowPendingNotification();
api.Dialogs.ShowMessage(
$"{fixed_count} executable(s) configured.\n\nClick the notification or use \"Create Pending Tasks\" to register the Windows tasks.",
"GameTask");
}
}
// =====================================================
// CLEAN ORPHAN TASKS
// =====================================================
private void CleanOrphanTasks()
{
try
{
var knownNames = api.Database.Games
.Where(HasGameTaskTag)
.Select(g => TaskManager.GetTaskName(g))
.ToList();
taskManager.WriteKnownTasks(knownNames);
logger.Log("Requesting elevated orphan cleanup...");
Process.Start(new ProcessStartInfo
{
FileName = "wscript.exe",
Arguments = $"\"{hiddenLauncherManager.GetCleanOrphansLauncherPath()}\"",
Verb = "runas",
UseShellExecute = true
});
api.Notifications.Remove("GameTaskOrphans");
}
catch (Exception ex) { logger.Log($"ERROR running orphan cleanup: {ex.Message}"); }
}
// =====================================================
// REPAIR ALL TAGGED GAMES
// =====================================================
private void RepairAll()
{
var taggedGames = api.Database.Games.Where(HasGameTaskTag).ToList();
if (taggedGames.Count == 0)
{
api.Dialogs.ShowMessage("No games with the GameTask tag were found.", "GameTask");
return;
}
foreach (var game in taggedGames)
{
RepairGameTask(game);
logger.Log($"GameTask repaired (all): {game.Name}");
}
notificationManager.ShowPendingNotification();
api.Dialogs.ShowMessage(
$"Repair complete: {taggedGames.Count} game(s) processed.\n\nIf new pending tasks were queued, click the notification or use \"Create Pending Tasks\" to register them.",
"GameTask");
}
// =====================================================
// REPAIR (single game)
// =====================================================
private void RepairGameTask(Game game)
{
string resolvedExe = ResolveExePathForGame(game);
launcherManager.CreateOrUpdateLauncher(game, resolvedExe);
actionManager.CreateOrUpdatePlayAction(game, api);
if (!TaskExists(game))
taskManager.AddPendingTask(game, ActionName, resolvedExe);
ValidateExecutable(game);
}
// =====================================================
// RESOLVE EXE PATH
// =====================================================
private string ResolveExePathForGame(Game game)
{
// 1. Custom path takes priority
string customExe = pathManager.GetCustomPath(game);
if (!string.IsNullOrWhiteSpace(customExe) && File.Exists(customExe))
return customExe;
var action = game.GameActions?.FirstOrDefault(a =>
a != null && a.Name != ActionName && !string.IsNullOrWhiteSpace(a.Path));
if (action == null) return null;
// 2. Steam URL actions — resolve via steam.exe
if (action.Path.StartsWith("steam://", StringComparison.OrdinalIgnoreCase))
{
string steamExe = ResolveSteamExe();
if (!string.IsNullOrWhiteSpace(steamExe)) return steamExe;
}
// 3. Regular exe action
string resolved = taskManager.ResolveExecutable(game, action);
return File.Exists(resolved) ? resolved : null;
}
private string ResolveSteamExe()
{
string[] candidates =
{
@"C:\Program Files (x86)\Steam\steam.exe",
@"C:\Program Files\Steam\steam.exe"
};
foreach (var path in candidates)
if (File.Exists(path)) return path;
try
{
using var key = Microsoft.Win32.Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\WOW6432Node\Valve\Steam") ??
Microsoft.Win32.Registry.LocalMachine
.OpenSubKey(@"SOFTWARE\Valve\Steam");
if (key != null)
{
string installPath = key.GetValue("InstallPath") as string;
if (!string.IsNullOrWhiteSpace(installPath))
{
string steamExe = Path.Combine(installPath, "steam.exe");
if (File.Exists(steamExe)) return steamExe;
}
}
}
catch { }
return null;
}
private string ResolveExeNameForGame(Game game)
{
string path = ResolveExePathForGame(game);
return string.IsNullOrWhiteSpace(path) ? null : Path.GetFileName(path);
}
// =====================================================
// VALIDATE EXECUTABLE
// =====================================================
private void ValidateExecutable(Game game)
{
string customExe = pathManager.GetCustomPath(game);
if (!string.IsNullOrWhiteSpace(customExe) && File.Exists(customExe))
{
notificationManager.RemoveExecutableFixNotification(game);
return;
}
var action = game.GameActions?.FirstOrDefault(a =>
a != null && a.Name != ActionName && !string.IsNullOrWhiteSpace(a.Path));
if (action == null) return;
string exePath = pathManager.GetExecutablePath(game, action);
if (string.IsNullOrWhiteSpace(exePath) || !File.Exists(exePath))
{
logger.Log($"EXE not found: {game.Name}");
notificationManager.ShowExecutableFixNotification(game, () => FixExecutablePath(game));
}
else
{
notificationManager.RemoveExecutableFixNotification(game);
}
}
// =====================================================
// FIX / REMOVE EXECUTABLE PATH
// =====================================================
private void FixExecutablePath(Game game)
{
bool fixedPath = pathManager.PromptForExecutable(game);
if (!fixedPath) return;
logger.Log($"Executable manually fixed: {game.Name}");
notificationManager.RemoveExecutableFixNotification(game);
string customExe = pathManager.GetCustomPath(game);
taskManager.RemovePendingEntry(game);
taskManager.AddPendingTask(game, ActionName, customExe);
launcherManager.CreateOrUpdateLauncher(game, customExe);
actionManager.CreateOrUpdatePlayAction(game, api);
notificationManager.ShowPendingNotification();
logger.Log($"Pending task queued after fix: {game.Name}");
api.Dialogs.ShowMessage(
$"Executable configured for \"{game.Name}\".\n\nClick \"Create Pending Tasks\" in the GameTask menu (or the notification) to register the Windows task with elevated rights.",
"GameTask");
}
private void RemoveCustomPath(Game game)
{
pathManager.RemoveCustomPath(game);
logger.Log($"Custom path removed: {game.Name}");
ValidateExecutable(game);
api.Dialogs.ShowMessage(
$"Custom executable path removed for \"{game.Name}\".\n\nGameTask will now try to detect the executable automatically.",
"GameTask");
}
// =====================================================
// TAG HELPERS
// =====================================================
private bool HasGameTaskTag(Game game)
{
if (game.Tags != null && game.Tags.Any(t => t != null && t.Name == TagName))
return true;
if (game.TagIds == null) return false;
foreach (var tagId in game.TagIds)
{
var tag = api.Database.Tags.Get(tagId);
if (tag != null && tag.Name == TagName) return true;
}
return false;
}
private Tag GetOrCreateGameTaskTag()
{
var existing = api.Database.Tags.FirstOrDefault(t => t.Name == TagName);
if (existing != null) return existing;
var tag = new Tag(TagName);
api.Database.Tags.Add(tag);
logger.Log("Tag created: " + TagName);
return tag;
}
// =====================================================
// ENABLE / DISABLE
// =====================================================
private void EnableGameTask(IEnumerable<Game> games)
{
var tag = GetOrCreateGameTaskTag();
foreach (var game in games)
{
if (game.TagIds == null) game.TagIds = new List<Guid>();
if (!game.TagIds.Contains(tag.Id))
{
game.TagIds.Add(tag.Id);
api.Database.Games.Update(game);
}
RepairGameTask(game);
logger.Log($"GameTask enabled: {game.Name}");
}
notificationManager.ShowPendingNotification();
}
private void DisableGameTask(IEnumerable<Game> games)
{
taskManager.ResetDeleteFile();
foreach (var game in games)
{
var tag = api.Database.Tags.FirstOrDefault(t => t.Name == TagName);
if (tag != null && game.TagIds != null && game.TagIds.Contains(tag.Id))
game.TagIds.Remove(tag.Id);
actionManager.RemovePlayAction(game, api);
launcherManager.RemoveLauncher(game);
taskManager.RemovePendingEntry(game);
taskManager.AddDeleteTask(game);
notificationManager.RemoveExecutableFixNotification(game);
api.Database.Games.Update(game);
logger.Log($"GameTask disabled: {game.Name}");
}
RunDeleteTasks();
}
// =====================================================
// REBUILD / REPAIR SELECTED
// =====================================================
private void RebuildSelected(IEnumerable<Game> games)
{
taskManager.ResetDeleteFile();
foreach (var game in games)
{
actionManager.RemovePlayAction(game, api);
launcherManager.RemoveLauncher(game);
taskManager.RemovePendingEntry(game);
taskManager.AddDeleteTask(game);
string resolvedExe = ResolveExePathForGame(game);
launcherManager.CreateOrUpdateLauncher(game, resolvedExe);
actionManager.CreateOrUpdatePlayAction(game, api);
taskManager.AddPendingTask(game, ActionName, resolvedExe);
ValidateExecutable(game);
logger.Log($"GameTask rebuilt: {game.Name}");
}
RunDeleteTasks();
notificationManager.ShowPendingNotification();
}
private void RepairSelected(IEnumerable<Game> games)
{
foreach (var game in games)
{
RepairGameTask(game);
logger.Log($"GameTask repaired: {game.Name}");
}
notificationManager.ShowPendingNotification();
}
// =====================================================
// TASK EXISTS CHECK
// =====================================================
private bool TaskExists(Game game)
{
string taskName = TaskManager.GetTaskName(game);
try
{
using var process = new Process();
process.StartInfo.FileName = "schtasks.exe";
process.StartInfo.Arguments = $"/query /tn \"\\GameTask\\{taskName}\"";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.WaitForExit();
return process.ExitCode == 0;
}
catch { return false; }
}
// =====================================================
// RUN PENDING TASKS
// =====================================================
private void RunPendingTasks()
{
// Cooldown — prevent double-launch
var now = DateTime.UtcNow;
if ((now - lastLaunchTime).TotalMilliseconds < settingsManager.Current.CooldownSeconds * 1000)
{
logger.Log("RunPendingTasks skipped — cooldown active.");
return;
}
lastLaunchTime = now;
// If PendingTasks.txt is empty, rescan all tagged games for missing tasks
// This handles the case where tasks were manually deleted from Task Scheduler
var pending = taskManager.GetPendingTasks();
if (pending.Count == 0)
{
logger.Log("PendingTasks.txt is empty — rescanning for missing tasks...");
foreach (var game in api.Database.Games.Where(HasGameTaskTag))
{
if (!TaskExists(game))
{
string resolvedExe = ResolveExePathForGame(game);
if (!string.IsNullOrWhiteSpace(resolvedExe))
{
taskManager.AddPendingTask(game, ActionName, resolvedExe);
logger.Log($"Re-queued missing task: {game.Name}");
}
}
}
pending = taskManager.GetPendingTasks();
if (pending.Count == 0)
{
logger.Log("No missing tasks found after rescan.");
api.Notifications.Add(new NotificationMessage(
"GameTaskNoPending",
"GameTask: No pending tasks found. All tasks are already created.",
NotificationType.Info,
null));
return;
}
}
try
{
string resultFile = hiddenLauncherManager.ResultFile;
if (File.Exists(resultFile)) File.Delete(resultFile);
logger.Log("Requesting elevated task creation...");
Process.Start(new ProcessStartInfo
{
FileName = "wscript.exe",
Arguments = $"\"{hiddenLauncherManager.GetCreateLauncherPath()}\"",
Verb = "runas",
UseShellExecute = true
});
// Poll for result file in background (up to 60 s)
Task.Run(() =>
{
for (int i = 0; i < 120; i++)
{
Thread.Sleep(500);
if (!File.Exists(resultFile)) continue;
try
{
string content = File.ReadAllText(resultFile).Trim();
int created = 0, failed = 0;
foreach (var part in content.Split('|'))
{
var kv = part.Split('=');
if (kv.Length != 2) continue;
if (kv[0] == "created") int.TryParse(kv[1], out created);
if (kv[0] == "failed") int.TryParse(kv[1], out failed);
}
logger.Log($"Task creation result: created={created} failed={failed}");
if (failed == 0)
notificationManager.ShowInfo($"{created} task(s) created successfully.");
else
notificationManager.ShowError($"{created} task(s) created, {failed} failed. Check Logs\\PS1.log for details.");
api.Notifications.Remove("GameTaskPending");
}
catch (Exception ex) { logger.Log($"ERROR reading result file: {ex.Message}"); }
break;
}
});
}
catch (Exception ex) { logger.Log($"ERROR running create helper: {ex.Message}"); }
}
private void RunDeleteTasks()
{
try
{
logger.Log("Requesting elevated task cleanup...");
Process.Start(new ProcessStartInfo
{
FileName = "wscript.exe",
Arguments = $"\"{hiddenLauncherManager.GetDeleteLauncherPath()}\"",
Verb = "runas",
UseShellExecute = true
});
}
catch (Exception ex) { logger.Log($"ERROR running delete helper: {ex.Message}"); }
}
// =====================================================
// PUBLIC METHODS FOR DIAGNOSTICS VIEW
// =====================================================
public bool HasGameTaskTagPublic(Game game) => HasGameTaskTag(game);
public string ResolveExePathPublic(Game game) => ResolveExePathForGame(game);
public bool HasNoGameAction(Game game)
{
if (game.GameActions == null || !game.GameActions.Any(a =>
a != null && a.Name != ActionName && !string.IsNullOrWhiteSpace(a.Path)))
return true;
return false;
}
public void InvokeFixAllUnknownExecutables() => FixAllUnknownExecutables();
public void InvokeRepairAll() => RepairAll();
public void InvokeRepairGame(Game game)
{
RepairGameTask(game);
notificationManager.ShowPendingNotification();
}
public void InvokeFixExecutablePath(Game game) => FixExecutablePath(game);
public void InvokeDisableGame(Game game) => DisableGameTask(new[] { game });
// =====================================================
// OPEN DIAGNOSTICS
// =====================================================
private void OpenDiagnostics()
{
var vm = new DiagnosticsViewModel(api, this, pathManager, taskManager, ActionName);
var view = new DiagnosticsView { DataContext = vm };
view.ShowDialog();
}
private void OpenDataFolder()
{
try { Process.Start(pluginDataPath); }
catch (Exception ex) { logger.Log($"ERROR opening data folder: {ex.Message}"); }
}
private void OpenTaskScheduler()
{
try
{
Process.Start(new ProcessStartInfo { FileName = "taskschd.msc", UseShellExecute = true });
logger.Log("Task Scheduler opened.");
}
catch (Exception ex) { logger.Log($"ERROR opening Task Scheduler: {ex.Message}"); }
}
// =====================================================
// MENUS
// =====================================================
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Enable GameTask",
Action = a => EnableGameTask(a.Games) };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Disable GameTask",
Action = a => DisableGameTask(a.Games) };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Create Pending Tasks",
Action = a => RunPendingTasks() };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Rebuild Selected",
Action = a => RebuildSelected(a.Games) };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Repair Selected",
Action = a => RepairSelected(a.Games) };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Fix Executable Path",
Action = a => { foreach (var g in a.Games) FixExecutablePath(g); } };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Remove Custom Executable Path",
Action = a => { foreach (var g in a.Games) RemoveCustomPath(g); } };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Open Data Folder",
Action = a => OpenDataFolder() };
yield return new GameMenuItem { MenuSection = "GameTask", Description = "Open Task Scheduler",
Action = a => OpenTaskScheduler() };
}
public override IEnumerable<MainMenuItem> GetMainMenuItems(GetMainMenuItemsArgs args)
{
int taggedCount = api.Database.Games.Count(HasGameTaskTag);
int unknownCount = api.Database.Games.Count(g => HasGameTaskTag(g) &&
string.IsNullOrWhiteSpace(ResolveExePathForGame(g)));
yield return new MainMenuItem
{
MenuSection = "@GameTask",
Description = $"Repair All Tagged Games ({taggedCount})",
Action = _ => RepairAll()
};
yield return new MainMenuItem
{
MenuSection = "@GameTask",
Description = unknownCount > 0
? $"Fix All Unknown Executables ({unknownCount})"
: "Fix All Unknown Executables",
Action = _ => FixAllUnknownExecutables()
};
yield return new MainMenuItem
{
MenuSection = "@GameTask",
Description = "Clean Orphan Tasks",
Action = _ => CleanOrphanTasks()
};
yield return new MainMenuItem
{
MenuSection = "@GameTask",
Description = "Open Data Folder",
Action = _ => OpenDataFolder()
};
yield return new MainMenuItem
{
MenuSection = "@GameTask",
Description = "Diagnostics",
Action = _ => OpenDiagnostics()
};
// Quick-access settings toggles
var s = settingsManager.Current;
yield return new MainMenuItem
{
MenuSection = "@GameTask|Settings",
Description = $"Bring Game to Foreground: {(s.BringWindowToForeground ? "ON" : "OFF")}",
Action = _ =>
{
s.BringWindowToForeground = !s.BringWindowToForeground;
settingsManager.Save();
api.Dialogs.ShowMessage(
$"\"Bring game window to foreground\" is now {(s.BringWindowToForeground ? "ON" : "OFF")}.\n\nRun \"Repair All Tagged Games\" so the launchers are regenerated.",
"GameTask – Settings");
}
};
yield return new MainMenuItem
{
MenuSection = "@GameTask|Settings",
Description = $"Detect Orphan Tasks on Startup: {(s.DetectOrphanTasks ? "ON" : "OFF")}",
Action = _ =>
{
s.DetectOrphanTasks = !s.DetectOrphanTasks;
settingsManager.Save();
api.Dialogs.ShowMessage(
$"\"Detect orphan tasks on startup\" is now {(s.DetectOrphanTasks ? "ON" : "OFF")}.",
"GameTask – Settings");
}
};
yield return new MainMenuItem
{
MenuSection = "@GameTask|Settings",
Description = $"Detect Corrupted Tasks on Startup: {(s.DetectCorruptedTasks ? "ON" : "OFF")}",
Action = _ =>
{
s.DetectCorruptedTasks = !s.DetectCorruptedTasks;
settingsManager.Save();
api.Dialogs.ShowMessage(
$"\"Detect corrupted tasks on startup\" is now {(s.DetectCorruptedTasks ? "ON" : "OFF")}.",
"GameTask – Settings");
}
};
}
}
}