-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathLuaConsole.cs
More file actions
1588 lines (1382 loc) · 43.9 KB
/
LuaConsole.cs
File metadata and controls
1588 lines (1382 loc) · 43.9 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 System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using BizHawk.Client.Common;
using BizHawk.Client.EmuHawk.Properties;
using BizHawk.Client.EmuHawk.ToolExtensions;
using BizHawk.Common;
using BizHawk.Common.CollectionExtensions;
using BizHawk.Common.PathExtensions;
using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Common;
namespace BizHawk.Client.EmuHawk
{
public partial class LuaConsole : ToolFormBase, IToolFormAutoConfig
{
private const string IconColumnName = "Icon";
private const string ScriptColumnName = "Script";
private const string PathColumnName = "PathName";
private static readonly FilesystemFilterSet JustScriptsFSFilterSet = new(FilesystemFilter.LuaScripts);
private static readonly FilesystemFilterSet ScriptsAndTextFilesFSFilterSet = new(FilesystemFilter.LuaScripts, FilesystemFilter.TextFiles);
private static readonly FilesystemFilterSet SessionsFSFilterSet = new(new FilesystemFilter("Lua Session Files", new[] { "luases" }));
public static Icon ToolIcon
=> Resources.TextDocIcon;
private readonly LuaAutocompleteInstaller _luaAutoInstaller = new();
private readonly Dictionary<LuaFile, FileSystemWatcher> _watches = new();
private readonly int _defaultSplitDistance;
private LuaFile _lastScriptUsed = null;
[RequiredService]
private IEmulator Emulator { get; set; }
private bool _sortReverse;
private string _lastColumnSorted;
private readonly List<string> _consoleCommandHistory = new();
private int _consoleCommandHistoryIndex = -1;
public ToolDialogSettings.ColumnList Columns { get; set; }
internal IMainFormForApi MainFormForApi { get; set; }
public class LuaConsoleSettings
{
public LuaConsoleSettings()
{
Columns = new List<RollColumn>
{
new(name: IconColumnName, widthUnscaled: 22, type: ColumnType.Image, text: " "),
new(name: ScriptColumnName, widthUnscaled: 92, text: "Script"),
new(name: PathColumnName, widthUnscaled: 300, text: "Path"),
};
}
public List<RollColumn> Columns { get; set; }
public bool ReloadOnScriptFileChange { get; set; }
public bool ToggleAllIfNoneSelected { get; set; } = true;
public int SplitDistance { get; set; }
public bool DisableLuaScriptsOnLoad { get; set; }
public bool WarnedOnceOnOverwrite { get; set; }
}
[ConfigPersist]
public LuaConsoleSettings Settings { get; set; }
protected override string WindowTitleStatic => "Lua Console";
public LuaConsole()
{
Settings = new LuaConsoleSettings();
_sortReverse = false;
_lastColumnSorted = "";
InitializeComponent();
ToggleScriptContextItem.Image = Resources.Refresh;
PauseScriptContextItem.Image = Resources.Pause;
EditScriptContextItem.Image = Resources.Cut;
RemoveScriptContextItem.Image = Resources.Close;
InsertSeperatorContextItem.Image = Resources.InsertSeparator;
StopAllScriptsContextItem.Image = Resources.Stop;
ClearRegisteredFunctionsContextItem.Image = Resources.Delete;
NewSessionMenuItem.Image = Resources.NewFile;
OpenSessionMenuItem.Image = Resources.OpenFile;
SaveSessionMenuItem.Image = Resources.SaveAs;
NewScriptMenuItem.Image = Resources.NewFile;
OpenScriptMenuItem.Image = Resources.OpenFile;
RefreshScriptMenuItem.Image = Resources.Refresh;
ToggleScriptMenuItem.Image = Resources.Checkbox;
PauseScriptMenuItem.Image = Resources.Pause;
EditScriptMenuItem.Image = Resources.Pencil;
RemoveScriptMenuItem.Image = Resources.Delete;
InsertSeparatorMenuItem.Image = Resources.InsertSeparator;
MoveUpMenuItem.Image = Resources.MoveUp;
MoveDownMenuItem.Image = Resources.MoveDown;
StopAllScriptsMenuItem.Image = Resources.Stop;
RegisterSublimeText2MenuItem.Image = Resources.GreenCheck;
ClearRegisteredFunctionsLogContextItem.Image = Resources.Delete;
NewScriptToolbarItem.Image = Resources.NewFile;
OpenScriptToolbarItem.Image = Resources.OpenFile;
ToggleScriptToolbarItem.Image = Resources.Checkbox;
RefreshScriptToolbarItem.Image = Resources.Refresh;
PauseToolbarItem.Image = Resources.Pause;
EditToolbarItem.Image = Resources.Pencil;
RemoveScriptToolbarItem.Image = Resources.Delete;
DuplicateToolbarButton.Image = Resources.Duplicate;
ClearConsoleToolbarButton.Image = Resources.ClearConsole;
MoveUpToolbarItem.Image = Resources.MoveUp;
toolStripButtonMoveDown.Image = Resources.MoveDown;
InsertSeparatorToolbarItem.Image = Resources.InsertSeparator;
EraseToolbarItem.Image = Resources.Erase;
RecentScriptsSubMenu.Image = Resources.Recent;
Icon = ToolIcon;
Closing += (o, e) =>
{
if (AskSaveChanges())
{
Settings.Columns = LuaListView.AllColumns;
DisplayManager.ClearApiHawkSurfaces();
DisplayManager.ClearApiHawkTextureCache();
ResetDrawSurfacePadding();
ClearFileWatches();
LuaImp?.Close();
DisplayManager.OSD.ClearGuiText();
}
else
{
e.Cancel = true;
}
};
LuaListView.QueryItemText += LuaListView_QueryItemText;
LuaListView.QueryItemBkColor += LuaListView_QueryItemBkColor;
LuaListView.QueryItemIcon += LuaListView_QueryItemImage;
// this is bad, in case we ever have more than one gui part running lua.. not sure how much other badness there is like that
LuaSandbox.DefaultLogger = WriteToOutputWindow;
_defaultSplitDistance = splitContainer1.SplitterDistance;
}
private LuaLibraries LuaImp;
private IEnumerable<LuaFile> SelectedItems => LuaListView.SelectedRows.Select(index => LuaImp.ScriptList[index]);
private IEnumerable<LuaFile> SelectedFiles => SelectedItems.Where(x => !x.IsSeparator);
private void LuaConsole_Load(object sender, EventArgs e)
{
if (Config.RecentLuaSession.AutoLoad && !Config.RecentLuaSession.Empty)
{
LoadSessionFromRecent(Config.RecentLuaSession.MostRecent);
}
else if (Config.RecentLua.AutoLoad)
{
if (!Config.RecentLua.Empty)
{
LoadLuaFile(Config.RecentLua.MostRecent);
}
}
LuaListView.AllColumns.Clear();
SetColumns();
splitContainer1.SetDistanceOrDefault(Settings.SplitDistance, _defaultSplitDistance);
}
private void BranchesMarkersSplit_SplitterMoved(object sender, SplitterEventArgs e)
{
Settings.SplitDistance = splitContainer1.SplitterDistance;
}
public override void Restart()
{
List<LuaFile> runningScripts = new();
ApiContainer apiContainer = ApiManager.RestartLua(
Emulator.ServiceProvider,
WriteToOutputWindow,
MainFormForApi,
DisplayManager,
InputManager,
MovieSession,
Tools,
Config,
Emulator,
Game,
DialogController);
// Things we need to do with the existing LuaImp before we can make a new one
if (LuaImp is not null)
{
if (LuaImp.IsRebootingCore)
{
// Even if the lua console is self-rebooting from client.reboot_core() we still want to re-inject dependencies
LuaImp.Restart(Emulator.ServiceProvider, Config, apiContainer);
return;
}
runningScripts = LuaImp.ScriptList.Where(lf => lf.Enabled).ToList();
// we don't use runningScripts here as the other scripts need to be stopped too
foreach (var file in LuaImp.ScriptList)
{
DisableLuaScript(file);
}
}
LuaFileList newScripts = new(LuaImp?.ScriptList, onChanged: SessionChangedCallback);
LuaFunctionList registeredFuncList = new(onChanged: UpdateRegisteredFunctionsDialog);
LuaImp?.Close();
LuaImp = new LuaLibraries(
newScripts,
registeredFuncList,
Emulator.ServiceProvider,
MainFormForApi,
Config,
Tools,
(IDialogParent)MainForm, // not sure why neither main form interface implements IDialogParent, but our MainForm class does
apiContainer);
InputBox.AutoCompleteCustomSource.Clear();
InputBox.AutoCompleteCustomSource.AddRange(LuaImp.Docs.Where(static f => f.SuggestInREPL)
.Select(static f => $"{f.Library}.{f.Name}")
.ToArray());
foreach (var file in runningScripts)
{
try
{
LuaSandbox.Sandbox(file.Thread, () =>
{
LuaImp.SpawnAndSetFileThread(file.Path, file);
LuaSandbox.CreateSandbox(file.Thread, Path.GetDirectoryName(file.Path));
file.State = LuaFile.RunState.Running;
}, () =>
{
file.State = LuaFile.RunState.Disabled;
});
}
catch (Exception ex)
{
DialogController.ShowMessageBox(ex.ToString());
}
}
UpdateDialog();
}
public void ToggleLastLuaScript()
{
if (_lastScriptUsed is not null)
{
ToggleLuaScript(_lastScriptUsed);
}
}
private void SetColumns()
{
LuaListView.AllColumns.AddRange(Settings.Columns);
LuaListView.Refresh();
}
private void AddFileWatches()
{
if (Settings.ReloadOnScriptFileChange)
{
ClearFileWatches();
foreach (var item in LuaImp.ScriptList.Where(s => !s.IsSeparator))
{
CreateFileWatcher(item);
}
}
}
private void ClearFileWatches()
{
foreach (var watch in _watches.Values)
watch.Dispose();
_watches.Clear();
}
private void CreateFileWatcher(LuaFile item)
{
if (_watches.ContainsKey(item))
return;
var (dir, file) = item.Path.SplitPathToDirAndFile();
// prevent error when (auto)loading session referencing scripts in deleted/renamed directories
if (!Directory.Exists(dir))
return;
var watcher = new FileSystemWatcher
{
Path = dir,
Filter = file,
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
EnableRaisingEvents = true,
SynchronizingObject = this, // invoke event handlers on GUI thread
};
// TODO, Deleted and Renamed events
watcher.Changed += (_, _) => OnLuaFileChanged(item);
_watches.Add(item, watcher);
}
private void RemoveFileWatcher(LuaFile item)
{
if (_watches.TryGetValue(item, out var watcher))
{
_watches.Remove(item);
watcher.Dispose();
}
}
private void OnLuaFileChanged(LuaFile item)
{
if (item.Enabled && LuaImp.ScriptList.Contains(item))
{
RefreshLuaScript(item);
}
}
public void LoadLuaFile(string path)
{
var absolutePath = Path.GetFullPath(path);
var alreadyLoadedFile = LuaImp.ScriptList.FirstOrDefault(t => absolutePath == t.Path);
if (alreadyLoadedFile is not null)
{
if (!alreadyLoadedFile.Enabled && !Settings.DisableLuaScriptsOnLoad)
{
ToggleLuaScript(alreadyLoadedFile);
}
}
else
{
var luaFile = new LuaFile("", absolutePath);
LuaImp.ScriptList.Add(luaFile);
LuaListView.RowCount = LuaImp.ScriptList.Count;
Config.RecentLua.Add(absolutePath);
if (!Settings.DisableLuaScriptsOnLoad)
{
luaFile.State = LuaFile.RunState.Running;
EnableLuaFile(luaFile);
}
else
{
luaFile.State = LuaFile.RunState.Disabled;
}
if (Settings.ReloadOnScriptFileChange)
{
CreateFileWatcher(luaFile);
}
}
UpdateDialog();
}
public void RemoveLuaFile(string path)
{
var absolutePath = Path.GetFullPath(path);
var luaFile = LuaImp.ScriptList.FirstOrDefault(t => absolutePath == t.Path);
if (luaFile is not null)
{
RemoveLuaFile(luaFile);
UpdateDialog();
}
}
private void RemoveLuaFile(LuaFile item)
{
if (!item.IsSeparator)
{
DisableLuaScript(item);
RemoveFileWatcher(item);
}
LuaImp.ScriptList.Remove(item);
}
private void RemoveAllLuaFiles()
{
while (LuaImp.ScriptList.Count > 0)
{
RemoveLuaFile(LuaImp.ScriptList[LuaImp.ScriptList.Count - 1]);
}
}
private void UpdateDialog()
{
LuaListView.RowCount = LuaImp.ScriptList.Count;
UpdateNumberOfScripts();
UpdateRegisteredFunctionsDialog();
}
private void SessionChangedCallback()
{
OutputMessages.Text =
(LuaImp.ScriptList.Changes ? "* " : "") +
Path.GetFileName(LuaImp.ScriptList.Filename);
}
private void LuaListView_QueryItemImage(int index, RollColumn column, ref Bitmap bitmap, ref int offsetX, ref int offsetY)
{
if (column.Name != IconColumnName)
{
return;
}
if (LuaImp.ScriptList[index].IsSeparator)
{
return;
}
bitmap = LuaImp.ScriptList[index].State switch
{
LuaFile.RunState.Running => Resources.ts_h_arrow_green,
LuaFile.RunState.Paused => Resources.Pause,
_ => Resources.Stop,
};
}
private void LuaListView_QueryItemBkColor(int index, RollColumn column, ref Color color)
{
var lf = LuaImp.ScriptList[index];
if (lf.IsSeparator) color = BackColor;
else if (lf.Paused) color = Color.LightPink;
else if (lf.Enabled) color = Color.LightCyan;
}
private void LuaListView_QueryItemText(int index, RollColumn column, out string text, ref int offsetX, ref int offsetY)
{
text = "";
if (LuaImp.ScriptList[index].IsSeparator)
{
return;
}
if (column.Name == ScriptColumnName)
{
text = Path.GetFileNameWithoutExtension(LuaImp.ScriptList[index].Path); // TODO: how about allow the user to name scripts?
}
else if (column.Name == PathColumnName)
{
text = DressUpRelative(LuaImp.ScriptList[index].Path);
}
}
private string DressUpRelative(string path)
{
return path.StartsWithOrdinal(".\\") ? path.Replace(".\\", "") : path;
}
private void UpdateNumberOfScripts()
{
var message = "";
var total = LuaImp.ScriptList.Count(file => !file.IsSeparator);
var active = LuaImp.ScriptList.Count(file => !file.IsSeparator && file.Enabled);
var paused = LuaImp.ScriptList.Count(static lf => !lf.IsSeparator && lf.Paused);
if (total == 1)
{
message += $"{total} script ({active} active, {paused} paused)";
}
else if (total == 0)
{
message += $"{total} scripts";
}
else
{
message += $"{total} scripts ({active} active, {paused} paused)";
}
NumberOfScripts.Text = message;
}
private void WriteLine(string message) => WriteToOutputWindow(message + "\n");
private int _messageCount;
private const int MaxCount = 100;
public void WriteToOutputWindow(string message)
{
if (!OutputBox.IsHandleCreated || OutputBox.IsDisposed)
{
return;
}
_messageCount++;
if (_messageCount > MaxCount) return;
if (_messageCount == MaxCount) message += "\nFlood warning! Message cap reached, suppressing output.\n";
OutputBox.BeginInvoke(() =>
{
OutputBox.Text += message;
OutputBox.SelectionStart = OutputBox.Text.Length;
OutputBox.ScrollToCaret();
});
}
public void ClearOutputWindow()
{
if (!OutputBox.IsHandleCreated || OutputBox.IsDisposed)
{
return;
}
OutputBox.BeginInvoke(() =>
{
OutputBox.SelectionLength = 0;
OutputBox.Text = "";
OutputBox.Refresh();
});
}
public bool LoadLuaSession(string path)
{
RemoveAllLuaFiles();
var result = LuaImp.ScriptList.Load(path, Settings.DisableLuaScriptsOnLoad);
foreach (var script in LuaImp.ScriptList)
{
if (!script.IsSeparator)
{
if (script.Enabled)
{
EnableLuaFile(script);
}
Config.RecentLua.Add(script.Path);
}
}
LuaImp.ScriptList.Changes = false;
Config.RecentLuaSession.Add(path);
UpdateDialog();
AddFileWatches();
ClearOutputWindow();
return result;
}
public void CallStateLoadCallbacks(string userFriendlyStateName)
=> LuaImp.CallLoadStateEvent(userFriendlyStateName);
public void CallStateSaveCallbacks(string userFriendlyStateName)
=> LuaImp.CallSaveStateEvent(userFriendlyStateName);
public void CallScriptExitCallbacks()
{
foreach (var lf in LuaImp.ScriptList) LuaImp.CallExitEvent(lf, alsoUnregister: true);
}
protected override void UpdateBefore()
{
if (LuaImp.IsUpdateSupressed)
{
return;
}
LuaImp.CallFrameBeforeEvent();
}
protected override void UpdateAfter()
{
if (LuaImp.IsUpdateSupressed)
{
return;
}
LuaImp.CallFrameAfterEvent();
ResumeScripts(true);
}
protected override void FastUpdateBefore()
{
if (Config.RunLuaDuringTurbo)
{
UpdateBefore();
}
}
protected override void FastUpdateAfter()
{
if (Config.RunLuaDuringTurbo)
{
UpdateAfter();
}
}
private void ResetDrawSurfacePadding()
{
var resized = false;
if (DisplayManager.ClientExtraPadding != (0, 0, 0, 0))
{
DisplayManager.ClientExtraPadding = (0, 0, 0, 0);
resized = true;
}
if (DisplayManager.GameExtraPadding != (0, 0, 0, 0))
{
DisplayManager.GameExtraPadding = (0, 0, 0, 0);
resized = true;
}
if (resized) MainForm.FrameBufferResized();
}
/// <summary>
/// resumes suspended Co-routines
/// </summary>
/// <param name="includeFrameWaiters">should frame waiters be waken up? only use this immediately before a frame of emulation</param>
public void ResumeScripts(bool includeFrameWaiters)
{
if (LuaImp.ScriptList.Count is 0
|| LuaImp.IsUpdateSupressed
|| (MainForm.IsTurboing && !Config.RunLuaDuringTurbo))
{
return;
}
foreach (var lf in LuaImp.ScriptList.Where(static lf => lf.State is LuaFile.RunState.Running && lf.Thread is not null))
{
try
{
LuaSandbox.Sandbox(lf.Thread, () =>
{
var prohibit = lf.FrameWaiting && !includeFrameWaiters;
if (!prohibit)
{
var (waitForFrame, terminated) = LuaImp.ResumeScript(lf);
if (terminated)
{
LuaImp.CallExitEvent(lf);
lf.Stop();
DetachRegisteredFunctions(lf);
UpdateDialog();
}
lf.FrameWaiting = waitForFrame;
}
}, () =>
{
lf.Stop();
DetachRegisteredFunctions(lf);
LuaListView.Refresh();
});
}
catch (Exception ex)
{
DialogController.ShowMessageBox(ex.ToString());
}
}
_messageCount = 0;
}
private void DetachRegisteredFunctions(LuaFile lf)
{
foreach (var nlf in LuaImp.RegisteredFunctions
.Where(f => f.LuaFile == lf))
{
nlf.DetachFromScript();
}
}
private FileInfo GetSaveFileFromUser()
{
string initDir;
string initFileName;
if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename))
{
(initDir, initFileName, _) = LuaImp.ScriptList.Filename.SplitPathToDirFileAndExt();
}
else
{
initDir = Config!.PathEntries.LuaAbsolutePath();
initFileName = Game.IsNullInstance() ? "NULL" : Game.FilesystemSafeName();
}
var result = this.ShowFileSaveDialog(
discardCWDChange: true,
filter: SessionsFSFilterSet,
initDir: initDir,
initFileName: initFileName);
return result is not null ? new FileInfo(result) : null;
}
private FileWriteResult SaveSessionAs()
{
var file = GetSaveFileFromUser();
if (file != null)
{
FileWriteResult saveResult = LuaImp.ScriptList.Save(file.FullName);
if (saveResult.IsError)
{
this.ErrorMessageBox(saveResult);
OutputMessages.Text = $"Lua session could not be saved to {file.Name}";
}
else
{
Config.RecentLuaSession.Add(file.FullName);
OutputMessages.Text = $"{file.Name} saved.";
}
return saveResult;
}
return new();
}
private void LoadSessionFromRecent(string path)
{
var load = true;
if (LuaImp.ScriptList.Changes)
{
load = AskSaveChanges();
}
if (load)
{
if (!LoadLuaSession(path))
{
Config.RecentLuaSession.HandleLoadError(this, path: path);
}
}
}
public override bool AskSaveChanges()
{
if (!LuaImp.ScriptList.Changes || string.IsNullOrEmpty(LuaImp.ScriptList.Filename)) return true;
var result = DialogController.DoWithTempMute(() => this.ModalMessageBox3(
caption: "Closing with Unsaved Changes",
icon: EMsgBoxIcon.Question,
text: $"Save {WindowTitleStatic} session?"));
if (result is null) return false;
if (result.Value)
{
TryAgainResult saveResult = this.DoWithTryAgainBox(SaveOrSaveAs, "Failed to save Lua session.");
return saveResult != TryAgainResult.Canceled;
}
else LuaImp.ScriptList.Changes = false;
return true;
}
private void UpdateRegisteredFunctionsDialog()
{
if (LuaImp is null) return;
foreach (var form in Application.OpenForms.OfType<LuaRegisteredFunctionsList>().ToList())
{
form.UpdateValues(LuaImp.RegisteredFunctions);
}
}
private FileWriteResult SaveOrSaveAs()
{
if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename))
{
FileWriteResult result = LuaImp.ScriptList.Save(LuaImp.ScriptList.Filename);
if (!result.IsError)
{
Config.RecentLuaSession.Add(LuaImp.ScriptList.Filename);
}
return result;
}
else
{
return SaveSessionAs();
}
}
private void FileSubMenu_DropDownOpened(object sender, EventArgs e)
{
SaveSessionMenuItem.Enabled = LuaImp.ScriptList.Changes;
}
private void RecentSessionsSubMenu_DropDownOpened(object sender, EventArgs e)
=> RecentSessionsSubMenu.ReplaceDropDownItems(Config!.RecentLuaSession.RecentMenu(this, LoadSessionFromRecent, "Session"));
private void RecentScriptsSubMenu_DropDownOpened(object sender, EventArgs e)
=> RecentScriptsSubMenu.ReplaceDropDownItems(Config!.RecentLua.RecentMenu(this, LoadLuaFile, "Script"));
private void NewSessionMenuItem_Click(object sender, EventArgs e)
{
var result = !LuaImp.ScriptList.Changes || AskSaveChanges();
if (result)
{
RemoveAllLuaFiles();
LuaImp.ScriptList.Clear();
ClearOutputWindow();
UpdateDialog();
}
}
private void OpenSessionMenuItem_Click(object sender, EventArgs e)
{
var initDir = Config!.PathEntries.LuaAbsolutePath();
Directory.CreateDirectory(initDir);
var result = this.ShowFileOpenDialog(
discardCWDChange: true,
filter: SessionsFSFilterSet,
initDir: initDir);
if (result is not null) LoadLuaSession(result);
}
private void SaveSessionMenuItem_Click(object sender, EventArgs e)
{
if (LuaImp.ScriptList.Changes)
{
FileWriteResult result = SaveOrSaveAs();
if (result.IsError)
{
this.ErrorMessageBox(result, "Failed to save Lua session.");
OutputMessages.Text = $"Failed to save {Path.GetFileName(LuaImp.ScriptList.Filename)}";
}
else
{
OutputMessages.Text = $"{Path.GetFileName(LuaImp.ScriptList.Filename)} saved.";
}
}
}
private void SaveSessionAsMenuItem_Click(object sender, EventArgs e)
{
SaveSessionAs();
}
private void ScriptSubMenu_DropDownOpened(object sender, EventArgs e)
{
ToggleScriptMenuItem.Enabled =
PauseScriptMenuItem.Enabled =
EditScriptMenuItem.Enabled =
SelectedFiles.Any();
RemoveScriptMenuItem.Enabled =
DuplicateScriptMenuItem.Enabled =
MoveUpMenuItem.Enabled =
MoveDownMenuItem.Enabled =
LuaListView.AnyRowsSelected;
SelectAllMenuItem.Enabled = LuaImp.ScriptList.Count is not 0;
StopAllScriptsMenuItem.Enabled = LuaImp.ScriptList.Any(script => script.Enabled);
RegisteredFunctionsMenuItem.Enabled = LuaImp.RegisteredFunctions.Count is not 0;
}
private void NewScriptMenuItem_Click(object sender, EventArgs e)
{
var luaDir = Config!.PathEntries.LuaAbsolutePath();
string initDir;
string ext;
if (!string.IsNullOrWhiteSpace(LuaImp.ScriptList.Filename))
{
(initDir, ext, _) = LuaImp.ScriptList.Filename.SplitPathToDirFileAndExt();
}
else
{
initDir = luaDir;
ext = Path.GetFileNameWithoutExtension(Game.Name);
}
var result = this.ShowFileSaveDialog(
fileExt: ".lua",
filter: JustScriptsFSFilterSet,
initDir: initDir,
initFileName: ext);
if (string.IsNullOrWhiteSpace(result)) return;
const string TEMPLATE_FILENAME = ".template.lua";
var templatePath = Path.Combine(luaDir, TEMPLATE_FILENAME);
const string DEF_TEMPLATE_CONTENTS = "-- This template lives at `.../Lua/.template.lua`.\nwhile true do\n\t-- Code here will run once when the script is loaded, then after each emulated frame.\n\temu.frameadvance();\nend\n";
if (!File.Exists(templatePath)) File.WriteAllText(path: templatePath, contents: DEF_TEMPLATE_CONTENTS);
if (!Settings.WarnedOnceOnOverwrite && File.Exists(result))
{
// the user normally gets an "are you sure you want to overwrite" message from the OS
// but some newcomer users seem to think the New Script button is for opening up scripts
// mostly due to weird behavior in other emulators with their lua implementations
// we'll warn again the first time, clarifying usage then let the OS handle warning the user
Settings.WarnedOnceOnOverwrite = true;
if (!this.ModalMessageBox2("You are about to overwrite an existing Lua script.\n" +
"Keep in mind the \"New Lua Script\" option is for creating a brand new Lua script, not for opening Lua scripts.\n" +
"This warning will not appear again! (the file manager would be warning you about an overwrite anyways)\n" +
"Proceed with overwrite?", "Overwrite", EMsgBoxIcon.Warning, useOKCancel: true))
{
return;
}
}
File.Copy(sourceFileName: templatePath, destFileName: result, overwrite: true);
LuaImp.ScriptList.Add(new LuaFile(Path.GetFileNameWithoutExtension(result), result));
Config!.RecentLua.Add(result);
UpdateDialog();
Process.Start(new ProcessStartInfo
{
Verb = "Open",
FileName = result,
});
AddFileWatches();
}
private void OpenScriptMenuItem_Click(object sender, EventArgs e)
{
var initDir = Config!.PathEntries.LuaAbsolutePath();
Directory.CreateDirectory(initDir);
var result = this.ShowFileMultiOpenDialog(
discardCWDChange: true,
filter: ScriptsAndTextFilesFSFilterSet,
initDir: initDir);
if (result is null) return;
foreach (var file in result)
{
LoadLuaFile(file);
Config.RecentLua.Add(file);
}
UpdateDialog();
}
private void ToggleScriptMenuItem_Click(object sender, EventArgs e)
{
var files = !SelectedFiles.Any() && Settings.ToggleAllIfNoneSelected
? LuaImp.ScriptList
: SelectedFiles;
foreach (var file in files)
{
ToggleLuaScript(file);
}
UpdateDialog();
}
private void EnableLuaFile(LuaFile item)
{
try
{
LuaSandbox.Sandbox(null, () =>
{
LuaImp.SpawnAndSetFileThread(item.Path, item);
LuaSandbox.CreateSandbox(item.Thread, Path.GetDirectoryName(item.Path));
}, () =>
{
item.State = LuaFile.RunState.Disabled;
});
// there used to be a call here which did a redraw of the Gui/OSD, which included a call to `Tools.UpdateToolsAfter` --yoshi
}
catch (IOException)
{
item.State = LuaFile.RunState.Disabled;
WriteLine($"Unable to access file {item.Path}");
}
catch (Exception ex)
{
DialogController.ShowMessageBox(ex.ToString());
}
}
private void PauseScriptMenuItem_Click(object sender, EventArgs e)
{
foreach (var s in SelectedFiles)
{
s.TogglePause();
}
UpdateDialog();
}
private void EditScriptMenuItem_Click(object sender, EventArgs e)
{
foreach (var file in SelectedFiles)
{
Process.Start(new ProcessStartInfo
{
Verb = "Open",
FileName = file.Path,
});
}
}
private void RemoveScriptMenuItem_Click(object sender, EventArgs e)
{
var items = SelectedItems.ToList();
if (items.Count is not 0)
{
foreach (var item in items)