-
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathITextUtils.cs
More file actions
2124 lines (1978 loc) · 77 KB
/
ITextUtils.cs
File metadata and controls
2124 lines (1978 loc) · 77 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) 2003-2022 SIL International
// This software is licensed under the LGPL, version 2.1 or later
// (http://www.gnu.org/licenses/lgpl-2.1.html)
#define PROFILING
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Icu;
using SIL.Extensions;
using SIL.LCModel.Core.Cellar;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.LCModel.Core.Scripture;
using SIL.LCModel.Core.Text;
using SIL.LCModel.Core.WritingSystems;
using SIL.LCModel.DomainImpl;
using SIL.LCModel.Utils;
namespace SIL.LCModel.DomainServices
{
#region ParagraphParserOptions class
/// <summary>
/// This class provides a relatively extensible way to pass options to the ParagraphParser.
/// </summary>
public class ParagraphParserOptions
{
/// <summary>
/// Make one with all the default settings.
/// </summary>
public ParagraphParserOptions()
{
}
/// <summary>
/// Make one, controlling the indicated options and taking defaults for others.
/// </summary>
public ParagraphParserOptions(bool fBuildConcordance, bool fResetConcordance)
{
CollectWordformOccurrencesInTexts = fBuildConcordance;
ResetConcordance = fResetConcordance;
}
/// <summary>
/// if true, collect wordform occurrences
/// </summary>
public bool CollectWordformOccurrencesInTexts;
/// <summary>
/// if true, reset the wordform inventory concordance before starting.
/// </summary>
public bool ResetConcordance;
}
#endregion
#region ReusableCbaItem class
internal class ReusableCbaItem
{
internal ReusableCbaItem(ICmBaseAnnotation cba)
{
Item = cba;
}
internal ICmBaseAnnotation Item { get; private set; }
internal void Reuse()
{
Reused = true;
}
internal static void MarkToRemove(ICmBaseAnnotation cbaToRemove, IList<ReusableCbaItem> reusableItems)
{
foreach (ReusableCbaItem item in reusableItems)
{
if (item == cbaToRemove)
{
item.MarkedToRemove = true;
return;
}
}
}
/// <summary>
/// indicate that we want to delete this.
/// </summary>
internal bool MarkedToRemove { get; private set; }
internal bool Reused { get; private set; }
}
#endregion
#region ParagraphParser class
/// <summary>
/// For tokenizing StTxtParas with segments, words and punctuation.
/// </summary>
public class ParagraphParser : IDisposable
{
/// <summary> The paragraph to be parsed. </summary>
protected IStTxtPara m_para;
private ITsString m_tssPara;
private WordMaker m_wordMaker;
/// <summary> </summary>
protected LcmCache m_cache;
IWfiWordformRepository m_wfr;
IWfiWordformFactory m_wordfactory;
/// <summary> the repository for getting annotations </summary>
protected ICmBaseAnnotationRepository m_cbar;
int m_paraWs = 0;
// keeps track of the paragraph ids we've parsed.
// If not null, list of existing annotation objects not yet reused.
// When one is reused, it is changed to zero.
Dictionary<string, HashSet<ITsString>> m_possiblePhrases;
bool m_fSegmentFormCollectionMode; // used to collect (and restore state of ParagraphParser).
// NB: Order is important to these three lists.
readonly List<IAnalysis> m_preExistingAnalyses = new List<IAnalysis>();
readonly List<ISegment> m_preExistingSegs = new List<ISegment>();
WordMaker m_paragraphTextScanner;
IDictionary<string, IList<int>> m_wordformAnnotationPossibilities = new Dictionary<string, IList<int>>();
// Variables used for profiling
#if PROFILING
int m_cAnnotations = 0;
long m_cTicksMakingAnnotations = 0;
static int s_cTotalAnnotationsMade = 0;
#endif
bool m_fRebuildingConcordanceWordforms; // true when we're rebuilding ConcordanceWordforms
bool m_fAddOccurrencesToWordforms; // true when recording the occurrences of a wordform in text(s).
// This Set is used to keep track of the wordformIds we've identified through a parse.
// On 12/2/2006, when I (RandyR) switched it to use a Set,
// the values (also ints) weren't being used at all.
static readonly HashSet<int> s_wordformIdOccurrencesTable = new HashSet<int>();
static LcmCache s_cache;
LcmCache Cache
{
get
{
CheckDisposed();
return m_cache;
}
}
// Caches the WF repository's collection of possible phrases organized by first word.
Dictionary<string, HashSet<ITsString>> PossiblePhrases
{
get
{
if (m_possiblePhrases == null)
m_possiblePhrases = ((IWfiWordformRepositoryInternal)m_cache.ServiceLocator.GetInstance<IWfiWordformRepository>())
.FirstWordToPhrases;
return m_possiblePhrases;
}
}
/// <summary>
/// There are certain static tables built during a parse session that may overlap data found from
/// subsequent parse sessions. Reset this information here.
/// </summary>
private static void ResetParseSessionDependentStaticData()
{
// Clear out the table that keeps track of our wordform instances during a parse session.
s_cache = null;
s_wordformIdOccurrencesTable.Clear();
}
/// <summary>
/// Retrieve the wordforms collected during the last parsing session.
/// </summary>
/// <param name="cache"></param>
/// <returns></returns>
public static ISet<int> WordformsFromLastParseSession(LcmCache cache)
{
using (ParagraphParser pp = new ParagraphParser(cache))
return new HashSet<int>(pp.WordformIdOccurrencesTable);
}
/// <summary>
/// Table collects the occurences of a wordform found during a parse.
/// </summary>
internal HashSet<int> WordformIdOccurrencesTable
{
get
{
CheckDisposed();
if (s_cache == null || s_cache != m_cache)
return new HashSet<int>();
return s_wordformIdOccurrencesTable;
}
}
/// <summary>
/// Indicates that we're in the process of rebuilding the concordance
/// from scratch, both the wordforms and their occurrences in the given texts.
/// </summary>
private bool RebuildingConcordanceWordforms
{
get { return m_fRebuildingConcordanceWordforms; }
set
{
m_fRebuildingConcordanceWordforms = value;
CollectWordformOccurrencesInTexts = value;
}
}
/// <summary>
/// if true during parsing we'll add occurrences to wordforms.
/// </summary>
private bool CollectWordformOccurrencesInTexts
{
get { return m_fAddOccurrencesToWordforms; }
set
{
m_fAddOccurrencesToWordforms = value;
}
}
/// <summary>
/// Session that parses through a paragraph, and collects information for it.
/// </summary>
public static void ParseParagraph(IStTxtPara para)
{
ParseParagraph(para, false);
}
/// <summary>
///
/// </summary>
public static void ParseParagraph(IStTxtPara para, bool fBuildConcordance)
{
ParseParagraph(para, fBuildConcordance, false);
}
/// <summary>
///
/// </summary>
/// <param name="para"></param>
/// <param name="fBuildConcordance">if true, collect wordform occurrences</param>
/// <param name="fResetConcordance">if true, reset the wordform inventory concordance</param>
public static void ParseParagraph(IStTxtPara para, bool fBuildConcordance, bool fResetConcordance)
{
ParseParagraph(para, new ParagraphParserOptions(fBuildConcordance, fResetConcordance));
}
/// <summary>
/// Parse a single paragraph with the specified options.
/// </summary>
public static void ParseParagraph(IStTxtPara para, ParagraphParserOptions options)
{
if (para.ParseIsCurrent)
return;
using (var pp = new ParagraphParser(para.Cache))
{
pp.ParseWithOptions(para, options);
}
}
private void ParseWithOptions(IStTxtPara para, ParagraphParserOptions options)
{
ParseWithOptionsCore(para, options);
}
private void ParseWithOptionsCore(IStTxtPara para, ParagraphParserOptions options)
{
ResetParseSessionDependentStaticData();
CollectWordformOccurrencesInTexts = options.CollectWordformOccurrencesInTexts;
Parse(para);
}
/// <summary>
/// Parse all the paragraphs in the text.
/// </summary>
public static void ParseText(IStText sttext)
{
using (var parser = new ParagraphParser(sttext.Cache))
{
foreach (IStTxtPara para in sttext.ParagraphsOS)
parser.Parse(para);
}
}
/// <summary>
/// Determine whether text ends with an EOS character.
/// This is used by the FieldWorks interlinear importer
/// to make sure that segments are well-formed.
/// </summary>
public static bool EndsWithEOS(ITsString text, LcmCache cache)
{
var collector = new SegmentMaker(text, cache.WritingSystemFactory, null);
collector.Run();
return !collector.ExtraSegment;
}
/// <summary>
/// tokenize the paragraph with segments and analyses (wordforms generally, though we try to preserve other existing ones).
/// </summary>
/// <param name="para"></param>
public void Parse(IStTxtPara para)
{
if (para.ParseIsCurrent)
return; // not needed.
ParseCore(para);
}
/// <summary>
/// tokenize the paragraph with segments and analyses (wordforms generally, though we try to preserve other existing ones).
/// </summary>
/// <param name="para"></param>
public void ForceParse(IStTxtPara para)
{
ParseCore(para);
}
private void ParseCore(IStTxtPara para)
{
Setup(para);
// Collect pre-existing annotations for paragraph.
CollectPreExistingParaAnnotations();
//BuildAnalysisList(new NullProgressState()); // load any existing data from the database.
Parse();
para.ParseIsCurrent = true;
}
internal void CollectPreExistingParaAnnotations()
{
m_preExistingAnalyses.Clear();
m_preExistingSegs.Clear();
foreach (var seg in m_para.SegmentsOS)
{
m_preExistingSegs.Add(seg);
m_preExistingAnalyses.AddRange(from analysis in seg.AnalysesRS where analysis.Wordform != null select analysis);
}
}
/// <summary>
///
/// </summary>
public ParagraphParser(LcmCache cache)
{
Init(cache);
}
/// <summary>
///
/// </summary>
public ParagraphParser(IStTxtPara para)
: this(para.Cache)
{
Setup(para);
}
private void Init(LcmCache cache)
{
m_cache = cache;
m_paragraphTextScanner = new WordMaker(null, cache.ServiceLocator.WritingSystemManager);
m_wfr = m_cache.ServiceLocator.GetInstance<IWfiWordformRepository>();
m_wordfactory = m_cache.ServiceLocator.GetInstance<IWfiWordformFactory>();
m_cbar = m_cache.ServiceLocator.GetInstance<ICmBaseAnnotationRepository>();
}
/// <summary>
/// if parsing over multiple paragraphs, use this to setup the state before
/// </summary>
/// <param name="para"></param>
private void Setup(IStTxtPara para)
{
m_para = para;
m_tssPara = para.Contents;
// must prevent a first para.seg.word in an analysis ws from corrupting the parse
// only word forms in this ws will have analyses, the rest are turned into punctuation! LT-12304
// Until a model change is made to store the user's preffered vernacular ws,
// the user will always be able to defeat whatever vern ws we use here.
// For now, look for the first vern ws in the baseline text
m_paraWs = TsStringUtils.GetFirstVernacularWs(m_para.Cache.LanguageProject.VernWss, m_para.Services.WritingSystemFactory, m_para.Contents);
if (m_paraWs <= 0)
m_paraWs = m_cache.DefaultVernWs;
m_wordMaker = new WordMaker(m_tssPara, para.Cache.ServiceLocator.WritingSystemManager);
m_paragraphTextScanner.Tss = m_tssPara;
}
/// <summary>
/// Creates a single punctuation annotation for the specified range.
/// </summary>
/// <param name="ichMin"></param>
/// <param name="ichLim"></param>
private IAnalysis CreatePunctAnnotation(int ichMin, int ichLim)
{
return WfiWordformServices.FindOrCreatePunctuationform(m_cache, m_para.Contents.GetSubstring(ichMin, ichLim));
}
/// <summary>
/// Here ichMin..Lim indicates a (possibly empty) range of characters between two words,
/// or before the first word or after the last. If this range contains anything other than
/// white space (typically punctuation), make one or more extra annotations for each
/// group of white-space-separated characters in the range.
/// </summary>
/// <param name="ichMin"></param>
/// <param name="ichLim"></param>
/// <param name="annotationIds">Append ids of new annotations here.</param>
private void CreatePunctAnnotations(int ichMin, int ichLim, IList<IAnalysis> annotationIds)
{
int ichStart = ichMin;
bool fPrevIsWhite = true; // for current purpose imagine white space before ich.
for (int ich = ichMin; ich < ichLim; ich = m_wordMaker.NextChar(ich))
{
bool fIsWhite = m_wordMaker.IsWhite(ich);
// Transition from non-white to white: make an annotation
if (fIsWhite && !fPrevIsWhite)
annotationIds.Add(CreatePunctAnnotation(ichStart, ich));
// Transition from white to non-white: note start of punctuation group.
else if (!fIsWhite && fPrevIsWhite)
ichStart = ich;
fPrevIsWhite = fIsWhite;
}
// If last character is non-white, make an annotation for it.
if(!fPrevIsWhite)
annotationIds.Add(CreatePunctAnnotation(ichStart, ichLim));
}
// Do the actual parsing.
private void Parse()
{
s_cache = m_cache;
// track the ids for this paragraph that we'll try to reuse.
SetupPossibleIndicesForWordform();
// Create (or reuse if possible) segment annotations.
List<int> segBreaksDummy;
IList<ISegment> segments = CollectSegmentsOfPara(out segBreaksDummy);
int ichLimLast = 0;
int ichLimCurSeg = Int32.MaxValue;
ITsString tssFirstWordOfNextSegment = null;
int cWfanalysis = 0;
foreach (var seg in segments)
{
ichLimCurSeg = seg.EndOffset;
var newAnalyses = (from analysis in CollectSegmentForms(m_wordMaker.CurrentCharOffset,
ichLimCurSeg, ref cWfanalysis, ref ichLimLast, ref tssFirstWordOfNextSegment) select analysis as ICmObject).ToArray();
if (AnalysesChanged(seg, newAnalyses))
seg.AnalysesRS.Replace(0, seg.AnalysesRS.Count, newAnalyses);
}
}
/// <summary>
/// Return true if the newly computed list of analyses is different from the current list.
/// </summary>
private bool AnalysesChanged(ISegment seg, ICmObject[] newAnalyses)
{
if (seg.AnalysesRS.Count != newAnalyses.Length)
return true;
for (int i = 0; i < newAnalyses.Length; i++)
{
if (seg.AnalysesRS[i] != newAnalyses[i])
return true;
}
return false;
}
/// <summary>
/// develop a map for wordform to corresponding indices in the paragraph where that wordform existed in the old
/// list of wordform Analyses of the paragraph's segments. The indices represent a position in the list of wordforms
/// (not counting punctuation). It's important not to count punctuation, because the paragraph parser is used
/// to verify that all is well after data migration. The old FieldWorks (6.0 and before) did not have persistent
/// punctuation annotations, so if we count them in determining the expected position of an annotation, we end
/// up looking too late in the list, when migrating something that doesn't have them to start with. OTOH, if we
/// for some reason re-parse a paragraph that does have punctuation annotations included, if we counted them here,
/// that would throw us off in the other direction.
/// </summary>
private void SetupPossibleIndicesForWordform()
{
m_wordformAnnotationPossibilities.Clear();
for (int i = 0; i < m_preExistingAnalyses.Count; i++ )
{
var analysis = m_preExistingAnalyses[i];
// NOTE: for phrase annotations, use the first word as a key (LT-5856)
string annFirstWordformLowered;
ITsString firstWord = FirstWord(analysis.Wordform.Form.get_String(m_paraWs), Cache.ServiceLocator.WritingSystemManager,
out annFirstWordformLowered);
if (firstWord != null)
{
string key = annFirstWordformLowered;
IList<int> possibleIndices = null;
if (!m_wordformAnnotationPossibilities.TryGetValue(key, out possibleIndices))
{
// create a list of indices for wordform-annotations in this paragraph.
possibleIndices = new List<int>();
m_wordformAnnotationPossibilities.Add(key, possibleIndices);
}
possibleIndices.Add(i);
}
}
}
/// <summary>
/// the tss of the wordform form of the given hvoMatchingWordform in the ws we are querying for.
/// </summary>
/// <param name="sda"></param>
/// <param name="tssTxtWord">the tss of the baseline at current word boundaries</param>
/// <param name="tssWordAnn">the tss of the wordform form (in the baseline ws) of the annotation.</param>
/// <param name="hvoMatchingWordform"></param>
/// <param name="wsMatchQuery">the ws of the wordform we're looking for</param>
/// <returns></returns>
private ITsString GetTssWffCandidate(ISilDataAccess sda, ITsString tssTxtWord, ITsString tssWordAnn,
int hvoMatchingWordform, int wsMatchQuery)
{
ITsString tssWff = tssWordAnn;
int wsTxtWord = TsStringUtils.GetWsAtOffset(tssTxtWord, 0);
if (hvoMatchingWordform == 0)
{
// return a candidate if it matches the ws we're trying to query.
return wsMatchQuery == wsTxtWord ? tssWordAnn : null;
}
// if the ws of the matcher doesn't match the ws of the baseline
// find the wordform in an alternative ws.
if (wsMatchQuery != wsTxtWord)
{
tssWff = sda.get_MultiStringAlt(hvoMatchingWordform, WfiWordformTags.kflidForm, wsMatchQuery);
}
return tssWff;
}
/// <summary>
/// This routine is responsible for breaking a paragraph into segments. This is primarily done by looking for
/// 'EOS' (end-of-segment) characters, which are various characters that usually end sentences, plus a special one
/// which the user can insert into the text to force smaller segments. Also, we make separate segments for chapter
/// and verse numbers (or whatever 'IsLabelText' identifies as labels).
///
/// Although we typically end a segment when we find an EOS character, things are actually a bit more complex.
/// There may be various punctuation following the EOS character, such as quotes and parentheses. We don't actually make
/// a segment break unless we find some word-forming characters (or label text) after the EOS, so the last segment
/// can include any amount of trailing non-letter data. There might also be a good deal of non-letter data between
/// the EOS and the following letter. The current algorithm, partly because numbers are likely to be labels of what
/// follows and belong with it, is that (once we find a letter and decide to make a following segment) the break is
/// at the end of the first run of white space following the EOS. If there is no white space, the segment break is
/// right at the first letter that follows the EOS.
///
/// For label text, the segment break is always exactly at the start of a run that has the label style. White space
/// following a label run is included in its segment, and multiple label-style runs (possibly separated by white
/// space and including following white space) are merged into a single segment.
///
/// The algorithm also returns, for each segment except possibly the last, the character index of the first EOS
/// character in the segment (or, for label segments or segments that end because of a label rather than an EOS
/// character, the index of the character following the segment). This is helpful in adjusting segment boundaries
/// because material inserted into a segment before the EOS is less likely to change the way the segments break
/// up (unless of course it includes an EOS).
/// </summary>
/// <param name="tssText"></param>
/// <param name="ichMinSegBreaks"></param>
/// <returns></returns>
internal IList<ISegment> CollectSegments(ITsString tssText, out List<int> ichMinSegBreaks)
{
if (m_para == null)
throw new InvalidOperationException("Paragraph not initialized");
// Get the information we need to reuse existing annotations if possible.
m_preExistingSegs.Clear();
m_preExistingSegs.AddRange(m_para.SegmentsOS);
var collector = new SegmentMaker(tssText, m_cache.WritingSystemFactory, this);
collector.Run();
ichMinSegBreaks = collector.EosPositions;
if (m_preExistingSegs.Count > 0)
{
// Delete left-over segments.
// Enhance JohnT: should we copy their annotations into the last surviving segment if any?
m_para.SegmentsOS.Replace(m_para.SegmentsOS.Count - m_preExistingSegs.Count, m_preExistingSegs.Count, new ICmObject[0]);
m_preExistingSegs.Clear(); // I (JohnT) don't think it will be used again, but play safe
}
return collector.Segments;
}
/// <summary>
/// This is very similar to CollectSegments on the base class, but does not make
/// even dummy annotations, just TsStringSegments.
/// </summary>
/// <param name="tssText"></param>
/// <param name="ichMinSegBreaks"></param>
/// <returns></returns>
internal List<TsStringSegment> CollectTempSegmentAnnotations(ITsString tssText, out List<int> ichMinSegBreaks)
{
SegmentCollector collector = new SegmentCollector(tssText, m_cache.WritingSystemFactory);
collector.Run();
ichMinSegBreaks = collector.EosPositions;
return collector.Segments;
}
/// <summary>
/// Collect existing segments, if possible reusing existing ones, for the paragraph passed to the constructor.
/// This is now just a pseudonym, since the main routine also needs to reuse existing segments.
/// </summary>
internal IList<ISegment> CollectSegmentsOfPara(out List<int> ichMinSegBreaks)
{
return CollectSegments(m_para.Contents, out ichMinSegBreaks);
}
/// <summary>
/// Returns the first word in the given tssWordAnn and its lower case form.
/// </summary>
/// <param name="tssWordAnn"></param>
/// <param name="wsManager"></param>
/// <param name="firstFormLowered"></param>
/// <returns>null if we couldn't find a word in the given tssWordAnn</returns>
internal static ITsString FirstWord(ITsString tssWordAnn, WritingSystemManager wsManager, out string firstFormLowered)
{
WordMaker wordScanner = new WordMaker(tssWordAnn, wsManager);
int ichMinFirstWord;
int ichLimFirstWord;
ITsString firstWord = wordScanner.NextWord(out ichMinFirstWord, out ichLimFirstWord);
// Handle null values without crashing. See LT-6309 for how this can happen.
if (firstWord != null)
firstFormLowered = wordScanner.ToLower(firstWord);
else
firstFormLowered = null;
return firstWord;
}
/// <summary>
/// Identifies whether the given tssWordAnn is a phrase (ie. contains multiple forms that count as 'words').
/// </summary>
/// <param name="cache"></param>
/// <param name="tssWordAnn"></param>
/// <returns></returns>
internal static bool IsPhrase(LcmCache cache, ITsString tssWordAnn)
{
string firstFormLowered;
ITsString firstWord = FirstWord(tssWordAnn, cache.ServiceLocator.WritingSystemManager, out firstFormLowered);
// Handle null values without crashing. See LT-6309 for how this can happen.
return firstWord != null && firstWord.Length < tssWordAnn.Length;
}
/// <summary>
/// Collects SegmentForms between ichMinCurSeg to ichLimCurSeg.
/// </summary>
/// <param name="ichMinCurSeg"></param>
/// <param name="ichLimCurSeg"></param>
/// <param name="cWfAnalysisPrev">number of previous wordform analyses in paragraph (indicates where to start looking in reuse list)</param>
/// <param name="fUpdateRealData">if false, ParagraphParser only creates dummy annotations for the segment,
/// but doesn't modify any real annotation or change the state of ParagraphParser.</param>
/// <returns></returns>
internal IList<IAnalysis> CollectSegmentForms(int ichMinCurSeg, int ichLimCurSeg, int cWfAnalysisPrev, bool fUpdateRealData)
{
// if we don't want to modify real data, then put ParagraphParser in SegmentFormCollectionMode.
SegmentFormCollectionMode = !fUpdateRealData;
// Save current state of ParagraphParser.
int originalParagraphOffset = m_wordMaker.CurrentCharOffset;
try
{
int ichLimLast = ichMinCurSeg;
ITsString tssFirstWordOfNextSegment = null;
int copyOfcWfAnalysisPrev = cWfAnalysisPrev;
return CollectSegmentForms(ichMinCurSeg, ichLimCurSeg, ref copyOfcWfAnalysisPrev, ref ichLimLast, ref tssFirstWordOfNextSegment);
}
finally
{
if (SegmentFormCollectionMode)
{
// Restore state of ParagraphParser.
m_wordMaker.CurrentCharOffset = originalParagraphOffset;
SegmentFormCollectionMode = false;
}
}
}
/// <summary>
/// Collects the SegmentForms in a paragraph phrase marked by ichMinCurSeg and ichLimCurSeg,
/// without changing the current state of the ParagraphParser.
/// (e.g. We will try to match real forms but won't actually 'UseId' or change the state of paragraph or wordform annotations.
/// Also, we will return m_wordMaker back to its original state.)
/// </summary>
/// <param name="ichMinCurPhrase">beginning of the phrase in the paragraph.</param>
/// <param name="ichLimCurPhrase">ending of the phrase in the paragraph.</param>
/// <param name="cwfAnalysisPrev">number of previous wordform analyses in paragraph (indicates where to start looking in reuse list)</param>
/// <param name="phraseSegmentForms">SegmentForms that match in this paragraph.</param>
/// <param name="iFirstSegmentFormWithNonTrivialAnalyis">index of the first segmentForm with a real analysis in phraseSegmentForms.
/// -1 if they're all wordform analyses.</param>
/// <returns>true, if phraseSegmentForms contains an annotation with a significant analysis (i.e. other than wordform).</returns>
internal bool TryRealSegmentFormsInPhrase(int ichMinCurPhrase, int ichLimCurPhrase, int cwfAnalysisPrev, out IList<IAnalysis> phraseSegmentForms,
out int iFirstSegmentFormWithNonTrivialAnalyis)
{
phraseSegmentForms = CollectSegmentForms(ichMinCurPhrase, ichLimCurPhrase, cwfAnalysisPrev, false);
// search for the first non-wordform analyses.
return HasNonTrivialAnalysis(phraseSegmentForms, out iFirstSegmentFormWithNonTrivialAnalyis);
}
/// <summary>
/// Find the first
/// </summary>
/// <param name="segmentForms"></param>
/// <param name="iFirstSegmentFormWithNonTrivialAnalyis"></param>
/// <returns></returns>
private bool HasNonTrivialAnalysis(IList<IAnalysis> segmentForms, out int iFirstSegmentFormWithNonTrivialAnalyis)
{
iFirstSegmentFormWithNonTrivialAnalyis = -1;
int iSegForm = 0;
foreach (IAnalysis analysis in segmentForms)
{
if (!HasTrivialAnalysis(analysis))
{
iFirstSegmentFormWithNonTrivialAnalyis = iSegForm;
break;
}
iSegForm++;
}
return iFirstSegmentFormWithNonTrivialAnalyis != -1;
}
/// <summary>
/// Enabling this will put the ParagraphParser in a 'real only' mode
/// used to collect/create dummy annotations describing the given text.
/// No real annotation
/// </summary>
bool SegmentFormCollectionMode
{
get { return m_fSegmentFormCollectionMode; }
set { m_fSegmentFormCollectionMode = value; }
}
private IList<IAnalysis> CollectSegmentForms(int ichMinCurSeg, int ichLimCurSeg, ref int cWfAnalysisPrev, ref int ichLimLast,
ref ITsString tssFirstWordOfNextSegment)
{
var formsInSegment = new List<IAnalysis>();
int ichMin, ichLim;
m_wordMaker.CurrentCharOffset = ichMinCurSeg;
ITsString tssWord;
if (tssFirstWordOfNextSegment != null)
{
tssWord = tssFirstWordOfNextSegment;
// back up by this word.
ichLim = ichMinCurSeg;
ichMin = ichLim - tssWord.Length;
}
else
{
tssWord = m_wordMaker.NextWord(out ichMin, out ichLim);
}
do
{
if (tssWord == null)
{
// we've run out of non-punctuation text. collect the last remaining punctuation annotations.
//Debug.Assert(m_tssPara.Length == ichLimCurSeg);
CreatePunctAnnotations(ichLimLast, ichLimCurSeg, formsInSegment);
break;
}
if (ichLimLast != ichMin)
{
// we need to add punctuations to the current segment.
CreatePunctAnnotations(ichLimLast, Math.Min(ichMin, ichLimCurSeg), formsInSegment);
if (ichMin >= ichLimCurSeg)
{
// we need to add this wordform to the next segment.
tssFirstWordOfNextSegment = tssWord;
ichLimLast = ichLimCurSeg;
break;
}
}
if (TsStringUtils.GetWsAtOffset(m_tssPara, ichMin) != m_paraWs)
{
formsInSegment.Add(CreatePunctAnnotation(ichMin, ichLim));
ichLimLast = ichLim; // We've done something with text up to here.
}
else
{
// Make a reference to a wordform; or if we can match it in the original analyses,
// preserve the reference to one of its analyses or glosses.
ITsString tssWordAnn;
formsInSegment.Add(CreateOrReuseAnnotation(tssWord, ichMin, ichLim, cWfAnalysisPrev, out tssWordAnn));
cWfAnalysisPrev++;
if (tssWordAnn != null && tssWord.Length < tssWordAnn.Length)
{
// this must be a phrase, so advance appropriately in the text.
ichLimLast = ichMin + tssWordAnn.Length;
m_wordMaker.CurrentCharOffset = ichLimLast;
}
else
{
// still stepping by the word boundary.
ichLimLast = ichLim;
}
}
tssWord = m_wordMaker.NextWord(out ichMin, out ichLim);
if (tssWord == null)
{
tssFirstWordOfNextSegment = tssWord;
}
} while (true);
return formsInSegment;
}
internal ISegment CreateSegment(int ichMin, int ichLim)
{
// NOTE: This code is similar to ParagraphParserForEditMonitoring.TryReuseFirstUnusedAnnotation
// but is not as stricted at handling the conditions
Segment unusedSeg = (Segment)m_preExistingSegs.FirstOrDefault();
if (unusedSeg != null)
{
// Reuse it.
// It's conceivable that it belongs to a later sentence, but we have AnnotationAdjuster to try to avoid that.
m_preExistingSegs.RemoveAt(0);
unusedSeg.BeginOffset = ichMin;
return unusedSeg;
}
// Review JohnT: do we always have a current para when calling this?
// Do we always want to put the new segment at the end of it?
return ((SegmentFactory)m_para.Services.GetInstance<ISegmentFactory>()).Create(m_para, ichMin);
}
/// <summary>
///
/// </summary>
/// <param name="reusableCbaItems"></param>
/// <param name="ichMin">begin offset in actual text</param>
/// <param name="ichLim">end offset in actual text</param>
/// <param name="cbaFirstUnused">the first unused cba, whether or not we could reuse it.</param>
/// <returns>true if we reused it.</returns>
internal bool TryReuseFirstUnusedCbaMatchingText(IList<ReusableCbaItem> reusableCbaItems, int ichMin, int ichLim,
out ICmBaseAnnotation cbaFirstUnused)
{
cbaFirstUnused = null;
ReusableCbaItem unusedCbaItem = UnusedCbaItems(reusableCbaItems).FirstOrDefault();
if (unusedCbaItem != null)
{
ICmBaseAnnotation unusedCba = unusedCbaItem.Item;
if (unusedCba.BeginOffset == ichMin && unusedCba.EndOffset == ichLim)
{
cbaFirstUnused = unusedCba;
unusedCbaItem.Reuse();
return true;
}
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name="reusableCbas"></param>
/// <param name="ichMin"></param>
/// <param name="ichLim"></param>
/// <param name="cbaUsed"></param>
/// <returns></returns>
internal virtual bool TryReuseFirstUnusedAnnotation(IList<ReusableCbaItem> reusableCbas, int ichMin, int ichLim, out ICmBaseAnnotation cbaUsed)
{
cbaUsed = null;
// see if we can reuse an annotation from the current paragraph.
ReusableCbaItem rci = UnusedCbaItems(reusableCbas).FirstOrDefault();
if (rci != null)
{
rci.Reuse();
cbaUsed = rci.Item;
}
return cbaUsed != null;
}
// Verify that the annotation matches the offsets. They should have been cached in BuildAnalysisList();
//
bool HasValidOffsets(int hvoAnnotation, int ichMin, int ichLim)
{
ISilDataAccess sda = m_cache.MainCacheAccessor;
Debug.Assert(sda.get_IsPropInCache(hvoAnnotation, CmBaseAnnotationTags.kflidBeginOffset,
(int)CellarPropertyType.Integer, 0), "We expect BuildAnalysisList() to cache the annotation offsets.");
return ichMin == sda.get_IntProp(hvoAnnotation, CmBaseAnnotationTags.kflidBeginOffset) &&
ichLim == sda.get_IntProp(hvoAnnotation, CmBaseAnnotationTags.kflidEndOffset) &&
m_para.Hvo == sda.get_ObjectProp(hvoAnnotation, CmBaseAnnotationTags.kflidBeginObject);
}
/// <summary>
///
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
static protected int IndexOfFirstUnusedId(List<int> ids)
{
if (ids == null)
throw new NullReferenceException("ids");
return IndexOfFirstUnusedId(ids.ToArray());
}
static internal IEnumerable<ReusableCbaItem> UnusedCbaItems(IList<ReusableCbaItem> cbaItems)
{
return cbaItems.Where(cbaItem => !cbaItem.Reused);
}
static int IndexOfFirstUnusedId(int[] ids)
{
var i = 0;
for (; i < ids.Length && ids[i] == 0; ++i)
{}
return i;
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <param name="cbaItems"></param>
/// <returns></returns>
internal ICmBaseAnnotation UseCba(int index, IList<ReusableCbaItem> cbaItems)
{
Debug.Assert(index >= 0 && index < cbaItems.Count);
ICmBaseAnnotation cba = cbaItems[index].Item;
if (!SegmentFormCollectionMode)
cbaItems[index].Reuse();
return cba;
}
bool TryReuseAnalysis(ITsString tssTxtWord, int ichMin, int ichLim, int ianalysis, out IWfiWordform wf, out ITsString tssWordAnn, out IAnalysis analysis)
{
analysis = null;
tssWordAnn = tssTxtWord;
wf = null; // default
if (m_preExistingAnalyses.Count == 0)
{
// Enhance: This is a new paragraph that may have resulted in breaking
// up a previously existing paragraph. In that case we'd probably want to
// try to preserve the annotations/analyses.
return false;
}
// First, see if we have cached annotation ids for the wordform in this paragraph.
// the wordform and its lowercase form may already be in the cache.
string key = m_paragraphTextScanner.ToLower(tssTxtWord);
IList<int> possibleIndices;
if (!m_wordformAnnotationPossibilities.TryGetValue(key, out possibleIndices) || possibleIndices.Count == 0)
return false; // we don't have any remaining annotations matching this wordform.
possibleIndices = m_wordformAnnotationPossibilities[key];
int iAnnClosest;
GetBestPossibleAnnotation(ianalysis, possibleIndices, ichMin, ichLim - ichMin, out iAnnClosest);
if (iAnnClosest == -1)
return false; // can happen, if all the possible reuseable ones are actually phrases.
bool fUsedBestPossible = false;
try
{
wf = m_preExistingAnalyses[iAnnClosest].Wordform;
int wsTxtWord = TsStringUtils.GetWsAtOffset(tssTxtWord, 0);
tssWordAnn = wf.Form.get_String(wsTxtWord);
// Did we find it at the exact expected place in the sequence?
if (ianalysis != iAnnClosest)
{
// No, we didn't. Apply various heuristics to see whether we should use it.
// Enhance: If the character offsets in this text paragraph overlap
// the user probably deleted a paragraph break.
// in that case we could be smarter about looking for matches at the end of the paragraph
// rather than at the beginning.
// Verify the closest is within reasonable bounds.
if (Math.Abs(ianalysis - iAnnClosest) > 100)
{
// someone may have significantly altered the text,
// or it belongs to a wordform later in the text.
// Either case, safe not to guess a match.
tssWordAnn = tssTxtWord;
return false;
}
if (tssWordAnn.Length == 0)
{
// There are certain cases (e.g. during import) where
// the paragraph text will not have a default vernacular writing system for the current
// wordform. So, instead of trying to find the best vernacular form (again), we'll
// just assume that it matches some form of the tssWordTxt in this context.
tssWordAnn = tssTxtWord;
}
// JohnT: don't see any equivalent for this optimization, we don't know where in the
// text the closest occurrence used to be.
//// see if we can match on the target offset, so we don't have to search more through the text.
//if (m_paragraphTextScanner.MatchesWordInText(tssWordAnn, ichMinAnnClosest))
//{
// tssWordAnn = tssTxtWord;
// return false;
//}
// Otherwise, verify there isn't another place in the text closer to the
// offsets for the annotation's wordform.
if (ianalysis < iAnnClosest)
{
int intermediateWordCount = m_paragraphTextScanner.NextOccurrenceOfWord(tssWordAnn, ichLim,
ichMin +
tssWordAnn.Length);
if (intermediateWordCount != -1 && intermediateWordCount < iAnnClosest - ianalysis)
{
// we found a closer possible occurrence.
tssWordAnn = tssTxtWord;
return false;
}
}
else
{
// the match is earlier in the text than expected; it will certainly be closer
// to this occurrence than any later one.
}
}