-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathEditorController.cs
2402 lines (2024 loc) · 95.3 KB
/
EditorController.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
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextAdventures.Quest.Scripts;
namespace TextAdventures.Quest
{
public enum EditorUpdateSource
{
// These enum values should match those in WorldModel's UpdateSource enum. We don't want
// to use the same enum here as the Editor component shouldn't access WorldModel directly.
System,
User
}
public enum ValidationMessage
{
OK,
ItemAlreadyExists,
ElementAlreadyExists,
InvalidAttributeName,
ExceptionOccurred,
InvalidElementName,
CircularTypeReference,
InvalidElementNameMultipleSpaces,
InvalidElementNameInvalidWord,
CannotRenamePlayerElement,
InvalidElementNameStartsWithNumber,
MismatchingBrackets,
MismatchingQuotes,
}
public enum EditorStyle
{
TextAdventure,
GameBook
}
// TO DO: When WebEditor is fully functional, there should be no need for this
public enum EditorMode
{
Desktop,
Web
}
public struct ValidationResult
{
public bool Valid;
public ValidationMessage Message;
public string MessageData;
public string SuggestedName;
}
public class TemplateData
{
public string TemplateName { get; set; }
public string Filename { get; set; }
public EditorStyle Type { get; set; }
}
public sealed class EditorController : IDisposable
{
private const string k_commands = "_gameCommands";
private const string k_verbs = "_gameVerbs";
private List<ElementType> m_ignoredTypes = new List<ElementType>
{
ElementType.ImpliedType,
ElementType.Delegate,
ElementType.Editor,
ElementType.EditorTab,
ElementType.EditorControl,
ElementType.Resource
};
private List<ElementType> m_advancedTypes = new List<ElementType>
{
ElementType.DynamicTemplate,
ElementType.Function,
ElementType.IncludedLibrary,
ElementType.Javascript,
ElementType.ObjectType,
ElementType.Template,
ElementType.Timer,
ElementType.Walkthrough
};
// TO DO: When WebEditor is fully functional, there should be no need for this
private List<ElementType> m_webEditorIgnoreTypes = new List<ElementType>
{
ElementType.DynamicTemplate,
ElementType.IncludedLibrary,
ElementType.Javascript,
ElementType.ObjectType,
ElementType.Template,
ElementType.Walkthrough
};
private static Dictionary<ValidationMessage, string> s_validationMessages = new Dictionary<ValidationMessage, string> {
{ValidationMessage.OK, "No error"},
{ValidationMessage.ItemAlreadyExists, "Item '{0}' already exists in the list"},
{ValidationMessage.ElementAlreadyExists,"An element called '{0}' already exists in this game"},
{ValidationMessage.InvalidAttributeName, "Invalid attribute name"},
{ValidationMessage.ExceptionOccurred, "An error occurred: {1}"},
{ValidationMessage.InvalidElementName, "Invalid element name"},
{ValidationMessage.CircularTypeReference, "Circular type reference"},
{ValidationMessage.InvalidElementNameMultipleSpaces, "Invalid element name. An element name cannot start or end with a space, and cannot contain multiple consecutive spaces."},
{ValidationMessage.InvalidElementNameInvalidWord, "Invalid element name. Elements cannot contain these words: " + string.Join(", ", EditorController.ExpressionKeywords)},
{ValidationMessage.CannotRenamePlayerElement, "The player object cannot be renamed"},
{ValidationMessage.InvalidElementNameStartsWithNumber, "Invalid element name. An element name cannot start with a number."},
{ValidationMessage.MismatchingBrackets, "The number of opening brackets \"(\" does not match the number of closing brackets \")\"."},
{ValidationMessage.MismatchingQuotes, "Missing quote character (\")"},
};
private WorldModel m_worldModel;
private ScriptFactory m_scriptFactory;
private AvailableFilters m_availableFilters;
private FilterOptions m_filterOptions;
private EditableScriptFactory m_editableScriptFactory;
private FontsManager m_fontsManager;
private Dictionary<string, EditorDefinition> m_editorDefinitions = new Dictionary<string, EditorDefinition>();
private Dictionary<string, EditorDefinition> m_expressionDefinitions = new Dictionary<string, EditorDefinition>();
private Dictionary<ElementType, TreeHeader> m_elementTreeStructure;
private Dictionary<string, string> m_treeTitles;
private bool m_initialised = false;
private Dictionary<string, Type> m_controlTypes = new Dictionary<string, Type>();
private string m_filename;
private List<Element> m_clipboardElements;
private ElementType m_clipboardElementType;
private List<IScript> m_clipboardScripts;
private bool m_simpleMode;
private EditorStyle m_editorStyle = EditorStyle.TextAdventure;
private EditorMode m_editorMode = EditorMode.Desktop;
public event EventHandler ClearTree;
public event EventHandler BeginTreeUpdate;
public event EventHandler EndTreeUpdate;
public class AddedNodeEventArgs : EventArgs
{
public string Key { get; set; }
public string Text { get; set; }
public string Parent { get; set; }
public bool IsLibraryNode { get; set; }
public int? Position { get; set; }
}
public event EventHandler<AddedNodeEventArgs> AddedNode;
public class RemovedNodeEventArgs : EventArgs
{
public string Key { get; set; }
}
public event EventHandler<RemovedNodeEventArgs> RemovedNode;
public class RenamedNodeEventArgs : EventArgs
{
public string OldName { get; set; }
public string NewName { get; set; }
}
public event EventHandler<RenamedNodeEventArgs> RenamedNode;
public class RetitledNodeEventArgs : EventArgs
{
public string Key { get; set; }
public string NewTitle { get; set; }
}
public event EventHandler<RetitledNodeEventArgs> RetitledNode;
public class ShowMessageEventArgs : EventArgs
{
public string Message { get; set; }
}
public event EventHandler<ShowMessageEventArgs> ShowMessage;
public class RequestAddElementEventArgs : EventArgs
{
public string ElementType { get; set; }
public string ObjectType { get; set; }
public string Filter { get; set; }
}
public event EventHandler<RequestAddElementEventArgs> RequestAddElement;
public class RequestEditEventArgs : EventArgs
{
public string Key { get; set; }
}
public event EventHandler<RequestEditEventArgs> RequestEdit;
public event EventHandler ElementsUpdated;
public class ElementMovedEventArgs : EventArgs
{
public string Key { get; set; }
}
public event EventHandler<ElementMovedEventArgs> ElementMoved;
public class ScriptClipboardUpdateEventArgs : EventArgs
{
public bool HasScript { get; set; }
}
public event EventHandler<ScriptClipboardUpdateEventArgs> ScriptClipboardUpdated;
public class RequestRunWalkthroughEventArgs : EventArgs
{
public string Name { get; set; }
public bool Record { get; set; }
}
public event EventHandler<RequestRunWalkthroughEventArgs> RequestRunWalkthrough;
public event EventHandler SimpleModeChanged;
public event EventHandler<ElementUpdatedEventArgs> ElementUpdated;
public event EventHandler<ElementRefreshedEventArgs> ElementRefreshed;
public event EventHandler<UpdateUndoListEventArgs> UndoListUpdated;
public event EventHandler<UpdateUndoListEventArgs> RedoListUpdated;
public event EventHandler<LoadStatusEventArgs> LoadStatus;
public event EventHandler<LibrariesUpdatedEventArgs> LibrariesUpdated;
public class ElementUpdatedEventArgs : EventArgs
{
internal ElementUpdatedEventArgs(string element, string attribute, object newValue, bool isUndo)
{
Element = element;
Attribute = attribute;
NewValue = newValue;
IsUndo = isUndo;
}
public string Element { get; private set; }
public string Attribute { get; private set; }
public object NewValue { get; private set; }
public bool IsUndo { get; private set; }
}
public class ElementRefreshedEventArgs : EventArgs
{
internal ElementRefreshedEventArgs(string element)
{
Element = element;
}
public string Element { get; private set; }
}
public class UpdateUndoListEventArgs : EventArgs
{
internal UpdateUndoListEventArgs(IEnumerable<string> undoList)
{
UndoList = undoList;
}
public IEnumerable<string> UndoList { get; private set; }
}
public class LoadStatusEventArgs : EventArgs
{
public LoadStatusEventArgs(string status)
{
Status = status;
}
public string Status { get; private set; }
}
public class LibrariesUpdatedEventArgs : EventArgs
{
public LibrariesUpdatedEventArgs()
{
}
}
private class TreeHeader
{
public string Key;
public string Title;
}
public EditorController()
{
m_availableFilters = new AvailableFilters();
m_availableFilters.Add("libraries", "Show Library Elements");
m_filterOptions = new FilterOptions();
// set default filters here
m_fontsManager = new FontsManager();
}
public class InitialiseResults : EventArgs
{
internal InitialiseResults(bool success)
{
Success = success;
}
public bool Success { get; private set; }
}
public event EventHandler<InitialiseResults> InitialiseFinished;
public void StartInitialise(string filename, string libFolder = null)
{
System.Threading.Thread newThread = new System.Threading.Thread(() =>
{
bool result = Initialise(filename, libFolder);
if (InitialiseFinished != null) InitialiseFinished(this, new InitialiseResults(result));
});
newThread.Start();
}
public bool Initialise(string filename, string libFolder = null)
{
m_filename = filename;
m_worldModel = new WorldModel(filename, libFolder, null);
m_scriptFactory = new ScriptFactory(m_worldModel);
m_worldModel.ElementFieldUpdated += m_worldModel_ElementFieldUpdated;
m_worldModel.ElementRefreshed += m_worldModel_ElementRefreshed;
m_worldModel.ElementMetaFieldUpdated += m_worldModel_ElementMetaFieldUpdated;
m_worldModel.UndoLogger.TransactionsUpdated += UndoLogger_TransactionsUpdated;
m_worldModel.Elements.ElementRenamed += Elements_ElementRenamed;
m_worldModel.LoadStatus += m_worldModel_LoadStatus;
bool ok = m_worldModel.InitialiseEdit();
if (ok)
{
if (m_worldModel.Game.Fields.Get("_editorstyle") as string == "gamebook")
{
m_editorStyle = EditorStyle.GameBook;
m_ignoredTypes.Add(ElementType.Template);
m_ignoredTypes.Add(ElementType.ObjectType);
}
// need to initialise the EditableScriptFactory after we've loaded the game XML above,
// as the editor definitions contain the "friendly" templates for script commands.
m_editableScriptFactory = new EditableScriptFactory(this, m_scriptFactory, m_worldModel);
m_initialised = true;
m_worldModel.ObjectsUpdated += m_worldModel_ObjectsUpdated;
foreach (Element e in m_worldModel.Elements.GetElements(ElementType.Editor))
{
EditorDefinition def = new EditorDefinition(m_worldModel, e);
if (def.AppliesTo != null)
{
// Normal editor definition for editing an element or a script command
m_editorDefinitions.Add(def.AppliesTo, def);
}
else if (def.Pattern != null)
{
// Editor definition for an expression template in the "if" editor
m_expressionDefinitions.Add(def.Pattern, def);
}
}
if (m_worldModel.Version == WorldModelVersion.v500)
{
m_worldModel.Elements.Get("game").Fields.Set("gameid", GetNewGameId());
}
}
else
{
string message = "Failed to load game due to the following errors:" + Environment.NewLine;
foreach (string error in m_worldModel.Errors)
{
message += "* " + error + Environment.NewLine;
}
ShowMessage(this, new ShowMessageEventArgs { Message = message });
}
return ok;
}
void m_worldModel_LoadStatus(object sender, WorldModel.LoadStatusEventArgs e)
{
if (LoadStatus != null)
{
LoadStatus(this, new LoadStatusEventArgs(e.Status));
}
}
void Elements_ElementRenamed(object sender, NameChangedEventArgs e)
{
string oldName = e.OldName;
string newName = e.Element.Name;
RenamedNode(this, new RenamedNodeEventArgs { OldName = oldName, NewName = newName });
if (ElementsUpdated != null) ElementsUpdated(this, new EventArgs());
}
void UndoLogger_TransactionsUpdated(object sender, EventArgs e)
{
if (UndoListUpdated != null) UndoListUpdated(this, new UpdateUndoListEventArgs(m_worldModel.UndoLogger.UndoList()));
if (RedoListUpdated != null) RedoListUpdated(this, new UpdateUndoListEventArgs(m_worldModel.UndoLogger.RedoList()));
}
void m_worldModel_ElementFieldUpdated(object sender, WorldModel.ElementFieldUpdatedEventArgs e)
{
if (!m_initialised) return;
if (ElementUpdated != null) ElementUpdated(this, new ElementUpdatedEventArgs(e.Element.Name, e.Attribute, WrapValue(e.NewValue, e.Element, e.Attribute), e.IsUndo));
if (e.Attribute == "parent")
{
BeginTreeUpdate(this, new EventArgs());
RemoveElementAndSubElementsFromTree(e.Element);
AddElementAndSubElementsToTree(e.Element);
EndTreeUpdate(this, new EventArgs());
if (ElementsUpdated != null) ElementsUpdated(this, new EventArgs());
}
if (e.Attribute == "anonymous" || e.Attribute == "alias"
|| e.Element.Type == ObjectType.Exit && (e.Attribute == "to" || e.Attribute == "name")
|| e.Element.Type == ObjectType.Command && (e.Attribute == "name" || e.Attribute == "pattern" || e.Attribute == "isverb")
|| e.Element.Type == ObjectType.TurnScript && (e.Attribute == "name")
|| e.Element.ElemType == ElementType.IncludedLibrary && (e.Attribute == "filename")
|| e.Element.ElemType == ElementType.Template && (e.Attribute == "templatename")
|| e.Element.ElemType == ElementType.Javascript && (e.Attribute == "src"))
{
if (e.Element.Name != null)
{
// element name might be null if we're undoing an element add
RetitledNode(this, new RetitledNodeEventArgs { Key = e.Element.Name, NewTitle = GetDisplayName(e.Element) });
if (ElementsUpdated != null) ElementsUpdated(this, new EventArgs());
}
}
if (e.Element.Type == ObjectType.Command && e.Attribute == "isverb")
{
MoveNove(e.Element.Name, GetDisplayName(e.Element), GetElementTreeParent(e.Element));
}
if (e.Element.ElemType == ElementType.IncludedLibrary && e.Attribute == "filename")
{
if (LibrariesUpdated != null) LibrariesUpdated(this, new LibrariesUpdatedEventArgs());
}
}
void m_worldModel_ElementMetaFieldUpdated(object sender, WorldModel.ElementFieldUpdatedEventArgs e)
{
if (!m_initialised) return;
//System.Diagnostics.Debug.Print("Updated: {0}.{1} = {2}", e.Element, e.Attribute, e.NewValue);
if (e.Attribute == "sortindex")
{
RemovedNode(this, new RemovedNodeEventArgs { Key = e.Element.Name });
AddElementAndSubElementsToTree(e.Element, GetElementPosition(e.Element));
if (ElementMoved != null) ElementMoved(this, new ElementMovedEventArgs { Key = e.Element.Name });
}
if (e.Attribute == "library")
{
// Refresh the element in the tree by deleting and readding it
RemovedNode(this, new RemovedNodeEventArgs { Key = e.Element.Name });
AddElementAndSubElementsToTree(e.Element);
}
}
private int GetElementPosition(Element e)
{
List<Element> siblings = new List<Element>(from Element child in m_worldModel.Elements.GetChildElements(e.Parent)
orderby child.MetaFields[MetaFieldDefinitions.SortIndex]
select child);
return siblings.IndexOf(e);
}
private void MoveNove(string key, string text, string newParent)
{
RemovedNode(this, new RemovedNodeEventArgs { Key = key });
AddedNode(this, new AddedNodeEventArgs { Key = key, Text = text, Parent = newParent, IsLibraryNode = false, Position = null });
}
private void AddElementAndSubElementsToTree(Element e, int? position = null)
{
AddElementToTree(e, position);
foreach (Element child in m_worldModel.Elements.GetChildElements(e))
{
AddElementToTree(child);
}
}
private void RemoveElementAndSubElementsFromTree(Element e)
{
List<string> nodesToRemove = new List<string>(m_worldModel.Elements.GetChildElements(e).Select(child => child.Name));
// reverse the list so we remove children before parents
nodesToRemove.Reverse();
foreach (string key in nodesToRemove)
{
RemovedNode(this, new RemovedNodeEventArgs { Key = key });
}
// finally remove the parent
RemovedNode(this, new RemovedNodeEventArgs { Key = e.Name });
}
void m_worldModel_ElementRefreshed(object sender, WorldModel.ElementRefreshEventArgs e)
{
if (m_initialised)
{
if (ElementRefreshed != null) ElementRefreshed(this, new ElementRefreshedEventArgs(e.Element.Name));
}
}
void m_worldModel_ObjectsUpdated(object sender, ObjectsUpdatedEventArgs args)
{
if (args.Added != null)
{
Element addedElement = m_worldModel.Elements.Get(args.Added);
AddElementToTree(addedElement, name: args.Added);
}
if (args.Removed != null)
{
RemovedNode(this, new RemovedNodeEventArgs { Key = args.Removed });
}
if (ElementsUpdated != null) ElementsUpdated(this, new EventArgs());
}
private void InitialiseTreeStructure()
{
m_treeTitles = new Dictionary<string, string> { { k_commands, "Commands" }, { k_verbs, "Verbs" } };
m_elementTreeStructure = new Dictionary<ElementType, TreeHeader>();
AddTreeHeader(EditorStyle.TextAdventure, ElementType.Object, "_objects", "Objects", null, false);
AddTreeHeader(EditorStyle.GameBook, ElementType.Object, "_objects", "Pages", null, false);
AddTreeHeader(null, ElementType.Function, "_functions", "Functions", null, false);
AddTreeHeader(EditorStyle.TextAdventure, ElementType.Timer, "_timers", "Timers", null, false);
if (m_editorMode == EditorMode.Desktop)
{
AddTreeHeader(EditorStyle.TextAdventure, ElementType.Walkthrough, "_walkthrough", "Walkthrough", null, false);
AddTreeHeader(null, null, "_advanced", "Advanced", null, false);
AddTreeHeader(null, ElementType.IncludedLibrary, "_include", "Included Libraries", "_advanced", false);
AddTreeHeader(EditorStyle.TextAdventure, ElementType.Template, "_template", "Templates", "_advanced", false);
AddTreeHeader(EditorStyle.TextAdventure, ElementType.DynamicTemplate, "_dynamictemplate", "Dynamic Templates", "_advanced", false);
AddTreeHeader(EditorStyle.TextAdventure, ElementType.ObjectType, "_objecttype", "Object Types", "_advanced", false);
AddTreeHeader(null, ElementType.Javascript, "_javascript", "Javascript", "_advanced", false);
}
}
private void AddTreeHeader(EditorStyle? editorStyle, ElementType? type, string key, string title, string parent, bool simple)
{
if (editorStyle.HasValue && m_editorStyle != editorStyle) return;
if (simple || !SimpleMode)
{
m_treeTitles.Add(key, title);
TreeHeader header = new TreeHeader {Key = key, Title = title};
if (type != null)
{
m_elementTreeStructure.Add(type.Value, header);
}
AddedNode(this, new AddedNodeEventArgs { Key = key, Text = title, Parent = parent, IsLibraryNode = false, Position = null });
}
}
public void UpdateTree()
{
if (BeginTreeUpdate == null) return;
BeginTreeUpdate(this, new EventArgs());
ClearTree(this, new EventArgs());
InitialiseTreeStructure();
foreach (ElementType type in Enum.GetValues(typeof(ElementType)))
{
foreach (Element o in m_worldModel.Elements.GetElements(type).Where(e => e.Parent == null))
{
AddElementAndChildrenToTree(o);
}
}
EndTreeUpdate(this, new EventArgs());
}
private void AddElementAndChildrenToTree(Element o)
{
AddElementToTree(o);
foreach (Element child in m_worldModel.Elements.GetDirectChildren(o))
{
AddElementAndChildrenToTree(child);
}
}
// optional name parameter to prevent an exception when redoing object creation, as the
// object will not have a name attribute immediately
private void AddElementToTree(Element o, int? position = null, string name = null)
{
if (!IsElementVisible(o)) return;
string parent = GetElementTreeParent(o);
string text = GetDisplayName(o);
bool display = true;
bool isLibrary = (o.MetaFields.GetAsType<bool>("library"));
if (isLibrary && !m_filterOptions.IsSet("libraries"))
{
display = false;
}
if (display)
{
string key = name ?? o.Name;
AddedNode(this, new AddedNodeEventArgs { Key = key, Text = text, Parent = parent, IsLibraryNode = isLibrary, Position = position });
if (o.Name == "game" && !SimpleMode && m_editorStyle == EditorStyle.TextAdventure)
{
if (m_editorMode == EditorMode.Desktop)
{
// TO DO: When WebEditor is fully functional, there should be no need for this
AddedNode(this, new AddedNodeEventArgs { Key = k_verbs, Text = "Verbs", Parent = "game", IsLibraryNode = false, Position = null });
}
AddedNode(this, new AddedNodeEventArgs { Key = k_commands, Text = "Commands", Parent = "game", IsLibraryNode = false, Position = null });
}
}
}
private bool IsElementVisible(Element e)
{
// Don't display implied types, editor elements etc.
if (m_ignoredTypes.Contains(e.ElemType)) return false;
if (SimpleMode && m_advancedTypes.Contains(e.ElemType)) return false;
// TO DO: When WebEditor is fully functional, there should be no need for this
if (m_editorMode == EditorMode.Web)
{
if (m_webEditorIgnoreTypes.Contains(e.ElemType)) return false;
if (e.ElemType == ElementType.Object && e.Type == ObjectType.Command && e.Fields[FieldDefinitions.IsVerb])
{
return false;
}
}
if (SimpleMode)
{
if (e.ElemType == ElementType.Object && e.Type == ObjectType.Command)
{
return false;
}
}
if (e.ElemType == ElementType.Template)
{
// Don't display verb templates (if the user wants to edit a verb's regex,
// they can do so directly on the verb itself).
if (e.Fields[FieldDefinitions.IsVerb])
{
return false;
}
// Don't display templates which have been overridden
if (e.Fields[FieldDefinitions.TemplateName] != null && m_worldModel.TryGetTemplateElement(e.Fields[FieldDefinitions.TemplateName]) != e)
{
return false;
}
}
return true;
}
private string GetElementTreeParent(Element o)
{
if (SimpleMode)
{
return o.Parent == null ? null : o.Parent.Name;
}
if (o.Parent != null) return o.Parent.Name;
if (o.ElemType == ElementType.Object && o.Type == ObjectType.Command)
{
return o.Fields.GetAsType<bool>("isverb") ? k_verbs : k_commands;
}
return m_elementTreeStructure[o.ElemType].Key;
}
private string GetDisplayName(Element e)
{
if (e.Fields[FieldDefinitions.Anonymous])
{
switch (e.ElemType)
{
case ElementType.Object:
switch (e.Type)
{
case ObjectType.Exit:
Element to = e.Fields[FieldDefinitions.To];
Boolean lookonly = e.Fields[FieldDefinitions.LookOnly];
if (lookonly)
{
return "Look: " + e.Fields[FieldDefinitions.Alias];
}
else
{
return "Exit: " + (to == null ? "(nowhere)" : to.Name);
}
case ObjectType.Command:
EditorCommandPattern pattern = e.Fields.GetAsType<EditorCommandPattern>("pattern");
bool isVerb = e.Fields.GetAsType<bool>("isverb");
return (isVerb ? "Verb" : "Command") + ": " + (pattern == null ? "(blank)" : pattern.Pattern);
case ObjectType.TurnScript:
return "Turn script";
}
break;
case ElementType.Walkthrough:
return "Walkthrough";
case ElementType.IncludedLibrary:
string filename = e.Fields[FieldDefinitions.Filename];
if (!string.IsNullOrEmpty(filename)) return filename;
return "(filename not set)";
case ElementType.Template:
return e.Fields[FieldDefinitions.TemplateName];
case ElementType.Javascript:
string src = e.Fields[FieldDefinitions.Src];
if (!string.IsNullOrEmpty(src)) return src;
return "(filename not set)";
}
}
return e.Name;
}
public string GetDisplayName(string element)
{
if (m_treeTitles.ContainsKey(element))
{
return m_treeTitles[element];
}
if (!m_worldModel.Elements.ContainsKey(element)) return null;
return GetDisplayName(m_worldModel.Elements.Get(element));
}
public AvailableFilters AvailableFilters
{
get { return m_availableFilters; }
}
public void UpdateFilterOptions(FilterOptions options)
{
m_filterOptions = options;
UpdateTree();
}
public string GetElementEditorName(string elementKey)
{
// elementKey is "game", "k1" (a command), "someobject", "myexit" etc.
// we return the editor type name, e.g. "game", "command", "object", "exit".
if (m_worldModel.Elements.ContainsKey(elementKey))
{
Element e = m_worldModel.Elements.Get(elementKey);
string type = null;
if (e.ElemType == ElementType.Object)
{
type = e.Fields.GetString("type");
}
if (string.IsNullOrEmpty(type))
{
type = e.Fields.GetString("elementtype");
}
else
{
if (type == "command")
{
if (e.Fields.GetAsType<bool>("isverb"))
{
type = "verb";
}
}
}
if (m_editorDefinitions.ContainsKey(type)) return type;
}
else if (m_editorDefinitions.ContainsKey(elementKey))
{
return elementKey;
}
return null;
}
public IEnumerable<string> GetAllEditorNames()
{
return m_editorDefinitions.Keys;
}
public Dictionary<string, EditableScriptData> GetScriptEditorData()
{
return m_editableScriptFactory.ScriptData;
}
public IEnumerable<string> GetAllScriptEditorCategories(bool showAll = false)
{
return m_editableScriptFactory.GetCategories(SimpleMode, showAll);
}
public IEditorDefinition GetEditorDefinition(IEditableScript script)
{
if (script.EditorName.StartsWith("(function)"))
{
// see if we have a specific editor definition for this function
EditorDefinition result;
if (m_editorDefinitions.TryGetValue(script.EditorName, out result))
{
return result;
}
// if not, return the default function call editor definition, and reset
// the EditorName for the script so it knows to get/set parameters via a
// parameter dictionary instead of individually.
script.EditorName = "()";
}
return m_editorDefinitions[script.EditorName];
}
public IEditorDefinition GetEditorDefinition(string editorName)
{
return m_editorDefinitions[editorName];
}
public IEditorData GetEditorData(string elementKey)
{
if (!m_worldModel.Elements.ContainsKey(elementKey)) return null;
return new EditorData(m_worldModel.Elements.Get(elementKey), this);
}
public IEditorData GetScriptEditorData(IEditableScript script)
{
switch (script.Type)
{
case ScriptType.Normal:
return new ScriptCommandEditorData(this, script);
default:
throw new NotImplementedException();
}
}
public string Save()
{
return m_worldModel.Save(SaveMode.Editor);
}
public string GameName
{
get { return m_worldModel.Game.Fields.GetString("gamename"); }
}
public void StartTransaction(string description)
{
m_worldModel.UndoLogger.StartTransaction(description);
}
public void EndTransaction()
{
m_worldModel.UndoLogger.EndTransaction();
}
public void Undo()
{
m_worldModel.UndoLogger.Undo();
}
public void Undo(int count)
{
for (int i = 0; i < count; i++)
{
m_worldModel.UndoLogger.Undo();
}
}
public void Redo()
{
m_worldModel.UndoLogger.Redo();
}
public void Redo(int count)
{
for (int i = 0; i < count; i++)
{
m_worldModel.UndoLogger.Redo();
}
}
public IEnumerable<string> GetUndoItems()
{
return m_worldModel.UndoLogger.UndoList();
}
internal EditableScriptFactory ScriptFactory
{
get { return m_editableScriptFactory; }
}
internal object WrapValue(object value)
{
return WrapValue(value, null, null);
}
internal object WrapValue(object value, Element element, string attribute)
{
if (value is IScript)
{
return EditableScripts.GetInstance(this, (IScript)value);
}
if (value is QuestList<string>)
{
return EditableList<string>.GetInstance(this, (QuestList<string>)value);
}
if (value is QuestDictionary<string>)
{
return EditableDictionary<string>.GetInstance(this, (QuestDictionary<string>)value);
}
if (value is QuestDictionary<IScript>)
{
return EditableWrappedItemDictionary<IScript, IEditableScripts>.GetInstance(this, (QuestDictionary<IScript>)value);
}
if (value is Element)
{
if (element == null || attribute == null)
{
throw new InvalidOperationException("Parent element and attribute must be specified to wrap object reference");
}
return new EditableObjectReference(this, (Element)value, element, attribute);
}
if (value is EditorCommandPattern)
{
if (element == null || attribute == null)
{
throw new InvalidOperationException("Parent element and attribute must be specified to wrap command pattern");
}
return new EditableCommandPattern(this, (EditorCommandPattern)value, element, attribute);
}
return value;
}
internal WorldModel WorldModel
{
get { return m_worldModel; }
}
public EditableScripts CreateNewEditableScripts(string parent, string attribute, string keyword, bool useTransaction, bool nullKeywordIsFunctionCall = false)
{
if (useTransaction)
{
WorldModel.UndoLogger.StartTransaction(string.Format("Set '{0}' {1} script to '{2}'", parent, attribute, keyword));
}
Element element = (parent == null) ? null : m_worldModel.Elements.Get(parent);
EditableScripts newValue = EditableScripts.GetInstance(this, new MultiScript(m_worldModel));
if (keyword != null || nullKeywordIsFunctionCall)
{
newValue.AddNewInternal(keyword);
}
if (element != null && attribute != null)
{
element.Fields.Set(attribute, newValue.GetUnderlyingValue());
// Setting the element field value will clone the IScript, so we need to return an updated reference
newValue = EditableScripts.GetInstance(this, element.Fields.GetAsType<IScript>(attribute));
}
if (useTransaction)
{
WorldModel.UndoLogger.EndTransaction();
}
return newValue;
}
public EditableScripts CreateNewEditableScriptsChild(ScriptCommandEditorData parent, string attribute, string keyword, bool useTransaction)
{
if (useTransaction)
{
WorldModel.UndoLogger.StartTransaction(string.Format("Add script '{0}'", keyword));
}
EditableScripts newValue = EditableScripts.GetInstance(this, new MultiScript(m_worldModel));
if (keyword != null)
{
newValue.AddNewInternal(keyword);
}
parent.SetAttribute(attribute, newValue);
if (useTransaction)
{