-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.axaml.cs
More file actions
2510 lines (2093 loc) · 94.1 KB
/
MainWindow.axaml.cs
File metadata and controls
2510 lines (2093 loc) · 94.1 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
using Avalonia;
using Avalonia.Animation.Easings;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Media.Fonts;
using Avalonia.OpenGL;
using Avalonia.Platform;
using Avalonia.Platform.Storage;
using Avalonia.Skia;
using Avalonia.Threading;
using Avalonia.VisualTree;
using CommunityToolkit.Mvvm.ComponentModel;
using CoreSpectrum.Debug;
using CoreSpectrum.Enums;
using CoreSpectrum.SupportClasses;
using HarfBuzzSharp;
using Metsys.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SkiaSharp;
using Svg;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Resources;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.Arm;
using System.Text;
using System.Threading.Tasks;
using ZXBasicStudio.BuildSystem;
using ZXBasicStudio.Classes;
using ZXBasicStudio.Common;
using ZXBasicStudio.Common.ZXSinclairBasic;
using ZXBasicStudio.Controls;
using ZXBasicStudio.Controls.DockSystem;
using ZXBasicStudio.Dialogs;
using ZXBasicStudio.DocumentEditors;
using ZXBasicStudio.DocumentEditors.ZXGraphics;
using ZXBasicStudio.DocumentEditors.ZXTextEditor.Controls;
using ZXBasicStudio.DocumentModel.Classes;
using ZXBasicStudio.DocumentModel.Interfaces;
using ZXBasicStudio.Emulator.Classes;
using ZXBasicStudio.Emulator.Controls;
using ZXBasicStudio.Extensions;
using I = ZXBasicStudio.Common.ZXSinclairBasic.ZXSinclairBasicInstruction;
namespace ZXBasicStudio
{
public partial class MainWindow : ZXWindowBase //, IObserver<RawInputEventArgs>
{
const string repoUrl = "https://github.com/gusmanb/ZXBasicStudio";
const string zxbHelpUrl = "https://zxbasic.readthedocs.io/en/docs/";
#region Shortcut handling
internal static Guid KeybSourceId = Guid.Parse("72af48c7-4d62-4bef-8676-63c10d99de20");
internal static ZXKeybCommand[] KeybCommands =
{
new ZXKeybCommand { CommandId = Guid.Parse("62c23849-7312-41ac-8788-9f6d851cc3b9"), CommandName = "Build and run", Key = Key.F5, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("d9222ec4-5d7a-4b04-b9e3-e29d6d8bca78"), CommandName = "Build and debug", Key = Key.F6, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("57aff55a-f4a1-4a57-a532-a38117e1a532"), CommandName = "Pause emulation", Key = Key.F7, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("d4dc5ad4-d5f2-431c-a550-541b56d52fbb"), CommandName = "Resume emulation", Key = Key.F8, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("df3bacb0-baab-40b9-a287-653fa339fe1d"), CommandName = "Assembler step", Key = Key.F9, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("bd77367e-f17b-4550-9dd1-26013f7d250a"), CommandName = "Basic step", Key = Key.F10, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("cf0216e0-3180-4429-8e09-664e6262dbd9"), CommandName = "Stop emulation", Key = Key.F11, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("703808fa-abec-4c65-940b-16544c2bd93d"), CommandName = "Turbo mode", Key = Key.F12, Modifiers = KeyModifiers.None },
new ZXKeybCommand { CommandId = Guid.Parse("077a0fb9-34a4-461b-9f44-8f3472f9e872"), CommandName = "Swap fullscreen mode", Key = Key.Enter, Modifiers = KeyModifiers.Alt },
new ZXKeybCommand { CommandId = Guid.Parse("573741e3-5e26-4195-aa89-c49066a28762"), CommandName = "Code View", Key = Key.F8, Modifiers = KeyModifiers.Control | KeyModifiers.Shift },
new ZXKeybCommand { CommandId = Guid.Parse("0aa2887d-4fb7-4234-81c1-c07efbf02eb3"), CommandName = "Project View", Key = Key.F9, Modifiers = KeyModifiers.Control | KeyModifiers.Shift },
new ZXKeybCommand { CommandId = Guid.Parse("7b50369f-3f48-4653-99c1-26e566691e3c"), CommandName = "Debug View", Key = Key.F10, Modifiers = KeyModifiers.Control | KeyModifiers.Shift },
new ZXKeybCommand { CommandId = Guid.Parse("86b341a1-8d07-4af2-b4b0-ca953cd3dbc0"), CommandName = "Play View", Key = Key.F11, Modifiers = KeyModifiers.Control | KeyModifiers.Shift },
new ZXKeybCommand { CommandId = Guid.Parse("424f7395-c29d-44f9-8f9e-43b8891ec261"), CommandName = "All tools View", Key = Key.F12, Modifiers = KeyModifiers.Control | KeyModifiers.Shift },
new ZXKeybCommand { CommandId = Guid.Parse("21bc5c34-df5e-449e-a826-88e1f42d7810"), CommandName = "Exit application", Key = Key.None, Modifiers = KeyModifiers.None }
};
Dictionary<Guid, Action> _shortcuts = new Dictionary<Guid, Action>();
#endregion
List<ZXDocumentEditorBase> openDocuments = new List<ZXDocumentEditorBase>();
ObservableCollection<TabItem> editTabs = new ObservableCollection<TabItem>();
ZXProgram? loadedProgram;
List<Breakpoint> basicBreakpoints = new List<Breakpoint>();
List<Breakpoint> disassemblyBreakpoints = new List<Breakpoint>();
List<Breakpoint> romBreakpoints = new List<Breakpoint>();
List<Breakpoint> userBreakpoints = new List<Breakpoint>();
List<ZXCodeLine> romLines = new List<ZXCodeLine>();
Breakpoint? currentBp;
public ObservableCollection<TabItem> EditItems { get; set; }
public FileInfoProvider FileInfo { get; set; } = new FileInfoProvider();
public EmulatorInfoProvider EmulatorInfo { get; set; } = new EmulatorInfoProvider();
protected override bool PersistBounds { get { return true; } }
private object? rootContent = null;
private bool skipLayout;
ZXTapePlayer _player;
ZXDockingControl _playerDock;
ZXDocumentEditorBase? _activeEditor = null;
bool skipCloseCheck = false;
public MainWindow()
{
InitializeComponent();
GlobalKeybHandler.KeyUp += GlobalKeyUp;
EditItems = editTabs;
DataContext = this;
#region Attach explorer events
peExplorer.OpenFileRequested += OpenFile;
peExplorer.NewFileRequested += CreateFile;
peExplorer.NewFolderRequested += CreateFolder;
peExplorer.RenameRequested += Rename;
peExplorer.DeleteRequested += Delete;
peExplorer.SelectedPathChanged += PeExplorer_SelectedPathChanged;
#endregion
#region Attach menu events
mnuOpenProject.Click += OpenProject;
mnuOpenLastProject.Click += OpenLastProject;
mnuCreateProject.Click += CreateProject;
mnuCreateFolder.Click += CreateFolder;
mnuCreateFile.Click += CreateFile;
mnuSaveFile.Click += SaveFile;
mnuCloseProject.Click += CloseProject;
mnuCloseFile.Click += CloseFile;
mnuExitApplication.Click += ExitApplication;
mnuConfigureProject.Click += ConfigureProject;
mnuBuild.Click += Build;
mnuBuildRun.Click += BuildAndRun;
mnuBuildDebug.Click += BuildAndDebug;
mnuExport.Click += Export;
mnuPause.Click += PauseEmulator;
mnuContinue.Click += ResumeEmulator;
mnuBasicStep.Click += BasicStepEmulator;
mnuAssemblerStep.Click += AssemblerStepEmulator;
mnuGlobalOptions.Click += ConfigureGlobalSettings;
mnuDumpMem.Click += DumpMemory;
mnuDumpRegs.Click += DumpRegisters;
mnuNext_PaletteBuilder.Click += Next_PaletteBuilder;
mnuTurbo.Click += TurboModeEmulator;
mnuRestoreLayout.Click += RestoreLayout;
mnuCodeView.Click += FullLayout;
mnuProjectView.Click += ExplorerLayout;
mnuAllToolsView.Click += ToolsLayout;
mnuDebugView.Click += DebugLayout;
mnuPlayView.Click += PlayLayout;
mnuDocumentation_Book.Click += MnuDocumentation_Book_Click;
mnuDocumentation_Boriel.Click += MnuDocumentation_Boriel_Click;
mnuDocumentation_Libro.Click += MnuDocumentation_Libro_Click;
mnuDownload_Boriel.Click += MnuDownload_Boriel_Click;
mnuDownload_ZXBS.Click += MnuDownload_ZXBS_Click;
mnuGitHub_Boriel.Click += MnuGitHub_Boriel_Click;
mnuGitHub_ZXBS.Click += MnuGitHub_ZXBS_Click;
mnuSocial_Forum.Click += MnuSocial_Forum_Click;
mnuSocial_TelegramEN.Click += MnuSocial_TelegramEN_Click;
mnuSocial_TelegramES.Click += MnuSocial_TelegramES_Click;
mnuSocial_Discord.Click += MnuSocial_Discord_Click;
mnuReportBug.Click += MnuReportBug_Click;
mnuAbout.Click += OpenAbout;
#endregion
#region Attach toolbar events
btnOpenProject.Click += OpenProject;
btnNewFolder.Click += CreateFolder;
btnNewFile.Click += CreateFile;
btnSave.Click += SaveFile;
btnSaveAll.Click += SaveAllFiles;
btnRun.Click += BuildAndRun;
btnDebug.Click += BuildAndDebug;
btnPause.Click += PauseEmulator;
btnResume.Click += ResumeEmulator;
btnNextInstruction.Click += AssemblerStepEmulator;
btnNextLine.Click += BasicStepEmulator;
btnStop.Click += StopEmulator;
btnFontIncrease.Click += BtnFontIncrease_Click;
btnFontDecrease.Click += BtnFontDecrease_Click;
btnCollapse.Click += BtnCollapse_Click;
btnExpand.Click += BtnExpand_Click;
btnComment.Click += BtnComment_Click;
btnUncomment.Click += BtnUncomment_Click;
btnRemoveBreakpoints.Click += BtnRemoveBreakpoints_Click;
btnTurbo.Click += TurboModeEmulator;
btnBorderless.Click += Borderless;
btnDirectScreen.Click += DirectScreen;
btnTape.Click += ShowTapePlayer;
btnPowerOn.Click += PowerOn;
btnMapKeyboard.Click += BtnMapKeyboard_Click;
#endregion
#region Attach Breakpoint manager events
BreakpointManager.BreakPointAdded += BreakpointManager_BreakPointAdded;
BreakpointManager.BreakPointRemoved += BreakpointManager_BreakPointRemoved;
#endregion
#region Attach emulator events
emu.Breakpoint += Emu_Breakpoint;
emu.ProgramReady += Emu_ProgramReady;
emu.ExceptionTrapped += Emu_ExceptionTrapped;
#endregion
#region Attach editors view events
tcEditors.SelectionChanged += TcEditors_SelectionChanged;
#endregion
#region Debugging tools initialization
regView.Registers = emu.Registers;
memView.Initialize(emu.Memory);
CreateRomBreakpoints();
#if DEBUG
this.AttachDevTools();
#endif
#endregion
#region Player intialization
_player = new ZXTapePlayer();
_player.Datacorder = emu.Datacorder;
_playerDock = new ZXDockingControl();
_playerDock.DockedControl = _player;
_playerDock.CanClose = true;
_playerDock.Title = "Tape player";
_playerDock.DesiredFloatingSize = new Size(230, 270);
_playerDock.Name = "TapePlayerDock";
#endregion
#region Shortcut initialization
_shortcuts = new Dictionary<Guid, Action>()
{
{ Guid.Parse("62c23849-7312-41ac-8788-9f6d851cc3b9"), () => {
if (EmulatorInfo.CanRun)
BuildAndRun(this, new RoutedEventArgs());} },
{ Guid.Parse("d9222ec4-5d7a-4b04-b9e3-e29d6d8bca78"), () => {
if (EmulatorInfo.CanDebug)
BuildAndDebug(this, new RoutedEventArgs()); } },
{ Guid.Parse("57aff55a-f4a1-4a57-a532-a38117e1a532"), () => {
if (EmulatorInfo.CanPause)
PauseEmulator(this, new RoutedEventArgs());} },
{ Guid.Parse("d4dc5ad4-d5f2-431c-a550-541b56d52fbb"), () => {
if (EmulatorInfo.CanResume)
ResumeEmulator(this, new RoutedEventArgs());} },
{ Guid.Parse("df3bacb0-baab-40b9-a287-653fa339fe1d"), () => {
if (EmulatorInfo.CanStep)
AssemblerStepEmulator(this, new RoutedEventArgs()); } },
{ Guid.Parse("bd77367e-f17b-4550-9dd1-26013f7d250a"), () => {
if (EmulatorInfo.CanStep)
BasicStepEmulator(this, new RoutedEventArgs());} },
{ Guid.Parse("cf0216e0-3180-4429-8e09-664e6262dbd9"), () => {
if (EmulatorInfo.IsRunning)
StopEmulator(this, new RoutedEventArgs());} },
{ Guid.Parse("703808fa-abec-4c65-940b-16544c2bd93d"), () => {
if (EmulatorInfo.IsRunning)
TurboModeEmulator(this, new RoutedEventArgs());} },
{ Guid.Parse("077a0fb9-34a4-461b-9f44-8f3472f9e872"), () => {
if (EmulatorInfo.IsRunning)
SwapFullScreen();} },
{ Guid.Parse("573741e3-5e26-4195-aa89-c49066a28762"), () => {
FullLayout(this, new RoutedEventArgs()); }},
{ Guid.Parse("0aa2887d-4fb7-4234-81c1-c07efbf02eb3"), () => {
ExplorerLayout(this, new RoutedEventArgs()); }},
{ Guid.Parse("7b50369f-3f48-4653-99c1-26e566691e3c"), () => {
DebugLayout(this, new RoutedEventArgs()); }},
{ Guid.Parse("86b341a1-8d07-4af2-b4b0-ca953cd3dbc0"), () => {
PlayLayout(this, new RoutedEventArgs()); }},
{ Guid.Parse("424f7395-c29d-44f9-8f9e-43b8891ec261"), () => {
ToolsLayout(this, new RoutedEventArgs()); }},
{ Guid.Parse("21bc5c34-df5e-449e-a826-88e1f42d7810"), () => {
ExitApplication(this, new RoutedEventArgs());
}},
};
#endregion
#region Default emulator settings
btnBorderless.IsChecked = emu.Borderless = ZXOptions.Current.Borderless;
emu.AntiAlias = ZXOptions.Current.AntiAlias;
#endregion
//Layout restoration
ZXLayoutPersister.RestoreLayout(grdMain, dockLeft, dockRight, dockBottom, new[] { _playerDock });
}
private void OpenAbout(object? sender, RoutedEventArgs e)
{
ZXAboutDialog zXAboutDialog = new ZXAboutDialog();
zXAboutDialog.ShowDialog(this);
}
private void OpenZXHelp(object? sender, RoutedEventArgs e)
{
OpenUrl(zxbHelpUrl);
}
private void OpenRepository(object? sender, RoutedEventArgs e)
{
OpenUrl(repoUrl);
}
#region File manipulation
private void PeExplorer_SelectedPathChanged(object? sender, System.EventArgs e)
{
if (peExplorer.SelectedPath != null)
FileInfo.FileSystemObjectSelected = true;
}
private async void Delete(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var path = peExplorer.SelectedPath;
if (path == null)
return;
bool isFile = File.Exists(path);
bool confirm = false;
if (isFile)
confirm = await this.ShowConfirm("Delete file", $"Are you sure you want to delete the file \"{Path.GetFileName(path)}\"?");
else
confirm = await this.ShowConfirm("Delete folder", $"Are you sure you want to delete the folder \"{Path.GetFileName(path)}\" and all its content?");
if (!confirm)
return;
try
{
if (isFile)
File.Delete(path);
else
Directory.Delete(path, true);
}
catch (Exception ex)
{
await this.ShowError("Delete error", $"Unexpected error trying to delete the {(isFile ? "file" : "directory")}: {ex.Message} - {ex.StackTrace}");
}
}
private async void Rename(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var path = peExplorer.SelectedPath;
if (path == null)
return;
bool isFile = File.Exists(path);
//TODO: Check better, it might match a folder wich has a partial name of other folder
if (!isFile && openDocuments.Any(e => e.DocumentPath.ToLower().StartsWith(path.ToLower())))
{
await this.ShowError("Open documents", "There are open documents in the selected folder, close any document in the folder before renaming it.");
return;
}
string? newName = null;
if (isFile)
newName = await this.ShowInput("Rename file", "Select the new name for the file", "File name", Path.GetFileName(path));
else
newName = await this.ShowInput("Rename folder", "Select the new name for the folder", "Folder name", Path.GetFileName(path));
if (newName == null)
return;
try
{
if (isFile)
{
var dir = Path.GetDirectoryName(path);
string newPath = Path.Combine(dir ?? "", newName);
var childFiles = peExplorer.GetChildFiles(path);
//Compose a list of old and new files, and its related document editors
List<(string oldFile, string newFile, ZXDocumentEditorBase? editor)> files = new List<(string oldFile, string newFile, ZXDocumentEditorBase? editor)>();
files.Add((path, newPath, openDocuments.FirstOrDefault(d => d.DocumentPath == path)));
foreach (var childPath in childFiles)
{
string ext = Path.GetExtension(childPath);
string cNewPath = newPath + ext;
files.Add((childPath, cNewPath, openDocuments.FirstOrDefault(d => d.DocumentPath == childPath)));
}
//First check if the file or any of its childs are open and modified
if (files.Any(f => f.editor?.Modified ?? false))
{
await this.ShowError("Rename file", "The file or one of its childs you are trying to rename is open and modified. Save or discard the changes before renaming.");
return;
}
//Create a list of renamed files in case of the need to undo
List<(string oldFile, string newFile, ZXDocumentEditorBase? editor)> renamed = new List<(string oldFile, string newFile, ZXDocumentEditorBase? editor)>();
bool undo = false;
//Move the files
foreach (var file in files)
{
try
{
File.Move(file.oldFile, file.newFile);
renamed.Add(file);
//Notify the editor about the file movement
if (file.editor != null)
{
if (!file.editor.RenameDocument(file.newFile, outLog.Writer))
{
//Error in the editor!
await this.ShowError("Error", "Error renaming the file, check the output log for more information.");
undo = true;
break;
}
//Update editor tab with new file name
var tab = editTabs.First(t => t.Content == file.editor);
tab.Tag = Path.GetFileName(file.newFile);
}
}
catch
{
undo = true;
break;
}
}
//Something went wrong, try to undo
if (undo)
{
foreach (var file in renamed)
{
try
{
File.Move(file.newFile, file.oldFile);
if (file.editor != null)
{
file.editor.RenameDocument(file.oldFile, outLog.Writer);
//Update editor tab with new file name
var tab = editTabs.First(t => t.Content == file.editor);
tab.Tag = Path.GetFileName(file.newFile);
}
}
catch
{
//Total failure, we can't do more...
await this.ShowError("Error", "Error reverting file changes, manual intervention required.");
break;
}
}
}
}
}
catch (Exception ex)
{
await this.ShowError("Rename error", $"Unexpected error trying to rename the {(isFile ? "file" : "directory")}: {ex.Message} - {ex.StackTrace}");
}
}
public async void CloseFile(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
TabItem? tab;
if (sender is Button)
{
var button = sender as Button;
if (button == null)
return;
tab = button.FindAncestorOfType<TabItem>();
if (tab == null)
return;
}
else
{
tab = editTabs.Where(t => t.IsSelected).FirstOrDefault();
if (tab == null)
return;
}
if (tab.Content is ZXDocumentEditorBase)
{
var document = tab.Content as ZXDocumentEditorBase;
if (document == null)
return;
if (document.Modified)
{
var res = await this.ShowConfirm("Modified", "This document has been modified, if you close it now you will lose the changes, are you sure you want to close it?");
if (!res)
return;
document.CloseDocument(outLog.Writer, true);
}
else
{
if (!document.CloseDocument(outLog.Writer, false))
{
var res = await this.ShowConfirm("Close error", "There was an error closing the document, do you want to force it? (more info on the output log).");
if (!res)
return;
document.CloseDocument(outLog.Writer, true);
}
}
openDocuments.Remove(document);
document.Dispose();
}
editTabs.Remove(tab);
if (openDocuments.Count == 0)
FileInfo.FileLoaded = false;
}
private async void CloseProject(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (openDocuments.Any(e => e.Modified))
{
var resConfirm = await this.ShowConfirm("Modified documents", "Some documents have been modified but not saved, if you close the project all the changes will be lost, are you sure you want to close the project?");
if (!resConfirm)
return;
}
foreach (var doc in openDocuments)
doc.CloseDocument(outLog.Writer, true);
ZXProjectManager.CloseProject();
editTabs.Clear();
peExplorer.UpdateProjectFolder();
FileInfo.FileLoaded = false;
FileInfo.ProjectLoaded = false;
EmulatorInfo.CanDebug = false;
EmulatorInfo.CanRun = false;
EmulatorInfo.CanPause = false;
EmulatorInfo.CanStep = false;
Cleanup();
BreakpointManager.ClearBreakpoints();
}
private async void SaveFile(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var activeTab = editTabs.FirstOrDefault(t => t.IsSelected);
if (activeTab == null)
return;
var editor = activeTab.Content as ZXDocumentEditorBase;
if (editor == null)
return;
if (!editor.SaveDocument(outLog.Writer))
{
await this.ShowError("Error", "Cannot save the file, check the output log for more info.");
return;
}
}
private void SaveAllFiles(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
SaveAllFiles();
}
private bool SaveAllFiles()
{
foreach (var edit in openDocuments)
{
if (edit.Modified)
if (!edit.SaveDocument(outLog.Writer))
return false;
}
return true;
}
private async void OpenFile(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var path = peExplorer.SelectedPath;
if (string.IsNullOrWhiteSpace(path))
return;
if (!File.Exists(path))
return;
await OpenFile(path);
}
private async void OpenNewFile(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var opts = new FilePickerOpenOptions();
opts.FileTypeFilter = ZXDocumentProvider.GetDocumentFilters();
opts.AllowMultiple = false;
opts.Title = "Open file...";
var result = await this.StorageProvider.OpenFilePickerAsync(opts);
if (result == null || result.Count == 0)
return;
await OpenFile(result[0].Path.LocalPath);
}
private async void OpenProject(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (FileInfo.ProjectLoaded)
{
if (openDocuments.Any(e => e.Modified))
{
var resConfirm = await this.ShowConfirm("Warning!", "There are unsaved documents, opening a new project will discard the changes, are you sure you want to open a new project?");
if (!resConfirm)
return;
foreach (var doc in openDocuments)
doc.CloseDocument(outLog.Writer, true);
}
ZXProjectManager.CloseProject();
}
FolderPickerOpenOptions opts = new FolderPickerOpenOptions { AllowMultiple = false, Title = "Open project" };
var res = await this.StorageProvider.OpenFolderPickerAsync(opts);
if (res == null || res.Count == 0)
return;
ZXProjectManager.OpenProject(res[0].Path.LocalPath);
ZXOptions.Current.LastProjectPath = res[0].Path.LocalPath;
ZXOptions.SaveCurrentSettings();
Cleanup();
BreakpointManager.ClearBreakpoints();
peExplorer.UpdateProjectFolder();
editTabs.Clear();
openDocuments.Clear();
FileInfo.ProjectLoaded = true;
FileInfo.FileLoaded = false;
FileInfo.FileSystemObjectSelected = false;
EmulatorInfo.CanRun = true;
EmulatorInfo.CanDebug = true;
}
private async void OpenLastProject(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (!FileInfo.ProjectLoaded && string.IsNullOrEmpty(ZXOptions.Current.LastProjectPath) == false)
{
ZXProjectManager.OpenProject(ZXOptions.Current.LastProjectPath);
Cleanup();
BreakpointManager.ClearBreakpoints();
peExplorer.UpdateProjectFolder();
editTabs.Clear();
openDocuments.Clear();
FileInfo.ProjectLoaded = true;
FileInfo.FileLoaded = false;
FileInfo.FileSystemObjectSelected = false;
EmulatorInfo.CanRun = true;
EmulatorInfo.CanDebug = true;
}
}
private async void CreateFile(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var path = peExplorer.SelectedPath;
if (path == null)
path = peExplorer.RootPath ?? "";
if (File.Exists(path))
path = Path.GetDirectoryName(path) ?? "";
var dlg = new ZXNewFileDialog();
var result = await dlg.ShowDialog<(IZXDocumentType DocumentType, string Name)?>(this);
if (result == null)
return;
var finalName = Path.Combine(path, result.Value.Name);
if (File.Exists(finalName))
{
if (!await this.ShowConfirm("Existing file", "Warning! File already exists, do you want to overwrite it?"))
return;
try
{
File.Delete(finalName);
}
catch (Exception ex)
{
await this.ShowError("Error", "Cannot delete existing file, aborting.");
return;
}
}
var created = result.Value.DocumentType.DocumentFactory.CreateDocument(finalName, outLog.Writer);
if (!created)
{
await this.ShowError("Error", "Cannot create file, check the output log for more details");
return;
}
await OpenFile(finalName);
await Task.Delay(100);
peExplorer.SelectPath(finalName);
}
private async void CreateFolder(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
var path = peExplorer.SelectedPath;
if (path == null)
path = peExplorer.RootPath;
if (File.Exists(path))
path = Path.GetDirectoryName(path);
var fileName = await this.ShowInput("New folder", "Enter the name of the folder to be created.", "Folder:");
if (string.IsNullOrWhiteSpace(fileName))
return;
var finalPath = Path.Combine(path ?? "", fileName);
try
{
Directory.CreateDirectory(finalPath);
}
catch (Exception ex)
{
await this.ShowError("Create error", $"Unexpected error trying to create the directory: {ex.Message} - {ex.StackTrace}");
}
}
private async void CreateProject(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (FileInfo.ProjectLoaded)
{
if (openDocuments.Any(e => e.Modified))
{
var resConfirm = await this.ShowConfirm("Warning!", "Current project has pending changes, creating a new project will discard those changes. Do you want to continue?");
if (!resConfirm)
return;
foreach (var doc in openDocuments)
doc.CloseDocument(outLog.Writer, true);
}
openDocuments.Clear();
editTabs.Clear();
ZXProjectManager.CloseProject();
}
outLog.Clear();
var fld = await StorageProvider.OpenFolderPickerAsync(new Avalonia.Platform.Storage.FolderPickerOpenOptions { AllowMultiple = false, Title = "Select project's folder." });
if (fld == null || fld.Count == 0)
return;
string selFolder = fld.First().Path.LocalPath;
var dlg = new ZXBuildSettingsDialog();
if (ZXOptions.Current.DefaultBuildSettings != null)
dlg.Settings = ZXOptions.Current.DefaultBuildSettings.Clone();
var setRes = await dlg.ShowDialog<bool>(this);
if (!setRes)
return;
if (!ZXProjectManager.CreateProject(selFolder, dlg.Settings, outLog.Writer))
{
await this.ShowError("Create error", $"Error creating project, check the output log for more details.");
return;
}
ZXProjectManager.OpenProject(selFolder);
peExplorer.UpdateProjectFolder();
editTabs.Clear();
openDocuments.Clear();
FileInfo.ProjectLoaded = true;
FileInfo.FileLoaded = false;
FileInfo.FileSystemObjectSelected = false;
EmulatorInfo.CanDebug = true;
EmulatorInfo.CanRun = true;
}
async Task<ZXDocumentEditorBase?> OpenFile(string file)
{
var opened = openDocuments.FirstOrDefault(ef => Path.GetFullPath(file) == Path.GetFullPath(ef.DocumentPath));
if (opened != null)
{
var tab = editTabs.First(t => t.Content == opened);
tab.IsSelected = true;
return opened;
}
var docType = ZXDocumentProvider.GetDocumentType(file);
if (docType == null || !docType.CanEdit)
{
await this.ShowError("Cannot open file", "The specified file is not editable by ZX Basic Studio. Operation aborted.");
return null;
}
//TODO: Provide commands
ZXDocumentEditorBase? editor = docType.DocumentFactory.CreateEditor(file, outLog.Writer);
if (editor == null)
{
await this.ShowError("Cannot open file", "Error opening document, check the output log for more information.");
return null;
}
TabItem tItem = new TabItem();
tItem.Classes.Add("closeTab");
tItem.Tag = Path.GetFileName(file);
tItem.Content = editor;
editTabs.Add(tItem);
openDocuments.Add(editor);
tItem.IsSelected = true;
editor.DocumentModified += EditorDocumentModified;
editor.DocumentSaved += EditorDocumentSaved;
editor.DocumentRestored += EditorDocumentRestored;
editor.RequestSaveDocument += EditorRequestSaveDocument;
FileInfo.FileLoaded = true;
peExplorer.SelectPath(file);
if (editor is ZXTextEditor)
{
var txtEdit = (ZXTextEditor)editor;
if (EmulatorInfo.IsRunning && !EmulatorInfo.IsPaused)
txtEdit.Readonly = true;
else if (EmulatorInfo.IsRunning && EmulatorInfo.IsPaused)
{
var bp = basicBreakpoints.FirstOrDefault(bp => bp.Address == emu.Registers.PC);
if (bp != null)
{
var line = bp.Tag as ZXCodeLine;
if (line != null)
{
if (line.File == file)
txtEdit.BreakLine = line.LineNumber + 1;
}
}
}
}
return editor;
}
private async void EditorRequestSaveDocument(object? sender, EventArgs e)
{
var editor = sender as ZXDocumentEditorBase;
if (editor == null)
return;
if (!editor.SaveDocument(outLog.Writer))
{
await this.ShowError("Error", "Cannot save the file, check if another program is blocking it.");
return;
}
}
private void EditorDocumentRestored(object? sender, EventArgs e)
{
if (sender is not ZXDocumentEditorBase)
return;
var editor = (ZXDocumentEditorBase)sender;
var tab = editor.Parent as TabItem;
if (tab == null)
return;
tab.Tag = tab.Tag?.ToString()?.Replace("*", "");
}
private void EditorDocumentSaved(object? sender, System.EventArgs e)
{
if (sender is not ZXDocumentEditorBase)
return;
var editor = (ZXDocumentEditorBase)sender;
var tab = editor.Parent as TabItem;
if (tab == null)
return;
tab.Tag = tab.Tag?.ToString()?.Replace("*", "");
}
private void EditorDocumentModified(object? sender, System.EventArgs e)
{
if (sender is not ZXDocumentEditorBase)
return;
var editor = (ZXDocumentEditorBase)sender;
var tab = editor.Parent as TabItem;
if (tab == null)
return;
tab.Tag = tab.Tag?.ToString() + "*";
}
private async Task CloseDocumentByFile(string File)
{
var disEdit = openDocuments.FirstOrDefault(ef => ef.DocumentPath == File);
if (disEdit != null)
{
if (disEdit.Modified)
{
var res = await this.ShowConfirm("Modified", "This document has been modified, if you close it now you will lose the changes, are you sure you want to close it?");
if (!res)
return;
}
disEdit.CloseDocument(outLog.Writer, true);
openDocuments.Remove(disEdit);
disEdit.Dispose();
var tab = editTabs.First(t => t.Content == disEdit);
editTabs.Remove(tab);
if (openDocuments.Count == 0)
FileInfo.FileLoaded = false;
}
}
#endregion
#region Emulator control
private void PowerOn(object? sender, RoutedEventArgs e)
{
CheckSpectrumModel();
emu.Start();
EmulatorInfo.IsRunning = true;
}
private void ShowTapePlayer(object? sender, RoutedEventArgs e)
{
if (!_player.IsAttachedToVisualTree())
ZXFloatController.MakeFloating(_playerDock);
_player.Datacorder = emu.Datacorder;
}
private void DirectScreen(object? sender, RoutedEventArgs e)
{