-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathTAStudio.cs
More file actions
1226 lines (1037 loc) · 36.1 KB
/
TAStudio.cs
File metadata and controls
1226 lines (1037 loc) · 36.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 System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using BizHawk.Client.Common;
using BizHawk.Client.EmuHawk.ToolExtensions;
using BizHawk.Client.EmuHawk.Properties;
using BizHawk.Common.CollectionExtensions;
using BizHawk.Common.StringExtensions;
using BizHawk.Emulation.Common;
using BizHawk.WinForms.Controls;
namespace BizHawk.Client.EmuHawk
{
public partial class TAStudio : ToolFormBase, IToolFormAutoConfig, IControlMainform
{
public static readonly FilesystemFilterSet TAStudioProjectsFSFilterSet = new(FilesystemFilter.TAStudioProjects);
public static Icon ToolIcon
=> Resources.TAStudioIcon;
public override bool BlocksInputWhenFocused => IsInMenuLoop;
public new IMainFormForTools MainForm => base.MainForm;
public new IMovieSession MovieSession => base.MovieSession;
// TODO: UI flow that conveniently allows to start from savestate
public ITasMovie CurrentTasMovie => MovieSession.Movie as ITasMovie;
public bool IsInMenuLoop { get; private set; }
private readonly List<TasClipboardEntry> _tasClipboard = new List<TasClipboardEntry>();
private const string CursorColumnName = "CursorColumn";
private const string FrameColumnName = "FrameColumn";
private UndoHistoryForm _undoForm;
private Timer _autosaveTimer;
private readonly int _defaultMainSplitDistance;
private readonly int _defaultBranchMarkerSplitDistance;
private bool _initialized;
private bool _exiting;
private bool _engaged;
private bool CanAutoload => Settings.RecentTas.AutoLoad && !string.IsNullOrEmpty(Settings.RecentTas.MostRecent);
/// <summary>
/// Gets a value that separates "restore last position" logic from seeking caused by navigation.
/// TASEditor never kills LastPositionFrame, and it only pauses on it, if it hasn't been greenzoned beforehand and middle mouse button was pressed.
/// </summary>
public int RestorePositionFrame { get; private set; } = -1;
private bool _shouldMoveGreenArrow;
private bool _seekingByEdit;
private int _seekingTo = -1;
[ConfigPersist]
public TAStudioSettings Settings { get; set; } = new TAStudioSettings();
public TAStudioPalette Palette => Settings.Palette;
[ConfigPersist]
public Font TasViewFont { get; set; } = new Font("Arial", 8.25F, FontStyle.Bold, GraphicsUnit.Point, 0);
/// <summary>
/// This is meant to be used by Lua.
/// </summary>
public bool StopRecordingOnNextEdit = true;
public class TAStudioSettings
{
public TAStudioSettings()
{
RecentTas = new RecentFiles(8);
AutoPause = false;
FollowCursor = true;
ScrollSpeed = 6;
FollowCursorAlwaysScroll = false;
FollowCursorScrollMethod = "near";
AutosaveInterval = 120000;
AutosaveAsBk2 = false;
AutosaveAsBackupFile = false;
BackupPerFileSave = false;
SingleClickAxisEdit = false;
OldControlSchemeForBranches = false;
LoadBranchOnDoubleClick = true;
CopyIncludesFrameNo = false;
AutoadjustInput = false;
// default to taseditor fashion
DenoteStatesWithIcons = false;
DenoteStatesWithBGColor = true;
DenoteMarkersWithIcons = false;
DenoteMarkersWithBGColor = true;
Palette = TAStudioPalette.Default;
}
public RecentFiles RecentTas { get; set; }
public bool AutoPause { get; set; }
public bool AutoRestoreLastPosition { get; set; }
public bool FollowCursor { get; set; }
public int ScrollSpeed { get; set; }
public bool FollowCursorAlwaysScroll { get; set; }
public string FollowCursorScrollMethod { get; set; }
public uint AutosaveInterval { get; set; }
public bool AutosaveAsBk2 { get; set; }
public bool AutosaveAsBackupFile { get; set; }
public bool BackupPerFileSave { get; set; }
public bool SingleClickAxisEdit { get; set; }
public bool OldControlSchemeForBranches { get; set; } // branch loading will behave differently depending on the recording mode
public bool LoadBranchOnDoubleClick { get; set; }
public bool DenoteStatesWithIcons { get; set; }
public bool DenoteStatesWithBGColor { get; set; }
public bool DenoteMarkersWithIcons { get; set; }
public bool DenoteMarkersWithBGColor { get; set; }
public int MainVerticalSplitDistance { get; set; }
public int BranchMarkerSplitDistance { get; set; }
public bool BindMarkersToInput { get; set; }
public bool CopyIncludesFrameNo { get; set; }
public bool AutoadjustInput { get; set; }
public TAStudioPalette Palette { get; set; }
public int MaxUndoSteps { get; set; } = 1000;
public int RewindStep { get; set; } = 1;
public int RewindStepFast { get; set; } = 4;
}
public TAStudio()
{
InitializeComponent();
ToolStripMenuItemEx goToFrameMenuItem = new()
{
ShortcutKeys = Keys.Control | Keys.G,
Text = "Go to Frame...",
};
goToFrameMenuItem.Click += (_, _) =>
{
MainForm.PauseEmulator();
using InputPrompt dialog = new()
{
Text = "Go to Frame",
Message = "Jump/Seek to frame index:",
TextInputType = InputPrompt.InputType.Unsigned,
};
if (this.ShowDialogWithTempMute(dialog).IsOk()) GoToFrame(int.Parse(dialog.PromptText));
};
_ = EditSubMenu.DropDownItems.InsertAfter(ReselectClipboardMenuItem, insert: goToFrameMenuItem);
RecentSubMenu.Image = Resources.Recent;
recentMacrosToolStripMenuItem.Image = Resources.Recent;
TASEditorManualOnlineMenuItem.Image = Resources.Help;
ForumThreadMenuItem.Image = Resources.TAStudio;
Icon = ToolIcon;
_defaultMainSplitDistance = MainVertialSplit.SplitterDistance;
_defaultBranchMarkerSplitDistance = BranchesMarkersSplit.SplitterDistance;
// TODO: show this at all times or hide it when saving is done?
ProgressBar.Visible = false;
WantsToControlStopMovie = true;
WantsToControlRestartMovie = true;
TasPlaybackBox.Tastudio = this;
MarkerControl.Tastudio = this;
BookMarkControl.Tastudio = this;
TasView.QueryItemText += TasView_QueryItemText;
TasView.QueryItemBkColor += TasView_QueryItemBkColor;
TasView.QueryRowBkColor += TasView_QueryRowBkColor;
TasView.QueryItemIcon += TasView_QueryItemIcon;
TasView.QueryFrameLag += TasView_QueryFrameLag;
TasView.PointedCellChanged += TasView_PointedCellChanged;
TasView.MouseLeave += TAStudio_MouseLeave;
TasView.CellHovered += (_, e) =>
{
if (e.NewCell.RowIndex is null)
{
toolTip1.Show(e.NewCell.Column!.Name, TasView, PointToClient(Cursor.Position));
}
};
}
private void Tastudio_Load(object sender, EventArgs e)
{
if (!Engage())
{
Close();
return;
}
RightClickMenu.Items.AddRange(TasView.GenerateContextMenuItems().ToArray());
TasView.ScrollSpeed = Settings.ScrollSpeed;
TasView.AlwaysScroll = Settings.FollowCursorAlwaysScroll;
TasView.ScrollMethod = Settings.FollowCursorScrollMethod;
_autosaveTimer = new Timer(components);
_autosaveTimer.Tick += AutosaveTimerEventProcessor;
if (Settings.AutosaveInterval > 0)
{
_autosaveTimer.Interval = (int)Settings.AutosaveInterval;
_autosaveTimer.Start();
}
MainVertialSplit.SetDistanceOrDefault(
Settings.MainVerticalSplitDistance,
_defaultMainSplitDistance);
BranchesMarkersSplit.SetDistanceOrDefault(
Settings.BranchMarkerSplitDistance,
_defaultBranchMarkerSplitDistance);
HandleHotkeyUpdate();
TasView.Font = TasViewFont;
RefreshDialog();
_initialized = true;
}
public override void HandleHotkeyUpdate()
{
UndoMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Undo"];
RedoMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Redo"];
SelectBetweenMarkersMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Sel. bet. Markers"];
SelectAllMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Select All"];
ReselectClipboardMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Reselect Clip."];
ClearFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clear Frames"];
DeleteFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Delete Frames"];
InsertFrameMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert Frame"];
InsertNumFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert # Frames"];
CloneFramesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clone Frames"];
CloneFramesXTimesMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clone # Times"];
SelectBetweenMarkersContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Sel. bet. Markers"];
ClearContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clear Frames"];
DeleteFramesContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Delete Frames"];
InsertFrameContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert Frame"];
InsertNumFramesContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Insert # Frames"];
CloneContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clone Frames"];
CloneXTimesContextMenuItem.ShortcutKeyDisplayString = Config.HotkeyBindings["Clone # Times"];
TasPlaybackBox.UpdateHotkeyTooltips(Config);
MarkerControl.UpdateHotkeyTooltips(Config);
}
private bool LoadMostRecentOrStartNew()
{
return LoadFileWithFallback(Settings.RecentTas.MostRecent);
}
private bool Engage()
{
_engaged = false;
MainForm.PauseOnFrame = null;
MainForm.PauseEmulator();
bool success = false;
// Nag if inaccurate core, but not if auto-loading or movie is already loaded
if (!CanAutoload && MovieSession.Movie.NotActive())
{
// Nag but allow the user to continue anyway, so ignore the return value
MainForm.EnsureCoreIsAccurate();
}
// Start Scenario 1: A regular movie is active
if (MovieSession.Movie.IsActive() && MovieSession.Movie is not ITasMovie)
{
var changesString = "Would you like to save the current movie before closing it?";
if (MovieSession.Movie.Changes)
{
changesString = "The current movie has unsaved changes. Would you like to save before closing it?";
}
var result = DialogController.ShowMessageBox3(
"TAStudio will create a new project file from the current movie.\n\n" + changesString,
"Convert movie",
EMsgBoxIcon.Question);
if (result == true)
{
MovieSession.Movie.Save();
}
else if (result == null)
{
return false;
}
var tasMovie = ConvertCurrentMovieToTasproj();
success = LoadMovie(tasMovie);
}
// Start Scenario 2: A tasproj is already active
else if (MovieSession.Movie.IsActive() && MovieSession.Movie is ITasMovie)
{
success = LoadMovie(CurrentTasMovie, gotoFrame: Emulator.Frame);
if (!success)
{
success = StartNewTasMovie();
}
}
// Start Scenario 3: No movie, but user wants to autoload their last project
else if (CanAutoload)
{
success = LoadMostRecentOrStartNew();
}
// Start Scenario 4: No movie, default behavior of engaging tastudio with a new default project
else
{
success = StartNewTasMovie();
}
// Attempts to load failed, abort
if (!success)
{
return false;
}
MainForm.AddOnScreenMessage("TAStudio engaged");
MainForm.DisableRewind();
MovieSession.ReadOnly = true;
SetSplicer();
_engaged = true;
return true;
}
private void AutosaveTimerEventProcessor(object sender, EventArgs e)
{
if (CurrentTasMovie == null)
{
return;
}
if (!CurrentTasMovie.Changes || Settings.AutosaveInterval == 0
|| CurrentTasMovie.Filename == DefaultTasProjName())
{
return;
}
if (Settings.AutosaveAsBackupFile)
{
if (Settings.AutosaveAsBk2)
{
SaveTas(saveAsBk2: true, saveBackup: true);
}
else
{
SaveTas(saveBackup: true);
}
}
else
{
if (Settings.AutosaveAsBk2)
{
SaveTas(saveAsBk2: true);
}
else
{
SaveTas();
}
}
}
private static readonly string[] N64CButtonSuffixes = { " C Up", " C Down", " C Left", " C Right" };
private void SetUpColumns()
{
TasView.AllColumns.Clear();
TasView.AllColumns.Add(new(name: CursorColumnName, widthUnscaled: 18, type: ColumnType.Boolean, text: string.Empty));
TasView.AllColumns.Add(new(name: FrameColumnName, widthUnscaled: 60, text: "Frame#")
{
Rotatable = true,
});
foreach ((string name, string mnemonic0, int maxLength) in MnemonicMap())
{
var mnemonic = Emulator.SystemId is VSystemID.Raw.N64 && N64CButtonSuffixes.Any(name.EndsWithOrdinal)
? $"c{mnemonic0.ToUpperInvariant()}" // prepend 'c' to differentiate from L/R buttons -- this only affects the column headers
: mnemonic0;
var type = ControllerType.Axes.ContainsKey(name) ? ColumnType.Axis : ColumnType.Boolean;
TasView.AllColumns.Add(new(
name: name,
verticalWidth: (Math.Max(maxLength, mnemonic.Length) * 6) + 14,
horizontalHeight: (maxLength * 6) + 14,
type: type,
text: mnemonic)
{
Rotatable = type is ColumnType.Axis,
});
}
var columnsToHide = TasView.AllColumns
.Where(c =>
// todo: make a proper user editable list?
c.Name == "Power"
|| c.Name == "Reset"
|| c.Name == "Light Sensor"
|| c.Name == "Disc Select"
|| c.Name == "Disk Index"
|| c.Name == "Next Drive"
|| c.Name == "Next Slot"
|| c.Name == "Insert Disk"
|| c.Name == "Eject Disk"
|| c.Name.StartsWithOrdinal("Tilt")
|| c.Name.StartsWithOrdinal("Key ")
|| c.Name.StartsWithOrdinal("Open")
|| c.Name.StartsWithOrdinal("Close")
|| c.Name.EndsWithOrdinal("Tape")
|| c.Name.EndsWithOrdinal("Disk")
|| c.Name.EndsWithOrdinal("Block")
|| c.Name.EndsWithOrdinal("Status"));
if (Emulator.SystemId is VSystemID.Raw.N64)
{
var fakeAnalogControls = TasView.AllColumns
.Where(c =>
c.Name.EndsWithOrdinal("A Up")
|| c.Name.EndsWithOrdinal("A Down")
|| c.Name.EndsWithOrdinal("A Left")
|| c.Name.EndsWithOrdinal("A Right"));
columnsToHide = columnsToHide.Concat(fakeAnalogControls);
}
else if (Emulator.SystemId is VSystemID.Raw.Doom)
{
var columns = TasView.AllColumns
.Where(c =>
c.Name.Contains("Forward")
|| c.Name.Contains("Backward")
|| c.Name.Contains("Automap")
|| c.Name.Contains("Camera")
|| c.Name.Contains("Gamma")
|| c.Name.Contains("Mouse")
|| c.Name.Contains("Weapon Select ")
|| c.Name.Contains("Turn ")
|| c.Name.Contains("Strafe")
|| c.Name.EndsWithOrdinal("Run"));
columnsToHide = columnsToHide.Concat(columns);
}
foreach (var column in columnsToHide)
{
column.Visible = false;
}
if (!TasView.AllColumns.Where(static c => c.Visible)
#if true
.CountIsAtLeast(2))
#else
.Select(static c => c.Name).Except([ CursorColumnName, FrameColumnName ]).Any())
#endif
{
// edge case: no columns are visible!
foreach (var c in TasView.AllColumns) c.Visible = true; // as a fallback, just show everything
}
foreach (var column in TasView.VisibleColumns)
{
if (InputManager.StickyHoldController.IsSticky(column.Name) || InputManager.StickyAutofireController.IsSticky(column.Name))
{
column.Emphasis = true;
}
}
TasView.AllColumns.ColumnsChanged();
}
private void SetupCustomPatterns()
{
// custom autofire patterns to allow configuring a unique pattern for each button or axis
BoolPatterns = new AutoPatternBool[ControllerType.BoolButtons.Count];
AxisPatterns = new AutoPatternAxis[ControllerType.Axes.Count];
for (int i = 0; i < BoolPatterns.Length; i++)
{
// standard 1 on 1 off autofire pattern
BoolPatterns[i] = new AutoPatternBool(1, 1);
}
for (int i = 0; i < AxisPatterns.Length; i++)
{
// autohold pattern with the maximum axis range as hold value (bit arbitrary)
var axisSpec = ControllerType.Axes[ControllerType.Axes[i]];
AxisPatterns[i] = new AutoPatternAxis([ axisSpec.Range.EndInclusive ]);
}
}
/// <remarks>for Lua</remarks>
public void AddColumn(string name, string text, int widthUnscaled)
=> TasView.AllColumns.Add(new(name: name, widthUnscaled: widthUnscaled, type: ColumnType.Text, text: text));
public void LoadBranchByIndex(int index) => BookMarkControl.LoadBranchExternal(index);
public void ClearFramesExternal()
=> ClearFramesMenuItem_Click(null, EventArgs.Empty);
public void InsertFrameExternal()
=> InsertFrameMenuItem_Click(null, EventArgs.Empty);
public void InsertNumFramesExternal()
=> InsertNumFramesMenuItem_Click(null, EventArgs.Empty);
public void DeleteFramesExternal()
=> DeleteFramesMenuItem_Click(null, EventArgs.Empty);
public void CloneFramesExternal()
=> CloneFramesMenuItem_Click(null, EventArgs.Empty);
public void CloneFramesXTimesExternal()
=> CloneFramesXTimesMenuItem_Click(null, EventArgs.Empty);
public void UndoExternal()
=> UndoMenuItem_Click(null, EventArgs.Empty);
public void RedoExternal()
=> RedoMenuItem_Click(null, EventArgs.Empty);
public void SelectBetweenMarkersExternal()
=> SelectBetweenMarkersMenuItem_Click(null, EventArgs.Empty);
public void SelectAllExternal()
=> SelectAllMenuItem_Click(null, EventArgs.Empty);
public void ReselectClipboardExternal()
=> ReselectClipboardMenuItem_Click(null, EventArgs.Empty);
public void SelectCurrentFrame()
{
TasView.DeselectAll();
TasView.SelectRow(Emulator.Frame, true);
RefreshDialog();
}
public IMovieController GetBranchInput(string branchId, int frame)
{
var branch = Guid.TryParseExact(branchId, format: "D", out var parsed)
? CurrentTasMovie.Branches.FirstOrDefault(b => b.Uuid == parsed)
: null;
if (branch == null || frame >= branch.InputLog.Count)
{
return null;
}
var controller = MovieSession.GenerateMovieController();
controller.SetFromMnemonic(branch.InputLog[frame]);
return controller;
}
private int? FirstNonEmptySelectedFrame
{
get
{
var empty = Bk2LogEntryGenerator.EmptyEntry(MovieSession.MovieController);
foreach (var row in TasView.SelectedRows)
{
if (CurrentTasMovie[row].LogEntry != empty)
{
return row;
}
}
return null;
}
}
private ITasMovie ConvertCurrentMovieToTasproj()
{
var tasMovie = MovieSession.Movie.ToTasMovie();
tasMovie.Save(); // should this be done?
return tasMovie;
}
private bool LoadMovie(ITasMovie tasMovie, bool startsFromSavestate = false, int gotoFrame = 0)
{
_engaged = false;
if (!StartNewMovieWrapper(tasMovie, isNew: false))
{
return false;
}
_engaged = true;
Settings.RecentTas.Add(CurrentTasMovie.Filename); // only add if it did load
if (startsFromSavestate)
{
GoToFrame(0);
}
else if (gotoFrame > 0)
{
GoToFrame(gotoFrame);
}
else
{
GoToFrame(CurrentTasMovie.TasSession.CurrentFrame);
}
// clear all selections
TasView.DeselectAll();
BookMarkControl.Restart();
MarkerControl.Restart();
RefreshDialog();
return true;
}
private bool StartNewTasMovie()
{
if (!AskSaveChanges())
{
return false;
}
if (Game.IsNullInstance()) throw new InvalidOperationException("how is TAStudio open with no game loaded? please report this including as much detail as possible");
var filename = DefaultTasProjName(); // TODO don't do this, take over any mainform actions that can crash without a filename
var tasMovie = (ITasMovie)MovieSession.Get(filename);
tasMovie.Author = Config.DefaultAuthor;
bool success = StartNewMovieWrapper(tasMovie, isNew: true);
if (success)
{
// clear all selections
TasView.DeselectAll();
BookMarkControl.Restart();
MarkerControl.Restart();
RefreshDialog();
}
return success;
}
private bool StartNewMovieWrapper(ITasMovie movie, bool isNew)
{
_initializing = true;
movie.InputRollSettingsForSave = () => TasView.UserSettingsSerialized();
movie.BindMarkersToInput = Settings.BindMarkersToInput;
movie.GreenzoneInvalidated = (f) => _ = FrameEdited(f);
movie.ChangeLog.MaxSteps = Settings.MaxUndoSteps;
movie.PropertyChanged += TasMovie_OnPropertyChanged;
System.Collections.Specialized.NotifyCollectionChangedEventHandler refreshOnMarker = (_, _) => RefreshDialog();
movie.Markers.CollectionChanged += refreshOnMarker;
this.Disposed += (s, e) =>
{
movie.PropertyChanged -= TasMovie_OnPropertyChanged;
movie.Markers.CollectionChanged -= refreshOnMarker;
};
SuspendLayout();
WantsToControlStopMovie = false;
bool result = ReferenceEquals(CurrentTasMovie, movie) || MainForm.StartNewMovie(movie, isNew);
WantsToControlStopMovie = true;
ResumeLayout();
if (result)
{
// Initialize stuff.
RestorePositionFrame = -1;
_lastRecordAction = -1;
_doPause = false;
StopSeeking();
BookMarkControl.UpdateTextColumnWidth();
MarkerControl.UpdateTextColumnWidth();
TastudioPlayMode();
UpdateWindowTitle();
if (CurrentTasMovie.InputRollSettings != null)
{
TasView.LoadSettingsSerialized(CurrentTasMovie.InputRollSettings);
}
else
{
SetUpColumns();
}
SetUpToolStripColumns();
SetupCustomPatterns();
UpdateAutoFire();
}
_initializing = false;
return result;
}
private void DummyLoadProject(string path)
{
if (AskSaveChanges())
{
LoadFileWithFallback(path);
}
}
private bool LoadFileWithFallback(string path)
{
bool movieLoadSucceeded = false;
if (!File.Exists(path))
{
Settings.RecentTas.HandleLoadError(MainForm, path);
}
else
{
var movie = MovieSession.Get(path, loadMovie: true);
var tasMovie = movie as ITasMovie ?? movie.ToTasMovie();
movieLoadSucceeded = LoadMovie(tasMovie);
}
if (!movieLoadSucceeded)
{
movieLoadSucceeded = StartNewTasMovie();
_engaged = true;
}
return movieLoadSucceeded;
}
private void DummyLoadMacro(string path)
{
if (!TasView.AnyRowsSelected)
{
return;
}
var loadZone = new MovieZone(path, MainForm, Emulator, MovieSession, Tools)
{
Start = TasView.SelectionStartIndex!.Value,
};
loadZone.PlaceZone(CurrentTasMovie, Config);
}
private void TastudioToggleReadOnly()
{
TasPlaybackBox.RecordingMode = !TasPlaybackBox.RecordingMode;
WasRecording = TasPlaybackBox.RecordingMode; // hard reset at manual click and hotkey
}
private void TastudioPlayMode(bool resetWasRecording = false)
{
TasPlaybackBox.RecordingMode = false;
// once user started editing, rec mode is unsafe
if (resetWasRecording)
{
WasRecording = TasPlaybackBox.RecordingMode;
}
}
private void TastudioRecordMode(bool resetWasRecording = false)
{
TasPlaybackBox.RecordingMode = true;
if (resetWasRecording)
{
WasRecording = TasPlaybackBox.RecordingMode;
}
}
private void TastudioStopMovie()
{
MovieSession.StopMovie(false);
MainForm.SetMainformMovieInfo();
}
private void Disengage()
{
_engaged = false;
MainForm.PauseOnFrame = null;
MainForm.AddOnScreenMessage("TAStudio disengaged");
WantsToControlRewind = false;
MainForm.EnableRewind(true);
}
private const string DefaultTasProjectName = "default";
// Used when starting a new project
private string DefaultTasProjName()
{
return Path.Combine(
Config.PathEntries.MovieAbsolutePath(),
$"{DefaultTasProjectName}.{MovieService.TasMovieExtension}");
}
// Used for things like SaveFile dialogs to suggest a name to the user
private string SuggestedTasProjName()
{
return Path.Combine(
Config.PathEntries.MovieAbsolutePath(),
$"{Game.FilesystemSafeName()}.{MovieService.TasMovieExtension}");
}
private void SaveTas(bool saveAsBk2 = false, bool saveBackup = false)
{
if (string.IsNullOrEmpty(CurrentTasMovie.Filename) || CurrentTasMovie.Filename == DefaultTasProjName())
{
SaveAsTas();
return;
}
_autosaveTimer.Stop();
MessageStatusLabel.Text = saveBackup
? "Saving backup..."
: "Saving...";
MessageStatusLabel.Owner.Update();
Cursor = Cursors.WaitCursor;
IMovie movieToSave = CurrentTasMovie;
if (saveAsBk2)
{
movieToSave = CurrentTasMovie.ToBk2();
movieToSave.Attach(Emulator);
}
if (saveBackup)
movieToSave.SaveBackup();
else
movieToSave.Save();
MessageStatusLabel.Text = saveBackup
? $"Backup .{(saveAsBk2 ? MovieService.StandardMovieExtension : MovieService.TasMovieExtension)} saved to \"Movie backups\" path."
: "File saved.";
Cursor = Cursors.Default;
if (Settings.AutosaveInterval > 0)
{
_autosaveTimer.Start();
}
}
private void SaveAsTas()
{
_autosaveTimer.Stop();
var filename = CurrentTasMovie.Filename;
if (string.IsNullOrWhiteSpace(filename) || filename == DefaultTasProjName())
{
filename = SuggestedTasProjName();
}
var fileInfo = SaveFileDialog(
currentFile: filename,
path: Config!.PathEntries.MovieAbsolutePath(),
TAStudioProjectsFSFilterSet,
this);
if (fileInfo != null)
{
MessageStatusLabel.Text = "Saving...";
MessageStatusLabel.Owner.Update();
Cursor = Cursors.WaitCursor;
CurrentTasMovie.Filename = fileInfo.FullName;
CurrentTasMovie.Save();
Settings.RecentTas.Add(CurrentTasMovie.Filename);
MessageStatusLabel.Text = "File saved.";
Cursor = Cursors.Default;
}
if (Settings.AutosaveInterval > 0)
{
_autosaveTimer.Start();
}
UpdateWindowTitle(); // changing the movie's filename does not flag changes, so we need to ensure the window title is always updated
MainForm.UpdateWindowTitle();
}
protected override string WindowTitle
=> CurrentTasMovie == null
? "TAStudio"
: CurrentTasMovie.Changes
? $"TAStudio - {CurrentTasMovie.Name}*"
: $"TAStudio - {CurrentTasMovie.Name}";
protected override string WindowTitleStatic => "TAStudio";
public IEnumerable<int> GetSelection() => TasView.SelectedRows;
public void RefreshDialog(bool refreshTasView = true, bool refreshBranches = true)
{
if (_exiting)
{
return;
}
if (refreshTasView)
{
SetTasViewRowCount();
}
MarkerControl?.UpdateValues();
if (refreshBranches)
{
BookMarkControl?.UpdateValues();
}
if (_undoForm != null && !_undoForm.IsDisposed)
{
_undoForm.UpdateValues();
}
}
private void SetTasViewRowCount()
{
TasView.RowCount = CurrentTasMovie.InputLogLength + 1;
_lastRefresh = Emulator.Frame;
}
/// <summary>
/// Get a savestate prior to the previous frame so code following the call can frame advance and have a framebuffer.
/// If frame is 0, return the initial state.
/// </summary>
private KeyValuePair<int,Stream> GetPriorStateForFramebuffer(int frame)
{
return CurrentTasMovie.TasStateManager.GetStateClosestToFrame(frame > 0 ? frame - 1 : 0);
}
public void LoadState(KeyValuePair<int, Stream> state, bool discardApiHawkSurfaces = false)
{
StatableEmulator.LoadStateBinary(new BinaryReader(state.Value));
if (state.Key == 0 && CurrentTasMovie.StartsFromSavestate)
{
Emulator.ResetCounters();
}
UpdateTools();
if (discardApiHawkSurfaces)
{
DisplayManager.DiscardApiHawkSurfaces();
}
}
public void AddBranchExternal() => BookMarkControl.AddBranchExternal();
public void RemoveBranchExternal() => BookMarkControl.RemoveBranchExternal();
private void UpdateTools()
{
Tools.UpdateToolsAfter();
}
public void TogglePause()
{
MainForm.TogglePause();
}
public override void OnPauseToggle(bool newPauseState)
{
// On pause, interrupt merging of recorded frames.
if (newPauseState) _lastRecordAction = -1;
}
private void SetSplicer()
{
// TODO: columns selected?
var selectedRowCount = TasView.SelectedRows.Count();
var temp = $"Selected: {selectedRowCount} {(selectedRowCount == 1 ? "frame" : "frames")}, States: {CurrentTasMovie.TasStateManager.Count}";
var clipboardCount = _tasClipboard.Count;
if (clipboardCount is not 0) temp += $", Clipboard: {clipboardCount} {(clipboardCount is 1 ? "frame" : "frames")}";
SplicerStatusLabel.Text = temp;
}
private void Tastudio_Closing(object sender, FormClosingEventArgs e)
{
if (!_initialized)
{
return;
}
_exiting = true;
if (AskSaveChanges())
{
WantsToControlStopMovie = false;
TastudioStopMovie();
Disengage();
}
else
{
e.Cancel = true;
_exiting = false;
}
_undoForm?.Close();
}
/// <summary>
/// This method is called every time the Changes property is toggled on a <see cref="TasMovie"/> instance.
/// </summary>
private void TasMovie_OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
UpdateWindowTitle();
}