-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
GraphEditor.cs
900 lines (743 loc) · 27 KB
/
GraphEditor.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using Godot;
using GodotExt;
using JetBrains.Annotations;
using OpenScadGraphEditor.Actions;
using OpenScadGraphEditor.History;
using OpenScadGraphEditor.Library;
using OpenScadGraphEditor.Library.External;
using OpenScadGraphEditor.Library.IO;
using OpenScadGraphEditor.Nodes;
using OpenScadGraphEditor.Refactorings;
using OpenScadGraphEditor.Utils;
using OpenScadGraphEditor.Widgets;
using OpenScadGraphEditor.Widgets.AddDialog;
using OpenScadGraphEditor.Widgets.CommentEditingDialog;
using OpenScadGraphEditor.Widgets.DocumentationDialog;
using OpenScadGraphEditor.Widgets.EditingInterface;
using OpenScadGraphEditor.Widgets.HelpDialog;
using OpenScadGraphEditor.Widgets.IconButton;
using OpenScadGraphEditor.Widgets.ImportDialog;
using OpenScadGraphEditor.Widgets.InvokableRefactorDialog;
using OpenScadGraphEditor.Widgets.LogConsole;
using OpenScadGraphEditor.Widgets.NodeColorDialog;
using OpenScadGraphEditor.Widgets.ProjectTree;
using OpenScadGraphEditor.Widgets.SettingsDialog;
using OpenScadGraphEditor.Widgets.StylusDebugDialog;
using OpenScadGraphEditor.Widgets.UsageDialog;
using OpenScadGraphEditor.Widgets.VariableCustomizer;
using OpenScadGraphEditor.Widgets.VariableRefactorDialog;
using Serilog;
namespace OpenScadGraphEditor
{
[UsedImplicitly]
public class GraphEditor : Control, IEditorContext
{
private AddDialog _addDialog;
private QuickActionsPopup _quickActionsPopup;
private TextEdit _textEdit;
private FileDialog _fileDialog;
private ProjectTree _projectTree;
private ImportDialog _importDialog;
private IconButton _undoButton;
private IconButton _redoButton;
private string _currentFile;
private bool _dirty;
private Button _forceSaveButton;
private Label _fileNameLabel;
private TabContainer _tabContainer;
private HistoryStack _currentHistoryStack;
private BuiltInLibrary _rootResolver;
private InvokableRefactorDialog _invokableRefactorDialog;
private VariableRefactorDialog _variableRefactorDialog;
private NodeColorDialog _nodeColorDialog;
private CommentEditingDialog _commentEditingDialog;
private StylusDebugDialog _stylusDebugDialog;
private SettingsDialog _settingsDialog;
private HelpDialog _helpDialog;
private UsageDialog _usageDialog;
private DocumentationDialog _documentationDialog;
private readonly List<IAddDialogEntry> _addDialogEntries = new List<IAddDialogEntry>();
private Foldout _leftFoldout;
private VariableCustomizer _variableCustomizer;
private SplitContainer _editingInterface;
private readonly List<IAddDialogEntryFactory> _addDialogEntryFactories =
typeof(IAddDialogEntryFactory)
.GetImplementors()
.CreateInstances<IAddDialogEntryFactory>()
.ToList();
private readonly List<IEditorAction> _editorActions =
typeof(IEditorActionFactory)
.GetImplementors()
.CreateInstances<IEditorActionFactory>()
.SelectMany(it => it.CreateActions())
.ToList();
private ScadGraph _copyBuffer;
private LogConsole _logConsole;
private Foldout _lowerFoldout;
private bool _codeChanged;
private bool _refactoringInProgress;
private readonly Dictionary<string, EditingInterface> _openEditors = new Dictionary<string, EditingInterface>();
private IconButton _openOpenScadButton;
public ScadProject CurrentProject { get; private set; }
public Configuration Configuration { get; } = new Configuration();
public override void _Ready()
{
_logConsole = this.WithName<LogConsole>("LogConsole");
_lowerFoldout = this.WithName<Foldout>("LowerFoldout");
var logFile = OS.GetUserDataDir() + "/log.txt";
OS.SetWindowTitle($"OpenSCAD Graph Editor ({AppVersion.Version})");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.File(logFile, rollingInterval: RollingInterval.Day, retainedFileCountLimit: 5)
.WriteTo.Sink(_logConsole)
.CreateLogger();
GD.Print("OpenSCAD log file is: " + logFile);
Log.Information("Initializing OpenScad Graph Editor");
OS.LowProcessorUsageMode = true;
_logConsole.OpenLogFileRequested += () => OS.ShellOpen(logFile);
Configuration.Load();
// scale all themes to editor scale
var percent = Configuration.GetEditorScalePercent();
foreach (var theme in Resources.AllThemes)
{
theme.Scale(percent);
}
_rootResolver = new BuiltInLibrary();
_tabContainer = this.WithName<TabContainer>("TabContainer");
_tabContainer
.Connect("tab_changed")
.To(this, nameof(OnTabChanged));
_addDialog = this.WithName<AddDialog>("AddDialog");
_quickActionsPopup = this.WithName<QuickActionsPopup>("QuickActionsPopup");
_importDialog = this.WithName<ImportDialog>("ImportDialog");
_importDialog.OnNewImportRequested += OnNewImportRequested;
_importDialog.OnUpdateImportRequested += OnUpdateImportRequested;
_usageDialog = this.WithName<UsageDialog>("UsageDialog");
_usageDialog.NodeHighlightRequested += OnNodeHighlightRequested;
_settingsDialog = this.WithName<SettingsDialog>("SettingsDialog");
_stylusDebugDialog = this.WithName<StylusDebugDialog>("StylusDebugDialog");
_helpDialog = this.WithName<HelpDialog>("HelpDialog");
_commentEditingDialog = this.WithName<CommentEditingDialog>("CommentEditingDialog");
_nodeColorDialog = this.WithName<NodeColorDialog>("NodeColorDialog");
_invokableRefactorDialog = this.WithName<InvokableRefactorDialog>("InvokableRefactorDialog");
_documentationDialog = this.WithName<DocumentationDialog>("DocumentationDialog");
_variableRefactorDialog = this.WithName<VariableRefactorDialog>("VariableRefactorDialog");
_editingInterface = this.WithName<SplitContainer>("EditingInterface");
_textEdit = this.WithName<TextEdit>("TextEdit");
_fileDialog = this.WithName<FileDialog>("FileDialog");
_fileNameLabel = this.WithName<Label>("FileNameLabel");
_forceSaveButton = this.WithName<Button>("ForceSaveButton");
_forceSaveButton.Connect("pressed")
.To(this, nameof(SaveChanges));
_projectTree = this.WithName<ProjectTree>("ProjectTree");
_projectTree.ItemActivated += Open;
_projectTree.ItemContextMenuRequested += OnItemContextMenuRequested;
_undoButton = this.WithName<IconButton>("UndoButton");
_undoButton.ButtonPressed += Undo;
_redoButton = this.WithName<IconButton>("RedoButton");
_redoButton.ButtonPressed += Redo;
this.WithName<IconButton>("AddExternalReferenceButton")
.ButtonPressed += OnImportScadFile;
this.WithName<Button>("NewButton")
.Connect("pressed")
.To(this, nameof(OnNewButtonPressed));
this.WithName<Button>("PreviewButton")
.Connect("toggled")
.To(this, nameof(OnPreviewToggled));
this.WithName<Button>("SettingsButton")
.Connect("pressed")
.To(this, nameof(OnSettingsButtonPressed));
_openOpenScadButton = this.WithName<IconButton>("OpenOpenScadButton");
_openOpenScadButton
.ButtonPressed += OnOpenOpenScadButtonPressed;
var openButton = this.WithName<OpenButton>("OpenButton");
openButton.OpenFileRequested += OnOpenFile;
openButton.OpenFileDialogRequested += OnOpenFileDialogRequested;
openButton.Init(Configuration);
_leftFoldout = this.WithName<Foldout>("LeftFoldout");
_leftFoldout.OnFoldoutChanged += (visible) => { _editingInterface.Collapsed = !visible; };
_variableCustomizer = this.WithName<VariableCustomizer>("VariableCustomizer");
this.WithName<Button>("SaveAsButton")
.Connect("pressed")
.To(this, nameof(OnSaveAsPressed));
this.WithName<IconButton>("AddModuleButton")
.ButtonPressed += OnAddModulePressed;
this.WithName<IconButton>("AddFunctionButton")
.ButtonPressed += OnAddFunctionPressed;
this.WithName<IconButton>("AddVariableButton")
.ButtonPressed += OnAddVariablePressed;
MarkDirty(true);
this.WithName<Timer>("Timer")
.Connect("timeout")
.To(this, nameof(SaveChanges));
_copyBuffer = new ScadGraph();
OnNewButtonPressed();
NotificationService.ShowNotification("Welcome to OpenScad Graph Editor");
}
private void OnOpenOpenScadButtonPressed()
{
var path = Configuration.GetOpenScadPath();
if (path.Empty())
{
NotificationService.ShowNotification("OpenSCAD path not set. Please set it in the settings dialog.");
return;
}
NotificationService.ShowNotification("Opening OpenSCAD. Please wait a few seconds for it to open.");
// ReSharper disable once StringLiteralTypo
OS.Execute(path, new[] {"--viewall", _currentFile + ".scad"}, blocking: false);
}
private void OnSettingsButtonPressed()
{
_settingsDialog.Open(this);
}
private void OnTabChanged(int index)
{
var editor = _tabContainer.GetChild<EditingInterface>(index);
if (editor.Graph != null)
{
// re-paint
editor.Render(editor.Graph);
}
}
private void OnNodeHighlightRequested(UsagePointInformation information)
{
var graph = CurrentProject.AllDeclaredInvokables.FirstOrDefault(it =>
it.Description.Id == information.GraphId);
var node = graph?.GetAllNodes().FirstOrDefault(it => it.Id == information.NodeId);
if (node != null)
{
var edit = Open(graph);
edit.FocusNode(node);
return;
}
NotificationService.ShowNotification("This usage no longer exists");
}
private void OnNewImportRequested(string path, IncludeMode includeMode)
{
PerformRefactoring($"Add reference to {path}",
new AddOrUpdateExternalReferenceRefactoring(path, includeMode));
}
private void OnUpdateImportRequested(ExternalReference reference, string path, IncludeMode includeMode)
{
PerformRefactoring($"Update reference to {path}",
new AddOrUpdateExternalReferenceRefactoring(path, includeMode, reference));
}
private void OnItemContextMenuRequested(ProjectTreeEntry entry, Vector2 mousePosition)
{
var requestContext = entry switch
{
ScadInvokableTreeEntry invokableTreeEntry => RequestContext.ForInvokableDescription(invokableTreeEntry.Description),
ExternalReferenceTreeEntry externalReferenceTreeEntry => RequestContext.ForExternalReference(externalReferenceTreeEntry.Description),
ScadVariableTreeEntry variableTreeEntry => RequestContext.ForVariableDescription(variableTreeEntry.Description),
_ => default
};
if (requestContext.IsEmpty)
{
return;
}
ShowPopupMenu(requestContext);
}
/// <summary>
/// Called when an entry is double clicked in the project tree.
/// </summary>
private void Open(ProjectTreeEntry entry)
{
if (entry is ScadInvokableTreeEntry invokableTreeEntry
&& CurrentProject.IsDefinedInThisProject(invokableTreeEntry.Description))
{
OpenGraph(invokableTreeEntry.Description);
}
if (entry is ScadVariableTreeEntry variableTreeEntry
&& CurrentProject.IsDefinedInThisProject(variableTreeEntry.Description))
{
OpenRefactorDialog(variableTreeEntry.Description);
}
if (entry is ExternalReferenceTreeEntry externalReferenceTreeEntry &&
// we dont want to open the import dialog for transitive imports
!externalReferenceTreeEntry.Description.IsTransitive)
{
OpenRefactorDialog(externalReferenceTreeEntry.Description);
}
}
private void Clear()
{
CurrentProject = null;
_currentHistoryStack = null;
_currentFile = null;
_fileNameLabel.Text = "<not yet saved to a file>";
_tabContainer.GetChildNodes<EditingInterface>().ForAll(it => it.RemoveAndFree());
_openEditors.Clear();
_projectTree.Clear();
_openOpenScadButton.Disabled = true;
_openOpenScadButton.HintTooltip = "(disabled) save project to enable";
}
private void RefreshControls()
{
_undoButton.Disabled = !_currentHistoryStack.CanUndo(out var undoDescription);
_undoButton.HintTooltip = $"Undo : {undoDescription}";
_redoButton.Disabled = !_currentHistoryStack.CanRedo(out var redoDescription);
_redoButton.HintTooltip = $"Redo : {redoDescription}";
_projectTree.Setup(new List<ProjectTreeEntry>() {new RootProjectTreeEntry(CurrentProject)});
_variableCustomizer.Setup(this, CurrentProject.Variables.ToList());
// Re-Build the list of entries for the add dialog.
_addDialogEntries.Clear();
_addDialogEntries.AddRange(
_addDialogEntryFactories.SelectMany(it => it.BuildEntries(this))
);
}
private void Undo()
{
GdAssert.That(_currentHistoryStack.CanUndo(out _), "Cannot undo");
var editorState = _currentHistoryStack.Undo(CurrentProject);
RestoreEditorState(editorState);
MarkDirty(true);
}
private void Redo()
{
GdAssert.That(_currentHistoryStack.CanRedo(out _), "Cannot redo");
var editorState = _currentHistoryStack.Redo(CurrentProject);
RestoreEditorState(editorState);
MarkDirty(true);
}
private void OnImportScadFile()
{
_importDialog.OpenForNewImport(_currentFile);
}
private EditingInterface Open(ScadGraph toOpen)
{
// check if it is already open
if (_openEditors.TryGetValue(toOpen.Description.Id, out var existingEditor))
{
_tabContainer.CurrentTab = existingEditor.GetIndex();
existingEditor.Render(toOpen);
return existingEditor;
}
// if not, open a new tab
var editor = Prefabs.InstantiateFromScene<EditingInterface>();
editor.Init(this);
editor.Name = toOpen.Description.Id;
editor.MoveToNewParent(_tabContainer);
editor.Render( toOpen);
_openEditors[toOpen.Description.Id] = editor;
_tabContainer.CurrentTab = _tabContainer.GetChildCount() - 1;
_tabContainer.SetTabTitle(_tabContainer.CurrentTab, toOpen.Description.NodeNameOrFallback);
if (toOpen.TryGetEntryPoint(out var entryPoint))
{
editor.FocusNode(entryPoint);
}
return editor;
}
private void Close(EditingInterface editor)
{
_openEditors.Remove(editor.Graph.Description.Id);
editor.RemoveAndFree();
}
private void OnAddFunctionPressed()
{
_invokableRefactorDialog.OpenForNewFunction(this);
}
private void OnAddVariablePressed()
{
_variableRefactorDialog.OpenForNewVariable(this);
}
private void OnAddModulePressed()
{
_invokableRefactorDialog.OpenForNewModule(this);
}
public RefactoringData PerformRefactorings(string description, IEnumerable<Refactoring> refactorings)
{
try
{
GdAssert.That(!_refactoringInProgress,
"Cannot run a refactoring while a refactoring is running. Probably some UI throws events when internal state is updated.");
_refactoringInProgress = true;
Log.Debug(">> Refactorings start");
var top = _currentHistoryStack.Peek();
var currentEditorState = GetEditorState();
// the editor state could be different from how it was when we finished the previous refactoring (e.g tab changed or
// the editor was moved). we therefore patch the new editor state onto the top of the stack.
// so we can return to that state once we undo this refactoring. This way we fix a problem that
// when you open a new tab, and move a node there, then undo that the new tab is closed.
// it is important to patch this _before_ we do the refactoring otherwise we may refer to
// data that is no longer there after the refactoring.
top.PatchEditorState(currentEditorState);
var context = new RefactoringContext(CurrentProject);
context.PerformRefactorings(refactorings);
// close all tabs referring to graphs which are no longer in the project
_tabContainer.GetChildNodes<EditingInterface>()
.Where(it => !CurrentProject.IsDefinedInThisProject(it.Graph.Description))
.ToList()
.ForAll(Close);
if (_tabContainer.CurrentTab >= _tabContainer.GetTabCount())
{
// open the left most tab
_tabContainer.CurrentTab = 0;
}
for (var i = 0; i < _tabContainer.GetTabCount(); i++)
{
var editingInterface = (EditingInterface) _tabContainer.GetTabControl(i);
// update the graph renderings.
editingInterface.Render( editingInterface.Graph);
// and update the tab title as it might have changed.
_tabContainer.SetTabTitle(i, editingInterface.Graph.Description.NodeNameOrFallback);
}
// important, the snapshot must be made _after_ the changes.
_currentHistoryStack.AddSnapshot(description, CurrentProject, GetEditorState());
RefreshControls();
MarkDirty(true);
_refactoringInProgress = false;
Log.Debug("<< Refactorings end");
return context.Data;
}
catch (Exception e)
{
NotificationService.ShowError(
"Unexpected exception occurred. Trying to run an undo to restore a known working state. See console for details.");
Log.Error(e, "Unexpected exception");
if (_currentHistoryStack.CanUndo(out _))
{
Undo();
}
else
{
NotificationService.ShowError("Undo failed. Please restart the application.");
}
// if we get an exception, we return an empty refactoring data, so the caller doesn't need to
// check for null.
return new RefactoringData();
}
}
private void OnNewButtonPressed()
{
Clear();
CurrentProject = new ScadProject(_rootResolver)
{
Preamble = Configuration.GetDefaultPreamble()
};
Open(CurrentProject.MainModule);
// important, this needs to be done after the main module is opened, so we get correct editor state
_currentHistoryStack = new HistoryStack(CurrentProject, GetEditorState());
RefreshControls();
RenderScadOutput();
}
private EditorState GetEditorState()
{
// create a list of currently open tabs
// order is important here, so we get the child order from the _tabContainer rather than using
// _openEditors
var tabs = _tabContainer.GetChildNodes<EditingInterface>()
.Select(it => new EditorOpenTab(it.Graph.Description.Id, it.ScrollOffset)).ToList();
return new EditorState(tabs, _tabContainer.CurrentTab);
}
private void RestoreEditorState(EditorState editorState)
{
// close all open tabs
foreach (var tab in _openEditors.Values.ToList())
{
Close(tab);
}
// open all tabs that were open back then
foreach (var openTab in editorState.OpenTabs)
{
var invokableId = openTab.InvokableId;
var invokable = CurrentProject.AllDeclaredInvokables.First(it => it.Description.Id == invokableId);
var editor = Open(invokable);
editor.ScrollOffset = openTab.ScrollOffset;
}
// and finally select the tab that was selected
_tabContainer.CurrentTab = editorState.CurrentTabIndex;
RefreshControls();
}
private void OnOpenFileDialogRequested()
{
_fileDialog.Mode = FileDialog.ModeEnum.OpenFile;
_fileDialog.PopupCentered();
_fileDialog.Connect("file_selected")
.WithFlags(ConnectFlags.Oneshot)
.To(this, nameof(OnOpenFile));
}
private void OnOpenFile(string filename)
{
var file = new File();
if (!file.FileExists(filename))
{
NotificationService.ShowError($"File {filename} does not exist anymore.");
return;
}
// set the directory of the file the current directory in the file open dialog
_fileDialog.CurrentDir = PathResolver.GetDirectoryFromFile(filename);
var savedProject = ResourceLoader.Load<SavedProject>(filename, "", noCache: true);
if (savedProject == null)
{
NotificationService.ShowError("Cannot load file " + filename);
return;
}
// make backup
FileBackups.BackupFile(filename, Configuration.GetNumberOfBackups());
// workaround for https://github.com/godotengine/godot/issues/59686
// as the "noCache" flag currently isn't working properly
savedProject.ResourcePath = "";
Clear();
_currentFile = filename;
Configuration.AddRecentFile(filename);
_fileNameLabel.Text = filename;
_openOpenScadButton.Disabled = false;
_openOpenScadButton.HintTooltip = "";
CurrentProject = new ScadProject(_rootResolver);
try
{
CurrentProject.Load(savedProject, _currentFile);
}
catch (Exception e)
{
NotificationService.ShowError("Error when loading file. See log for details.");
Log.Error(e, "Exception when loading file {File}", _currentFile);
// don't load a half-broken file
OnNewButtonPressed();
return;
}
Open(CurrentProject.MainModule);
// again, important, must be done after the main module is opened
_currentHistoryStack = new HistoryStack(CurrentProject, GetEditorState());
RefreshControls();
RenderScadOutput();
}
private void OnSaveAsPressed()
{
_fileDialog.Mode = FileDialog.ModeEnum.SaveFile;
_fileDialog.PopupCentered();
_fileDialog.Connect("file_selected")
.WithFlags(ConnectFlags.Oneshot)
.To(this, nameof(OnSaveFileSelected));
}
private void OnSaveFileSelected(string filename)
{
_currentFile = filename;
Configuration.AddRecentFile(filename);
_fileNameLabel.Text = filename;
_openOpenScadButton.Disabled = false;
_openOpenScadButton.HintTooltip = "";
// repaint all open graphs as the file name is now known and this enables relative paths
// in node path references
for (var i = 0; i < _tabContainer.GetTabCount(); i++)
{
var editingInterface = (EditingInterface) _tabContainer.GetTabControl(i);
// update the graph renderings.
editingInterface.Render( editingInterface.Graph);
}
MarkDirty(true);
}
private void OnPreviewToggled(bool preview)
{
_editingInterface.Visible = !preview;
_textEdit.Visible = preview;
}
private void MarkDirty(bool codeChange)
{
_dirty = true;
_codeChanged = codeChange;
_forceSaveButton.Text = _codeChanged ? "[.!.]" : "[...]";
}
private void SaveChanges()
{
if (!_dirty)
{
return;
}
if (_codeChanged)
{
RenderScadOutput();
}
if (_currentFile != null)
{
// save resource
var savedProject = CurrentProject.Save();
var error = ResourceSaver.Save(_currentFile, savedProject);
if (error != Error.Ok)
{
NotificationService.ShowNotification("Cannot save project, see log for details");
Log.Warning("Unable to save project to {File} -> Error {Error}", _currentFile, error);
}
else
{
Log.Information("Saved project");
}
}
_forceSaveButton.Text = "[OK]";
_dirty = false;
}
private void RenderScadOutput()
{
var rendered = CurrentProject.Render();
_textEdit.Text = rendered;
if (_currentFile != null)
{
// save rendered output
var file = new File();
var outputPath = _currentFile + ".scad";
var error = file.Open(outputPath, File.ModeFlags.Write);
if (error == Error.Ok)
{
file.StoreString(rendered);
file.Close();
}
else
{
NotificationService.ShowError("Cannot save SCAD file, see log for details");
Log.Warning("Unable to save SCAD output file to {File} -> Error {Error}", outputPath, error);
}
}
}
public override void _Input(InputEvent evt)
{
if (evt.IsUndo() && _currentHistoryStack.CanUndo(out _))
{
Undo();
}
if (evt.IsRedo() && _currentHistoryStack.CanRedo(out _))
{
Redo();
}
if (evt.IsStylusDebug())
{
_stylusDebugDialog.Show();
}
}
public void FindAndShowUsages(VariableDescription variableDescription)
{
var usagePoints = CurrentProject.FindAllReferencingNodes(variableDescription)
.Select(it => new UsagePointInformation($"{it.Node.NodeTitle} in ({it.Graph.Description.Name})",
it.Graph.Description.Id, it.Node.Id))
.ToList();
if (usagePoints.Count == 0)
{
NotificationService.ShowNotification("No usages found.");
return;
}
_usageDialog.Open($"Usages of variable {variableDescription.Name}", usagePoints);
_lowerFoldout.ShowChild(_usageDialog);
}
public void FindAndShowUsages(InvokableDescription invokableDescription)
{
var usagePoints = CurrentProject.FindAllReferencingNodes(invokableDescription)
.Select(it => new UsagePointInformation($"{it.Node.NodeTitle} in ({it.Graph.Description.Name})",
it.Graph.Description.Id, it.Node.Id))
.ToList();
if (usagePoints.Count == 0)
{
NotificationService.ShowNotification("No usages found.");
return;
}
var type = invokableDescription is FunctionDescription ? "function" : "module";
_usageDialog.Open($"Usages of {type} {invokableDescription.Name}", usagePoints);
_lowerFoldout.ShowChild(_usageDialog);
}
public override void _Notification(int what)
{
if (what == NotificationWmAbout)
{
// OSX about menu.
NotificationService.ShowNotification($"This is OpenSCAD Graph Editor ({AppVersion.Version}");
}
}
public void OpenRefactorDialog(InvokableDescription invokableDescription)
{
_invokableRefactorDialog.OpenForEditing(this, invokableDescription);
}
public void OpenRefactorDialog(VariableDescription variableDescription)
{
_variableRefactorDialog.Open(this, variableDescription);
}
public void OpenRefactorDialog(ExternalReference externalReference)
{
_importDialog.OpenForExistingImport(externalReference, CurrentProject.ProjectPath);
}
public void OpenDocumentationDialog(InvokableDescription invokableDescription)
{
_documentationDialog.Open(this, invokableDescription);
}
public RefactoringData PerformRefactoring(string description, Refactoring refactoring)
{
return PerformRefactorings(description, new []{refactoring});
}
public void OpenGraph(InvokableDescription invokableDescription)
{
Open(CurrentProject.FindDefiningGraph(invokableDescription));
}
public void EditComment(ScadGraph graph, ScadNode node) {
_commentEditingDialog.Open(this, graph, node);
}
public void EditNodeColor(ScadGraph graph, ScadNode node)
{
_nodeColorDialog.Open(this, graph, node);
}
public void ShowHelp(ScadGraph graph, ScadNode node)
{
_helpDialog.Open(CurrentProject, graph, node);
}
public void ShowInfo(string message)
{
NotificationService.ShowNotification(message);
}
public void CopyNodesToClipboard(ScadGraph graph, IEnumerable<ScadNode> selection)
{
_copyBuffer = graph.CloneSelection(CurrentProject, selection, out _);
}
public ScadGraph GetNodesInClipboard()
{
return _copyBuffer;
}
public void OpenAddDialog(RequestContext requestContext)
{
_addDialog.Open(_addDialogEntries, requestContext);
}
public void ShowPopupMenu(RequestContext context)
{
var popupActions = _editorActions
.OrderBy(it => it.Order)
.GroupBy(it => it.Group)
.SelectMany(group =>
{
var result = new List<QuickAction>();
// first gather all the quick actions for this group
var actions = group.SelectMany(it =>
it.TryBuildQuickAction(this, context, out var action)
? new[] {action}
: Enumerable.Empty<QuickAction>()).ToList();
// no actions in the group? then we just skip it.
if (actions.Count == 0)
{
return result;
}
// if the group name starts with a dash, we add a separator before the group
// and then just inline all the actions.
if (group.Key.StartsWith("-"))
{
result.Add(new QuickAction(group.Key.Substring(1)));
result.AddRange(actions);
}
// if we have a group name, create a submenu for the group
else if (!group.Key.Empty())
{
result.Add(new QuickAction(group.Key, actions));
}
else
{
// otherwise just add the actions to the result
result.AddRange(actions);
}
return result;
}).ToList();
context.TryGetPosition(out var position);
ShowPopupMenu(position, popupActions);
}
public void ShowPopupMenu(Vector2 position, List<QuickAction> entries)
{
_quickActionsPopup.Open(position, entries);
}
}
}