-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPaintPower_Engine.cs
More file actions
687 lines (543 loc) · 18.8 KB
/
PaintPower_Engine.cs
File metadata and controls
687 lines (543 loc) · 18.8 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
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
using PaintPower.Dialogs;
using PaintPower.Editors;
using PaintPower.FileExplorer;
using PaintPower.Logging;
using PaintPower.Networking;
using PaintPower.ProjectSystem;
using PaintPower.SpriteEditor;
using PaintPower.Time;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using PaintPower.Accessibility.Translation;
using System.Reflection;
using PaintPower.VMPanel;
using PaintPower.Templates.FileTemplates;
using PaintPower.Tools.SoundEffects;
using Avalonia.Input;
using PaintPower.Tools.Keyboard;
namespace PaintPower;
public class PaintPower_Engine
{
public static readonly string versionNumber = "1.0.1.2";
public static readonly string buildTime = new Date().getBuildTimestamp();
public static readonly string devStatus = "Pre-Alpha";
public static string MajorVersion = $"{Translator.Map(devStatus)} {versionNumber}";
public static string version = $"{Translator.Map("Version")}: {MajorVersion} {Translator.Map("build")} {buildTime}";
public Vm.Vm vm;
public static bool PlayerOnly = false;
public void translateVersion()
{
MajorVersion = $"{Translator.Map("Pre-Alpha")} {versionNumber}";
version = $"{Translator.Map("Version")}: {MajorVersion} {Translator.Map("build")} {buildTime}";
}
private Editor _editorManager;
private EditorBase _editor;
public PaintProject _project;
public Server server;
public VmPanel vmAreaPart;
public EditorPart editorGui;
public bool isNewProject = true;
private SpriteEditorView _spriteEditorView;
public bool saveNeeded = false;
#pragma warning disable
public static PaintPower_Engine App { get; private set; }
public static MainWindow window;
public PaintPower_Engine()
{
_project = new PaintProject();
_editorManager = new Editor(_project.Workspace);
server = new Server();
Log.QuickLog(version);
// After, make a static reference.
App = this;
}
public void setupTranslation()
{
// Set-up translation
Translator.load(null);
var langs = Translator.GetAvailableLanguages();
foreach (var pair in langs)
{
string fullName = pair.Key;
string code = pair.Value;
var item = new MenuItem { Header = fullName };
item.Click += (_, __) =>
{
Translator.load(code);
};
editorGui.LanguageDropdown.Items.Add(item);
}
}
public void attachWindow(MainWindow w)
{
window = w;
}
public void attachEditorPart(EditorPart p)
{
editorGui = p;
}
public string SetProjectStatus(string status)
{
editorGui.ProjectStatus.Text = status;
FixUserStatus();
return status;
}
public string NetworkStatus = "Not connected";
public string UserStatus = "not logged in.";
public string SetNetworkStatus(string status)
{
NetworkStatus = status;
FixUserStatus();
return status;
}
public string SetUserStatus(string status)
{
UserStatus = status;
FixUserStatus();
return status;
}
public async void FixUserStatus()
{
editorGui.StatusBarText.Text = $"{NetworkStatus} | {((await server.IsLoggedIn()) ? $"Logged in as {server.Username}" : UserStatus)} | {editorGui.ProjectStatus.Text}";
editorGui.InvalidateVisual();
MainWindow.window.InvalidateVisual();
}
private void OnSpriteSelected(PaintSprite sprite)
{
if (_project == null)
{
editorGui.SpriteManager.SpriteList.ItemsSource = null;
MainWindow.window.InvalidateVisual();
return;
}
SoundEffects.Click.Play();
// Create the sprite editor panel
_spriteEditorView = new SpriteEditorView(sprite, _project.Workspace);
// Replace the center panel with the sprite editor
editorGui.CenterHost.Content = _spriteEditorView;
SetProjectStatus($"{Translator.Translate("Editing Sprite:")} {sprite.Name}");
}
public void CloseProject()
{
MainWindow.window.Title = "The PaintPower Engine";
SetProjectStatus(Translator.Map("Select or create a project to get started."));
saveNeeded = false;
Translator.load(null); // reset translation to default (in case project has different language)
// Reset current project/editor
CloseCurrentEditor();
// Clear existing sprites to avoid duplicates when loading.
_project.Sprites.Clear();
editorGui.SpriteManager.SpriteList.ItemsSource = null;
CloseEditor();
_project = null;
_editorManager = null;
_editor = null;
server = null;
MainWindow.window.InvalidateVisual();
}
public async Task OpenProjectFile(string filePath = "")
{
SoundEffects.Click.Play();
if (string.IsNullOrWhiteSpace(filePath))
{
var result = await window.StorageProvider.OpenFilePickerAsync(
new FilePickerOpenOptions
{
Title = Translator.Map("Open PaintPower Project"),
AllowMultiple = false,
FileTypeFilter = new[]
{
new FilePickerFileType(Translator.Map("PaintPower Project"))
{
Patterns = new[] { "*.xPaint", "*.zip" }
}
}
});
if (result.Count == 0)
return; // user cancelled
filePath = result[0].Path.LocalPath;
}
Translator.load(null); // reset translation to default (in case project has different language)
// Reset current project/editor
CloseCurrentEditor();
// Clear existing sprites to avoid duplicates when loading.
_project.Sprites.Clear();
MainWindow.window.InvalidateVisual();
// Load project
await AnimateStatus(
Translator.Map("Loading Project"),
() => Task.Run(() => _project.Load(filePath))
);
_project.ProjectPath = filePath;
RefreshSession(false);
MainWindow.window.InvalidateVisual();
// Update window title
window.Title = $"{Translator.Map("PaintPower")} - {_project.Metadata.name}";
}
public async void newProject()
{
Translator.load(null); // reset translation to default (in case current project has different language)
if (saveNeeded)
{
var dialog = new SaveBeforeContinueDialog();
var result = await dialog.ShowAsync(MainWindow.window);
switch (result)
{
case "save":
await Save();
break;
case "saveas":
SaveAs();
break;
case "dontsave":
break; // continue without saving
case null:
return; // cancel new project
}
}
// Reset everything
_project = new PaintProject();
_project.CreateNew();
_editorManager = new Editor(_project.Workspace);
server = new Server();
MainWindow.window.InvalidateVisual();
Start();
}
public virtual async void RefreshSession(bool makeNew = true)
{
CloseEditor();
_project = makeNew ? new PaintProject() : _project;
_editorManager = new Editor(_project.Workspace);
_editor = null;
window.Title = $"{Translator.Map("PaintPower")} - {_project.Metadata.name}";
editorGui.SpriteManager.Initialize(_project);
editorGui.SpriteManager.SpriteSelected -= OnSpriteSelected;
editorGui.SpriteManager.SpriteSelected += OnSpriteSelected;
MainWindow.window.InvalidateVisual();
// Set up translation
setupTranslation();
}
public virtual async void Start()
{
await Task.Yield();
CloseEditor();
_project = new PaintProject();
_editorManager = new Editor(_project.Workspace);
_editor = null;
_project.CreateNew();
window.Title = $"{Translator.Map("PaintPower")} - {_project.Metadata.name}";
SetProjectStatus(Translator.Translate("Not edited yet."));
editorGui.SpriteManager.Initialize(_project);
editorGui.SpriteManager.SpriteSelected += OnSpriteSelected;
MainWindow.window.InvalidateVisual();
// Set up translation
setupTranslation();
//vm = new Vm.Vm();
}
/*public void OpenEditor(EditorBase editor)
{
_editor = editor;
CenterHost.Content = editor;
}*/
public void OpenFile(string path)
{
Log.Info("Opening file: " + path);
Log.Info("Closing current editor.");
CloseCurrentEditor(); // Close current editor if open...
Log.Info("Getting new editor for file type...");
var editor = _editorManager.GetEditorFromFileType(path);
_editor = editor;
if (_spriteEditorView != null)
_spriteEditorView.OpenEditor(editor, path);
}
public void CloseCurrentEditor()
{
if (_editor != null)
{
Log.Info("Closing current editor.");
_editor.Close();
_editor = null;
}
else
{
Log.Info("No editor to close.");
}
}
public void CloseEditor()
{
Log.Info("Closing current editor.");
_editor?.Close();
editorGui.CenterHost.Content = null;
_editor = null;
}
public async void AskToLinkProject(PaintProject project)
{
var dialog = new LinkBeforeUploadDialog();
var result = await dialog.ShowDialog<string>(MainWindow.window);
if (result == "cancel")
return;
if (result == "new")
{
string? id = await server.CreateNewServerProject(project.Metadata.name);
if (id != null)
{
project.Metadata.serverId = id;
project.SaveMetadata();
}
return;
}
if (result == "existing")
{
var list = await server.ListUserProjects();
var selectDialog = new SelectServerProjectDialog(list);
var chosenId = await selectDialog.ShowDialog<string>(MainWindow.window);
if (!string.IsNullOrEmpty(chosenId))
{
project.Metadata.serverId = chosenId;
project.SaveMetadata();
}
}
}
public async Task AnimateStatus(string baseMessage, Func<Task> action)
{
string[] frames = new[]
{
baseMessage,
baseMessage + ".",
baseMessage + "..",
baseMessage + "..."
};
int index = 0;
bool isRunning = true;
// Start animation loop
var animationLoop = Task.Run(async () =>
{
while (isRunning)
{
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
SetProjectStatus(frames[index]);
});
index = (index + 1) % frames.Length;
await Task.Delay(300);
}
});
// Run the actual work on a background thread
await action();
// Stop animation
isRunning = false;
// Wait for animation loop to finish
await animationLoop;
// Final status
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
{
SetProjectStatus(Translator.Map("Done!"));
});
}
public bool _isSavingAnimationRunning = false;
public bool _isUploadAnimationRunning = false;
public async Task RunSavingAnimation()
{
_isSavingAnimationRunning = true;
string[] frames = new[]
{
"Saving Project",
"Saving Project.",
"Saving Project..",
"Saving Project..."
};
int index = 0;
while (_isSavingAnimationRunning)
{
SetProjectStatus(Translator.Map(frames[index]));
index = (index + 1) % frames.Length;
await Task.Delay(300); // smooth animation
}
}
// Save function. Don't even care about what it returns, but C#
// Requires it to be a Task in order to await it. C# core.
async public Task Save()
{
if (!saveNeeded && !isNewProject) return;
try
{
var dialog = new DoSaveWindowDialog();
var result = await dialog.ShowAsync(window);
if (result == "saveas")
{
SaveAs();
return;
}
if (result != "save")
{
Log.QuickLog($"Not saving. {result}");
return;
}
// If no path yet -> ask user where to save
if (string.IsNullOrWhiteSpace(_project.ProjectPath) || isNewProject)
{
isNewProject = true; // Keep isNewProject checks
var res = await _project.SaveNewProject(MainWindow.window);
if (string.IsNullOrWhiteSpace(res.Path))
return; // user cancelled
_project.ProjectPath = res.Path;
isNewProject = false;
}
Log.QuickLog("Saving Project...");
// Start animation (non-blocking)
var animationTask = RunSavingAnimation();
// Run save off UI thread
await ProjectSaver.Save(_project, _editor);
// Stop animation
_isSavingAnimationRunning = false;
await animationTask; // wait for animation loop to exit
// Final status
Log.QuickLog(SetProjectStatus(Translator.Map("Project Saved!")));
}
catch (Exception ex)
{
Log.QuickLog($"Error while saving project! {ex}");
}
}
async public void SaveAs()
{
var savePicker = await window.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = $"Save {_project.Metadata.name} As",
DefaultExtension = "xPaint",
SuggestedFileName = $"{_project.Metadata.name}.xPaint",
ShowOverwritePrompt = true
});
if (savePicker == null)
return;
string newPath = savePicker.Path.LocalPath;
// Update project path
_project.ProjectPath = newPath;
try
{
// Start animation
var animationTask = RunSavingAnimation();
// Run save off UI thread
await ProjectSaver.Save(_project, _editor);
// Stop animation
_isSavingAnimationRunning = false;
await animationTask;
// Update metadata + UI
_project.Metadata.name = Path.GetFileNameWithoutExtension(newPath);
window.Title = $"PaintPower - {_project.Metadata.name}";
SetProjectStatus("Project Saved!");
Log.QuickLog($"Project saved as {newPath}");
}
catch (Exception ex)
{
Log.QuickLog($"SaveAs failed: {ex}");
}
}
public async void SaveToServer()
{
var project = _project;
var server = App.server;
// 1. Must be signed in
if (!await server.IsLoggedIn())
{
new PopupWindowDialog("Upload", "You must sign in before uploading.", "").ShowDialog(MainWindow.window);
return;
}
// 2. Project not linked → ask to link
if (!project.Metadata.IsLinked)
{
var linkDialog = new LinkBeforeUploadDialog();
var linkChoice = await linkDialog.ShowDialog<string>(MainWindow.window);
if (linkChoice == "cancel")
return;
if (linkChoice == "new")
{
string? id = await server.CreateNewServerProject(project.Metadata.name);
if (id != null)
{
project.Metadata.serverId = id;
project.SaveMetadata();
}
else
{
new PopupWindowDialog("Upload", "Failed to create server project.", "").ShowDialog(MainWindow.window);
return;
}
}
else if (linkChoice == "existing")
{
var list = await server.ListUserProjects();
var selectDialog = new SelectServerProjectDialog(list);
var chosenId = await selectDialog.ShowDialog<string>(MainWindow.window);
if (string.IsNullOrEmpty(chosenId))
return;
project.Metadata.serverId = chosenId;
project.SaveMetadata();
}
}
// 3. Project is linked → ask overwrite/unlink
if (project.Metadata.IsLinked)
{
var uploadDialog = new UploadOptionsDialog(project.Metadata.serverId!);
var choice = await uploadDialog.ShowDialog<string>(MainWindow.window);
if (choice == "cancel")
return;
if (choice == "unlink")
{
project.Metadata.serverId = null;
project.SaveMetadata();
return;
}
if (choice == "overwrite")
{
await server.UploadProject(project);
return;
}
}
}
public async Task login(string username, string password)
{
bool ok = await Net.Login(username, password);
if (ok)
{
SetUserStatus($"Logged in as {username}");
}
else
{
SetUserStatus("Login failed");
}
}
public async Task DownloadProjectFromServer()
{
var savePicker = await window.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
{
Title = $"Save {_project.Metadata.name} As",
DefaultExtension = "xPaint",
SuggestedFileName = $"{_project.Metadata.name}.xPaint",
ShowOverwritePrompt = true
});
if (savePicker == null)
return;
string path = savePicker.Path.LocalPath;
var list = await server.ListUserProjects();
var selectDialog = new SelectServerProjectDialog(list);
var chosenId = await selectDialog.ShowDialog<string>(MainWindow.window);
if (string.IsNullOrEmpty(chosenId))
return;
server.DownloadProject(path, Convert.ToInt32(chosenId));
}
public void HandleKeyDown(KeyEventArgs e)
{
KeyPress p = new KeyPress(e);
if (p.isPressed("s") && p.isPressed("ctrl"))
{
Save();
}
}
}