-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathInterlinDocForAnalysis.cs
2460 lines (2299 loc) · 94.7 KB
/
InterlinDocForAnalysis.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) 2015-2018 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.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using SIL.LCModel.Core.Text;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.FieldWorks.Common.ViewsInterfaces;
using SIL.FieldWorks.Common.FwUtils;
using SIL.FieldWorks.Common.RootSites;
using SIL.LCModel;
using SIL.LCModel.Application;
using SIL.LCModel.DomainServices;
using SIL.LCModel.Infrastructure;
using SIL.LCModel.Utils;
using SIL.PlatformUtilities;
using XCore;
namespace SIL.FieldWorks.IText
{
public partial class InterlinDocForAnalysis : InterlinDocRootSiteBase
{
/// <summary>
/// Review(EricP) consider making a subclass of InterlinDocForAnalysis (i.e. InterlinDocForGlossing)
/// so we can put all AddWordsToLexicon related code there rather than having this
/// class do double duty.
/// </summary>
internal const string ksPropertyAddWordsToLexicon = "ITexts_AddWordsToLexicon";
public InterlinDocForAnalysis()
{
InitializeComponent();
RightMouseClickedEvent += InterlinDocForAnalysis_RightMouseClickedEvent;
DoSpellCheck = true;
}
void InterlinDocForAnalysis_RightMouseClickedEvent(SimpleRootSite sender, FwRightMouseClickEventArgs e)
{
e.EventHandled = true;
// for the moment we always claim to have handled it.
ContextMenuStrip menu = new ContextMenuStrip();
// Add spelling items if any (i.e., if we clicked a squiggle word).
int hvoObj, tagAnchor;
if (GetTagAndObjForOnePropSelection(e.Selection, out hvoObj, out tagAnchor) &&
(tagAnchor == SegmentTags.kflidFreeTranslation || tagAnchor == SegmentTags.kflidLiteralTranslation ||
tagAnchor == NoteTags.kflidContent))
{
var helper = new SpellCheckHelper(Cache);
helper.MakeSpellCheckMenuOptions(e.MouseLocation, this, menu);
}
int hvoNote;
if (CanDeleteNote(e.Selection, out hvoNote))
{
if (menu.Items.Count > 0)
{
menu.Items.Add(new ToolStripSeparator());
}
// Add the delete item.
string sMenuText = ITextStrings.ksDeleteNote;
ToolStripMenuItem item = new ToolStripMenuItem(sMenuText);
item.Click += OnDeleteNote;
menu.Items.Add(item);
}
if (menu.Items.Count > 0)
{
e.Selection.Install();
menu.Show(this, e.MouseLocation);
}
}
internal void SuppressResettingGuesses(Action task)
{
Vc.GuessCache.SuppressResettingGuesses(task);
}
public override void PropChanged(int hvo, int tag, int ivMin, int cvIns, int cvDel)
{
base.PropChanged(hvo, tag, ivMin, cvIns, cvDel);
if (IsFocusBoxInstalled && FocusBox.SelectedOccurrence != null
&& tag == SegmentTags.kflidAnalyses && FocusBox.SelectedOccurrence.Segment.Hvo == hvo)
{
int index = FocusBox.SelectedOccurrence.Index;
var seg = FocusBox.SelectedOccurrence.Segment;
if (!seg.IsValidObject || index >= seg.AnalysesRS.Count ||
(FocusBox.SelectedOccurrence.Analysis is IPunctuationForm))
{
// Somebody drastically changed things under us, maybe from another window.
// Try to fend off a crash.
TryHideFocusBoxAndUninstall();
return;
}
if (seg.AnalysesRS[index] != FocusBox.InitialAnalysis.Analysis)
{
// Somebody made a less drastic change under us. Reset the focus box.
FocusBox.SelectOccurrence(FocusBox.SelectedOccurrence);
MoveFocusBoxIntoPlace();
}
}
}
protected override void UpdateWordforms(HashSet<IWfiWordform> wordforms)
{
base.UpdateWordforms(wordforms);
// It's fairly pathological for the Analysis of an occurrence to be null, and while the Wordform of an analyis can
// be null (if it's punctuation), the focus box shouldn't be pointing at punctuation. However, we've had reported
// null ref exceptions in the absence of testing for this (LT-13702), and we certainly don't need to update the focus box
// because its wordform has been updated if we can't find an actual wordform associated with the focus box.
if (IsFocusBoxInstalled && FocusBox.SelectedOccurrence != null && FocusBox.SelectedOccurrence.Analysis != null
&& FocusBox.SelectedOccurrence.Analysis.Wordform != null
&& wordforms.Contains(FocusBox.SelectedOccurrence.Analysis.Wordform)
&& !FocusBox.IsDirty)
{
// update focus box to display new guess
FocusBox.SelectOccurrence(FocusBox.SelectedOccurrence);
MoveFocusBoxIntoPlace();
}
}
void OnDeleteNote(object sender, EventArgs e)
{
ToolStripMenuItem item = (ToolStripMenuItem)sender;
UndoableUnitOfWorkHelper.Do(string.Format(ITextStrings.ksUndoCommand, item.Text),
string.Format(ITextStrings.ksRedoCommand, item.Text), Cache.ActionHandlerAccessor,
() => DeleteNote(RootBox.Selection));
}
private void DeleteNote(IVwSelection sel)
{
int hvoNote;
if (!CanDeleteNote(sel, out hvoNote))
return;
var note = Cache.ServiceLocator.GetInstance<INoteRepository>().GetObject(hvoNote);
var segment = (ISegment)note.Owner;
segment.NotesOS.Remove(note);
}
/// <summary>
/// Answer true if the indicated selection is within a single note we can delete.
/// </summary>
/// <param name="sel"></param>
/// <returns></returns>
private bool CanDeleteNote(IVwSelection sel, out int hvoNote)
{
hvoNote = 0;
int tagAnchor, hvoObj;
if (!GetTagAndObjForOnePropSelection(sel, out hvoObj, out tagAnchor))
return false;
if (tagAnchor != NoteTags.kflidContent)
return false; // must be a selection in a note to be deletable.
hvoNote = hvoObj;
return true;
}
/// <summary>
/// Answer true if the indicated selection is within a single note we can delete. Also obtain
/// the object and property.
/// </summary>
private bool GetTagAndObjForOnePropSelection(IVwSelection sel, out int hvoObj, out int tagAnchor)
{
hvoObj = tagAnchor = 0;
if (sel == null)
return false;
ITsString tss;
int ichEnd, hvoEnd, tagEnd, wsEnd;
bool fAssocPrev;
sel.TextSelInfo(true, out tss, out ichEnd, out fAssocPrev, out hvoEnd, out tagEnd, out wsEnd);
int ichAnchor, hvoAnchor, wsAnchor;
sel.TextSelInfo(false, out tss, out ichAnchor, out fAssocPrev, out hvoAnchor, out tagAnchor, out wsAnchor);
if (hvoEnd != hvoAnchor || tagEnd != tagAnchor || wsEnd != wsAnchor)
return false; // must be a one-property selection
hvoObj = hvoAnchor;
return true;
}
/// <summary>
/// factory
/// </summary>
protected override void MakeVc()
{
Vc = new InterlinDocForAnalysisVc(m_cache);
}
#region Overrides of RootSite
/// <summary>
/// If you lost focus while processing a key or click, it may be because you are
/// making a new selection before calling a method like TryHideFocusBoxAndUninstall().
/// Hide focus and uninstall first!
/// </summary>
protected override void OnLostFocus(EventArgs e)
{
if (Vc != null)
Vc.SetActiveFreeform(0, 0, 0, 0);
base.OnLostFocus(e);
}
/// <summary>
/// If we have an active focus box put the focus back there when this is focused.
/// </summary>
protected override void OnGotFocus(EventArgs e)
{
if (ExistingFocusBox != null)
ExistingFocusBox.Focus();
base.OnGotFocus(e);
}
#endregion
#region ISelectOccurrence
/// <summary>
/// Select the word indicated by the occurrence.
/// Note that this does not save any changes made in the Sandbox. It is mainly used
/// when the view is read-only.
/// </summary>
public override void SelectOccurrence(AnalysisOccurrence target)
{
if (target == null)
{
TryHideFocusBoxAndUninstall();
return;
}
if (SelectedOccurrence == target && IsFocusBoxInstalled)
{
// Don't steal the focus from another window. See FWR-1795.
if (ParentForm == Form.ActiveForm)
{
if (ExistingFocusBox.CanFocus)
{
ExistingFocusBox.Focus(); // important when switching tabs with ctrl-tab.
}
else
{
VisibleChanged += FocusWhenVisible;
}
}
return;
}
if (!Vc.CanBeAnalyzed(target))
return;
#if DEBUG
// test preconditions.
Debug.Assert(target.IsValid && !(target.Analysis is IPunctuationForm), "Given annotation type should not be punctuation"
+ " but was " + target.Analysis.ShortName + ".");
#endif
TriggerAnnotationSelected(target, true);
}
/// <summary>
/// Move the sandbox (see main method), making the default selection.
/// </summary>
/// <param name="target"></param>
/// <param name="fSaveGuess">if true, saves guesses; if false, skips guesses but still saves edits.</param>
public void TriggerAnnotationSelected(AnalysisOccurrence target, bool fSaveGuess)
{
TriggerAnalysisSelected(target, fSaveGuess, true);
}
/// <summary>
/// Move the sandbox to the AnalysisOccurrence, (which may be a WfiWordform, WfiAnalysis, or WfiGloss).
/// </summary>
/// <param name="target"></param>
/// <param name="fSaveGuess">if true, saves guesses; if false, skips guesses but still saves edits.</param>
/// <param name="fMakeDefaultSelection">true to make the default selection within the new sandbox.</param>
public virtual void TriggerAnalysisSelected(AnalysisOccurrence target, bool fSaveGuess, bool fMakeDefaultSelection)
{
TriggerAnalysisSelected(target, fSaveGuess, fMakeDefaultSelection, true);
}
/// <summary>
/// Move the sandbox to the AnalysisOccurrence, (which may be a WfiWordform, WfiAnalysis, or WfiGloss).
/// </summary>
/// <param name="target"></param>
/// <param name="fSaveGuess">if true, saves guesses; if false, skips guesses but still saves edits.</param>
/// <param name="fMakeDefaultSelection">true to make the default selection within the new sandbox.</param>
/// <param name="fShow">true makes the focusbox visible.</param>
public virtual void TriggerAnalysisSelected(AnalysisOccurrence target, bool fSaveGuess, bool fMakeDefaultSelection, bool fShow)
{
// This can happen, though it is rare...see LT-8193.
if (!target.IsValid)
{
return;
}
if (IsFocusBoxInstalled)
FocusBox.UpdateRealFromSandbox(null, fSaveGuess);
TryHideFocusBoxAndUninstall();
RecordGuessIfNotKnown(target);
InstallFocusBox();
RootBox.DestroySelection();
FocusBox.SelectOccurrence(target);
SetFocusBoxSizeForVc();
SelectedOccurrence = target;
if (fShow)
{
SimulateReplaceAnalysis(target);
MoveFocusBoxIntoPlace();
// Now it is the right size and place we can show it.
TryShowFocusBox();
// All this CAN happen because we're editing in another window...for example,
// if we edit something that deletes the current wordform in a concordance view.
// In that case we don't want to steal the focus.
if (ParentForm == Form.ActiveForm)
FocusBox.FocusSandbox();
}
if (fMakeDefaultSelection)
m_mediator.IdleQueue.Add(IdleQueuePriority.Medium, FocusBox.MakeDefaultSelection);
}
// Set the VC size to match the FocusBox. Return true if it changed.
bool SetFocusBoxSizeForVc()
{
if (Vc == null || ExistingFocusBox == null)
return false;
var interlinDocForAnalysisVc = Vc as InterlinDocForAnalysisVc;
if (interlinDocForAnalysisVc == null)
return false; // testing only? Anyway nothing can change.
//FocusBox.PerformLayout();
int dpiX, dpiY;
using (Graphics g = CreateGraphics())
{
dpiX = (int)g.DpiX;
dpiY = (int)g.DpiY;
}
int width = FocusBox.Width;
if (width > 10000)
{
// Debug.Assert(width < 10000); // Is something taking the full available width of MaxInt/2?
width = 500; // arbitrary, may allow something to work more or less
}
Size newSize = new Size(width * 72000 / dpiX,
FocusBox.Height * 72000 / dpiY);
if (newSize.Width == interlinDocForAnalysisVc.FocusBoxSize.Width && newSize.Height == interlinDocForAnalysisVc.FocusBoxSize.Height)
return false;
interlinDocForAnalysisVc.FocusBoxSize = newSize;
return true;
}
/// <summary>
/// Something about the display of the AnalysisOccurrence has changed...perhaps it has become or ceased to
/// be the current annotation displayed using the Sandbox, or the Sandbox changed size. Produce
/// a PropChanged that makes the system think it has been replaced (with itself) to refresh the
/// relevant part of the display.
/// </summary>
void SimulateReplaceAnalysis(AnalysisOccurrence occurrence)
{
UpdateDisplayForOccurrence(occurrence);
}
protected override void SetRootInternal(int hvo)
{
// If the focus box is showing when we change the root object, we must get rid of it,
// otherwise strange things may happen as the pane is laid out and we get OnSizeChanged calls.
// The existing focus box can't be in any state that is useful to a different text, anyway.
TryHideFocusBoxAndUninstall();
base.SetRootInternal(hvo);
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
if (IsFocusBoxInstalled)
MoveFocusBoxIntoPlace();
}
/// <summary>
/// Move the sand box to the appropriate place.
/// Note: if we're already in the process of MoveSandbox, let's not do anything. It may crash
/// if we try it again (LT-5932).
/// </summary>
private bool m_fMovingSandbox;
internal void MoveFocusBoxIntoPlace()
{
MoveFocusBoxIntoPlace(false);
}
internal void MoveFocusBoxIntoPlace(bool fJustChecking)
{
if (m_fMovingSandbox)
return;
try
{
m_fMovingSandbox = true;
var sel = MakeSandboxSel();
if (fJustChecking)
{
// Called during paint...don't want to force a scroll to show it (FWR-1711)
if (ExistingFocusBox == null || sel == null)
return;
var desiredLocation = GetSandboxSelLocation(sel);
if (desiredLocation == FocusBox.Location)
return; // don't force a scroll.
}
// The sequence is important here. Even without doing this scroll, the sandbox is always
// visible: I think .NET must automatically scroll to make the focused control visible,
// or maybe we have some other code I've forgotten about that does it. But, if we don't
// both scroll and update, the position we move the sandbox to may be wrong, after the
// main window is fully painted, with possible position changes due to expanding lazy stuff.
// If you change this, be sure to test that in a several-page interlinear text, with the
// Sandbox near the bottom, you can turn 'show morphology' on and off and the sandbox
// ends up in the right place.
if (sel == null)
{
Debug.WriteLine("could not select annotation");
return;
}
if (!fJustChecking)
{
// During paint we do NOT want to force another paint, still less to force the focus box
// into view when it may have been purposely scrolled off.
// At other times we need the part of the view that contains the focus box to be actually
// painted (and hence lazy stuff expanded) before we make our final determination of the position.
ScrollSelectionIntoView(sel, VwScrollSelOpts.kssoDefault);
Update();
}
var ptLoc = GetSandboxSelLocation(sel);
if (ExistingFocusBox != null && FocusBox.Location != ptLoc)
FocusBox.Location = ptLoc;
}
finally
{
m_fMovingSandbox = false;
}
}
/// <summary>
/// If we try to scroll to show the focus box before we are Created, our attempt to set the scroll position is ignored.
/// This is an attempt to recover and make sure that even the first time the view is being created, we are scrolled
/// to show the focus box if we have set one up.
/// </summary>
protected override void OnCreateControl()
{
base.OnCreateControl();
Debug.Assert(Created);
if (IsFocusBoxInstalled)
MoveFocusBoxIntoPlace(false);
}
/// <summary>
/// As a last resort for making sure the focus box is where we think it should be,
/// check every time we paint. A recursive call may well happen, since
/// an Update() is called if MoveFocusBoxIntoPlace needs to scroll. However, it can't get
/// infinitely recursive, since MoveFocusBoxIntoPlace is guarded against being called
/// again while it is active.
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (Platform.IsMono)
return;
// FWNX-419
if (!MouseMoveSuppressed && IsFocusBoxInstalled)
MoveFocusBoxIntoPlace(true);
}
/// <summary>
/// Return the selection that corresponds to the SandBox position.
/// </summary>
/// <returns></returns>
internal IVwSelection MakeSandboxSel()
{
if (m_hvoRoot == 0 || SelectedOccurrence == null)
return null;
return SelectOccurrenceInIText(SelectedOccurrence);
}
/// <summary>
/// Get the next segment with either a non-null annotation that is configured or
/// a non-punctuation analysis. Also skip segments that are Scripture labels (like
/// Chapter/Verse/Footnote numbers.
/// It tries the next one after the SelectedOccurrence.Segment
/// then tries the next paragraph, etc..
/// Use this version if the calling code already has the actual para/seg objects.
/// </summary>
/// <param name="currentPara"></param>
/// <param name="seg"></param>
/// <param name="upward">true if moving up and left, false otherwise</param>
/// <param name="realAnalysis">the first or last real analysis found in the next segment</param>
/// <returns>A segment meeting the criteria or null if not found.</returns>
private ISegment GetNextSegment(IStTxtPara currentPara, ISegment seg, bool upward,
out AnalysisOccurrence realAnalysis)
{
ISegment nextSeg = null;
realAnalysis = null;
var currentText = currentPara.Owner as IStText;
Debug.Assert(currentText != null, "Paragraph not owned by a text.");
var lines = LineChoices.EnabledLineSpecs as IEnumerable<InterlinLineSpec>;
var delta = upward ? -1 : 1;
var nextSegIndex = delta + seg.IndexInOwner;
do
{
if (0 <= nextSegIndex && nextSegIndex < currentPara.SegmentsOS.Count)
{
nextSeg = currentPara.SegmentsOS[nextSegIndex];
nextSegIndex += delta; // increment for next loop in case it doesn't check out
}
else
{ // try the first (last) segment in the next (previous) paragraph
int nextParaIndex = delta + currentPara.IndexInOwner;
nextSeg = null;
IStTxtPara nextPara = null;
if (0 <= nextParaIndex && nextParaIndex < currentText.ParagraphsOS.Count)
{ // try to find this paragraph's first (last) segment
currentPara = (IStTxtPara)currentText.ParagraphsOS[nextParaIndex];
nextSegIndex = upward ? currentPara.SegmentsOS.Count - 1 : 0;
}
else
{ // no more paragraphs in this text
break;
}
}
realAnalysis = FindRealAnalysisInSegment(nextSeg, !upward);
} while (nextSeg == null || (realAnalysis == null && !HasVisibleTranslationOrNote(nextSeg, lines)));
return nextSeg;
}
/// <summary>
/// Get the next segment with either a non-null annotation that is configured or
/// a non-punctuation analysis.
/// It tries the next one after the SelectedOccurrence.Segment
/// then tries the next paragraph, etc..
/// </summary>
/// <param name="paraIndex"></param>
/// <param name="segIndex"></param>
/// <param name="upward">true if moving up and left, false otherwise</param>
/// <param name="realAnalysis">the first or last real analysis found in the next segment</param>
/// <returns>A segment meeting the criteria or null if not found.</returns>
internal ISegment GetNextSegment(int paraIndex, int segIndex, bool upward, out AnalysisOccurrence realAnalysis)
{
var currentPara = (IStTxtPara)RootStText.ParagraphsOS[paraIndex];
Debug.Assert(currentPara != null, "Tried to use a null paragraph ind=" + paraIndex);
ISegment currentSeg = currentPara.SegmentsOS[segIndex];
Debug.Assert(currentSeg != null, "Tried to use a null segment ind=" + segIndex + " in para " + paraIndex);
return GetNextSegment(currentPara, currentSeg, upward, out realAnalysis);
}
/// <summary>
/// Gets the first visible (non-null and configured) translation or note line in the current segment.
/// </summary>
/// <param name="segment">The segment to get the translation or note flid from.</param>
/// <param name="ws">The returned writing system for the line needed to identify it or -1.</param>
/// <returns>The flid of the translation or note or 0 if none is found.</returns>
internal int GetFirstVisibleTranslationOrNoteFlid(ISegment segment, out int ws)
{
var lines = LineChoices.EnabledLineSpecs as IEnumerable<InterlinLineSpec>;
Debug.Assert(lines != null, "Interlinear line configurations not enumerable 2");
var annotations = lines.SkipWhile(line => line.WordLevel);
int tryAnnotationIndex = lines.Count() - annotations.Count();
if (annotations.Count() > 0)
{ // We want to select at the start of this translation or note if it is not a null note.
bool isaNote = annotations.First().Flid == InterlinLineChoices.kflidNote;
if (isaNote && segment.NotesOS.Count == 0)
{ // this note is not visible - skip to the next non-note translation or note
var otherAnnotations = annotations.SkipWhile(line => line.Flid == InterlinLineChoices.kflidNote);
tryAnnotationIndex = lines.Count() - otherAnnotations.Count();
if (otherAnnotations.Count() == 0)
tryAnnotationIndex = -1; // no more translations or notes, go to an analysis in the next segment.
}
}
else // no translations or notes to go to
tryAnnotationIndex = -1;
int tryAnnotationFlid = 0;
ws = -1;
if (tryAnnotationIndex > -1)
{
var lineSpec = lines.Skip(tryAnnotationIndex).First();
tryAnnotationFlid = lineSpec.Flid;
ws = lineSpec.WritingSystem;
}
return tryAnnotationFlid;
}
/// <summary>
/// Select the first non-null translation or note in the current segment
/// of the current analysis occurance.
/// </summary>
/// <returns>true if successful, false if there is no real translation or note</returns>
internal bool SelectFirstTranslationOrNote()
{
int ws;
int annotationFlid = GetFirstVisibleTranslationOrNoteFlid(SelectedOccurrence.Segment, out ws);
if (annotationFlid == 0) return false;
var sel = MakeSandboxSel();
int clev = sel.CLevels(true);
clev--; // result it returns is one more than what the AllTextSelInfo routine wants.
SelLevInfo[] rgvsli;
using (ArrayPtr rgvsliTemp = MarshalEx.ArrayToNative<SelLevInfo>(clev))
{
int ihvoRoot;
int cpropPrevious;
int ichAnchor;
int ichEnd;
int ihvoEnd1;
int tag, ws1;
bool fAssocPrev;
ITsTextProps ttp;
sel.AllTextSelInfo(out ihvoRoot, clev, rgvsliTemp, out tag, out cpropPrevious,
out ichAnchor, out ichEnd, out ws1, out fAssocPrev, out ihvoEnd1, out ttp);
rgvsli = MarshalEx.NativeToArray<SelLevInfo>(rgvsliTemp, clev);
}
// What non-word "choice" ie., translation text or note is on this line?
int tagTextProp = ConvertTranslationOrNoteFlidToSegmentFlid(annotationFlid, SelectedOccurrence.Segment, ws);
int levels;
SelLevInfo noteLevel = MakeInnerLevelForFreeformSelection(tagTextProp);
var vsli = new SelLevInfo[3];
vsli[0] = noteLevel; // note or translation line
vsli[1] = rgvsli[0]; // segment
vsli[2] = rgvsli[1]; // para
int cPropPrevious = 0; // todo: other if not the first WS for tagTextProp
TryHideFocusBoxAndUninstall();
RootBox.MakeTextSelection(0, vsli.Length, vsli, tagTextProp, cPropPrevious,
0, 0, 0, false, -1, null, true);
Focus();
return true;
}
/// <summary>
/// Return the first non-null translation or note selection in the specified segment.
/// The segment does not need to be the current occurance.
/// </summary>
/// <param name="segment">A valid segment.</param>
/// <returns>The selection or null if there is no real translation or note.</returns>
internal IVwSelection SelectFirstTranslationOrNote(ISegment segment)
{
if (segment == null)
return null;
int ws;
int annotationFlid = GetFirstVisibleTranslationOrNoteFlid(segment, out ws);
if (annotationFlid == 0)
return null;
int tagTextProp = ConvertTranslationOrNoteFlidToSegmentFlid(annotationFlid, segment, ws);
SelLevInfo noteLevel = MakeInnerLevelForFreeformSelection(tagTextProp);
// notes and translation lines have 3 levels: 2:para, 1:seg, 0:content or self property
var vsli = new SelLevInfo[3];
vsli[0] = noteLevel; // note or translation line
vsli[1].ihvo = segment.IndexInOwner; // specifies where segment is in para
vsli[1].tag = StTxtParaTags.kflidSegments;
vsli[2].ihvo = segment.Paragraph.IndexInOwner; // specifies where para is in IStText.
vsli[2].tag = StTextTags.kflidParagraphs;
int cPropPrevious = 0; // todo: other if not the first WS for tagTextProp
var sel = RootBox.MakeTextSelection(0, vsli.Length, vsli, tagTextProp, cPropPrevious,
0, 0, 0, false, 0, null, true);
Focus();
TryHideFocusBoxAndUninstall();
return sel;
}
/// <summary>
/// Sets up the tags for the 0 level of a selection of a free translation or note.
/// This will be the level "inside" the ones that select the paragraph and segment.
/// For a note, we need to select the first note.
/// For a free translation, we need to insert the level for the 'self' property
/// which the VC inserts to isolate the free translations and make it easier to update them.
/// </summary>
/// <param name="tagTextProp">The segment or note tag of an annotation to be selected.</param>
private SelLevInfo MakeInnerLevelForFreeformSelection(int tagTextProp)
{
var noteLevel = new SelLevInfo();
noteLevel.ihvo = 0;
if (tagTextProp == NoteTags.kflidContent)
{
noteLevel.tag = SegmentTags.kflidNotes;
}
else
{
noteLevel.tag = Cache.MetaDataCacheAccessor.GetFieldId2(CmObjectTags.kClassId, "Self", false);
}
return noteLevel;
}
/// <summary>
/// Converts InterlinLineChoices flids to corresponding SegmentTags.
/// or NoteTags.
/// This is useful when making translation or note selections.
/// </summary>
/// <param name="annotationFlid">The translation or note Flid to be converted.</param>
/// <param name="segment">The segment the flid applies to.</param>
/// <param name="ws">The writing system of the text.</param>
/// <returns>A flid suitable for making translation or note selections or -1 if unknown.</returns>
internal int ConvertTranslationOrNoteFlidToSegmentFlid(int annotationFlid, ISegment segment, int ws)
{
int tagTextProp = -1;
switch (annotationFlid)
{
case InterlinLineChoices.kflidFreeTrans:
tagTextProp = SegmentTags.kflidFreeTranslation;
//if (segment.FreeTranslation.StringOrNull(ws) == null)
// tagTextProp = kTagUserPrompt; // user prompt property for empty translation annotations
break;
case InterlinLineChoices.kflidLitTrans:
tagTextProp = SegmentTags.kflidLiteralTranslation;
//if (segment.LiteralTranslation.StringOrNull(ws) == null)
// tagTextProp = kTagUserPrompt; // user prompt property for empty translation annotations
break;
case InterlinLineChoices.kflidNote:
tagTextProp = NoteTags.kflidContent;
break;
default:
Debug.Assert(false, "An annotation flid was not converted for selection - flid = " + annotationFlid);
break;
}
return tagTextProp;
}
/// summary>
/// Get the location of the given selection, presumably that of a Sandbox.
/// /summary>
Point GetSandboxSelLocation(IVwSelection sel)
{
Debug.Assert(sel != null);
Rect rcPrimary = GetPrimarySelRect(sel);
// The location includes margins, so for RTL we need to adjust the
// Sandbox so it isn't hard up against the next word.
// Enhance JohnT: ideally we would probably figure this margin
// to exactly match the margin between words set by the VC.
int left = rcPrimary.left;
if (Vc.RightToLeft)
left += 8;
return new Point(left, rcPrimary.top);
}
/// <summary>
/// Overridden for subclasses needing a Sandbox.
/// </summary>
/// <param name="rgvsli"></param>
/// <returns></returns>
protected override IVwSelection MakeWordformSelection(SelLevInfo[] rgvsli)
{
// top prop is atomic, leave index 0. Specifies displaying the contents of the Text.
IVwSelection sel;
try
{
// This is fine for InterlinDocForAnalysis, since it treats the area that the sandbox
// will fill as a picture. Not so good for panes (see above).
sel = RootBox.MakeSelInObj(0, rgvsli.Length, rgvsli, 0, false);
}
catch (Exception e)
{
Debug.WriteLine(e.StackTrace);
return null;
}
return sel;
}
#endregion
internal override AnalysisOccurrence OccurrenceContainingSelection()
{
if (m_rootb == null)
return null;
// This works fine for non-Sandbox panes,
// Sandbox panes' selection may be in the Sandbox.
if (ExistingFocusBox != null &&
ExistingFocusBox.SelectedOccurrence != null &&
ExistingFocusBox.SelectedOccurrence.IsValid)
{
return ExistingFocusBox.SelectedOccurrence;
}
// If the above didn't work, this probably won't either, but try anyway...
return base.OccurrenceContainingSelection();
}
#region Properties
/// <summary>
/// Wordform currently being edited through the FocusBox overlay; null if none.
/// </summary>
internal AnalysisOccurrence SelectedOccurrence
{
get
{
return ((InterlinDocForAnalysisVc) Vc).FocusBoxOccurrence;
}
set
{
if (Vc == null)
return;
((InterlinDocForAnalysisVc)Vc).FocusBoxOccurrence = value;
m_propertyTable.SetProperty("TextSelectedWord",
value != null && value.HasWordform ? value.Analysis.Wordform : null,
true);
m_propertyTable.SetPropertyPersistence("TextSelectedWord", false);
}
}
/// <summary>
/// (LT-7807) true if this document is in the context/state for adding glossed words to lexicon.
/// </summary>
internal bool InModeForAddingGlossedWordsToLexicon
{
get
{
return LineChoices.Mode == InterlinLineChoices.InterlinMode.GlossAddWordsToLexicon;
}
}
#endregion
#region AddWordsToLexicon
public override void OnPropertyChanged(string name)
{
CheckDisposed();
switch (name)
{
case ksPropertyAddWordsToLexicon:
if (this.LineChoices != null)
{
// whenever we change this mode, we may also
// need to show the proper line choice labels, so put the lineChoices in the right mode.
InterlinLineChoices.InterlinMode newMode = GetSelectedLineChoiceMode();
if (LineChoices.Mode != newMode)
{
var saved = SelectedOccurrence;
this.TryHideFocusBoxAndUninstall();
this.LineChoices.Mode = newMode;
// the following reconstruct will destroy any valid selection (e.g. in Free line).
// is there anyway to do a less drastic refresh (e.g. via PropChanged?)
// that properly adjusts things?
this.RefreshDisplay();
if (saved != null)
TriggerAnnotationSelected(saved, false);
}
}
break;
default:
base.OnPropertyChanged(name);
break;
}
}
internal InterlinLineChoices.InterlinMode GetSelectedLineChoiceMode()
{
return m_propertyTable.GetBoolProperty(ksPropertyAddWordsToLexicon, false) ?
InterlinLineChoices.InterlinMode.GlossAddWordsToLexicon : InterlinLineChoices.InterlinMode.Gloss;
}
#endregion
#region AddGlossesToFreeTranslation
protected override void OnKeyDown(KeyEventArgs e)
{
// detect whether the user is doing a range selection with the keyboard within
// a freeform annotation, and try to keep the selection within the bounds of the editable selection. (LT-2910)
if (RootBox != null && (e.Modifiers & Keys.Shift) == Keys.Shift)
{
TextSelInfo tsi = new TextSelInfo(RootBox);
int hvoAnchor = tsi.HvoAnchor;
if (hvoAnchor != 0)
{
ICmObject coAnchor = Cache.ServiceLocator.GetInstance<ICmObjectRepository>().GetObject(hvoAnchor);
if ((coAnchor is ISegment && (tsi.TagAnchor == SegmentTags.kflidFreeTranslation || tsi.TagAnchor == SegmentTags.kflidLiteralTranslation))
|| (coAnchor is INote && tsi.TagAnchor == NoteTags.kflidContent))
{
// we are in a segment-level annotation.
if (e.KeyCode == Keys.Home)
{
// extend the selection to the beginning of the comment.
SelectionHelper selHelper = SelectionHelper.GetSelectionInfo(tsi.Selection, this);
selHelper.IchEnd = 0;
selHelper.MakeRangeSelection(RootBox, true);
return;
}
}
}
}
// LT-9570 for the Tree Translation line, Susanna wanted Enter to copy Word Glsses
// into the Free Translation line. Note: DotNetBar is not handling shortcut="Enter"
// for the XML <command id="CmdAddWordGlossesToFreeTrans"...
if (RootBox != null && e.KeyCode == Keys.Enter)
OnAddWordGlossesToFreeTrans(null);
// LT-4029 Capture arrow keys from inside the translation lines and notes.
var change = HandleArrowKeys(e);
// LT-12097 Right and left arrow keys from an empty translation line (part of the issue)
// The up and down arrows work, so here we changed the event appropriately to up or down.
if (change != ArrowChange.Handled)
{
KeyEventArgs e2;
switch (change)
{ // might need to change the key event so the base method will handle it right.
case ArrowChange.Down:
e2 = new System.Windows.Forms.KeyEventArgs(Keys.Down);
break;
case ArrowChange.Up:
e2 = new System.Windows.Forms.KeyEventArgs(Keys.Up);
break;
case ArrowChange.None:
e2 = e;
break;
default:
e2 = e;
break;
}
base.OnKeyDown(e2);
}
}
enum ArrowChange {None, Up, Down, Handled}
/// <summary>
/// Performs a change in IP when arrow keys should take the IP from a translation or note
/// to an analysis. Also handles right and left arrow for empty translation lines via the
/// output enum.
/// two directions of concern for Left to Right(LTR) and Right To Left(RTL):
/// 1: up from the first translation or note in a paragraph after a word line possibly
/// in another paragraph via up arrow or a left (right if RTL) arrow from the first (last)
/// character of the annotaton
/// 2: down from the last translation or note in a paragraph before a word line possibly
/// in another paragraph via down arrow or a right (left if RTL) arrow from the last (right)
/// character of the annotaton
/// The following logic accounts for the configured position of notes and whether the user added them.
/// The idea here is to eliminate as many default cases as possible as early as possible to be handled by
/// the old annotation OnKeyDown() method.
/// </summary>
/// <param name="e">The keyboard event</param>
/// <returns>handled if it handled the situation, None if not and Up or Down
/// when that is what's needed from the base method.</returns>
private ArrowChange HandleArrowKeys(KeyEventArgs e)
{
if (SelectedOccurrence == null &&
(e.KeyCode == Keys.Down || e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Right || e.KeyCode == Keys.Left) &&
((e.KeyCode & Keys.Shift) != Keys.Shift) && ((e.KeyCode & Keys.Control) != Keys.Control))
{
// It's an arrow key, but is it in a translation line or note?
// Get the current selection so we can obtain the actual translation or note objects
SelLevInfo[] rgvsli;
int clev, tag, ichAnchor, ichEnd, ws;
bool haveSelection = GetCurrentSelection(out clev, out rgvsli, out tag, out ichAnchor, out ichEnd, out ws);
if (!haveSelection)
return ArrowChange.None;
// get the text, paragraph, segment and note, if there is one
int curSegIndex, curParaIndex, curNoteIndex;
ISegment curSeg;
INote curNote;
GetCurrentTextObjects(clev, rgvsli, tag,
out curParaIndex, out curSegIndex, out curNoteIndex, out curSeg, out curNote);
// what kind of line is it and where is the selection (ie., IP) in the text?
int id, lineNum;
WhichEnd where;
bool isRightToLeft;
bool hasPrompt;
bool haveLineInfo = GetLineInfo(curSeg, curNote, tag, ichAnchor, ichEnd, ws,
out id, out lineNum, out where, out isRightToLeft, out hasPrompt);
if (!haveLineInfo)
return ArrowChange.None;
var lines = LineChoices.EnabledLineSpecs as IEnumerable<InterlinLineSpec>; // so we can use linq
Debug.Assert(lines != null, "Interlinear line configurations not enumerable");
bool isUpNewSeg;
bool isUpMove = DetectUpMove(e, lines, lineNum, curSeg, curNoteIndex, where, isRightToLeft, out isUpNewSeg);
bool isDownNewSeg = false;
if (!isUpMove)
{ // might be a downward move
isDownNewSeg = DetectDownMove(e, lines, lineNum, curSeg, curNoteIndex, isRightToLeft, where);
// Should = isDownMove since hasFollowingAnalysis should be false
}
if (isUpNewSeg || isDownNewSeg)
{ // Get the next segment in direction with a real analysis or a real translation or note
if (IsTranslationOrNoteNext(curParaIndex, curSeg, isUpNewSeg))
if (hasPrompt && (id == InterlinLineChoices.kflidFreeTrans ||
id == InterlinLineChoices.kflidLitTrans))
{ // moving from an empty translation line to another translation line
return isUpNewSeg ? ArrowChange.Up : ArrowChange.Down;
}
else return ArrowChange.None; // let default handle it
// a real analysis is next or no more segments
var occurrence = MoveVerticallyToNextAnalysis(curParaIndex, curSegIndex, isUpNewSeg);
if (occurrence == null)
return ArrowChange.None; // only a real translation or note, or it couldn't find a suitable segment
SelectOccurrence(occurrence); // only works for analyses, not annotations
return ArrowChange.Handled;
}
if (isUpMove)
{ // Need to move up to a real analysis in the same segment
IAnalysis nextAnalysis = null;
int index = 0;
foreach (var an in curSeg.AnalysesRS.Reverse())
{ // need to count because an.IndexInOwner == 0 for all an - go figure
index++;