-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFwDataMiniLcmApi.cs
More file actions
1813 lines (1636 loc) · 76.7 KB
/
Copy pathFwDataMiniLcmApi.cs
File metadata and controls
1813 lines (1636 loc) · 76.7 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
using System.Collections.Frozen;
using System.Globalization;
using System.Text;
using FwDataMiniLcmBridge.Api.UpdateProxy;
using FwDataMiniLcmBridge.LcmUtils;
using FwDataMiniLcmBridge.Media;
using Gridify;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MiniLcm;
using MiniLcm.Exceptions;
using MiniLcm.Media;
using MiniLcm.Models;
using MiniLcm.SyncHelpers;
using MiniLcm.Validators;
using SIL.LCModel;
using SIL.LCModel.Core.KernelInterfaces;
using SIL.LCModel.Core.Text;
using SIL.LCModel.Core.WritingSystems;
using SIL.LCModel.DomainServices;
using SIL.LCModel.Infrastructure;
using CollectionExtensions = SIL.Extensions.CollectionExtensions;
namespace FwDataMiniLcmBridge.Api;
public class FwDataMiniLcmApi(
Lazy<LcmCache> cacheLazy,
bool onCloseSave,
ILogger<FwDataMiniLcmApi> logger,
FwDataProject project,
IMediaAdapter mediaAdapter,
IOptions<FwDataBridgeConfig> config) : IMiniLcmApi, IMiniLcmSaveApi
{
private FwDataBridgeConfig Config => config.Value;
public const string AudioVisualFolder = "AudioVisual";
public LcmCache Cache
{
get
{
var cache = cacheLazy.Value;
// Guard against use-after-dispose (e.g. "Open in FieldWorks" closed the cache mid-request).
if (cache.IsDisposed)
throw new ObjectDisposedException(nameof(LcmCache),
$"FwData project '{Project.FileName}' was closed during this request (likely opened in FieldWorks or evicted from cache).");
return cache;
}
}
public FwDataProject Project { get; } = project;
public Guid ProjectId => Cache.LangProject.Guid;
private IWritingSystemContainer WritingSystemContainer => Cache.ServiceLocator.WritingSystems;
internal ILexEntryRepository EntriesRepository => Cache.ServiceLocator.GetInstance<ILexEntryRepository>();
internal IRepository<ILexSense> SenseRepository => Cache.ServiceLocator.GetInstance<IRepository<ILexSense>>();
private IRepository<ILexExampleSentence> ExampleSentenceRepository => Cache.ServiceLocator.GetInstance<IRepository<ILexExampleSentence>>();
private ILexEntryFactory LexEntryFactory => Cache.ServiceLocator.GetInstance<ILexEntryFactory>();
private ILexSenseFactory LexSenseFactory => Cache.ServiceLocator.GetInstance<ILexSenseFactory>();
private ILexExampleSentenceFactory LexExampleSentenceFactory => Cache.ServiceLocator.GetInstance<ILexExampleSentenceFactory>();
private IMoMorphTypeRepository MorphTypeRepository => Cache.ServiceLocator.GetInstance<IMoMorphTypeRepository>();
private IPartOfSpeechRepository PartOfSpeechRepository => Cache.ServiceLocator.GetInstance<IPartOfSpeechRepository>();
private ILexEntryTypeRepository LexEntryTypeRepository => Cache.ServiceLocator.GetInstance<ILexEntryTypeRepository>();
private ICmSemanticDomainRepository SemanticDomainRepository => Cache.ServiceLocator.GetInstance<ICmSemanticDomainRepository>();
private ICmTranslationFactory CmTranslationFactory => Cache.ServiceLocator.GetInstance<ICmTranslationFactory>();
private ICmPossibilityRepository CmPossibilityRepository => Cache.ServiceLocator.GetInstance<ICmPossibilityRepository>();
private ICmPossibilityList ComplexFormTypes => Cache.LangProject.LexDbOA.ComplexEntryTypesOA;
internal IEnumerable<ILexEntryType> ComplexFormTypesFlattened => ComplexFormTypes.PossibilitiesOS.Cast<ILexEntryType>().Flatten();
private ICmPossibilityList VariantTypes => Cache.LangProject.LexDbOA.VariantEntryTypesOA;
private ICmPossibilityList Publications => Cache.LangProject.LexDbOA.PublicationTypesOA;
public void Dispose()
{
if (onCloseSave && cacheLazy.IsValueCreated)
{
Save();
}
}
public void Save()
{
if (cacheLazy.Value.IsDisposed) return;
logger.LogInformation("Saving FW data file {Name}", Cache.ProjectId.Name);
Cache.ActionHandlerAccessor.Commit();
}
public int EntryCount => EntriesRepository.Count;
internal WritingSystemId GetWritingSystemId(int ws)
{
return Cache.GetWritingSystemId(ws);
}
internal int GetWritingSystemHandle(WritingSystemId ws, WritingSystemType? type = null)
{
return Cache.GetWritingSystemHandle(ws, type);
}
public Task<WritingSystems> GetWritingSystems()
{
var writingSystems = new WritingSystems
{
Vernacular = WritingSystemContainer.CurrentVernacularWritingSystems.Select((definition, index) =>
FromLcmWritingSystem(definition, WritingSystemType.Vernacular, index)).ToArray(),
Analysis = WritingSystemContainer.CurrentAnalysisWritingSystems.Select((definition, index) =>
FromLcmWritingSystem(definition, WritingSystemType.Analysis, index)).ToArray()
};
// Not used and not implemented in CRDT (also not done in GetWritingSystem())
// CompleteExemplars(writingSystems);
return Task.FromResult(writingSystems);
}
private WritingSystem FromLcmWritingSystem(CoreWritingSystemDefinition ws, WritingSystemType type, int index = default)
{
return new WritingSystem
{
Id = Guid.Empty,
// todo: Order probably shouldn't be relied on in fwdata, because it's implicit,
// so it probably shouldn't be used or set at all
Order = index,
Type = type,
//todo determine current and create a property for that.
WsId = ws.Id,
Name = ws.LanguageTag,
Abbreviation = ws.Abbreviation,
Font = ws.DefaultFontName,
Exemplars = ws.CharacterSets.FirstOrDefault(s => s.Type == "index")?.Characters.ToArray() ?? []
};
}
public Task<WritingSystem?> GetWritingSystem(WritingSystemId id, WritingSystemType type)
{
var lcmWs = Cache.TryGetCoreWritingSystem(id, type);
if (lcmWs is null) return Task.FromResult<WritingSystem?>(null);
var ws = FromLcmWritingSystem(lcmWs, type);
return Task.FromResult<WritingSystem?>(ws);
}
internal void CompleteExemplars(WritingSystems writingSystems)
{
var wsExemplars = writingSystems.Vernacular.Concat(writingSystems.Analysis)
.DistinctBy(ws => ws.WsId)
.ToDictionary(ws => ws, ws => ws.Exemplars.Select(s => s[0]).ToHashSet());
var wsExemplarsByHandle = wsExemplars.ToFrozenDictionary(kv => GetWritingSystemHandle(kv.Key.WsId), kv => kv.Value);
foreach (var entry in EntriesRepository.AllInstances())
{
if (entry.CitationForm is not null)
LcmHelpers.ContributeExemplars(entry.CitationForm, wsExemplarsByHandle);
if (entry.LexemeFormOA is { Form: not null })
LcmHelpers.ContributeExemplars(entry.LexemeFormOA.Form, wsExemplarsByHandle);
}
foreach (var ws in wsExemplars.Keys)
{
ws.Exemplars = [.. wsExemplars[ws].Order().Select(s => s.ToString())];
}
}
public async Task<WritingSystem> CreateWritingSystem(WritingSystem writingSystem, BetweenPosition<WritingSystemId?>? between = null)
{
var type = writingSystem.Type;
var exitingWs = type == WritingSystemType.Analysis ? Cache.ServiceLocator.WritingSystems.AnalysisWritingSystems : Cache.ServiceLocator.WritingSystems.VernacularWritingSystems;
if (exitingWs.Any(ws => ws.Id == writingSystem.WsId))
{
throw new DuplicateObjectException($"Writing system {writingSystem.WsId.Code} already exists");
}
CoreWritingSystemDefinition? ws = null;
await Cache.DoUsingNewOrCurrentUOW("Create Writing System",
"Remove writing system",
async () =>
{
Cache.ServiceLocator.WritingSystemManager.GetOrSet(writingSystem.WsId.Code, out ws);
ws.Abbreviation = writingSystem.Abbreviation;
switch (type)
{
case WritingSystemType.Analysis:
Cache.ServiceLocator.WritingSystems.AddToCurrentAnalysisWritingSystems(ws);
break;
case WritingSystemType.Vernacular:
Cache.ServiceLocator.WritingSystems.AddToCurrentVernacularWritingSystems(ws);
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
if (between is not null && (between.Previous is not null || between.Next is not null))
await MoveWritingSystem(writingSystem.WsId, type, between);
});
if (ws is null) throw new InvalidOperationException("Writing system not found");
var index = type switch
{
WritingSystemType.Analysis => WritingSystemContainer.CurrentAnalysisWritingSystems.Count,
WritingSystemType.Vernacular => WritingSystemContainer.CurrentVernacularWritingSystems.Count,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
} - 1;
return FromLcmWritingSystem(ws, type, index);
}
public async Task<WritingSystem> UpdateWritingSystem(WritingSystemId id, WritingSystemType type, UpdateObjectInput<WritingSystem> update)
{
if (!Cache.ServiceLocator.WritingSystemManager.TryGet(id.Code, out var lcmWritingSystem))
{
throw new InvalidOperationException($"Writing system {id.Code} not found");
}
await Cache.DoUsingNewOrCurrentUOW("Update WritingSystem",
"Revert WritingSystem",
() =>
{
var updateProxy = new UpdateWritingSystemProxy(lcmWritingSystem)
{
Id = Guid.Empty,
Type = type,
};
update.Apply(updateProxy);
return ValueTask.CompletedTask;
});
return await GetWritingSystem(id, type) ?? throw new NullReferenceException($"unable to find writing system with id {id}");
}
public async Task<WritingSystem> UpdateWritingSystem(WritingSystem before, WritingSystem after, IMiniLcmApi? api = null)
{
await Cache.DoUsingNewOrCurrentUOW("Update WritingSystem",
"Revert WritingSystem",
async () =>
{
await WritingSystemSync.Sync(before, after, api ?? this);
});
return await GetWritingSystem(after.WsId, after.Type) ?? throw new NullReferenceException($"unable to find {after.Type} writing system with id {after.WsId}");
}
public async Task MoveWritingSystem(WritingSystemId id, WritingSystemType type, BetweenPosition<WritingSystemId?> between)
{
var wsToUpdate = GetNonDefaultLexWritingSystem(id, type);
if (wsToUpdate is null) throw new NullReferenceException($"unable to find writing system with id {id}");
var previousWs = between.Previous is null ? null : GetNonDefaultLexWritingSystem(between.Previous.Value, type);
var nextWs = between.Next is null ? null : GetNonDefaultLexWritingSystem(between.Next.Value, type);
if (nextWs is null && previousWs is null) throw new NullReferenceException($"unable to find writing system with id {between.Previous} or {between.Next}");
await Cache.DoUsingNewOrCurrentUOW("Move WritingSystem",
"Revert Move WritingSystem",
() =>
{
var exitingWs = type == WritingSystemType.Analysis
? WritingSystemContainer.AnalysisWritingSystems
: WritingSystemContainer.VernacularWritingSystems;
var currentExistingWs = type == WritingSystemType.Analysis
? WritingSystemContainer.CurrentAnalysisWritingSystems
: WritingSystemContainer.CurrentVernacularWritingSystems;
MoveWs(wsToUpdate, previousWs, nextWs, exitingWs);
MoveWs(wsToUpdate, previousWs, nextWs, currentExistingWs);
void MoveWs(CoreWritingSystemDefinition ws,
CoreWritingSystemDefinition? previous,
CoreWritingSystemDefinition? next,
ICollection<CoreWritingSystemDefinition> list)
{
var index = -1;
if (previous is not null)
{
index = CollectionExtensions.IndexOf(list, previous);
if (index >= 0) index++;
}
if (index < 0 && next is not null)
{
index = CollectionExtensions.IndexOf(list, next);
}
if (index < 0)
throw new InvalidOperationException("unable to find writing system with id " + between.Previous + " or " + between.Next);
LcmHelpers.AddOrMoveInList(list, index, ws);
}
return ValueTask.CompletedTask;
});
}
private CoreWritingSystemDefinition? GetNonDefaultLexWritingSystem(WritingSystemId id, WritingSystemType type)
{
if (id == default) throw new ArgumentException("Cannot use default writing system ID", nameof(id));
return Cache.TryGetCoreWritingSystem(id, type);
}
public IAsyncEnumerable<PartOfSpeech> GetPartsOfSpeech()
{
return Cache.LangProject.AllPartsOfSpeech
.OrderBy(p => p.Name.BestAnalysisAlternative.Text)
.ToAsyncEnumerable()
.Select(FromLcmPartOfSpeech);
}
public Task<PartOfSpeech?> GetPartOfSpeech(Guid id)
{
return Task.FromResult(
PartOfSpeechRepository
.TryGetObject(id, out var partOfSpeech)
? FromLcmPartOfSpeech(partOfSpeech) : null);
}
public Task<PartOfSpeech> CreatePartOfSpeech(PartOfSpeech partOfSpeech)
{
IPartOfSpeech? lcmPartOfSpeech = null;
if (partOfSpeech.Id == default) partOfSpeech.Id = Guid.NewGuid();
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Create Part of Speech",
"Remove part of speech",
Cache.ServiceLocator.ActionHandler,
() =>
{
lcmPartOfSpeech = Cache.ServiceLocator.GetInstance<IPartOfSpeechFactory>()
.Create(partOfSpeech.Id, Cache.LangProject.PartsOfSpeechOA);
UpdateLcmMultiString(lcmPartOfSpeech.Name, partOfSpeech.Name);
});
return Task.FromResult(FromLcmPartOfSpeech(
lcmPartOfSpeech ?? throw new InvalidOperationException("Part of speech was not created")));
}
public Task<PartOfSpeech> UpdatePartOfSpeech(Guid id, UpdateObjectInput<PartOfSpeech> update)
{
var lcmPartOfSpeech = PartOfSpeechRepository.GetObject(id);
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Update Part of Speech",
"Revert Part of Speech",
Cache.ServiceLocator.ActionHandler,
() =>
{
var updateProxy = new UpdatePartOfSpeechProxy(lcmPartOfSpeech, this);
update.Apply(updateProxy);
});
return Task.FromResult(FromLcmPartOfSpeech(lcmPartOfSpeech));
}
public async Task<PartOfSpeech> UpdatePartOfSpeech(PartOfSpeech before, PartOfSpeech after, IMiniLcmApi? api = null)
{
await PartOfSpeechSync.Sync(before, after, api ?? this);
return await GetPartOfSpeech(after.Id) ?? throw new NullReferenceException($"unable to find part of speech with id {after.Id}");
}
public Task DeletePartOfSpeech(Guid id)
{
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Delete Part of Speech",
"Revert delete",
Cache.ServiceLocator.ActionHandler,
() =>
{
PartOfSpeechRepository.GetObject(id).Delete();
});
return Task.CompletedTask;
}
public async Task<Publication> CreatePublication(Publication pub)
{
if (pub.Id == default) pub.Id = Guid.NewGuid();
ICmPossibility? lcmPublication = null;
NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(Cache.ServiceLocator.ActionHandler, () =>
{
lcmPublication = Cache.ServiceLocator.GetInstance<ICmPossibilityFactory>().Create(pub.Id, Cache.LangProject.LexDbOA.PublicationTypesOA);
UpdateLcmMultiString(lcmPublication.Name, pub.Name);
}
);
return await Task.FromResult(FromLcmPossibility(
lcmPublication ?? throw new InvalidOperationException("Failed to create publication")));
}
private Publication FromLcmPossibility(ICmPossibility lcmPossibility)
{
var possibility = new Publication
{
Id = lcmPossibility.Guid,
Name = FromLcmMultiString(lcmPossibility.Name)
};
return possibility;
}
public Task<Publication> UpdatePublication(Guid id, UpdateObjectInput<Publication> update)
{
var lcmPublication = GetLcmPublication(id);
if (lcmPublication is null) throw new InvalidOperationException("Tried to update a non-existent publication");
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Update publication",
"Revert publication",
Cache.ServiceLocator.ActionHandler,
() =>
{
var updateProxy = new UpdatePublicationProxy(lcmPublication, this);
update.Apply(updateProxy);
});
return Task.FromResult(FromLcmPossibility(lcmPublication));
}
public async Task<Publication> UpdatePublication(Publication before, Publication after, IMiniLcmApi? api = null)
{
await PublicationSync.Sync(before, after, api ?? this);
return await GetPublication(after.Id) ?? throw new NullReferenceException($"Unable to find publication with id {after.Id}");
}
public Task DeletePublication(Guid id)
{
NonUndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW(Cache.ServiceLocator.ActionHandler, () =>
{
Cache.ServiceLocator.GetObject(id).Delete();
}
);
return Task.CompletedTask;
}
internal SemanticDomain FromLcmSemanticDomain(ICmSemanticDomain semanticDomain)
{
return new SemanticDomain
{
Id = semanticDomain.Guid,
Name = FromLcmMultiString(semanticDomain.Name),
Code = LcmHelpers.GetSemanticDomainCode(semanticDomain),
Predefined = CanonicalGuidsSemanticDomain.CanonicalSemDomGuids.Contains(semanticDomain.Guid),
};
}
public IAsyncEnumerable<SemanticDomain> GetSemanticDomains()
{
return
SemanticDomainRepository
.AllInstances()
.OrderBy(LcmHelpers.GetSemanticDomainCode)
.ToAsyncEnumerable()
.Select(FromLcmSemanticDomain);
}
public Task<SemanticDomain?> GetSemanticDomain(Guid id)
{
var semDom = GetLcmSemanticDomain(id);
return Task.FromResult(semDom is null ? null : FromLcmSemanticDomain(semDom));
}
public async Task<SemanticDomain> CreateSemanticDomain(SemanticDomain semanticDomain)
{
if (semanticDomain.Id == Guid.Empty) semanticDomain.Id = Guid.NewGuid();
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Create Semantic Domain",
"Remove semantic domain",
Cache.ActionHandlerAccessor,
() =>
{
var lcmSemanticDomain = Cache.ServiceLocator.GetInstance<ICmSemanticDomainFactory>()
.Create(semanticDomain.Id, Cache.LangProject.SemanticDomainListOA);
lcmSemanticDomain.OcmCodes = semanticDomain.Code;
UpdateLcmMultiString(lcmSemanticDomain.Name, semanticDomain.Name);
// TODO: Find out if semantic domains are guaranteed to have an "en" writing system, or if we should use lcmCache.DefautlAnalWs instead
UpdateLcmMultiString(lcmSemanticDomain.Abbreviation, new MultiString(){{"en", semanticDomain.Code}});
});
return await GetSemanticDomain(semanticDomain.Id) ?? throw new InvalidOperationException("Semantic domain was not created");
}
public Task<SemanticDomain> UpdateSemanticDomain(Guid id, UpdateObjectInput<SemanticDomain> update)
{
var lcmSemanticDomain = SemanticDomainRepository.GetObject(id);
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Update Semantic Domain",
"Revert Semantic Domain",
Cache.ServiceLocator.ActionHandler,
() =>
{
var updateProxy = new UpdateSemanticDomainProxy(lcmSemanticDomain, this);
update.Apply(updateProxy);
});
return Task.FromResult(FromLcmSemanticDomain(lcmSemanticDomain));
}
public async Task<SemanticDomain> UpdateSemanticDomain(SemanticDomain before, SemanticDomain after, IMiniLcmApi? api = null)
{
await SemanticDomainSync.Sync(before, after, api ?? this);
return await GetSemanticDomain(after.Id) ?? throw new NullReferenceException($"unable to find semantic domain with id {after.Id}");
}
public Task DeleteSemanticDomain(Guid id)
{
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Delete Semantic Domain",
"Revert delete",
Cache.ServiceLocator.ActionHandler,
() =>
{
SemanticDomainRepository.GetObject(id).Delete();
});
return Task.CompletedTask;
}
internal ICmSemanticDomain? GetLcmSemanticDomain(Guid semanticDomainId)
{
SemanticDomainRepository.TryGetObject(semanticDomainId, out var semanticDomain);
return semanticDomain;
}
public IAsyncEnumerable<ComplexFormType> GetComplexFormTypes()
{
return ComplexFormTypesFlattened.Select(ToComplexFormType).ToAsyncEnumerable();
}
public Task<ComplexFormType?> GetComplexFormType(Guid id)
{
var lexEntryType = ComplexFormTypesFlattened.SingleOrDefault(c => c.Guid == id);
if (lexEntryType is null) return Task.FromResult<ComplexFormType?>(null);
return Task.FromResult<ComplexFormType?>(ToComplexFormType(lexEntryType));
}
private ComplexFormType ToComplexFormType(ILexEntryType t)
{
return new ComplexFormType() { Id = t.Guid, Name = FromLcmMultiString(t.Name) };
}
public Task<ComplexFormType> CreateComplexFormType(ComplexFormType complexFormType)
{
if (complexFormType.Id == default) complexFormType.Id = Guid.NewGuid();
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Create complex form type",
"Remove complex form type",
Cache.ActionHandlerAccessor,
() =>
{
var lexComplexFormType = Cache.ServiceLocator
.GetInstance<ILexEntryTypeFactory>()
.Create(complexFormType.Id);
ComplexFormTypes.PossibilitiesOS.Add(lexComplexFormType);
UpdateLcmMultiString(lexComplexFormType.Name, complexFormType.Name);
});
return Task.FromResult(ToComplexFormType(ComplexFormTypesFlattened.Single(c => c.Guid == complexFormType.Id)));
}
public Task<ComplexFormType> UpdateComplexFormType(Guid id, UpdateObjectInput<ComplexFormType> update)
{
var type = ComplexFormTypesFlattened.SingleOrDefault(c => c.Guid == id);
if (type is null) throw new NullReferenceException($"unable to find complex form type with id {id}");
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Update Complex Form Type",
"Revert Complex Form Type",
Cache.ServiceLocator.ActionHandler,
() =>
{
var updateProxy = new UpdateComplexFormTypeProxy(type, this);
update.Apply(updateProxy);
});
return Task.FromResult(ToComplexFormType(type));
}
public async Task<ComplexFormType> UpdateComplexFormType(ComplexFormType before, ComplexFormType after, IMiniLcmApi? api = null)
{
await ComplexFormTypeSync.Sync(before, after, api ?? this);
return ToComplexFormType(ComplexFormTypesFlattened.Single(c => c.Guid == after.Id));
}
public async Task DeleteComplexFormType(Guid id)
{
var type = ComplexFormTypesFlattened.SingleOrDefault(c => c.Guid == id);
if (type is null) return;
await Cache.DoUsingNewOrCurrentUOW("Delete Complex Form Type",
"Revert delete",
() =>
{
type.Delete();
return ValueTask.CompletedTask;
});
}
public IAsyncEnumerable<MorphType> GetMorphTypes()
{
return
MorphTypeRepository
.AllInstances()
.ToAsyncEnumerable()
.Select(FromLcmMorphType);
}
public Task<MorphType?> GetMorphType(Guid id)
{
MorphTypeRepository.TryGetObject(id, out var lcmMorphType);
if (lcmMorphType is null) return Task.FromResult<MorphType?>(null);
return Task.FromResult<MorphType?>(FromLcmMorphType(lcmMorphType));
}
public Task<MorphType?> GetMorphType(MorphTypeKind kind)
{
var guid = LcmHelpers.ToLcmMorphTypeId(kind);
if (guid is null) return Task.FromResult<MorphType?>(null);
MorphTypeRepository.TryGetObject(guid.Value, out var lcmMorphType);
if (lcmMorphType is null) return Task.FromResult<MorphType?>(null);
return Task.FromResult<MorphType?>(FromLcmMorphType(lcmMorphType));
}
internal MorphType FromLcmMorphType(IMoMorphType morphType)
{
return new MorphType
{
Id = morphType.Guid,
Kind = LcmHelpers.FromLcmMorphType(morphType),
Name = FromLcmMultiString(morphType.Name),
Abbreviation = FromLcmMultiString(morphType.Abbreviation),
Description = FromLcmMultiString(morphType.Description),
Prefix = morphType.Prefix,
Postfix = morphType.Postfix,
SecondaryOrder = morphType.SecondaryOrder,
};
}
public Task<MorphType> CreateMorphType(MorphType morphType)
{
throw new NotSupportedException("Morph types cannot be created in fwdata; they are predefined");
}
public Task<MorphType> UpdateMorphType(Guid id, UpdateObjectInput<MorphType> update)
{
var lcmMorphType = MorphTypeRepository.GetObject(id);
if (lcmMorphType is null) throw new NullReferenceException($"unable to find morph type with id {id}");
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Update Morph Type",
"Revert Morph Type",
Cache.ServiceLocator.ActionHandler,
() =>
{
var updateProxy = new UpdateMorphTypeProxy(lcmMorphType, this);
update.Apply(updateProxy);
});
return Task.FromResult(FromLcmMorphType(lcmMorphType));
}
public async Task<MorphType> UpdateMorphType(MorphType before, MorphType after, IMiniLcmApi? api = null)
{
await MorphTypeSync.Sync(before, after, api ?? this);
return await GetMorphType(after.Id) ?? throw new NullReferenceException("unable to find morph type with id " + after.Id);
}
public IAsyncEnumerable<VariantType> GetVariantTypes()
{
return VariantTypes.PossibilitiesOS
.Select(t => new VariantType() { Id = t.Guid, Name = FromLcmMultiString(t.Name) })
.ToAsyncEnumerable();
}
public IAsyncEnumerable<Publication> GetPublications()
{
return Publications.PossibilitiesOS
.Select(FromLcmPossibility)
.ToAsyncEnumerable();
}
public Task<Publication?> GetPublication(Guid id)
{
var publication = GetLcmPublication(id);
return Task.FromResult(publication is null ? null : FromLcmPossibility(publication));
}
internal ICmPossibility? GetLcmPublication(Guid id)
{
return Publications.PossibilitiesOS.FirstOrDefault(p => p.Guid == id);
}
private PartOfSpeech FromLcmPartOfSpeech(IPartOfSpeech lcmPos)
{
return new PartOfSpeech
{
Id = lcmPos.Guid,
Name = FromLcmMultiString(lcmPos.Name),
// TODO: Abreviation = FromLcmMultiString(partOfSpeech.Abreviation),
Predefined = CanonicalGuidsPartOfSpeech.CanonicalPosGuids.Contains(lcmPos.Guid),
};
}
private Entry FromLexEntry(ILexEntry entry)
{
try
{
var result = new Entry
{
Id = entry.Guid,
Note = FromLcmMultiString(entry.Comment),
LexemeForm = FromLcmMultiString(entry.LexemeFormOA?.Form),
CitationForm = FromLcmMultiString(entry.CitationForm),
LiteralMeaning = FromLcmMultiString(entry.LiteralMeaning),
MorphType = LcmHelpers.FromLcmMorphType(entry.PrimaryMorphType), // TODO: Decide what to do about entries with *mixed* morph types
HomographNumber = entry.HomographNumber,
Senses = [.. entry.AllSenses.Select(FromLexSense)],
ComplexFormTypes = ToComplexFormTypes(entry),
Components = [.. ToComplexFormComponents(entry)],
ComplexForms = [
..entry.ComplexFormEntries.Select(complexEntry => ToEntryReference(entry, complexEntry)),
..entry.AllSenses.SelectMany(sense => sense.ComplexFormEntries.Select(complexEntry => ToSenseReference(sense, complexEntry)))
],
// ILexEntry.PublishIn is a virtual property that inverts DoNotPublishInRC against all publications
PublishIn = entry.PublishIn.Select(FromLcmPossibility).ToList(),
};
return result;
}
catch (Exception e)
{
var headword = entry.LexEntryHeadwordOrUnknown();
throw new InvalidOperationException($"Failed to map FW entry to MiniLCM entry '{headword}' ({entry.Guid})", e);
}
}
private List<ComplexFormType> ToComplexFormTypes(ILexEntry entry)
{
return entry.ComplexFormEntryRefs
.SelectMany(r => r.ComplexEntryTypesRS, (_, type) => ToComplexFormType(type))
.DistinctBy(c => c.Id)
.ToList();
}
private IEnumerable<ComplexFormComponent> ToComplexFormComponents(ILexEntry entry)
{
return entry.ComplexFormEntryRefs.SelectMany(r => r.ComponentLexemesRS,
(_, o) => o switch
{
ILexEntry component => ToEntryReference(component, entry),
ILexSense s => ToSenseReference(s, entry),
_ => throw new NotSupportedException($"object type {o.ClassName} not supported")
}).DistinctBy(c => (c.ComponentEntryId, c.ComplexFormEntryId, c.ComponentSenseId));
}
private Variants? ToVariants(ILexEntry entry)
{
var variantEntryRef = entry.VariantEntryRefs.SingleOrDefault();
if (variantEntryRef is null) return null;
return new Variants
{
Id = variantEntryRef.Guid,
VariantsOf =
[
..variantEntryRef.ComponentLexemesRS.Select(o => o switch
{
ILexEntry component => ToEntryReference(component, entry),
ILexSense s => ToSenseReference(s, entry),
_ => throw new NotSupportedException($"object type {o.ClassName} not supported")
})
],
Types =
[
..variantEntryRef.VariantEntryTypesRS.Select(t =>
new VariantType() { Id = t.Guid, Name = FromLcmMultiString(t.Name), })
]
};
}
private ComplexFormComponent ToEntryReference(ILexEntry component, ILexEntry complexEntry)
{
return new ComplexFormComponent
{
ComponentEntryId = component.Guid,
ComponentHeadword = component.LexEntryHeadwordOrUnknown(applyMorphTokens: false), // match CRDT for now
ComplexFormEntryId = complexEntry.Guid,
ComplexFormHeadword = complexEntry.LexEntryHeadwordOrUnknown(applyMorphTokens: false), // match CRDT for now
Order = Order(component, complexEntry)
};
}
private ComplexFormComponent ToSenseReference(ILexSense componentSense, ILexEntry complexEntry)
{
return new ComplexFormComponent
{
ComponentEntryId = componentSense.Entry.Guid,
ComponentSenseId = componentSense.Guid,
ComponentHeadword = componentSense.Entry.LexEntryHeadwordOrUnknown(applyMorphTokens: false), // match CRDT for now
ComplexFormEntryId = complexEntry.Guid,
ComplexFormHeadword = complexEntry.LexEntryHeadwordOrUnknown(applyMorphTokens: false), // match CRDT for now
Order = Order(componentSense, complexEntry)
};
}
private static int Order(ICmObject component, ILexEntry complexEntry)
{
var order = 0;
foreach (var entryRef in complexEntry.ComplexFormEntryRefs)
{
var foundIndex = entryRef.ComponentLexemesRS.IndexOf(component);
if (foundIndex == -1)
{
order += entryRef.ComponentLexemesRS.Count;
}
else
{
order += foundIndex + 1;
break;
}
}
return order;
}
private Sense FromLexSense(ILexSense sense)
{
var pos = sense.MorphoSyntaxAnalysisRA?.GetPartOfSpeech();
var s = new Sense
{
Id = sense.Guid,
EntryId = sense.Entry.Guid,
Gloss = FromLcmMultiString(sense.Gloss),
Definition = FromLcmMultiString(sense.Definition),
PartOfSpeech = pos is null ? null : FromLcmPartOfSpeech(pos),
PartOfSpeechId = pos?.Guid,
SemanticDomains = [.. sense.SemanticDomainsRC.Select(FromLcmSemanticDomain)],
ExampleSentences = [.. sense.ExamplesOS.Select(sentence => FromLexExampleSentence(sense.Guid, sentence))]
};
return s;
}
private ExampleSentence FromLexExampleSentence(Guid senseGuid, ILexExampleSentence sentence)
{
return new ExampleSentence
{
Id = sentence.Guid,
SenseId = senseGuid,
Sentence = FromLcmMultiString(sentence.Example),
Reference = ToRichString(sentence.Reference),
Translations = sentence.TranslationsOC.Select(t => new Translation
{
Id = t.Guid,
Text = t.Translation is null ? [] : FromLcmMultiString(t.Translation),
}).ToList()
};
}
private MultiString FromLcmMultiString(ITsMultiString? multiString)
{
if (multiString is null) return [];
var result = new MultiString(multiString.StringCount);
for (var i = 0; i < multiString.StringCount; i++)
{
var tsString = multiString.GetStringFromIndex(i, out var ws);
var wsId = GetWritingSystemId(ws);
if (!wsId.IsAudio)
{
// Text is null if TsStringUtils.MakeString was called with an empty string.
// So, we map it back for consistent round-tripping and
// so we can continue to assume that MultiStrings never have null values.
result.Values.Add(wsId, tsString.Text ?? string.Empty);
}
else
{
result.Values.Add(wsId, ToMediaUri(tsString.Text));
}
}
return result;
}
private RichMultiString FromLcmMultiString(IMultiString multiString)
{
var result = new RichMultiString(multiString.StringCount);
for (var i = 0; i < multiString.StringCount; i++)
{
var tsString = multiString.GetStringFromIndex(i, out var ws);
var richString = ToRichString(tsString);
if (richString is null) continue;
var wsId = GetWritingSystemId(ws);
if (wsId.IsAudio && richString.Spans.Count == 1)
{
var span = richString.Spans[0];
richString.Spans[0] = span with { Text = ToMediaUri(span.Text) };
}
result.Add(wsId, richString);
}
return result;
}
private string ToMediaUri(string tsString)
{
//rooted media paths aren't supported
if (Path.IsPathRooted(tsString))
throw new ArgumentException("Media path must be relative", nameof(tsString));
var fullFilePath = Path.Join(Cache.LangProject.LinkedFilesRootDir, AudioVisualFolder, tsString);
return mediaAdapter.MediaUriFromPath(fullFilePath, Cache).ToString();
}
internal string FromMediaUri(string mediaUriString)
{
//path includes `AudioVisual` currently
var mediaUri = new MediaUri(mediaUriString);
var path = mediaAdapter.PathFromMediaUri(mediaUri, Cache);
if (path is null) throw new NotFoundException($"File ID: {mediaUri.FileId}.", nameof(MediaFile));
return Path.GetRelativePath(Path.Join(Cache.LangProject.LinkedFilesRootDir, AudioVisualFolder), path);
}
internal RichString? ToRichString(ITsString? tsString)
{
/// Same null mapping logic as <see cref="RichStringConverter"/>
if (tsString is null or { Length: 0 }) return null;
return RichTextMapping.FromTsString(tsString,
h =>
{
if (h is null) return null;
return GetWritingSystemId(h.Value);
});
}
public Task<int> CountEntries(string? query = null, FilterQueryOptions? options = null)
{
if (options?.HasFilter == true || query?.Length is > 0)
return Task.FromResult(GetLexEntries(EntrySearchPredicate(query), options).Count());
return Task.FromResult(EntriesRepository.Count);
}
public IAsyncEnumerable<Entry> GetEntries(QueryOptions? options = null)
{
return GetEntries(null, options);
}
public IEnumerable<ILexEntry> GetLexEntries(
Func<ILexEntry, bool>? predicate, FilterQueryOptions? options = null)
{
var entries = EntriesRepository.AllInstances();
options ??= FilterQueryOptions.Default;
if (predicate is not null) entries = entries.Where(predicate);
if (!string.IsNullOrEmpty(options.Filter?.GridifyFilter))
{
var query = new GridifyQuery() { Filter = options.Filter.GridifyFilter };
var filter = query.GetFilteringExpression(config.Value.Mapper).Compile();
entries = entries.Where(filter);
}
if (options.Exemplar is not null)
{
var ws = GetWritingSystemHandle(options.Exemplar.WritingSystem, WritingSystemType.Vernacular);
var exemplar = options.Exemplar.Value.Normalize(NormalizationForm.FormD);//LCM data is NFD so the should be as well
entries = entries.Where(e =>
{
var value = (e.CitationForm.get_String(ws).Text ?? e.LexemeFormOA.Form.get_String(ws).Text)?
.Trim(LcmHelpers.WhitespaceAndFormattingChars);
if (value is null || value.Length < exemplar.Length) return false;
//exemplar is normalized, so we can use StartsWith
//there may still be cases where value.StartsWith(value[0].ToString()) == false (e.g. "آبراهام")
//another example is "เพือ" does not start with "เ"
//but I don't have the data to test that
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(value, exemplar, CompareOptions.IgnoreCase);
});
}
return entries;
}
public IAsyncEnumerable<Entry> GetEntries(
Func<ILexEntry, bool>? predicate, QueryOptions? options = null, string? query = null)
{
options ??= QueryOptions.Default;
var entries = GetFilteredAndSortedEntries(predicate, options, options.Order, query);
entries = options.ApplyPaging(entries);
return entries.ToAsyncEnumerable().Select(FromLexEntry);
}
private IEnumerable<ILexEntry> GetFilteredAndSortedEntries(Func<ILexEntry, bool>? predicate, FilterQueryOptions? filterOptions, SortOptions order, string? query)
{
var entries = GetLexEntries(predicate, filterOptions);
return ApplySorting(order, entries, query);
}
private IEnumerable<ILexEntry> ApplySorting(SortOptions order, IEnumerable<ILexEntry> entries, string? query)
{
var sortWs = GetWritingSystemHandle(order.WritingSystem, WritingSystemType.Vernacular);
var stemSecondaryOrder = MorphTypeRepository.GetObject(MoMorphTypeTags.kguidMorphStem).SecondaryOrder;
if (order.Field == SortField.SearchRelevance)
{
return entries.ApplyRoughBestMatchOrder(order, sortWs, stemSecondaryOrder, query);
}
return entries.ApplyHeadwordOrder(order, sortWs, stemSecondaryOrder);
}
public IAsyncEnumerable<Entry> SearchEntries(string query, QueryOptions? options = null)
{
var entries = GetEntries(EntrySearchPredicate(query), options, query);
return entries;
}
private Func<ILexEntry, bool>? EntrySearchPredicate(string? query = null)
{
if (string.IsNullOrEmpty(query)) return null;
return entry => entry.SearchHeadWord(query) || // CitationForm.SearchValue would be redundant
entry.LexemeFormOA?.Form.SearchValue(query) is true ||
entry.AllSenses.Any(s => s.Gloss.SearchValue(query));
}
public Task<Entry?> GetEntry(Guid id)
{
EntriesRepository.TryGetObject(id, out var lexEntry);
return Task.FromResult(lexEntry is null ? null : FromLexEntry(lexEntry));
}
public Task<int> GetEntryIndex(Guid entryId, string? query = null, IndexQueryOptions? options = null)
{
var predicate = EntrySearchPredicate(query);
var entries = GetFilteredAndSortedEntries(predicate, options, options?.Order ?? SortOptions.Default, query);
var rowIndex = 0;
foreach (var entry in entries)
{
if (entry.Guid == entryId)
{
return Task.FromResult(rowIndex);
}
rowIndex++;
}
return Task.FromResult(-1);
}
public async Task<Entry> CreateEntry(Entry entry, CreateEntryOptions? options = null)
{
options ??= CreateEntryOptions.Everything;
entry.Id = entry.Id == default ? Guid.NewGuid() : entry.Id;
try
{
UndoableUnitOfWorkHelper.DoUsingNewOrCurrentUOW("Create Entry",
"Remove entry",