-
-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathYarnProjectImporterEditor.cs
More file actions
822 lines (652 loc) · 33 KB
/
YarnProjectImporterEditor.cs
File metadata and controls
822 lines (652 loc) · 33 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
/*
Yarn Spinner is licensed to you under the terms found in the file LICENSE.md.
*/
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEngine;
using System.Linq;
using Yarn.Compiler;
using System.IO;
using UnityEditorInternal;
using System.Collections;
using System.Reflection;
#nullable enable
#if USE_ADDRESSABLES
using UnityEditor.AddressableAssets;
#endif
#if USE_UNITY_LOCALIZATION
using UnityEditor.Localization;
using UnityEngine.Localization.Tables;
#endif
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using System;
namespace Yarn.Unity.Editor
{
[CustomEditor(typeof(YarnProjectImporter))]
public class YarnProjectImporterEditor : ScriptedImporterEditor
{
// A runtime-only field that stores the defaultLanguage of the
// YarnProjectImporter. Used during Inspector GUI drawing.
internal static SerializedProperty? CurrentProjectDefaultLanguageProperty;
internal const string ProjectUpgradeHelpURL = "https://docs.yarnspinner.dev/using-yarnspinner-with-unity/importing-yarn-files/yarn-projects#upgrading-yarn-projects";
internal const string CreateNewIssueURL = "https://github.com/YarnSpinnerTool/YarnSpinner-Unity/issues/new?assignees=&labels=bug&projects=&template=bug_report.md&title=Project Import Error";
internal const string AddStringTagsButtonLabel = "Add Line Tags to Yarn Scripts";
internal const string GenerateStringsFileButtonLabel = "Export Strings and Metadata as CSV";
internal const string UpdateExistingStringsFilesButtonLabel = "Update Existing Strings Files";
private SerializedProperty? useAddressableAssetsProperty;
public VisualTreeAsset? editorUI;
public VisualTreeAsset? localizationUIAsset;
public VisualTreeAsset? sourceFileUIAsset;
public StyleSheet? yarnProjectStyleSheet;
private VisualElement? uiRoot;
private string? baseLanguage = null;
private List<LocalizationEntryElement> localizationEntryFields = new List<LocalizationEntryElement>();
private List<SourceFileEntryElement> sourceEntryFields = new List<SourceFileEntryElement>();
private VisualElement? localisationFieldsContainer;
private VisualElement? sourceFileEntriesContainer;
private VisualElement? variableStorageSettingsContainer;
private SerializedProperty? generateVariablesSourceFileProperty;
private SerializedProperty? variablesClassNameProperty;
private SerializedProperty? variablesClassNamespaceProperty;
private SerializedProperty? variablesClassParentProperty;
#if USE_UNITY_LOCALIZATION
private SerializedProperty? useUnityLocalisationSystemProperty;
private SerializedProperty? unityLocalisationTableCollectionGUIDProperty;
#endif
private bool AnyModifications
{
get
{
return AnyLocalisationModifications
|| AnySourceFileModifications
;
}
}
private bool AnyLocalisationModifications => LocalisationsAddedOrRemoved || localizationEntryFields.Any(f => f.IsModified) || BaseLanguageNameModified || StringTableModified;
private bool AnySourceFileModifications => SourceFilesAddedOrRemoved || sourceEntryFields.Any(f => f.IsModified);
private bool LocalisationsAddedOrRemoved = false;
private bool BaseLanguageNameModified = false;
private bool SourceFilesAddedOrRemoved = false;
private bool StringTableModified = false;
public override void OnEnable()
{
base.OnEnable();
useAddressableAssetsProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.useAddressableAssets));
#if USE_UNITY_LOCALIZATION
useUnityLocalisationSystemProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.UseUnityLocalisationSystem));
unityLocalisationTableCollectionGUIDProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.unityLocalisationStringTableCollectionGUID));
#endif
generateVariablesSourceFileProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.generateVariablesSourceFile));
variablesClassNameProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.variablesClassName));
variablesClassNamespaceProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.variablesClassNamespace));
variablesClassParentProperty = serializedObject.FindProperty(nameof(YarnProjectImporter.variablesClassParent));
}
public override void OnDisable()
{
base.OnDisable();
if (AnyModifications)
{
if (EditorUtility.DisplayDialog("Unapplied Changes", "The currently selected Yarn Project has unapplied changes. Do you want to apply them or revert?", "Apply", "Revert"))
{
#if UNITY_2022_2_OR_NEWER
this.SaveChanges();
#else
this.ApplyAndImport();
#endif
}
}
}
protected override void Apply()
{
base.Apply();
if (!(this.target is YarnProjectImporter importer))
{
throw new InvalidOperationException($"Internal error: importer for {this.target} is not a {nameof(YarnProjectImporter)}!");
}
var data = importer.GetProject()
?? throw new InvalidOperationException($"Failed to open project at {importer.assetPath}. Is it damaged?");
var importerFolder = Path.GetDirectoryName(importer.assetPath);
var removedLocalisations = data.Localisation.Keys.Except(localizationEntryFields.Select(f => f.value.languageID)).ToList();
foreach (var removedLocalisation in removedLocalisations)
{
data.Localisation.Remove(removedLocalisation);
}
data.SourceFilePatterns = this.sourceEntryFields.Select(f => f.value);
foreach (var locField in localizationEntryFields)
{
// Does this localisation field represent a localisation that
// used to be the base localisation, but is now no longer? If it
// is, even if it's unmodified, we need to make sure we add it
// to the project data.
bool wasPreviouslyBaseLocalisation =
locField.value.languageID == data.BaseLanguage
&& BaseLanguageNameModified;
// Skip any records that we don't need to touch
if (locField.IsModified == false && !wasPreviouslyBaseLocalisation)
{
continue;
}
var locInfo = new Project.LocalizationInfo();
if (locField.value.isExternal && locField.value.externalLocalization != null && AssetDatabase.TryGetGUIDAndLocalFileIdentifier(locField.value.externalLocalization, out var guid, out long _))
{
var path = AssetDatabase.GetAssetPath(locField.value.externalLocalization);
locInfo.Strings = "unity:" + guid;
locInfo.Assets = "unity:" + guid;
}
else
{
var stringFile = locField.value.stringsFile;
var assetFolder = locField.value.assetsFolder;
if (stringFile != null)
{
string stringFilePath = AssetDatabase.GetAssetPath(stringFile);
locInfo.Strings = Path.GetRelativePath(importerFolder, stringFilePath);
}
if (assetFolder != null)
{
string assetFolderPath = AssetDatabase.GetAssetPath(assetFolder);
locInfo.Assets = Path.GetRelativePath(importerFolder, assetFolderPath);
}
}
data.Localisation[locField.value.languageID] = locInfo;
locField.ClearModified();
}
data.BaseLanguage = this.baseLanguage ?? "unknown";
if (data.Localisation.TryGetValue(data.BaseLanguage, out var baseLanguageInfo))
{
if (string.IsNullOrEmpty(baseLanguageInfo.Strings)
&& string.IsNullOrEmpty(baseLanguageInfo.Assets))
{
// We have a localisation info entry, but it doesn't provide
// any useful information (the strings field is unused, and
// the assets field defaults to empty anyway). Trim it from
// the data.
data.Localisation.Remove(data.BaseLanguage);
}
}
foreach (var sourceField in this.sourceEntryFields)
{
sourceField.ClearModified();
}
BaseLanguageNameModified = false;
SourceFilesAddedOrRemoved = false;
LocalisationsAddedOrRemoved = false;
StringTableModified = false;
data.SaveToFile(importer.assetPath);
if (localizationEntryFields.Any(f => f.value.languageID == this.baseLanguage) == false)
{
var newBaseLanguageField = CreateLocalisationEntryElement(new ProjectImportData.LocalizationEntry
{
assetsFolder = null,
stringsFile = null,
languageID = baseLanguage ?? "unknown",
}, baseLanguage ?? "unknown");
localizationEntryFields.Add(newBaseLanguageField);
localisationFieldsContainer?.Add(newBaseLanguageField);
}
}
#if UNITY_2022_2_OR_NEWER
public override void DiscardChanges()
{
localizationEntryFields.Clear();
sourceEntryFields.Clear();
LocalisationsAddedOrRemoved = false;
BaseLanguageNameModified = false;
SourceFilesAddedOrRemoved = false;
base.DiscardChanges();
var inspectorRoot = uiRoot?.parent;
uiRoot?.RemoveFromHierarchy();
inspectorRoot?.Add(CreateInspectorGUI());
}
#else
protected override void ResetValues()
{
localizationEntryFields.Clear();
sourceEntryFields.Clear();
LocalisationsAddedOrRemoved = false;
BaseLanguageNameModified = false;
SourceFilesAddedOrRemoved = false;
base.ResetValues();
var inspectorRoot = uiRoot?.parent;
uiRoot?.RemoveFromHierarchy();
inspectorRoot?.Add(CreateInspectorGUI());
}
#endif
public override VisualElement CreateInspectorGUI()
{
if (!(target is YarnProjectImporter yarnProjectImporter))
{
throw new InvalidOperationException($"Internal error: importer for {this.target} is not a {nameof(YarnProjectImporter)}!");
}
var importData = yarnProjectImporter.ImportData;
var ui = new VisualElement();
uiRoot = ui;
ui.styleSheets.Add(yarnProjectStyleSheet);
// nice header bit with logo and links
var yarnspinnerHeader = new IMGUIContainer(DialogueRunnerEditor.DrawYarnSpinnerHeader);
ui.Add(yarnspinnerHeader);
// if the import data is null it means import has crashed
// we need to let the user know and perhaps ask them to file an issue
if (importData == null)
{
ui.Add(CreateCriticalErrorUI());
return ui;
}
// next we need to handle the two edge cases
// either the importData is for the older format
// or it's completely unknown (most likely a error)
// in both cases we show the respective custom UI and return
switch (importData.ImportStatus)
{
case ProjectImportData.ImportStatusCode.NeedsUpgradeFromV1:
{
ui.Add(CreateUpgradeUI(yarnProjectImporter));
return ui;
}
case ProjectImportData.ImportStatusCode.Unknown:
{
ui.Add(CreateUnknownErrorUI());
return ui;
}
}
var importDataSO = new SerializedObject(importData);
var diagnosticsProperty = importDataSO.FindProperty(nameof(ProjectImportData.diagnostics));
var errorsContainer = new VisualElement();
errorsContainer.name = "errors";
var sourceFilesContainer = new VisualElement();
var localisationControls = new VisualElement();
var yarnInternalControls = new VisualElement();
var unityControls = new VisualElement();
var useAddressableAssetsField = new PropertyField(useAddressableAssetsProperty);
useAddressableAssetsField.BindProperty(useAddressableAssetsProperty);
#if USE_UNITY_LOCALIZATION
var useUnityLocalisationSystemField = new PropertyField(useUnityLocalisationSystemProperty);
useUnityLocalisationSystemField.BindProperty(useUnityLocalisationSystemProperty);
// References to string table collections are stored as GUIDs,
// because ScriptedImporters can't refer to ScriptableObjects
// directly without causing drama. To preserve a good user
// experience, we'll add and manage an ObjectField directly.
var unityLocalisationTableCollectionField = new ObjectField("String Table Collection");
unityLocalisationTableCollectionField.objectType = typeof(StringTableCollection);
unityLocalisationTableCollectionField.SetValueWithoutNotify(yarnProjectImporter.UnityLocalisationStringTableCollection);
#endif
localisationFieldsContainer = new VisualElement();
sourceFileEntriesContainer = new VisualElement();
variableStorageSettingsContainer = new VisualElement();
localisationControls.style.marginBottom = 8;
if (importData.diagnostics.Any())
{
var header = new Label();
header.text = "Errors";
header.style.unityFontStyleAndWeight = FontStyle.Bold;
errorsContainer.Add(header);
foreach (var error in importData.diagnostics)
{
var errorContainer = new VisualElement();
errorContainer.style.marginLeft = 15;
var objectField = new ObjectField();
objectField.value = error.yarnFile;
objectField.objectType = typeof(TextAsset);
var messagesField = new IMGUIContainer(() =>
{
foreach (var message in error.errorMessages)
{
EditorGUILayout.HelpBox(message, MessageType.Error);
}
});
messagesField.style.marginLeft = 30;
// if an error isn't able to be linked to a yarn file specifically
// such as an error in the library defining an invalid external function
// we don't want to show an empty text asset
if (error.yarnFile != null)
{
errorContainer.Add(objectField);
}
errorContainer.Add(messagesField);
errorsContainer.Add(errorContainer);
}
errorsContainer.style.marginBottom = 15;
ui.Add(errorsContainer);
}
sourceFileEntriesContainer.style.marginLeft = 8;
ui.Add(sourceFilesContainer);
var sourceFilesHeader = new Label();
sourceFilesHeader.text = "Source Yarn Scripts";
sourceFilesHeader.style.unityFontStyleAndWeight = FontStyle.Bold;
sourceFilesContainer.Add(sourceFilesHeader);
sourceFilesContainer.Add(sourceFileEntriesContainer);
foreach (var path in importData.sourceFilePatterns)
{
var locElement = CreateSourceFileEntryElement(path);
sourceFileEntriesContainer.Add(locElement);
sourceEntryFields.Add(locElement);
}
var addSourceFileButton = new Button();
addSourceFileButton.text = "Add";
sourceFilesContainer.Add(addSourceFileButton);
addSourceFileButton.style.marginLeft = 8;
addSourceFileButton.clicked += () =>
{
var loc = CreateSourceFileEntryElement("**/*.yarn");
sourceEntryFields.Add(loc);
sourceFileEntriesContainer.Add(loc);
SourceFilesAddedOrRemoved = true;
};
var localisationHeader = new Label();
localisationHeader.text = "Localisation";
localisationHeader.style.unityFontStyleAndWeight = FontStyle.Bold;
localisationHeader.style.marginTop = 8;
localisationControls.Add(localisationHeader);
var languagePopup = new LanguageField("Base Language");
var generateStringsFileButton = new Button();
var addStringTagsButton = new Button();
var updateExistingStringsFilesButton = new Button();
baseLanguage = importData.baseLanguageName;
languagePopup.SetValueWithoutNotify(baseLanguage ?? "unknown");
languagePopup.RegisterValueChangedCallback(evt =>
{
baseLanguage = evt.newValue;
foreach (var loc in localizationEntryFields)
{
loc.ProjectBaseLanguage = baseLanguage;
}
BaseLanguageNameModified = true;
});
localisationControls.Add(languagePopup);
#if USE_ADDRESSABLES
yarnInternalControls.Add(useAddressableAssetsField);
#endif
yarnInternalControls.Add(localisationFieldsContainer);
foreach (var localisation in importData.localizations)
{
var locElement = CreateLocalisationEntryElement(localisation, baseLanguage ?? "unknown");
localisationFieldsContainer.Add(locElement);
localizationEntryFields.Add(locElement);
}
var addLocalisationButton = new Button();
addLocalisationButton.text = "Add Localisation";
addLocalisationButton.clicked += () =>
{
var loc = CreateLocalisationEntryElement(new ProjectImportData.LocalizationEntry()
{
languageID = importData.baseLanguageName ?? "unknown",
}, baseLanguage ?? "unknown");
localizationEntryFields.Add(loc);
localisationFieldsContainer.Add(loc);
LocalisationsAddedOrRemoved = true;
};
yarnInternalControls.Add(addLocalisationButton);
#if USE_UNITY_LOCALIZATION
localisationControls.Add(useUnityLocalisationSystemField);
unityControls.Add(unityLocalisationTableCollectionField);
var emptyTableCollectionWarning = new IMGUIContainer(() =>
{
EditorGUILayout.HelpBox("A string table collection is required.", MessageType.Warning);
});
unityControls.Add(emptyTableCollectionWarning);
void UpdateLocalizationVisibility()
{
SetElementVisible(unityControls, useUnityLocalisationSystemProperty?.boolValue ?? false);
SetElementVisible(yarnInternalControls, !useUnityLocalisationSystemProperty?.boolValue ?? false);
}
void UpdateUnityTableCollectionEmptyWarningVisibility()
{
SetElementVisible(emptyTableCollectionWarning, string.IsNullOrEmpty(unityLocalisationTableCollectionGUIDProperty?.stringValue));
}
UpdateLocalizationVisibility();
UpdateUnityTableCollectionEmptyWarningVisibility();
useUnityLocalisationSystemField.RegisterCallback<ChangeEvent<bool>>(evt =>
{
UpdateLocalizationVisibility();
});
unityLocalisationTableCollectionField.RegisterValueChangedCallback(evt =>
{
// When the localisation table changes, get the GUID for it and
// store it in the property.
if (unityLocalisationTableCollectionGUIDProperty == null)
{
throw new InvalidOperationException($"{nameof(unityLocalisationTableCollectionGUIDProperty)} is null");
}
if (evt.newValue != null && AssetDatabase.TryGetGUIDAndLocalFileIdentifier(evt.newValue, out string guid, out long _))
{
unityLocalisationTableCollectionGUIDProperty.stringValue = guid;
unityLocalisationTableCollectionGUIDProperty.serializedObject.ApplyModifiedProperties();
}
else
{
// The object is null, or a GUID for it can't be found.
unityLocalisationTableCollectionGUIDProperty.stringValue = string.Empty;
unityLocalisationTableCollectionGUIDProperty.serializedObject.ApplyModifiedProperties();
}
// Flag that we've changed our importer's settings.
StringTableModified = true;
UpdateUnityTableCollectionEmptyWarningVisibility();
});
#endif
var cantGenerateUnityStringTableMessage = new IMGUIContainer(() =>
{
EditorGUILayout.HelpBox($"All lines must have a line ID tag in order to create a string table. Click '{AddStringTagsButtonLabel}' to fix this problem.", MessageType.Warning);
});
addStringTagsButton.text = AddStringTagsButtonLabel;
addStringTagsButton.clicked += () =>
{
YarnProjectUtility.AddLineTagsToFilesInYarnProject(yarnProjectImporter);
UpdateTaggingButtonsEnabled();
};
generateStringsFileButton.text = GenerateStringsFileButtonLabel;
generateStringsFileButton.clicked += () => ExportStringsData(yarnProjectImporter);
updateExistingStringsFilesButton.text = UpdateExistingStringsFilesButtonLabel;
updateExistingStringsFilesButton.clicked += () =>
{
YarnProjectUtility.UpdateLocalizationCSVs(yarnProjectImporter);
};
yarnInternalControls.Add(updateExistingStringsFilesButton);
localisationControls.Add(yarnInternalControls);
localisationControls.Add(unityControls);
ui.Add(localisationControls);
ui.Add(cantGenerateUnityStringTableMessage);
ui.Add(addStringTagsButton);
ui.Add(generateStringsFileButton);
var generateVariablesSourceFileField = new PropertyField(generateVariablesSourceFileProperty);
var variablesClassNameField = new PropertyField(variablesClassNameProperty);
var variablesClassNamespaceField = new PropertyField(variablesClassNamespaceProperty);
generateVariablesSourceFileField.Bind(serializedObject);
variablesClassNameField.Bind(serializedObject);
variablesClassNamespaceField.Bind(serializedObject);
// Find all loaded assemblies that are not YarnSpinner.dll. Find all
// types that implement IVariableStorage, are not abstract, and are
// not generated code. Get the full names of the result.
var variableStorageClasses = AppDomain.CurrentDomain
.GetAssemblies()
.Where(a => a != typeof(Yarn.Dialogue).Assembly)
.SelectMany(a => a.GetTypes())
.Where(t => t.GetInterfaces().Any(i => i == typeof(IVariableStorage)))
.Where(t => t.IsAbstract == false)
.Where(t => !t.CustomAttributes.Any(a => a.AttributeType == typeof(System.CodeDom.Compiler.GeneratedCodeAttribute)))
.Select(t => t.FullName)
.ToList();
var variablesClassParentDropdownField = new DropdownField(
"Variables Parent Class",
variableStorageClasses,
variablesClassParentProperty?.stringValue ?? string.Empty
);
variablesClassParentDropdownField.RegisterValueChangedCallback(v =>
{
if (variablesClassParentProperty != null)
{
variablesClassParentProperty.stringValue = v.newValue;
}
serializedObject.ApplyModifiedProperties();
});
void UpdateVariableSettingsVisibility()
{
foreach (var field in new VisualElement[] { variablesClassNameField, variablesClassNamespaceField, variablesClassParentDropdownField })
{
SetElementVisible(field, generateVariablesSourceFileProperty?.boolValue ?? false);
}
}
UpdateVariableSettingsVisibility();
generateVariablesSourceFileField.RegisterValueChangeCallback(e => UpdateVariableSettingsVisibility());
variableStorageSettingsContainer.Add(generateVariablesSourceFileField);
variableStorageSettingsContainer.Add(variablesClassNameField);
variableStorageSettingsContainer.Add(variablesClassNamespaceField);
variableStorageSettingsContainer.Add(variablesClassParentDropdownField);
ui.Add(variableStorageSettingsContainer);
ui.Add(new IMGUIContainer(ApplyRevertGUI));
UpdateTaggingButtonsEnabled();
return ui;
void UpdateTaggingButtonsEnabled()
{
addStringTagsButton.SetEnabled(yarnProjectImporter.CanGenerateStringsTable == false && importData.yarnFiles.Any());
generateStringsFileButton.SetEnabled(yarnProjectImporter.CanGenerateStringsTable);
bool isUnityLocalisationAvailable;
#if USE_UNITY_LOCALIZATION
isUnityLocalisationAvailable = true;
#else
isUnityLocalisationAvailable = false;
#endif
cantGenerateUnityStringTableMessage.style.display = (isUnityLocalisationAvailable && yarnProjectImporter.HasErrors == false && yarnProjectImporter.CanGenerateStringsTable == false) ? DisplayStyle.Flex : DisplayStyle.None;
}
}
private LocalizationEntryElement CreateLocalisationEntryElement(ProjectImportData.LocalizationEntry localisation, string baseLanguage)
{
if (localizationUIAsset == null)
{
throw new InvalidOperationException($"Can't create {nameof(LocalizationEntryElement)}: {nameof(localizationUIAsset)} is null");
}
var locElement = new LocalizationEntryElement(localizationUIAsset, localisation, baseLanguage);
locElement.OnDelete += () =>
{
locElement.RemoveFromHierarchy();
localizationEntryFields.Remove(locElement);
LocalisationsAddedOrRemoved = true;
};
return locElement;
}
private SourceFileEntryElement CreateSourceFileEntryElement(string path)
{
if (sourceFileUIAsset == null)
{
throw new InvalidOperationException($"Can't create {nameof(SourceFileEntryElement)}: {nameof(sourceFileUIAsset)} is null");
}
if (!(this.target is YarnProjectImporter importer))
{
throw new InvalidOperationException($"Internal error: importer for {this.target} is not a {nameof(YarnProjectImporter)}!");
}
var sourceElement = new SourceFileEntryElement(sourceFileUIAsset, path, importer);
sourceElement.OnDelete += () =>
{
sourceElement.RemoveFromHierarchy();
sourceEntryFields.Remove(sourceElement);
SourceFilesAddedOrRemoved = true;
};
return sourceElement;
}
private void ExportStringsData(YarnProjectImporter yarnProjectImporter)
{
var currentPath = AssetDatabase.GetAssetPath(yarnProjectImporter);
var currentFileName = Path.GetFileNameWithoutExtension(currentPath);
var currentDirectory = Path.GetDirectoryName(currentPath);
var destinationPath = EditorUtility.SaveFilePanel("Export Strings CSV", currentDirectory, $"{currentFileName}.csv", "csv");
if (string.IsNullOrEmpty(destinationPath) == false)
{
// Generate the file on disk
YarnProjectUtility.WriteStringsFile(destinationPath, yarnProjectImporter);
// Also generate the metadata file.
var destinationDirectory = Path.GetDirectoryName(destinationPath);
var destinationFileName = Path.GetFileNameWithoutExtension(destinationPath);
var metadataDestinationPath = Path.Combine(destinationDirectory, $"{destinationFileName}-metadata.csv");
YarnProjectUtility.WriteMetadataFile(metadataDestinationPath, yarnProjectImporter);
// destinationPath may have been inside our Assets
// directory, so refresh the asset database
AssetDatabase.Refresh();
}
}
private static void SetElementVisible(VisualElement e, bool visible)
{
if (visible)
{
e.style.display = DisplayStyle.Flex;
}
else
{
e.style.display = DisplayStyle.None;
}
}
public override bool HasModified()
{
return base.HasModified() || AnyModifications;
}
private VisualElement CreateUpgradeUI(YarnProjectImporter importer)
{
var ui = new VisualElement();
var box = new VisualElement();
box.AddToClassList("help-box");
Label header = new Label("This project needs to be upgraded.");
header.style.unityFontStyleAndWeight = FontStyle.Bold;
box.Add(header);
box.Add(new Label("After upgrading, you will need to update your localisations, and ensure that all of the Yarn scripts for this project are in the same folder as the project."));
box.Add(new Label("Your Yarn scripts will not be modified."));
var learnMoreLink = new Label("Learn more...");
learnMoreLink.RegisterCallback<MouseDownEvent>(evt =>
{
Application.OpenURL(ProjectUpgradeHelpURL);
});
learnMoreLink.AddToClassList("link");
box.Add(learnMoreLink);
var upgradeButton = new Button(() =>
{
YarnProjectUtility.UpgradeYarnProject(importer);
// Reload the entire inspector - we will have changed the
// project significantly
ActiveEditorTracker.sharedTracker.ForceRebuild();
});
upgradeButton.text = "Upgrade Yarn Project";
box.Add(upgradeButton);
ui.Add(box);
ui.Add(new IMGUIContainer(ApplyRevertGUI));
return ui;
}
private VisualElement CreateErrorUI(string headerText, string[] labels, string linkLabel, string link)
{
var ui = new VisualElement();
var box = new VisualElement();
box.AddToClassList("help-box");
Label header = new Label(headerText);
header.style.unityFontStyleAndWeight = FontStyle.Bold;
box.Add(header);
foreach (var label in labels)
{
box.Add(new Label(label));
}
var learnMoreLink = new Label(linkLabel);
learnMoreLink.RegisterCallback<MouseDownEvent>(evt =>
{
Application.OpenURL(link);
});
learnMoreLink.AddToClassList("link");
box.Add(learnMoreLink);
ui.Add(box);
ui.Add(new IMGUIContainer(ApplyRevertGUI));
return ui;
}
private VisualElement CreateCriticalErrorUI()
{
string[] labels = {
"This is likely due to a bug on our end, and not in your project.",
"Try recreating the project and see if this resolves the issue."
};
return CreateErrorUI("This project has failed to import due to an internal error.", labels, "If the issue persists, please open an issue.", CreateNewIssueURL);
}
private VisualElement CreateUnknownErrorUI()
{
string[] labels = {
"The type of this Yarn Project is unknown.",
"Try recreating the project and see if this resolves the issue."
};
return CreateErrorUI("This project has failed to import correctly.", labels, "If the issue persists, please open an issue.", CreateNewIssueURL);
}
}
}