-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathDictionaryConfigurationController.cs
More file actions
1682 lines (1550 loc) · 65.3 KB
/
Copy pathDictionaryConfigurationController.cs
File metadata and controls
1682 lines (1550 loc) · 65.3 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
// Copyright (c) 2014-2017 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SIL.LCModel.Core.Cellar;
using SIL.LCModel.Core.WritingSystems;
using SIL.FieldWorks.Common.Controls;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.FieldWorks.Common.FwUtils;
using static SIL.FieldWorks.Common.FwUtils.FwUtils;
using SIL.LCModel;
using SIL.LCModel.Application;
using SIL.LCModel.DomainImpl;
using SIL.LCModel.DomainServices;
using SIL.LCModel.Infrastructure;
using SIL.FieldWorks.XWorks.DictionaryDetailsView;
using XCore;
namespace SIL.FieldWorks.XWorks
{
internal class DictionaryConfigurationController
{
/// <summary>
/// The current model being worked with
/// </summary>
internal DictionaryConfigurationModel _model;
/// <summary>
/// The entry being used for preview purposes
/// </summary>
internal ICmObject _previewEntry;
/// <summary>
/// PropertyTable to use
/// </summary>
internal PropertyTable _propertyTable;
private LcmCache Cache { get { return _propertyTable.GetValue<LcmCache>("cache"); } }
/// <summary>
/// The view to display the model in
/// </summary>
internal IDictionaryConfigurationView View { get; set; }
/// <summary>
/// Controls the portion of the dialog where an element in a dictionary entry is configured in detail
/// </summary>
private DictionaryDetailsController DetailsController { get; set; }
/// <summary>
/// Available dictionary configurations (eg stem- and root-based)
/// </summary>
internal List<DictionaryConfigurationModel> _dictionaryConfigurations;
/// <summary>
/// Directory where configurations of the current type (Dictionary, Reversal, ...) are stored
/// for the project.
/// </summary>
private string _projectConfigDir;
/// <summary>
/// Publication decorator necessary to view sense numbers in the preview
/// </summary>
private DictionaryPublicationDecorator _allEntriesPublicationDecorator;
/// <summary>
/// Directory where shipped default configurations of the current type (Dictionary, Reversal, ...)
/// are stored.
/// </summary>
internal string _defaultConfigDir;
private bool m_isDirty;
/// <summary>
/// Flag whether we're highlighting the affected node in the preview area.
/// </summary>
private bool _isHighlighted;
/// <summary>
/// Whether any changes have been saved, including changes to the Configs, which Config is the current Config, changes to Styles, etc.,
/// that require the preview to be updated.
/// </summary>
public bool MasterRefreshRequired { get; private set; }
public enum ExclusionReasonCode
{
NotExcluded,
NotInPublication,
ExcludedHeadword,
ExcludedMinorEntry
}
/// <summary>
/// Figure out what alternate dictionaries are available (eg root-, stem-, ...)
/// Populate _dictionaryConfigurations with available models.
/// Populate view's list of alternate dictionaries with available choices.
/// </summary>
private void LoadDictionaryConfigurations()
{
_dictionaryConfigurations = GetDictionaryConfigurationModels(Cache, _defaultConfigDir, _projectConfigDir);
View.SetChoices(_dictionaryConfigurations);
}
/// <summary>
/// Loads a List of configuration choices from default and projcet folders.
/// Project-specific configurations override default configurations of the same (file)name.
/// </summary>
/// <param name="defaultPath"></param>
/// <param name="projectPath"></param>
/// <seealso cref="XhtmlDocView.GatherBuiltInAndUserConfigurations()"/>
/// <returns>List of paths to configurations</returns>
internal static List<string> ListDictionaryConfigurationChoices(string defaultPath, string projectPath)
{
var choices = new Dictionary<string, string>();
foreach(var file in Directory.EnumerateFiles(defaultPath, "*" + DictionaryConfigurationModel.FileExtension))
{
choices[Path.GetFileNameWithoutExtension(file)] = file;
}
if(!Directory.Exists(projectPath))
{
Directory.CreateDirectory(projectPath);
}
else
{
foreach(var choice in Directory.EnumerateFiles(projectPath, "*" + DictionaryConfigurationModel.FileExtension))
{
choices[Path.GetFileNameWithoutExtension(choice)] = choice;
}
}
return choices.Values.ToList();
}
/// <summary>
/// Return dictionary configurations from default and project-specific paths, skipping default/shipped configurations that are
/// superceded by project-specific configurations. Keys are labels, values are the models.
/// </summary>
public static Dictionary<string, DictionaryConfigurationModel> GetDictionaryConfigurationLabels(LcmCache cache, string defaultPath, string projectPath)
{
var configurationModels = GetDictionaryConfigurationModels(cache, defaultPath, projectPath);
var labelToFileDictionary = new Dictionary<string, DictionaryConfigurationModel>();
foreach(var model in configurationModels)
{
labelToFileDictionary[model.Label] = model;
}
return labelToFileDictionary;
}
public static List<DictionaryConfigurationModel> GetDictionaryConfigurationModels(LcmCache cache, string defaultPath, string projectPath)
{
var configurationPaths = ListDictionaryConfigurationChoices(defaultPath, projectPath);
var configurationModels = configurationPaths.Select(path => new DictionaryConfigurationModel(path, cache)).ToList();
configurationModels.Sort((lhs, rhs) => string.Compare(lhs.Label, rhs.Label, StringComparison.InvariantCulture));
return configurationModels;
}
/// <summary>
/// Populate dictionary elements tree, from model.
/// </summary>
internal void PopulateTreeView()
{
RefreshView();
}
/// <summary>
/// Refresh view from model. Try to select nodeToSelect in the view afterward. If nodeToSelect is null, try to preserve the existing node selection.
/// </summary>
private void RefreshView(ConfigurableDictionaryNode nodeToSelect = null)
{
var tree = View.TreeControl.Tree;
var expandedNodes = new List<ConfigurableDictionaryNode>();
FindExpandedNodes(tree.Nodes, ref expandedNodes);
ConfigurableDictionaryNode topVisibleNode = null;
if (tree.TopNode != null)
topVisibleNode = tree.TopNode.Tag as ConfigurableDictionaryNode;
if (nodeToSelect == null && tree.SelectedNode != null)
nodeToSelect = tree.SelectedNode.Tag as ConfigurableDictionaryNode;
// Rebuild view from model
tree.Nodes.Clear();
var rootNodes = _model.Parts;
CreateTreeOfTreeNodes(null, rootNodes);
// Preserve treenode expansions
foreach (var expandedNode in expandedNodes)
{
//If an expanded node is removed it is added to the expanedNodes list before
//the tree is rebuilt. Therefore when tree is rebuilt FindTreeNode returns null since
//it cannot find that node anymore.
var node = FindTreeNode(expandedNode, tree.Nodes);
if (node != null)
node.Expand();
}
if (nodeToSelect != null)
tree.SelectedNode = FindTreeNode(nodeToSelect, tree.Nodes);
// Fallback to selecting first root, trying to make sure there is always a selection for the buttons to be enabled or disabled with respect to.
if (tree.SelectedNode == null && tree.Nodes.Count > 0)
tree.SelectedNode = tree.Nodes[0];
// Try to prevent scrolling away from what the user was seeing in the tree. But if necessary, scroll so the selected node is visible.
if (topVisibleNode != null)
tree.TopNode = FindTreeNode(topVisibleNode, tree.Nodes);
if (tree.SelectedNode != null)
tree.SelectedNode.EnsureVisible();
RefreshPreview();
DisplayPublicationTypes();
}
/// <summary>Refresh the Preview without reloading the entire configuration tree</summary>
private void RefreshPreview(bool isChangeInDictionaryModel = true)
{
if (isChangeInDictionaryModel)
m_isDirty = true;
else
MasterRefreshRequired = true;
//_propertyTable should be null only for unit tests which don't need styles
if (_propertyTable == null || _previewEntry == null || !_previewEntry.IsValidObject)
return;
View.PreviewData = LcmXhtmlGenerator.GenerateEntryHtmlWithStyles(_previewEntry, _model, _allEntriesPublicationDecorator, _propertyTable);
if(_isHighlighted)
View.HighlightContent(View.TreeControl.Tree.SelectedNode.Tag as ConfigurableDictionaryNode, Cache);
}
/// <summary>
/// Populate a list of dictionary nodes that correspond to treenodes that are expanded in the 'treenodes' or its children.
/// </summary>
private static void FindExpandedNodes(TreeNodeCollection treenodes, ref List<ConfigurableDictionaryNode> expandedNodes)
{
foreach (TreeNode treenode in treenodes)
{
if (treenode.IsExpanded)
expandedNodes.Add(treenode.Tag as ConfigurableDictionaryNode);
FindExpandedNodes(treenode.Nodes, ref expandedNodes);
}
}
/// <summary>
/// Create a tree of TreeNodes from a list of nodes and their Children, adding
/// them into the TreeView parented by the TreeNode corresponding
/// to parent.
/// If parent is null, the nodes are added as direct children of the TreeView
/// </summary>
internal void CreateTreeOfTreeNodes(ConfigurableDictionaryNode parent, List<ConfigurableDictionaryNode> nodes)
{
if (nodes == null)
throw new ArgumentNullException();
foreach(var node in nodes)
{
CreateAndAddTreeNodeForNode(parent, node);
// Configure shared nodes exactly once: under their master parent
if (!node.IsSubordinateParent && node.ReferencedOrDirectChildren != null)
CreateTreeOfTreeNodes(node, node.ReferencedOrDirectChildren);
}
}
/// <summary>
/// Create a TreeNode corresponding to node, and add it to the
/// TreeView parented by the TreeNode corresponding to parentNode.
/// If parentNode is null, node is considered to be at the root.
/// </summary>
/// <param name="parentNode"></param>
/// <param name="node"></param>
internal void CreateAndAddTreeNodeForNode(ConfigurableDictionaryNode parentNode, ConfigurableDictionaryNode node)
{
if (node == null)
throw new ArgumentNullException();
node.StringTable = StringTable.Table; // for localization
var newTreeNode = new TreeNode(node.DisplayLabel) { Tag = node, Checked = node.IsEnabled };
var treeView = View.TreeControl.Tree;
if (parentNode == null)
{
treeView.Nodes.Add(newTreeNode);
treeView.TopNode = newTreeNode;
return;
}
var parentTreeNode = FindTreeNode(parentNode, treeView.Nodes);
if (parentTreeNode != null)
{
parentTreeNode.Nodes.Add(newTreeNode);
}
}
/// <summary>
/// FindTreeNode returns the treenode which has the tag that matches nodeToMatch, or null
/// </summary>
/// <param name="nodeToMatch"></param>
/// <param name="treeNodeCollection"></param>
/// <returns></returns>
internal static TreeNode FindTreeNode(ConfigurableDictionaryNode nodeToMatch, TreeNodeCollection treeNodeCollection)
{
if(nodeToMatch == null || treeNodeCollection == null)
{
throw new ArgumentNullException();
}
// Prefer ReferenceEquals over Equals when there are duplicate custom nodes.
// You can have duplicate custom nodes when a node is an IEntryOrSense
// and both LexEntry and LexSense have a custom field with the same name.
// This fixes the configuration outline problem in LT-18913.
foreach (TreeNode treeNode in treeNodeCollection)
{
if (ReferenceEquals(nodeToMatch, treeNode.Tag))
{
return treeNode;
}
}
foreach(TreeNode treeNode in treeNodeCollection)
{
if(nodeToMatch.Equals(treeNode.Tag))
{
return treeNode;
}
var branchResult = FindTreeNode(nodeToMatch, treeNode.Nodes);
if(branchResult != null)
{
return branchResult;
}
}
return null;
}
/// <summary>
/// Default constructor to make testing easier.
/// </summary>
internal DictionaryConfigurationController()
{
}
/// <summary>
/// Constructs a DictionaryConfigurationController with a view and a model pulled from user settings
/// </summary>
/// <param name="view"></param>
/// <param name="propertyTable"></param>
/// <param name="previewEntry"></param>
public DictionaryConfigurationController(IDictionaryConfigurationView view, PropertyTable propertyTable, Mediator mediator, ICmObject previewEntry)
{
_propertyTable = propertyTable;
var cache = propertyTable.GetValue<LcmCache>("cache");
_allEntriesPublicationDecorator = new DictionaryPublicationDecorator(cache,
(ISilDataAccessManaged)cache.MainCacheAccessor, cache.ServiceLocator.GetInstance<Virtuals>().LexDbEntries);
_previewEntry = previewEntry ?? GetDefaultEntryForType(DictionaryConfigurationListener.GetDictionaryConfigurationBaseType(propertyTable), cache);
View = view;
_projectConfigDir = DictionaryConfigurationListener.GetProjectConfigurationDirectory(propertyTable, previewEntry);
_defaultConfigDir = DictionaryConfigurationListener.GetDefaultConfigurationDirectory(propertyTable, previewEntry);
LoadDictionaryConfigurations();
LoadLastDictionaryConfiguration(previewEntry);
PopulateTreeView();
View.ManageConfigurations += (sender, args) =>
{
var currentModel = _model;
bool managerMadeChanges;
// show the Configuration Manager dialog
using (var dialog = new DictionaryConfigurationManagerDlg(_propertyTable.GetValue<IHelpTopicProvider>("HelpTopicProvider")))
{
var configurationManagerController = new DictionaryConfigurationManagerController(dialog, _propertyTable, mediator,
_dictionaryConfigurations, GetAllPublications(cache), _projectConfigDir, _defaultConfigDir, _model);
configurationManagerController.Finished += SelectModelFromManager;
configurationManagerController.ConfigurationViewImported += () =>
{
SaveModel();
MasterRefreshRequired = false; // We're reloading the whole app, that's refresh enough
View.Close();
Publisher.Publish(new PublisherParameterObject(EventConstants.ReloadAreaTools, "lists"));
};
SetManagerTypeInfo(dialog);
dialog.ShowDialog(View as Form);
managerMadeChanges = configurationManagerController.IsDirty || _model != currentModel;
}
// if the manager has not updated anything then we don't need to make any adustments
if (!managerMadeChanges)
return;
// Update our Views
View.SetChoices(_dictionaryConfigurations);
SaveModel();
SelectCurrentConfigurationAndRefresh();
};
View.SaveModel += SaveModelHandler;
View.SwitchConfiguration += (sender, args) =>
{
if (_model == args.ConfigurationPicked)
return;
_model = args.ConfigurationPicked;
SetConfigureHomographParameters(_model, cache);
RefreshView(); // isChangeInDictionaryModel: true, because we update the current config in the PropertyTable when we save the model.
};
View.TreeControl.MoveUp += node => Reorder(node.Tag as ConfigurableDictionaryNode, Direction.Up);
View.TreeControl.MoveDown += node => Reorder(node.Tag as ConfigurableDictionaryNode, Direction.Down);
View.TreeControl.Duplicate += node =>
{
var dictionaryNode = node.Tag as ConfigurableDictionaryNode;
var siblings = dictionaryNode.Parent == null ? _model.Parts : dictionaryNode.Parent.Children;
var duplicate = dictionaryNode.DuplicateAmongSiblings(siblings);
RefreshView(duplicate);
};
View.TreeControl.Rename += node =>
{
var dictionaryNode = node.Tag as ConfigurableDictionaryNode;
var siblings = dictionaryNode.Parent == null ? _model.Parts : dictionaryNode.Parent.Children;
using (var renameDialog = new DictionaryConfigurationNodeRenameDlg())
{
renameDialog.DisplayLabel = dictionaryNode.DisplayLabel;
renameDialog.NewSuffix = dictionaryNode.LabelSuffix;
// Unchanged?
if (renameDialog.ShowDialog() != DialogResult.OK || renameDialog.NewSuffix == dictionaryNode.LabelSuffix)
return;
if (!dictionaryNode.ChangeSuffix(renameDialog.NewSuffix, siblings))
{
MessageBox.Show(xWorksStrings.FailedToRename);
return;
}
}
RefreshView();
};
View.TreeControl.Remove += node =>
{
var dictionaryNode = node.Tag as ConfigurableDictionaryNode;
if (dictionaryNode.Parent == null)
_model.Parts.Remove(dictionaryNode);
else
dictionaryNode.UnlinkFromParent();
RefreshView();
};
View.TreeControl.Highlight += (node, button, tooltip) =>
{
_isHighlighted = !_isHighlighted;
if (_isHighlighted)
{
View.HighlightContent(node.Tag as ConfigurableDictionaryNode, cache);
button.BackColor = Color.White;
tooltip.SetToolTip(button, xWorksStrings.RemoveHighlighting);
}
else
{
View.HighlightContent(null, cache); // turns off current highlighting.
button.BackColor = Color.Yellow;
tooltip.SetToolTip(button, xWorksStrings.HighlightAffectedContent);
}
};
View.TreeControl.Tree.AfterCheck += (sender, args) =>
{
var node = (ConfigurableDictionaryNode) args.Node.Tag;
node.IsEnabled = args.Node.Checked;
// Details may need to be enabled or disabled
RefreshPreview();
View.TreeControl.Tree.SelectedNode = FindTreeNode(node, View.TreeControl.Tree.Nodes);
BuildAndShowOptions(node);
};
View.TreeControl.Tree.AfterSelect += (sender, args) =>
{
var node = (ConfigurableDictionaryNode) args.Node.Tag;
View.TreeControl.MoveUpEnabled = CanReorder(node, Direction.Up);
View.TreeControl.MoveDownEnabled = CanReorder(node, Direction.Down);
View.TreeControl.DuplicateEnabled = !node.IsMainEntry;
View.TreeControl.RemoveEnabled = node.IsDuplicate;
View.TreeControl.RenameEnabled = node.IsDuplicate;
BuildAndShowOptions(node);
if (_isHighlighted)
{
// Highlighting is turned on, change what is highlighted.
View.HighlightContent(node, cache);
}
};
View.TreeControl.CheckAll += treeNode =>
{
EnableNodeAndDescendants(treeNode.Tag as ConfigurableDictionaryNode);
RefreshView();
};
View.TreeControl.UnCheckAll += treeNode =>
{
DisableNodeAndDescendants(treeNode.Tag as ConfigurableDictionaryNode);
RefreshView();
};
SelectCurrentConfigurationAndRefresh();
MasterRefreshRequired = m_isDirty = false;
}
/// <summary>
/// Sets Parameters for Numbering styles.
/// </summary>
/// <param name="model"></param>
/// <param name="cache"></param>
public static void SetConfigureHomographParameters(DictionaryConfigurationModel model, LcmCache cache)
{
var cacheHc = cache.ServiceLocator.GetInstance<HomographConfiguration>();
if (model.HomographConfiguration == null)
{
model.HomographConfiguration = new DictionaryHomographConfiguration(new HomographConfiguration());
}
model.HomographConfiguration.ExportToHomographConfiguration(cacheHc);
if (model.Parts.Count == 0) return;
var mainEntryNode = model.Parts[0];
//Sense Node
string senseType = (mainEntryNode.DisplayLabel == "Reversal Entry") ? "Referenced Senses" : "Senses";
var senseNode = mainEntryNode.Children.Where(prop => prop.Label == senseType).FirstOrDefault();
if (senseNode == null) return;
var senseOptions = (DictionaryNodeSenseOptions)senseNode.DictionaryNodeOptions;
cacheHc.ksSenseNumberStyle = senseOptions.NumberingStyle;
//SubSense Node
var subSenseNode = senseNode.Children.Where(prop => prop.Label == "Subsenses").FirstOrDefault();
if (subSenseNode == null) return;
var subSenseOptions = (DictionaryNodeSenseOptions)subSenseNode.DictionaryNodeOptions;
cacheHc.ksSubSenseNumberStyle = subSenseOptions.NumberingStyle;
cacheHc.ksParentSenseNumberStyle = subSenseOptions.ParentSenseNumberingStyle;
//SubSubSense Node
var subSubSenseNode = subSenseNode.ReferencedOrDirectChildren.Where(prop => prop.Label == "Subsenses").FirstOrDefault();
if (subSubSenseNode == null) return;
var subSubSenseOptions = (DictionaryNodeSenseOptions)subSubSenseNode.DictionaryNodeOptions;
cacheHc.ksSubSubSenseNumberStyle = subSubSenseOptions.NumberingStyle;
cacheHc.ksParentSubSenseNumberStyle = subSubSenseOptions.ParentSenseNumberingStyle;
}
private void SetManagerTypeInfo(DictionaryConfigurationManagerDlg dialog)
{
dialog.HelpTopic = DictionaryConfigurationListener.GetDictionaryConfigurationBaseType(_propertyTable) == xWorksStrings.Dictionary
? "khtpDictConfigManager"
: "khtpRevIndexConfigManager";
if (DictionaryConfigurationListener.GetDictionaryConfigurationBaseType(_propertyTable) == xWorksStrings.ReversalIndex)
{
dialog.Text = xWorksStrings.ReversalIndexConfigurationDlgTitle;
dialog.ConfigurationGroupText = xWorksStrings.DictionaryConfigurationMangager_ReversalConfigurations_GroupLabel;
}
else if (DictionaryConfigurationListener.GetDictionaryConfigurationBaseType(_propertyTable) == xWorksStrings.ClassifiedDictionary)
{
dialog.Text = xWorksStrings.ClassifiedDictionaryConfigurationDlgTitle;
dialog.ConfigurationGroupText = xWorksStrings.DictionaryConfigurationMangager_ClassifiedConfigurations_GroupLabel;
}
}
public void SelectModelFromManager(DictionaryConfigurationModel model)
{
_model = model;
}
/// <summary>
/// Returns a default entry for the given configuration type or null if the cache has no items for that type.
/// </summary>
internal static ICmObject GetDefaultEntryForType(string configurationType, LcmCache cache)
{
var serviceLocator = cache.ServiceLocator;
switch(configurationType)
{
case "Dictionary":
{
var entryRepo = serviceLocator.GetInstance<ILexEntryRepository>().AllInstances().ToList();
// try to find the first entry with a headword not equal to "???"; otherwise, any entry will have to do.
return entryRepo.FirstOrDefault(entry => StringServices.DefaultHomographString() != entry.HeadWord.Text)
?? entryRepo.FirstOrDefault();
}
case "Reversal Index":
{
var entryRepo = serviceLocator.GetInstance<IReversalIndexEntryRepository>().AllInstances().ToList(); // TODO pH 2015.07: filter by WS
// try to find the first entry with a headword not equal to "???"; otherwise, any entry will have to do.
return entryRepo.FirstOrDefault(
entry => StringServices.DefaultHomographString() != entry.ReversalForm.BestAnalysisAlternative.Text)
?? entryRepo.FirstOrDefault() ?? serviceLocator.GetInstance<IReversalIndexEntryFactory>().Create();
}
default:
{
throw new NotImplementedException(String.Format("Default entry for {0} type not implemented.", configurationType));
}
}
}
private void LoadLastDictionaryConfiguration(ICmObject obj)
{
var lastUsedConfiguration = DictionaryConfigurationListener.GetCurrentConfiguration(_propertyTable, null, obj);
_model = _dictionaryConfigurations.FirstOrDefault(config => config.FilePath == lastUsedConfiguration)
?? _dictionaryConfigurations.First();
}
private void SaveModelHandler(object sender, EventArgs e)
{
if (m_isDirty)
SaveModel();
}
internal void SaveModel()
{
foreach (var config in _dictionaryConfigurations)
{
config.FilePath = GetProjectConfigLocationForPath(config.FilePath);
config.Save();
}
// This property must be set *after* saving, because the initial save changes the FilePath
DictionaryConfigurationListener.SetCurrentConfiguration(_propertyTable, _model.FilePath, false);
MasterRefreshRequired = true;
m_isDirty = false;
}
internal string GetProjectConfigLocationForPath(string filePath)
{
var projectConfigDir = LcmFileHelper.GetConfigSettingsDir(Cache.ProjectId.ProjectFolder);
if(filePath.StartsWith(projectConfigDir))
{
return filePath;
}
var detailedConfig = filePath.Substring(FwDirectoryFinder.DefaultConfigurations.Length + 1);
return Path.Combine(projectConfigDir, detailedConfig);
}
/// <summary>
/// Populate options pane, from model.
/// </summary>
private void BuildAndShowOptions(ConfigurableDictionaryNode node)
{
if (DetailsController == null)
{
DetailsController = new DictionaryDetailsController(new DetailsView(), _propertyTable);
DetailsController.DetailsModelChanged += (sender, e) => RefreshPreview();
DetailsController.StylesDialogMadeChanges += (sender, e) =>
{
EnsureValidStylesInModel(_model, Cache); // in case the change was a rename or deletion
RefreshPreview(false);
};
DetailsController.SelectedNodeChanged += (sender, e) =>
{
var nodeToSelect = sender as ConfigurableDictionaryNode;
if (nodeToSelect != null)
View.TreeControl.Tree.SelectedNode = FindTreeNode(nodeToSelect, View.TreeControl.Tree.Nodes);
};
}
DetailsController.LoadNode(_model, node);
View.DetailsView = DetailsController.View;
}
/// <summary>
/// Whether node can be moved among its siblings, or if it can be moved out of a grouping node.
/// </summary>
public static bool CanReorder(ConfigurableDictionaryNode node, Direction direction)
{
if (node == null)
throw new ArgumentNullException();
var parent = node.Parent;
// Root nodes can't be moved
if (parent == null)
return false;
var nodeIndex = parent.Children.IndexOf(node);
if (direction == Direction.Up && nodeIndex == 0 && !(parent.DictionaryNodeOptions is DictionaryNodeGroupingOptions))
return false;
var lastSiblingIndex = parent.Children.Count - 1;
if (direction == Direction.Down && nodeIndex == lastSiblingIndex && !(parent.DictionaryNodeOptions is DictionaryNodeGroupingOptions))
return false;
return true;
}
/// <summary>
/// Display the list of publications configured by the current dictionary configuration.
/// </summary>
private void DisplayPublicationTypes()
{
View.ShowPublicationsForConfiguration(AffectedPublications);
}
/// <summary>
/// Friendly display string listing the publications affected by making changes to the current dictionary configuration.
/// </summary>
public string AffectedPublications
{
get
{
if (_model.AllPublications)
return xWorksStrings.Allpublications;
var strbldr = new StringBuilder();
if (_model.Publications == null || !_model.Publications.Any())
return xWorksStrings.ksNone1;
foreach (var pubType in _model.Publications)
{
strbldr.AppendFormat("{0}, ", pubType);
}
var str = strbldr.ToString();
return str.Substring(0, str.Length - 2);
}
}
private void SelectCurrentConfigurationAndRefresh()
{
View.SelectConfiguration(_model);
// if the model has no homograph configurations saved then fill it with a default version
if (_model.HomographConfiguration == null)
{
_model.HomographConfiguration = new DictionaryHomographConfiguration(new HomographConfiguration());
}
_model.HomographConfiguration.ExportToHomographConfiguration(Cache.ServiceLocator.GetInstance<HomographConfiguration>());
RefreshView(); // REVIEW pH 2016.02: this is called only in ctor and after ManageViews. do we even want to refresh and set isDirty?
}
/// <summary>
/// Represents the direction of moving a configuration node among its siblings. (Not up or down a hierarchy).
/// </summary>
internal enum Direction
{
Up,
Down
}
/// <summary>
/// Move a node among its siblings in the model, and cause the view to update accordingly.
/// </summary>
public void Reorder(ConfigurableDictionaryNode node, Direction direction)
{
if (node == null)
throw new ArgumentNullException();
if (!CanReorder(node, direction))
throw new ArgumentOutOfRangeException();
var parent = node.Parent;
var nodeIndex = parent.Children.IndexOf(node);
// For Direction.Up
var newNodeIndex = nodeIndex - 1;
// or Down
if (direction == Direction.Down)
newNodeIndex = nodeIndex + 1;
var movingOutOfGroup = (newNodeIndex == -1 || newNodeIndex >= parent.Children.Count) &&
parent.DictionaryNodeOptions is DictionaryNodeGroupingOptions;
if (movingOutOfGroup)
{
MoveNodeOutOfGroup(node, direction, parent, nodeIndex);
}
else if (parent.Children[newNodeIndex].DictionaryNodeOptions is DictionaryNodeGroupingOptions &&
!(node.DictionaryNodeOptions is DictionaryNodeGroupingOptions))
{
MoveNodeIntoGroup(node, direction, parent, newNodeIndex, nodeIndex);
}
else
{
parent.Children.RemoveAt(nodeIndex);
parent.Children.Insert(newNodeIndex, node);
}
RefreshView();
}
private static void MoveNodeIntoGroup(ConfigurableDictionaryNode node, Direction direction,
ConfigurableDictionaryNode parent, int newNodeIndex, int nodeIndex)
{
var targetGroupNode = parent.Children[newNodeIndex];
parent.Children.RemoveAt(nodeIndex);
if (targetGroupNode.Children == null)
targetGroupNode.Children = new List<ConfigurableDictionaryNode>();
if (direction == Direction.Up)
{
targetGroupNode.Children.Add(node);
}
else
{
targetGroupNode.Children.Insert(0, node);
}
node.Parent = targetGroupNode;
}
private static void MoveNodeOutOfGroup(ConfigurableDictionaryNode node, Direction direction,
ConfigurableDictionaryNode parent, int nodeIndex)
{
parent.Children.RemoveAt(nodeIndex);
var indexOfParentGroup = parent.Parent.Children.IndexOf(parent);
if (direction == Direction.Down)
{
parent.Parent.Children.Insert(indexOfParentGroup + 1, node);
}
else
{
parent.Parent.Children.Insert(indexOfParentGroup, node);
}
node.Parent = parent.Parent;
}
/// <summary>
/// Link this node to a SharedItem to use its children. Returns true if this node is the first (Master) parent; false otherwise
/// </summary>
public static bool LinkReferencedNode(List<ConfigurableDictionaryNode> sharedItems, ConfigurableDictionaryNode node, string referenceItem)
{
node.ReferencedNode = sharedItems.FirstOrDefault(
si => si.Label == referenceItem && si.FieldDescription == node.FieldDescription && si.SubField == node.SubField);
if (node.ReferencedNode == null)
throw new KeyNotFoundException(String.Format("Could not find Referenced Node named {0} for field {1}.{2}",
referenceItem, node.FieldDescription, node.SubField));
node.ReferenceItem = referenceItem;
node.ReferencedNode.IsEnabled = true;
if (node.ReferencedNode.Parent != null)
return false;
node.ReferencedNode.Parent = node;
return true;
}
/// <summary>
/// Allow other nodes to reference this node's children
/// </summary>
public static void ShareNodeAsReference(List<ConfigurableDictionaryNode> sharedItems, ConfigurableDictionaryNode node, string cssClass = null)
{
if (node.ReferencedNode != null)
throw new InvalidOperationException(String.Format("Node {0} is already shared as {1}",
DictionaryConfigurationMigrator.BuildPathStringFromNode(node), node.ReferenceItem ?? node.ReferencedNode.Label));
if (node.Children == null || !node.Children.Any())
return; // no point sharing Children there aren't any
var dupItem = sharedItems.FirstOrDefault(item => item.FieldDescription == node.FieldDescription && item.SubField == node.SubField);
if (dupItem != null)
{
var fullField = String.IsNullOrEmpty(node.SubField)
? node.FieldDescription
: String.Format("{0}.{1}", node.FieldDescription, node.SubField);
MessageBoxUtils.Show(String.Format(xWorksStrings.InadvisableToShare,
node.DisplayLabel, fullField, DictionaryConfigurationMigrator.BuildPathStringFromNode(dupItem.Parent)));
return;
}
// ENHANCE (Hasso) 2016.03: enforce that the specified node is part of *this* model (incl shared items)
var key = String.IsNullOrEmpty(node.ReferenceItem) ? String.Format("Shared{0}", node.Label) : node.ReferenceItem;
cssClass = String.IsNullOrEmpty(cssClass) ? String.Format("shared{0}", CssGenerator.GetClassAttributeForConfig(node)) : cssClass.ToLowerInvariant();
// Ensure the shared node's Label and CSSClassNameOverride are both unique within this Configuration
if (sharedItems.Any(item => item.Label == key || item.CSSClassNameOverride == cssClass))
{
throw new ArgumentException(String.Format("A SharedItem already exists with the Label '{0}' or the class '{1}'", key, cssClass));
}
var sharedItem = new ConfigurableDictionaryNode
{
Label = key,
CSSClassNameOverride = cssClass,
FieldDescription = node.FieldDescription,
SubField = node.SubField,
Parent = node,
Children = node.Children, // ENHANCE (Hasso) 2016.03: deep-clone so that unshared changes are not lost? Or only on share-with?
IsEnabled = true // shared items are always enabled (for configurability)
};
foreach (var child in sharedItem.Children)
child.Parent = sharedItem;
sharedItems.Add(sharedItem);
node.ReferenceItem = key;
node.ReferencedNode = sharedItem;
node.Children = null; // For now, we expect that nodes have ReferencedChildren NAND direct Children.
// ENHANCE pH 2016.04: if we ever allow nodes to have both Referenced and direct Children, all DC-model-sync code will need to change.
}
#region ModelSynchronization
public static void MergeTypesIntoDictionaryModel(DictionaryConfigurationModel model, LcmCache cache)
{
var complexTypes = new HashSet<Guid>();
foreach (var pos in cache.LangProject.LexDbOA.ComplexEntryTypesOA.ReallyReallyAllPossibilities)
complexTypes.Add(pos.Guid);
complexTypes.Add(XmlViewsUtils.GetGuidForUnspecifiedComplexFormType());
var variantTypes = new HashSet<Guid>();
foreach (var pos in cache.LangProject.LexDbOA.VariantEntryTypesOA.ReallyReallyAllPossibilities)
variantTypes.Add(pos.Guid);
variantTypes.Add(XmlViewsUtils.GetGuidForUnspecifiedVariantType());
var referenceTypes = new HashSet<Guid>();
if (cache.LangProject.LexDbOA.ReferencesOA != null)
{
foreach (var pos in cache.LangProject.LexDbOA.ReferencesOA.PossibilitiesOS)
{
referenceTypes.Add(pos.Guid);
}
}
var noteTypes = new HashSet<Guid>();
if (cache.LangProject.LexDbOA.ExtendedNoteTypesOA != null)
{
noteTypes = new HashSet<Guid>(cache.LangProject.LexDbOA.ExtendedNoteTypesOA.ReallyReallyAllPossibilities.Select(pos => pos.Guid))
{
XmlViewsUtils.GetGuidForUnspecifiedExtendedNoteType()
};
}
foreach (var part in model.PartsAndSharedItems)
{
FixTypeListOnNode(part, complexTypes, variantTypes, referenceTypes, noteTypes, model.IsHybrid, cache);
}
}
private static void FixTypeListOnNode(ConfigurableDictionaryNode node,
HashSet<Guid> complexTypes, HashSet<Guid> variantTypes, HashSet<Guid> referenceTypes, HashSet<Guid> noteTypes,
bool isHybrid, LcmCache cache)
{
var listOptions = node.DictionaryNodeOptions as DictionaryNodeListOptions;
if (listOptions != null)
{
switch (listOptions.ListId)
{
case DictionaryNodeListOptions.ListIds.None:
break;
case DictionaryNodeListOptions.ListIds.Complex:
FixOptionsAccordingToCurrentTypes(listOptions.Options, complexTypes, node, false, cache);
break;
case DictionaryNodeListOptions.ListIds.Variant:
FixOptionsAccordingToCurrentTypes(listOptions.Options, variantTypes, node,
IsFilteringInflectionalVariantTypes(node, isHybrid), cache);
break;
case DictionaryNodeListOptions.ListIds.Entry:
FixOptionsAccordingToCurrentTypes(listOptions.Options, referenceTypes, node, false, cache);
break;
case DictionaryNodeListOptions.ListIds.Sense:
FixOptionsAccordingToCurrentTypes(listOptions.Options, referenceTypes, node, false, cache);
break;
case DictionaryNodeListOptions.ListIds.Minor:
Guid[] complexAndVariant = complexTypes.Union(variantTypes).ToArray();
FixOptionsAccordingToCurrentTypes(listOptions.Options, complexAndVariant, node, false, cache);
break;
case DictionaryNodeListOptions.ListIds.Note:
FixOptionsAccordingToCurrentTypes(listOptions.Options, noteTypes, node, false, cache);
break;
default:
System.Diagnostics.Debug.Fail("Unhandled List Type: " + listOptions.ListId);
break;
}
}
//Recurse into child nodes and fix the type lists on them
if (node.Children != null)
{
foreach (var child in node.Children)
FixTypeListOnNode(child, complexTypes, variantTypes, referenceTypes, noteTypes, isHybrid, cache);
}
}
/// <summary>Called on nodes with Variant options to determine whether they are sharing Variants with a sibling</summary>
private static bool IsFilteringInflectionalVariantTypes(ConfigurableDictionaryNode node, bool isHybrid)
{
if (!isHybrid)
return false;
if (node.IsDuplicate)
return true;
var siblings = node.ReallyReallyAllSiblings;
// check whether this node has a duplicate, most likely "Variants (Inflectional Variants)"
return siblings != null && siblings.Any(sib => sib.FieldDescription == node.FieldDescription);
}
private static void FixOptionsAccordingToCurrentTypes(List<DictionaryNodeListOptions.DictionaryNodeOption> options,
ICollection<Guid> possibilities, ConfigurableDictionaryNode node, bool filterInflectionalVariantTypes, LcmCache cache)
{
var isDuplicate = node.IsDuplicate;
var currentGuids = new HashSet<Guid>();
foreach (var opt in options)
{
Guid guid;
if (Guid.TryParse(opt.Id, out guid)) // can be empty string
currentGuids.Add(guid);
}
if (filterInflectionalVariantTypes)
{
foreach (var custVariantType in possibilities.Where(type => !currentGuids.Contains(type)))
{
//Variants without any type are not Inflectional
var showCustomVariant = (custVariantType != XmlViewsUtils.GetGuidForUnspecifiedVariantType()
&& cache.ServiceLocator.GetObject(custVariantType) is ILexEntryInflType)
^ !isDuplicate;
// add new custom variant types disabled for the original and enabled for the inflectional variants copy
options.Add(new DictionaryNodeListOptions.DictionaryNodeOption
{
Id = custVariantType.ToString(),
IsEnabled = showCustomVariant
});
}
}
else
{
// add types that do not exist already
foreach (var pos in possibilities)
{
if (options.Any(x => x.Id == pos.ToString() + ":f" || x.Id == pos.ToString() + ":r"))
continue;
var lexRelType =
(ILexRefType) cache.LangProject.LexDbOA.ReferencesOA?.ReallyReallyAllPossibilities.FirstOrDefault(x =>
x.Guid == pos);
if (lexRelType != null)
{
if (LexRefTypeTags.IsAsymmetric((LexRefTypeTags.MappingTypes)lexRelType.MappingType))
{
options.Add(new DictionaryNodeListOptions.DictionaryNodeOption
{
Id = pos.ToString() + ":f",