-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameSnapPlugin.cs
More file actions
390 lines (347 loc) · 15.2 KB
/
GameSnapPlugin.cs
File metadata and controls
390 lines (347 loc) · 15.2 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
using Playnite.SDK;
using Playnite.SDK.Events;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls;
namespace GameSnapPlugin
{
public class GameSnapPlugin : GenericPlugin
{
public override Guid Id { get; } = Guid.Parse("a1b2c3d4-e5f6-7890-abcd-ef1234567890");
private GameSnapSettings _settings = new GameSnapSettings();
private GameSnapLogger? _logger;
private DictionaryService? _dict;
private OrganizerService? _organizer;
private WatcherService? _watcher;
private SteamService? _steam;
private LocalProviderService? _localProvider;
private EmulatorService? _emulator;
public GameSnapPlugin(IPlayniteAPI api) : base(api)
{
Properties = new GenericPluginProperties { HasSettings = true };
}
public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
{
try
{
// Load settings synchronously — must complete before GetSettings() is called
_settings = LoadSettings();
InitServices(_settings);
// Start watcher in background to avoid blocking Playnite startup
System.Threading.Tasks.Task.Run(() =>
{
try { _watcher?.Start(); }
catch (Exception ex)
{
_logger?.Error($"Watcher start error: {ex.Message}");
}
});
}
catch (Exception ex)
{
// Never crash Playnite — log and continue with defaults
System.Diagnostics.Debug.WriteLine($"GameSnap OnApplicationStarted error: {ex}");
try
{
_settings = new GameSnapSettings();
InitServices(_settings);
}
catch { /* last resort — give up gracefully */ }
}
}
public override void OnApplicationStopped(OnApplicationStoppedEventArgs args)
{
_watcher?.Stop();
_watcher?.Dispose();
}
public override void OnGameStarted(OnGameStartedEventArgs args)
{
_organizer?.SetCurrentGame(args.Game.Name);
TryAutoCreateFolder(args.Game.Name);
}
public override void OnGameStopped(OnGameStoppedEventArgs args)
{
_organizer?.SetCurrentGame(null);
}
// ──────────────────────────────────────────────
// Auto-create folder
// ──────────────────────────────────────────────
private void TryAutoCreateFolder(string gameName)
{
if (!_settings.AutoCreateFolders) return;
if (string.IsNullOrWhiteSpace(_settings.DestinationBase)) return;
if (!Directory.Exists(_settings.DestinationBase)) return;
var invalid = Path.GetInvalidFileNameChars();
var folderName = string.Concat(gameName.Split(invalid)).Trim();
if (string.IsNullOrWhiteSpace(folderName)) return;
var folderPath = Path.Combine(_settings.DestinationBase, folderName);
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
_logger?.Info($"Auto-created folder: {folderPath}");
}
}
// ──────────────────────────────────────────────
// Settings
// ──────────────────────────────────────────────
public override ISettings GetSettings(bool firstRunSettings)
=> new SettingsViewModel(this);
public override UserControl GetSettingsView(bool firstRunSettings)
=> new Views.SettingsTabView();
public GameSnapSettings LoadSettings()
{
try
{
var saved = LoadPluginSettings<GameSnapSettings>();
var defaults = new GameSnapSettings();
if (saved == null)
{
_settings = defaults;
return _settings;
}
// Merge: preserve saved values, fill new fields with defaults
if (saved.ImageExtensions == null || saved.ImageExtensions.Count == 0)
saved.ImageExtensions = defaults.ImageExtensions;
if (saved.VideoExtensions == null || saved.VideoExtensions.Count == 0)
saved.VideoExtensions = defaults.VideoExtensions;
if (saved.WindowBlacklist == null || saved.WindowBlacklist.Count == 0)
saved.WindowBlacklist = defaults.WindowBlacklist;
if (saved.AdditionalSourceFolders == null)
saved.AdditionalSourceFolders = defaults.AdditionalSourceFolders;
if (saved.EmulatorProfiles == null || saved.EmulatorProfiles.Count == 0)
saved.EmulatorProfiles = defaults.EmulatorProfiles;
else
{
// Merge: ensure all built-in emulators exist, preserve user settings
foreach (var builtIn in EmulatorProfile.BuiltInNames)
{
if (!saved.EmulatorProfiles.Any(p => p.Name == builtIn))
saved.EmulatorProfiles.Insert(
System.Array.IndexOf(EmulatorProfile.BuiltInNames, builtIn),
new EmulatorProfile { Name = builtIn, Enabled = false });
}
}
if (string.IsNullOrEmpty(saved.UnmatchedFolderName))
saved.UnmatchedFolderName = defaults.UnmatchedFolderName;
if (string.IsNullOrEmpty(saved.RenamePattern))
saved.RenamePattern = defaults.RenamePattern;
if (saved.PollingIntervalSeconds <= 0)
saved.PollingIntervalSeconds = defaults.PollingIntervalSeconds;
_settings = saved;
return _settings;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"GameSnap LoadSettings error: {ex.Message}");
_settings = new GameSnapSettings();
return _settings;
}
}
public void SaveSettings(GameSnapSettings settings)
{
try
{
_settings = settings;
SavePluginSettings(settings);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"GameSnap SaveSettings error: {ex.Message}");
PlayniteApi.Dialogs.ShowErrorMessage(
$"GameSnap failed to save settings:\n{ex.Message}", "GameSnap");
}
}
public void ApplySettings(GameSnapSettings settings)
{
if (_watcher != null)
{
_watcher.Stop();
_watcher.Dispose();
_watcher = null;
}
InitServices(settings);
_watcher?.Start();
}
// ──────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────
private void InitServices(GameSnapSettings settings)
{
try
{
var dataPath = GetPluginUserDataPath();
Directory.CreateDirectory(dataPath);
_logger = new GameSnapLogger(dataPath);
_dict = new DictionaryService(dataPath);
_organizer = new OrganizerService(settings, _dict, _logger);
// Steam support
if (settings.EnableSteamSupport)
{
_steam = new SteamService(PlayniteApi, _logger);
_organizer.SteamService = _steam;
}
else
{
_steam = null;
_organizer.SteamService = null;
}
// Notificação toast quando arquivos são movidos
_organizer.OnFileMoved = (title, message) =>
{
if (settings.ShowNotifications)
PlayniteApi.Notifications.Add(
new NotificationMessage(
Guid.NewGuid().ToString(),
message,
NotificationType.Info));
};
_watcher = new WatcherService(settings, _organizer, _logger);
// Emulator support
if (settings.EnableEmulatorSupport)
_emulator = new EmulatorService(PlayniteApi, settings, _logger);
else
_emulator = null;
_organizer.EmulatorService = _emulator;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"GameSnap InitServices error: {ex}");
_logger?.Error($"InitServices failed: {ex.Message}");
}
// Local Provider integration
_localProvider = new LocalProviderService(PlayniteApi, _logger);
if (settings.EnableLocalProviderIntegration && !string.IsNullOrEmpty(settings.DestinationBase))
{
if (_localProvider.IsInstalled())
_localProvider.RegisterDestinationFolder(settings.DestinationBase);
else
_logger.Info("Local Provider: not installed, skipping registration.");
}
}
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
// Screenshot counter
var game = args.Games.FirstOrDefault();
if (game != null && !string.IsNullOrEmpty(_settings.DestinationBase))
{
var count = CountScreenshots(game.Name);
yield return new GameMenuItem
{
Description = count >= 0
? $"Screenshots: {count} file(s)"
: "Screenshots: folder not found",
MenuSection = "GameSnap",
Action = _ =>
{
var folder = FindGameFolder(game.Name);
if (folder != null)
{
var psi = new System.Diagnostics.ProcessStartInfo(folder)
{
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
}
};
}
yield return new GameMenuItem
{
Description = "Organize screenshots now",
MenuSection = "GameSnap",
Action = _ => _organizer?.Organize()
};
}
private int CountScreenshots(string gameName)
{
var folder = FindGameFolder(gameName);
if (folder == null) return -1;
var allExts = new System.Collections.Generic.HashSet<string>(
System.StringComparer.OrdinalIgnoreCase);
foreach (var e in _settings.ImageExtensions) allExts.Add(e);
foreach (var e in _settings.VideoExtensions) allExts.Add(e);
return Directory.GetFiles(folder, "*", SearchOption.AllDirectories)
.Count(f => allExts.Contains(Path.GetExtension(f)));
}
private string? FindGameFolder(string gameName)
{
if (string.IsNullOrEmpty(_settings.DestinationBase) ||
!Directory.Exists(_settings.DestinationBase))
return null;
var normGame = DictionaryService.Normalize(gameName);
return Directory.GetDirectories(_settings.DestinationBase)
.Where(d =>
{
var normFolder = DictionaryService.Normalize(Path.GetFileName(d));
return normFolder.Contains(normGame) || normGame.Contains(normFolder);
})
.OrderByDescending(d => DictionaryService.Normalize(Path.GetFileName(d)).Length)
.FirstOrDefault();
}
public override IEnumerable<MainMenuItem> GetMainMenuItems(GetMainMenuItemsArgs args)
{
yield return new MainMenuItem
{
Description = "Organize screenshots now",
MenuSection = "@GameSnap",
Action = _ => _organizer?.Organize()
};
yield return new MainMenuItem
{
Description = "Open log",
MenuSection = "@GameSnap",
Action = _ =>
{
var path = Path.Combine(GetPluginUserDataPath(), "gamesnap.log");
if (File.Exists(path))
{
var psi = new System.Diagnostics.ProcessStartInfo("notepad.exe", path)
{
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
}
};
yield return new MainMenuItem
{
Description = "Open dictionary",
MenuSection = "@GameSnap",
Action = _ =>
{
var path = Path.Combine(GetPluginUserDataPath(), "dictionary.txt");
if (!File.Exists(path))
File.WriteAllText(path, "# Format:\n# [Game Name]\n# alias1\n");
var psi = new System.Diagnostics.ProcessStartInfo("notepad.exe", path)
{
UseShellExecute = true
};
System.Diagnostics.Process.Start(psi);
}
};
yield return new MainMenuItem
{
Description = "Review unmatched screenshots",
MenuSection = "@GameSnap",
Action = _ => OpenReviewWindow()
};
}
private void OpenReviewWindow()
{
if (_organizer == null || _dict == null || _logger == null)
{
PlayniteApi.Dialogs.ShowMessage("GameSnap is not fully initialized.", "GameSnap");
return;
}
var vm = new ReviewViewModel(
PlayniteApi, _settings, _dict, _organizer, _logger);
var window = new Views.ReviewWindow(vm);
vm.SetCloseAction(() => window.Close());
window.ShowDialog();
}
}
}