/
ControlTreeView.cs
1995 lines (1759 loc) · 79 KB
/
ControlTreeView.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
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Schema;
using Microsoft.Win32;
using Office = Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
namespace XmlMappingTaskPane.Controls
{
public partial class ControlTreeView : Controls.ControlBase
{
// the current option set
private int m_grfOptions;
/// <summary>
/// Constant values corresponding to each option in the bitflag (for comparison).
/// </summary>
internal const int cOptionsShowAttributes = 1;
internal const int cOptionsShowText = 2;
internal const int cOptionsShowPI = 4;
internal const int cOptionsShowComments = 8;
internal const int cOptionsShowPropertyPage = 16;
internal const int cOptionsAutoSelectNode = 32;
//update the progress UI every N nodes
private const int cintUpdateFrequency = 33;
private TreeNode m_tnRoot; // the root treenode
private IDictionary<XmlNode, TreeNode> m_dicXnTn = new Dictionary<XmlNode, TreeNode>();
public ControlTreeView()
{
InitializeComponent();
//set up the options
try
{
Options = (int)Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\XML Mapping Task Pane").GetValue("Options");
}
catch (NullReferenceException nrex)
{
Debug.Fail("regkey corruption", "either the user manually deleted the regkeys, or something bad happened." + Environment.NewLine + nrex.Message);
}
}
/// <summary>
/// Get/set the options specified for the current treeview.
/// </summary>
internal int Options
{
get
{
return m_grfOptions;
}
set
{
m_grfOptions = value;
}
}
/// <summary>
/// Get the XmlDocument for the current XML part.
/// </summary>
private XmlDocument OwnerDocument
{
get
{
XmlDocument xdoc = null;
if (((XmlNode)m_tnRoot.Tag).NodeType == XmlNodeType.Document)
xdoc = (XmlDocument)m_tnRoot.Tag;
else
xdoc = ((XmlNode)m_tnRoot.Tag).OwnerDocument;
return xdoc;
}
}
#region Timer methods
/// <summary>
/// Start the loading timer.
/// </summary>
private delegate void StartTimerDelegate();
private void StartTimer()
{
if (InvokeRequired)
{
Invoke(new StartTimerDelegate(StartTimer), new object[] { });
return;
}
timerLoading.Start();
labelLoading.Visible = true;
}
/// <summary>
/// Stop the loading timer.
/// </summary>
private delegate void StopTimerDelegate();
private void StopTimer()
{
if (InvokeRequired)
{
Invoke(new StopTimerDelegate(StopTimer), new object[] { });
return;
}
timerLoading.Stop();
}
/// <summary>
/// Reset the loading timer.
/// </summary>
private delegate void ResetTimerDelegate();
private void ResetTimer()
{
if (InvokeRequired)
{
Invoke(new ResetTimerDelegate(ResetTimer), new object[] { });
return;
}
timerLoading.Stop();
labelLoading.Text = string.Empty;
labelLoading.Visible = false;
}
private void timerLoading_Tick(object sender, EventArgs e)
{
Debug.WriteLine("timer ticked");
SetLabelText(Properties.Resources.LoadingMessage);
StopTimer();
}
#endregion
#region TreeView manipulation methods
/// <summary>
/// Select the treeview node corresponding to a specific CustomXMLNode object.
/// </summary>
/// <param name="mxnBB">A CustomXMLNode specifying the node to be selected.</param>
internal delegate void SelectNodeFromTreeDelegate(Office.CustomXMLNode mxnBB);
internal void SelectNodeFromTree(Office.CustomXMLNode mxnBB)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new SelectNodeFromTreeDelegate(SelectNodeFromTree), new object[] { mxnBB });
return;
}
//we select the root (2nd) node to get the DOM
Debug.Assert(m_tnRoot != null, "Node doesn't exist", "You can't expect a root node?");
XmlDocument xdoc = OwnerDocument;
//then go mxn -> tn
XmlNode xnBB = Utilities.XnFromMxn(xdoc, mxnBB, null);
TreeNode tnBB = m_dicXnTn[xnBB];
treeView.SelectedNode = tnBB;
//update the properties
ControlMain controlMain = GetMainControl();
controlMain.RefreshProperties(mxnBB);
}
/// <summary>
/// Clear out all of the tree nodes from a treeview.
/// </summary>
/// <param name="tv">A TreeView whose contents should be cleared.</param>
private delegate void ClearTreeNodesDelegate(TreeView tv);
private void ClearTreeNodes(TreeView tv)
{
if (InvokeRequired)
{
Invoke(new ClearTreeNodesDelegate(ClearTreeNodes), new object[] { tv });
return;
}
tv.Nodes.Clear();
}
/// <summary>
/// Set the label on the loading control.
/// </summary>
/// <param name="s">A string specifying the new text for the control.</param>
private delegate void SetLabelTextDelegate(string s);
private void SetLabelText(string s)
{
if (InvokeRequired)
{
Invoke(new SetLabelTextDelegate(SetLabelText), new object[] { s });
return;
}
labelLoading.Text = s;
labelLoading.PerformLayout(this, "Text");
}
/// <summary>
/// Expand a specific node in the tree.
/// </summary>
/// <param name="tn">A TreeNode specifying the node to expand.</param>
private delegate void ExpandTreeNodeDelegate(TreeNode tn);
private void ExpandTreeNode(TreeNode tn)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new ExpandTreeNodeDelegate(ExpandTreeNode), new object[] { tn });
return;
}
tn.Expand();
}
/// <summary>
/// Ensure a specific tree element is visible.
/// </summary>
/// <param name="tn">A TreeNode specifying the node to make visible.</param>
private delegate void EnsureTreeNodeDelegate(TreeNode tn);
private void EnsureTreeNode(TreeNode tn)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new EnsureTreeNodeDelegate(EnsureTreeNode), new object[] { tn });
return;
}
tn.EnsureVisible();
}
/// <summary>
/// Add a tree node to the control.
/// </summary>
/// <param name="tnBase">The TreeNode within which the new node should be added.</param>
/// <param name="tnToAdd">The TreeNode to be added to the control.</param>
private delegate void AddTreeNodeDelegate(TreeNode tnBase, TreeNode tnToAdd);
private void AddTreeNode(TreeNode tnBase, TreeNode tnToAdd)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new AddTreeNodeDelegate(AddTreeNode), new object[] { tnBase, tnToAdd });
return;
}
tnBase.Nodes.Add(tnToAdd);
}
/// <summary>
/// Add the root node to the tree view control.
/// </summary>
/// <param name="tnToAdd">The TreeNode to be added to the control.</param>
private delegate void AddRootTreeNodeDelegate(TreeNode tnToAdd);
private void AddRootTreeNode(TreeNode tnToAdd)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new AddRootTreeNodeDelegate(AddRootTreeNode), new object[] { tnToAdd });
return;
}
treeView.Nodes.Add(tnToAdd);
}
/// <summary>
/// Set the image associated with a tree node.
/// </summary>
/// <param name="tn">The TreeNode whose image should be changed.</param>
/// <param name="ImageIndex">An integer containing the index of the desired image in the image collection.</param>
private delegate void SetTreeNodeImageDelegate(TreeNode tn, int ImageIndex);
private void SetTreeNodeImage(TreeNode tn, int ImageIndex)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new SetTreeNodeImageDelegate(SetTreeNodeImage), new object[] { tn, ImageIndex });
return;
}
tn.ImageIndex = ImageIndex;
tn.SelectedImageIndex = ImageIndex;
}
/// <summary>
/// Add a tree node to the tree view control at a specific position.
/// </summary>
/// <param name="tnBase">A TreeNode specifying the parent of the new tree node.</param>
/// <param name="tnToInsert">A TreeNode specifying the tree node to be added.</param>
/// <param name="Position">An integer specifying the ordinal position of the new node within the parent's child nodes.</param>
private delegate void InsertTreeNodeDelegate(TreeNode tnBase, TreeNode tnToInsert, int Position);
private void InsertTreeNode(TreeNode tnBase, TreeNode tnToInsert, int Position)
{
if (backgroundWorkerBuildTree.CancellationPending)
{
throw new QuitNowException();
}
else if (InvokeRequired)
{
Invoke(new InsertTreeNodeDelegate(InsertTreeNode), new object[] { tnBase, tnToInsert, Position });
return;
}
tnBase.Nodes.Insert(Position, tnToInsert);
}
#endregion
#region Tree Refresh methods/events
/// <summary>
/// Refresh the tree view.
/// </summary>
/// <param name="mxnToSelect">A CustomXMLNode specifying the node which should be selected after refresh completes.</param>
internal void RefreshTree(Office.CustomXMLNode mxnToSelect)
{
// build the tree view on a background thread
// this ensures that a large CustomXMLPart cannot hang the application, and
// that we can cancel load if the user wishes to
if (!backgroundWorkerMain.IsBusy)
{
backgroundWorkerMain.RunWorkerAsync(mxnToSelect);
}
else
{
Debug.Fail("unable to execute a refresh because the worker was already busy.");
}
}
/// <summary>
/// Tell the background worker thread to populate the tree view.
/// </summary>
private void backgroundWorkerMain_DoWork(object sender, DoWorkEventArgs e)
{
LWait:
//check if we've got a refresh going
if (backgroundWorkerBuildTree.IsBusy)
{
//we're already refreshing, so cancel it
backgroundWorkerBuildTree.CancelAsync();
//wait for it...
while (backgroundWorkerBuildTree.IsBusy)
{
Thread.Sleep(0);
}
}
//start a timer to ensure we only show progress if necessary
StartTimer();
//populate it
if (CurrentPart.DocumentElement != null)
{
TreeViewElements tve = new TreeViewElements(CurrentPart, (Office.CustomXMLNode)e.Argument);
if (!backgroundWorkerBuildTree.IsBusy)
{
backgroundWorkerBuildTree.RunWorkerAsync(tve);
}
else
goto LWait; //we started a task between now and the last cancel
}
else
{
//clear out
ClearTreeNodes(treeView);
ResetTimer();
}
}
/// <summary>
/// Do the work to actually build the tree view.
/// </summary>
private void backgroundWorkerBuildTree_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//load up the stream into an XML DOM
TreeViewElements tve = (TreeViewElements)e.Argument;
//load the DOM
tve.TreeViewDOM.PreserveWhitespace = true; //keep whitespace, like Office does
tve.TreeViewDOM.XmlResolver = null; // no entity/DTD expansion
tve.TreeViewDOM.LoadXml(tve.TreeViewPart.XML);
//get XSDs
if (CurrentPart.SchemaCollection != null && CurrentPart.SchemaCollection.Count > 0)
{
ValidationEventHandler veh = new ValidationEventHandler(xs_veh);
XmlSchemaSet xss = new XmlSchemaSet();
foreach (Office.CustomXMLSchema cxs in CurrentPart.SchemaCollection)
{
if (!string.IsNullOrEmpty(cxs.NamespaceURI) && !string.IsNullOrEmpty(cxs.Location))
xss.Add(cxs.NamespaceURI, cxs.Location);
}
if (xss.Count != 0)
{
xss.Compile();
tve.TreeViewDOM.Schemas = xss;
tve.TreeViewDOM.Validate(veh);
}
}
//clear the hashtable
m_dicXnTn.Clear();
//get total # of nodes
int intNumberProcessed = 0;
int intNumberTotal = tve.TreeViewDOM.SelectNodes("//*").Count;
if ((Options & cOptionsShowAttributes) != 0)
intNumberTotal += (tve.TreeViewDOM.SelectNodes("//@*").Count * 2); //2x because we have attribute and its text node
if ((Options & cOptionsShowComments) != 0)
intNumberTotal += tve.TreeViewDOM.SelectNodes("//comment()").Count;
if ((Options & cOptionsShowPI) != 0)
intNumberTotal += tve.TreeViewDOM.SelectNodes("//processing-instruction()").Count;
if ((Options & cOptionsShowText) != 0)
intNumberTotal += tve.TreeViewDOM.SelectNodes("//text()").Count;
//if too few, never start a timer
if (intNumberTotal < 100)
ResetTimer();
//report progress
backgroundWorkerBuildTree.ReportProgress(0, intNumberTotal);
XmlNode xn = null;
if ((tve.TreeViewDOM.DocumentElement.PreviousSibling != null && tve.TreeViewDOM.DocumentElement.PreviousSibling.NodeType != XmlNodeType.XmlDeclaration) || tve.TreeViewDOM.DocumentElement.NextSibling != null)
xn = tve.TreeViewDOM as XmlNode;
else
xn = tve.TreeViewDOM.DocumentElement;
//build a tree node for the root
m_tnRoot = TnBuildFromXn(xn);
//clear the tree - invoking on another thread
ClearTreeNodes(treeView);
//start at the root and populate
AddRootTreeNode(m_tnRoot);
m_tnRoot.Tag = xn;
//work through all nodes
PopulateTreeNode(xn, m_tnRoot, intNumberProcessed, intNumberTotal);
//make sure the first level is expanded
ExpandTreeNode(m_tnRoot);
if (((XmlNode)m_tnRoot.Tag).NodeType == XmlNodeType.Document)
foreach (TreeNode tnNode in m_tnRoot.Nodes)
{
ExpandTreeNode(tnNode);
}
//make sure we're at the top
if (tve.NodeToSelect == null)
EnsureTreeNode(m_tnRoot);
else
SelectNodeFromTree(tve.NodeToSelect);
//turn off the loading screen
ResetTimer();
}
catch (QuitNowException qnex)
{
Debug.WriteLine(qnex.Message);
//clear up, and quit
ClearTreeNodes(treeView);
e.Cancel = true;
return;
}
}
/// <summary>
/// Report progress on building the tree view (by updating the label on the tree view appropriately).
/// </summary>
private void backgroundWorkerBuildTree_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
SetLabelText(string.Format(CultureInfo.CurrentCulture, Properties.Resources.LoadingMessageWithPercentage, (int)(((double)e.ProgressPercentage / (int)e.UserState) * 100)));
}
private void xs_veh(object o, ValidationEventArgs vea)
{
//we don't care about the validation errors, we just want to validate part against the schema set and know if it was successful or not
}
#endregion
#region External add/remove/replace methods/events
/// <summary>
/// Add a node that was added to the XML part.
/// </summary>
/// <param name="mxnNew">The CustomXMLNode used to create the coresponding tree node.</param>
internal void AddMxnToTree(Office.CustomXMLNode mxnNew)
{
//if background worker is building the tree, block on that call
while (backgroundWorkerBuildTree.IsBusy)
{
Debug.WriteLine("waiting for tree to be ready so we can add a node...");
Thread.Sleep(500);
}
//get the xn for the parent
Debug.Assert(mxnNew.ParentNode != null, "null parentNode", "how can a node not have a parent?!!?");
XmlNode xnParent = Utilities.XnFromMxn(OwnerDocument, mxnNew.ParentNode, null);
//get the xn for the next sibling
XmlNode xnNextSibling = null;
if (mxnNew.NextSibling != null)
xnNextSibling = Utilities.XnFromMxn(OwnerDocument, mxnNew.NextSibling, mxnNew);
//build an XmlNode
XmlNode xnNew = Utilities.XnBuildFromMxn(mxnNew, OwnerDocument);
//add the node into the DOM
if (xnNew.NodeType == XmlNodeType.Attribute)
xnNew = xnParent.Attributes.Append((XmlAttribute)xnNew);
else
xnNew = xnParent.InsertBefore(xnNew, xnNextSibling);
xnNew.OwnerDocument.Normalize();
//normalizing the DOM disconnects the text node(?!), so get it back
if (xnNew.NodeType != XmlNodeType.Attribute)
{
if (xnNextSibling == null)
{
xnNew = xnParent.LastChild;
}
else
{
xnNew = xnNextSibling.PreviousSibling;
}
}
xnNew = AddNodeToTree(xnParent, xnNextSibling, xnNew);
}
/// <summary>
/// Remove a node that was removed from the XML part.
/// </summary>
/// <param name="mxnOldNode">The CustomXMLNode removed from the XML part.</param>
/// <param name="mxnOldParent">The CustomXMLNode specifying the parent of the deleted node.</param>
/// <param name="mxnOldNextSibling">The CustomXMLNode specifying the next sibling of the deleted node.</param>
/// <param name="mxnNew">A CustomXMLNode specifying the node the deleted node is being replaced with. Only used during replace actions.</param>
internal void RemoveMxnFromTree(Office.CustomXMLNode mxnOldNode, Office.CustomXMLNode mxnOldParent, Office.CustomXMLNode mxnOldNextSibling, Office.CustomXMLNode mxnNew)
{
//if background worker is building the tree, block on that call
while (backgroundWorkerBuildTree.IsBusy)
{
Debug.WriteLine("waiting for tree to be ready so we can add a node...");
Thread.Sleep(500);
}
//assume we have a parent
Debug.Assert(mxnOldParent != null, "deleted a node without a parent?");
//hold onto the parent treenode
TreeNode tnParent = null;
XmlNode xnParent = null;
//if we have a next sibling, get it's previous sibling in the local DOM
if (mxnOldNextSibling != null)
{
xnParent = Utilities.XnFromMxn(OwnerDocument, mxnOldParent, null);
//get the tree node and xml node
XmlNode xnNextSibling = Utilities.XnFromMxn(OwnerDocument, mxnOldNextSibling, mxnNew);
Debug.Assert(xnNextSibling.PreviousSibling != null, "asked to delete a prev sibling that doesn't exist");
//check if this node was in the tree
if (TnVisibiltyFetchFromGrf(xnNextSibling.PreviousSibling, Options))
{
TreeNode tnOld = m_dicXnTn[xnNextSibling.PreviousSibling];
tnParent = tnOld.Parent;
//remove from the tree
tnOld.Remove();
//remove from the list
m_dicXnTn.Remove(xnNextSibling.PreviousSibling);
}
//remove from the DOM
Debug.Assert(xnNextSibling.PreviousSibling.LocalName == mxnOldNode.BaseName && xnNextSibling.PreviousSibling.NamespaceURI == mxnOldNode.NamespaceURI, "DOMs falling out of sync - we're removing a different node than the MXSI just did.");
xnNextSibling.ParentNode.RemoveChild(xnNextSibling.PreviousSibling);
}
else if (mxnOldNode.NodeType == Office.MsoCustomXMLNodeType.msoCustomXMLNodeAttribute)
{
//find the attribute with the same namespace and basename on the parent and kill it
xnParent = Utilities.XnFromMxn(OwnerDocument, mxnOldParent, null);
XmlAttribute xaToRemove = null;
foreach (XmlAttribute xaAttribute in xnParent.Attributes)
if (xaAttribute.NamespaceURI == mxnOldNode.NamespaceURI && xaAttribute.LocalName == mxnOldNode.BaseName)
{
if (TnVisibiltyFetchFromGrf(xaAttribute, Options) == true)
{
TreeNode tnOld = m_dicXnTn[xaAttribute];
tnParent = tnOld.Parent;
//remove from the tree
tnOld.Remove();
//remove from the list
m_dicXnTn.Remove(xaAttribute);
//cache it to remove later
xaToRemove = xaAttribute;
}
}
//remove it
Debug.Assert(xaToRemove != null, "didn't find the right attr?");
xnParent.Attributes.Remove(xaToRemove);
}
else
{
xnParent = Utilities.XnFromMxn(OwnerDocument, mxnOldParent, null);
Debug.Assert(xnParent.LastChild != null || (!string.IsNullOrEmpty(mxnOldNode.NodeValue) && mxnOldNode.NodeType == Office.MsoCustomXMLNodeType.msoCustomXMLNodeText), "why don't we have this child node?");
if (xnParent.LastChild != null)
{
if (TnVisibiltyFetchFromGrf(xnParent.LastChild, Options))
{
TreeNode tnOld;
Debug.Assert(m_dicXnTn.ContainsKey(xnParent.LastChild) || (xnParent.LastChild.NodeType == XmlNodeType.Text && string.IsNullOrEmpty(xnParent.LastChild.InnerText)), "why don't we have this text node?");
if (m_dicXnTn.ContainsKey(xnParent.LastChild))
{
tnOld = m_dicXnTn[xnParent.LastChild];
tnParent = tnOld.Parent;
//remove the tree node
tnOld.Remove();
//remove from the list
m_dicXnTn.Remove(xnParent.LastChild);
}
}
Debug.Assert(mxnOldNode.BaseName == xnParent.LastChild.LocalName && mxnOldNode.NamespaceURI == xnParent.LastChild.NamespaceURI, "we're deleting the wrong node");
xnParent.RemoveChild(xnParent.LastChild);
}
}
//fix the parent's icon
if (tnParent != null)
{
bool bIsLeafNode = IsLeafNode(tnParent);
if (!bIsLeafNode)
{
tnParent.ImageIndex = 0;
tnParent.SelectedImageIndex = 0;
}
else
{
tnParent.ImageIndex = 2;
tnParent.SelectedImageIndex = 2;
}
}
}
/// <summary>
/// Replace a node that was replaced in the XML part.
/// </summary>
/// <param name="mxnOld">The CustomXMLNode removed from the XML part.</param>
/// <param name="mxnNew">The CustomXMLNode added to the XML part.</param>
internal void ReplaceMxnInTree(Office.CustomXMLNode mxnOld, Office.CustomXMLNode mxnNew)
{
//if background worker is building the tree, block on that call
while (backgroundWorkerBuildTree.IsBusy)
{
Debug.WriteLine("waiting for tree to be ready so we can add a node...");
Thread.Sleep(500);
}
XmlNode xn = null;
if(mxnNew.PreviousSibling != null)
{
xn = Utilities.XnFromMxn(OwnerDocument, mxnNew.PreviousSibling, null);
xn = xn.NextSibling;
}
else
{
xn = Utilities.XnFromMxn(OwnerDocument, mxnNew.ParentNode, null);
if (mxnOld.NodeType == Office.MsoCustomXMLNodeType.msoCustomXMLNodeAttribute)
xn = xn.Attributes[mxnOld.BaseName, mxnOld.NamespaceURI];
else
xn = xn.FirstChild;
}
TreeNode tn = null;
bool fExpandTreeNode = false;
if (TnVisibiltyFetchFromGrf(xn, Options))
{
tn = m_dicXnTn[xn];
fExpandTreeNode = tn.IsExpanded;
}
//replace by deleting and adding from our DOM
RemoveMxnFromTree(mxnOld, mxnNew.ParentNode, mxnNew.NextSibling, mxnNew);
AddMxnToTree(mxnNew);
if (tn != null && fExpandTreeNode)
{
xn = Utilities.XnFromMxn(OwnerDocument, mxnNew, null);
tn = m_dicXnTn[xn];
tn.Expand();
}
}
/// <summary>
/// Add a new node to our local XML tree.
/// </summary>
/// <param name="xnParent">An XmlNode specifying the parent of the new node.</param>
/// <param name="xnNextSibling">An XmlNode specifying the next sibling of the new node. Specify null if this should be the last child of the parent node.</param>
/// <param name="xnNew">An XmlNode specifying the node to be added.</param>
/// <returns>An XmlNode specifying the node added to our local XML tree.</returns>
private XmlNode AddNodeToTree(XmlNode xnParent, XmlNode xnNextSibling, XmlNode xnNew)
{
//create a treenode
TreeNode tnToAdd = TnBuildFromXn(xnNew);
//add it to the tree
//unless we get back that we don't care about this node type
//(e.g. they turned it off in the properties), then exit
if (tnToAdd != null)
{
AddXnToTree(xnNew, xnParent, xnNextSibling);
}
return xnNew;
}
/// <summary>
/// Add a node to the tree view.
/// </summary>
/// <param name="xnNew">An XmlNode specifying the node to be added.</param>
/// <param name="xnParent">An XmlNode specifying the parent of the new node.</param>
/// <param name="xnNextSibling">An XmlNode specifying the next sibling of the new node. Specify null if this should be the last child of the parent node.</param>
private void AddXnToTree(XmlNode xnNew, XmlNode xnParent, XmlNode xnNextSibling)
{
TreeNode tnNew = m_dicXnTn[xnNew];
TreeNode tnParent = m_dicXnTn[xnParent];
TreeNode tnNextSibling = null;
if (xnNextSibling != null)
{
tnNextSibling = m_dicXnTn[xnNextSibling];
}
if (xnNew.NodeType == XmlNodeType.Attribute)
{
//add it within the attributes
if (tnNextSibling != null)
{
InsertTreeNode(tnParent, tnNew, tnNextSibling.Index);
PopulateTreeNode(xnNew, tnNew, 0, 1);
}
//no, add it within the elements
else
{
if (tnParent.Nodes.Count > 0)
{
foreach (TreeNode tn in tnParent.Nodes)
{
//find the first non-attribute or attribute sorted after this one, put it before that tree node
if (((XmlNode)tn.Tag).NodeType != XmlNodeType.Attribute || (((XmlNode)tn.Tag).NodeType == XmlNodeType.Attribute && string.Compare(tn.Text, tnNew.Text, StringComparison.CurrentCulture) > 0) /*&& (tn.PrevNode == null || ((XmlNode)tn.PrevNode.Tag).NodeType == XmlNodeType.Attribute)*/)
{
InsertTreeNode(tnParent, tnNew, tn.Index);
PopulateTreeNode(xnNew, tnNew, 0, 1);
break;
}
}
}
else
{
//it's the only child node, so just put it at the end
AddTreeNode(tnParent, tnNew);
PopulateTreeNode(xnNew, tnNew, 0, 1);
}
}
}
else
{
//add it within the child nodes
if (tnNextSibling != null)
{
InsertTreeNode(tnParent, tnNew, tnNextSibling.Index);
PopulateTreeNode(xnNew, tnNew, 0, 1);
}
else
{
InsertTreeNode(tnParent, tnNew, tnParent.Nodes.Count);
PopulateTreeNode(xnNew, tnNew, 0, 1);
}
}
//fix the parent's icon
if (xnNew.NodeType == XmlNodeType.Element)
{
SetTreeNodeImage(tnParent, 0);
}
}
/// <summary>
/// Populate the tree view based on the XML structure of a node.
/// </summary>
/// <param name="xn">The XmlNode to use to populate the tree.</param>
/// <param name="tn">The TreeNode to populate.</param>
/// <param name="NumberProcessed">An integer specifying the number of nodes already processed in the XML tree.</param>
/// <param name="NumberTotal">An integer specifying the total number of node in the XML tree.</param>
/// <returns></returns>
private int PopulateTreeNode(XmlNode xn, TreeNode tn, int NumberProcessed, int NumberTotal)
{
int i = NumberProcessed;
//create attributes
if (xn.Attributes != null)
{
foreach (XmlNode xnChild in xn.Attributes)
{
TreeNode tnChild = TnBuildFromXn(xnChild);
if (tnChild != null)
{
if (tn.Nodes.Count > 0)
{
//check the existing list first
bool placed = false;
foreach (TreeNode tnAttr in tn.Nodes)
{
//find the first non-attribute or attribute sorted after this one, put it before that tree node
if (string.Compare(tnAttr.Text, tnChild.Text, StringComparison.CurrentCulture) > 0)
{
InsertTreeNode(tn, tnChild, tnAttr.Index);
placed = true;
break;
}
}
//if it didn't fall into the existing list, put it at the end
if (!placed)
{
AddTreeNode(tn, tnChild);
}
}
else
{
//no children yet, put it at the end
AddTreeNode(tn, tnChild);
}
i++;
if (NumberTotal > cintUpdateFrequency && i % (int)(NumberTotal / cintUpdateFrequency) == 0 && backgroundWorkerBuildTree.IsBusy)
backgroundWorkerBuildTree.ReportProgress(i, NumberTotal);
i = PopulateTreeNode(xnChild, tnChild, i, NumberTotal);
}
}
}
//create children
foreach (XmlNode xnChild in xn.ChildNodes)
{
TreeNode tnChild = TnBuildFromXn(xnChild);
if (tnChild != null)
{
AddTreeNode(tn, tnChild);
i++;
if (NumberTotal > cintUpdateFrequency && i % (int)(NumberTotal / cintUpdateFrequency) == 0 && backgroundWorkerBuildTree.IsBusy)
backgroundWorkerBuildTree.ReportProgress(i, NumberTotal);
i = PopulateTreeNode(xnChild, tnChild, i, NumberTotal);
}
}
return i;
}
/// <summary>
/// Build a tree node out of an XML node, to put into the tree view control.
/// </summary>
/// <param name="xn">The XmlNode from which to create the tree node.</param>
/// <returns>The corresponding TreeNode.</returns>
private TreeNode TnBuildFromXn(XmlNode xn)
{
string strName = null;
TreeNode tnResult = null;
//write out the proper content into the node
switch (xn.NodeType)
{
case XmlNodeType.Attribute:
//hide namespace declarations & attribs if not selected in options
if (!xn.Prefix.Equals("xmlns") && !xn.Name.Equals("xmlns") && (Options & cOptionsShowAttributes) != 0)
{
strName = xn.LocalName;
}
break;
case XmlNodeType.Element:
{
strName = xn.LocalName;
break;
}
case XmlNodeType.ProcessingInstruction:
{
if ((Options & cOptionsShowPI) != 0)
{
XmlProcessingInstruction xpi = xn as XmlProcessingInstruction;
strName = "<?" + xpi.Target + " " + xpi.Value + "?>";
}
break;
}
case XmlNodeType.Text:
if (!xn.ParentNode.Prefix.Equals("xmlns") && !xn.ParentNode.Name.Equals("xmlns") && (Options & cOptionsShowText) != 0)
strName = xn.Value;
break;
case XmlNodeType.Comment:
if ((Options & cOptionsShowComments) != 0)
strName = "<!--" + xn.Value + "-->";
break;
case XmlNodeType.Document:
strName = "/";
break;
case XmlNodeType.CDATA:
strName = "<![CDATA[" + xn.Value + "]]>";
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
break;
}
//if this is something we're displaying, set up the view
if (!string.IsNullOrEmpty(strName))
{
//add to hashtables
tnResult = new TreeNode(strName);
m_dicXnTn.Add(xn, tnResult);
//add the xn to the tn
tnResult.Tag = xn;
//put a nice icon on it
AddIconToTreeNode(xn, tnResult);
}
return tnResult;
}
#endregion
#region TreeView events
private void treeView_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("FileDrop"))
{
bool bNewStream = false;
StartTimer();
string[] files = (string[])e.Data.GetData("FileDrop");
foreach (string file in files)