Repository navigation
Expand file tree
/
Copy pathTagCollection.cs
More file actions
676 lines (619 loc) · 25.1 KB
/
Copy pathTagCollection.cs
File metadata and controls
676 lines (619 loc) · 25.1 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Drawing;
namespace SharpTagManager
{
/// <summary>
/// Represents the data of a tag
/// Instances should be held inside of a TagCollection and there should be ONLY ONE instance of a tag.
/// The same Tag instance may be part of multiple TagCollection (when multiple images have the same tag)
/// </summary>
class TagItem
{
public string Name { get; private set;}
public TagLayer Layer { get; private set; }
public TagDatabase.TagEntry DatabaseEntry;
public List<ImageItem> Items = new List<ImageItem>();
public override string ToString() { return Name;}
/// <summary>
/// Creates a TagItem that is managed by the project that the provided TagLayer belongs to
/// </summary>
public TagItem(string name = null, TagLayer layer = null)
{
Name = name;
Layer = layer;
if (Layer != null)
DatabaseEntry = FormTagSelector.TagMatchToDatabase(name);
}
/// <summary>
/// Creates a UNMANAGED TagItem
/// This tag is not tracked as part of the project (mostly useful when importing stuff that is not yet part of it)
/// </summary>
public TagItem(string name, string layer)
{
Name = name;
Layer = new TagLayer_Tags(layer);
}
}
/// <summary>
/// Wrapper for TagItem that adds info used for easily sorting tags according to different criteria
/// </summary>
class TagItemOrdered
{
public TagItem Item;
public int NaturalOrder;
public double Weight;
public TagLayer Layer;
public TagLayer AssimilatedFromLayer;
public int Count;
public string NewName = null;
public string TextNote = null;
public BoundArea BoundArea = null;
public bool HasMoved = false;
public bool MoveNotAllowed = false;
public Color StripeColor = default;
public Color BorderColor = default;
public bool IsPlaceholder = false;
// Constructor
public TagItemOrdered(TagItem item, double weight=1)
{
Item = item;
Weight = weight;
if (item != null)
{
Layer = item.Layer;
}
}
// Convenient cast back to a normal TagItem
public static explicit operator TagItem(TagItemOrdered tag) { return tag?.Item; }
public override string ToString()
{
string str = $"{NaturalOrder}:{Item}";
if (NewName != null) str += $"-> {NewName}";
if ((Weight != 0) && (Weight != 1)) str += $" Weight:{Weight}";
return str;
}
}
/// <summary>
/// Holds a ordered list of TagItem
/// The TagItem objects it holds are not unique instances for this collection, they may appear in multiple collections
/// </summary>
class TagCollection
{
private List<TagItem> Tags = new List<TagItem>();
private Dictionary<TagItem, double> Weights = new Dictionary<TagItem, double>();
private Dictionary<TagItem, BoundArea> BoundAreas = new Dictionary<TagItem, BoundArea>();
public string Name;
public ReadOnlyCollection<TagItem> Items => Tags.AsReadOnly();
public ReadOnlyDictionary<TagItem, double> ItemWeights => new ReadOnlyDictionary<TagItem, double>(Weights);
public int Count => Tags.Count();
public TagLayer ParentTagLayer { get; private set; }
public ImageItem ParentImageItem { get; private set; }
public bool ReadOnly = false;
public bool HasChanged = false;
public override string ToString() { return $"TagCollection '{Name}': {Tags?.Count}"; }
public TagCollection(string name = null)
{
Name = name;
}
public TagCollection(ImageItem parent, string name = null)
{
Name = name;
ParentImageItem = parent;
}
public TagCollection(TagLayer parent, string name = null)
{
Name = name;
ParentTagLayer = parent;
}
/// <summary>
/// Add the given tag to the collection
/// </summary>
public void Add(TagItem tag, int index = -1, double weight=1)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
if (tag == null)
return; // Nothing to add
if (Tags.Contains(tag))
return; // Tag is already added
if ((ParentTagLayer != null) && (tag.Layer != ParentTagLayer))
throw new Exception($"Tag {tag} is already on layer '{tag.Layer}' and so can't be added to '{ParentTagLayer}'");
if(index > Tags.Count)
index = Tags.Count; // Index was out of range, so clamp down
// Insert at the end if not specified
if (index < 0)
Tags.Add(tag);
else
Tags.Insert(index, tag);
// Set weight if needed
if (weight != 1)
Weights[tag] = weight;
// Only link real, project-tracked images - not transient ones like augment variants
if ((ParentImageItem != null) && (ParentImageItem.Project != null))
{
if(!tag.Items.Contains(ParentImageItem))
tag.Items.Add(ParentImageItem);
}
HasChanged = true;
}
/// <summary>
/// Add the given tag to the collection
/// </summary>
public void Add(TagItemOrdered tag, int index = -1)
{
Add(tag.Item, index, tag.Weight);
if (tag.BoundArea != null)
SetBoundArea(tag.Item, tag.BoundArea);
}
/// <summary>
/// Add the given tags to the collection
/// </summary>
public void Add(IEnumerable<TagItem> tags, int index = -1)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
foreach (TagItem tag in tags)
{
Add(tag, index);
if (index >= 0)
index++;
}
}
/// <summary>
/// Add the given tags to the collection
/// </summary>
public void Add(TagCollection tags, int index = -1)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
foreach (TagItem tag in tags.Items)
{
Add(tag, index, tags.GetWeight(tag));
BoundArea area = tags.GetBoundArea(tag);
if (area != null)
SetBoundArea(tag, area);
if (index >= 0)
index++;
}
}
/// <summary>
/// Remove the given tag from the collection
/// </summary>
public void Remove(TagItem tag)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
// Remove the tag from the collection
Tags.Remove(tag);
Weights.Remove(tag);
BoundAreas.Remove(tag);
// Unlink the images and tags
if (ParentImageItem != null)
tag.Items.Remove(ParentImageItem);
HasChanged = true;
// This may have left the tag with 0 images using it — let the layer clean it up if so.
if (tag.Layer != null)
tag.Layer.Prune();
}
/// <summary>
/// Change the name of a tag (makes sure to not change it globally)
/// </summary>
public TagItem Rename(TagItem tag, string newName)
{
double weight = GetWeight(tag);
BoundArea area = GetBoundArea(tag);
int index = Tags.IndexOf(tag);
Remove(tag);
TagItem tagNew;
if (tag.Layer?.Project != null)
tagNew = tag.Layer.Project.IntroduceTag(newName, tag.Layer.Name); // Tag is bound to a project to check in with the project instance
else
tagNew = new TagItem(newName, tag.Layer); // Not in a project, so just make a new one on the same layer (null layer included)
Add(tagNew, index, weight);
if (area != null)
SetBoundArea(tagNew, area);
return tagNew;
}
/// <summary>
/// Swaps out an existing tag with a new one
/// </summary>
public void Swap(TagItem tagOld, TagItem tagNew)
{
if (tagOld == tagNew)
return; // Tags are already the same, nothing to do
int index = Tags.IndexOf(tagOld);
double weight = GetWeight(tagOld);
BoundArea area = GetBoundArea(tagOld);
Remove(tagOld);
Add(tagNew, index, weight);
if (area != null)
SetBoundArea(tagNew, area);
}
/// <summary>
/// Swaps out an existing tag with a new one everywhere
/// </summary>
public static void SwapRecursive(TagItem tagOld, TagItem tagNew)
{
// Find all the items associated with the tag (clone it as it will get modified)
List<ImageItem> items = new List<ImageItem>(tagOld.Items);
// Iterate over all the images
foreach (ImageItem item in items)
{
item.Tags.Swap(tagOld, tagNew);
}
}
/// <summary>
/// Swaps tagOld for tagNew everywhere it's used, then deletes tagOld. No-ops if they're the same instance.
/// </summary>
public static void ReplaceTag(TagItem tagOld, TagItem tagNew)
{
if (tagOld == tagNew)
return;
SwapRecursive(tagOld, tagNew);
tagOld.Layer.Tags.RemoveFromAll(tagOld);
}
/// <summary>
/// Reorder the tags to match the given list
/// </summary>
public void Reorder(IEnumerable<TagItemOrdered> tags)
{
foreach (TagItemOrdered tag in tags.Reverse())
{
if (tag?.Item != null)
Reorder(tag.Item, 0);
}
}
/// <summary>
/// Move the given tag into the new position
/// Weights and bound areas are keyed by tag, so they follow it to the new position
/// </summary>
public void Reorder(TagItem tag, int toIndex)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
int srcIndex = Tags.IndexOf(tag);
if (srcIndex < 0)
return; // Tag is not in this collection
if (toIndex > srcIndex)
toIndex--; // Compensate for the offset caused by pulling the tag out before shifting the whole list
Tags.RemoveAt(srcIndex);
if (toIndex < 0)
toIndex = 0;
if (toIndex > Tags.Count)
toIndex = Tags.Count;
Tags.Insert(toIndex, tag);
HasChanged = true;
}
public void SetWeight(TagItem item, double weight)
{
if(Tags.Contains(item))
Weights[item] = weight;
}
public double GetWeight(TagItem item)
{
double weight;
if (Weights.TryGetValue(item, out weight) == false)
weight = 1;
return weight;
}
public void SetBoundArea(TagItem item, BoundArea area)
{
if (Tags.Contains(item))
{
if (area == null)
BoundAreas.Remove(item);
else
BoundAreas[item] = area;
}
}
public BoundArea GetBoundArea(TagItem item)
{
BoundArea area;
BoundAreas.TryGetValue(item, out area);
return area; // null when not set
}
/// <summary>
/// Remove all tags from collection
/// </summary>
public void Clear()
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
foreach (TagItem tag in Tags.ToArray())
{
Remove(tag);
}
}
/// <summary>
/// Remove tags in a way that nukes the tag from everywhere it is used
/// </summary>
public void RemoveFromAll(TagItem tag)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
foreach (ImageItem image in tag.Items.ToList())
{
image.Tags.Remove(tag);
}
tag.Layer?.Tags?.Remove(tag);
}
public TagItem Get(string name)
{
foreach (TagItem tag in Tags)
{
if (tag.Name == name)
return tag;
}
return null;
}
public bool Contains(string name)
{
return Get(name) != null;
}
public bool Contains(TagItem tag)
{
return Items.Contains(tag);
}
public TagItem Get(string name, string layerName)
{
foreach (TagItem tag in Tags)
{
if((tag.Name == name) && (tag.Layer?.Name == layerName))
return tag;
}
return null;
}
public List<TagItemOrdered> ToList()
{
List<TagItemOrdered> result = new List<TagItemOrdered>();
int i = 0;
foreach (TagItem tag in Items)
{
TagItemOrdered tagO = new TagItemOrdered(tag);
tagO.Count = 1;
tagO.NaturalOrder = i++;
tagO.Weight = GetWeight(tag);
tagO.BoundArea = GetBoundArea(tag);
result.Add(tagO);
}
return result;
}
/// <summary>
/// Copies tags into a new collection owned by <paramref name="newParent"/>, carrying weight and
/// bound area across for every kept tag. Used by image augments (crop/resize/rotate/mirror/mask)
/// that need a per-variant tag collection instead of sharing the original by reference.
/// </summary>
/// <param name="newParent">Image the new collection belongs to</param>
/// <param name="filter">Optional: return false to drop a tag from the copy. Null keeps everything</param>
/// <param name="transformArea">Optional: re-expresses a kept tag's bound area (e.g. scaled/shifted/rotated to match a geometry change). Only invoked for tags that have one. Null keeps areas unchanged</param>
public TagCollection CloneTransformed(ImageItem newParent, Func<TagItem, bool> filter = null, Func<BoundArea, BoundArea> transformArea = null)
{
return CopyInto(new TagCollection(newParent, newParent.Name), Items, filter, transformArea);
}
/// <summary>
/// Copies tags into a new, unparented collection (e.g. a transient tag-augment variant that
/// isn't tied to any single ImageItem), carrying weight and bound area across for every kept tag.
/// </summary>
/// <param name="name">Name for the new collection</param>
/// <param name="order">Order to copy tags in (e.g. a shuffled sequence). Must only contain tags already in this collection. Null keeps the current order</param>
/// <param name="filter">Optional: return false to drop a tag from the copy. Null keeps everything</param>
public TagCollection CloneTransformed(string name, IEnumerable<TagItem> order = null, Func<TagItem, bool> filter = null)
{
return CopyInto(new TagCollection(name), order ?? Items, filter, null);
}
private TagCollection CopyInto(TagCollection result, IEnumerable<TagItem> order, Func<TagItem, bool> filter, Func<BoundArea, BoundArea> transformArea)
{
foreach (TagItem tag in order)
{
if ((filter != null) && (filter(tag) == false))
continue;
result.Add(tag, weight: GetWeight(tag));
BoundArea area = GetBoundArea(tag);
if (area != null)
result.SetBoundArea(tag, transformArea != null ? transformArea(area) : area);
}
return result;
}
/// <summary>
/// Merges in tags into the collection and perform best effort matching
/// </summary>
/// <param name="tags"> List of new tags to be merged</param>
/// <param name="defaultLayer"> Default layer to assume if item has none </param>
/// <param name="modeAdd"> Add in tags that don't exist yet in this collection </param>
/// <param name="modePrune"> Remove any items that don't match the provided list of tags</param>
/// <param name="modePruneDefault"> Remove any non matching items (only when they are on the same layer as defaultLayer)</param>
public void MergeAdvanced(IEnumerable<TagItemOrdered> tags, string defaultLayer = null, bool modeAdd = false, bool modePrune = false, bool modePruneDefault = false)
{
if (ReadOnly)
throw new UnauthorizedAccessException("Collection is read only");
// Find the differences between to existing tags
Dictionary<TagItem, TagItemOrdered> tagsMatched = new Dictionary<TagItem, TagItemOrdered>();
List<TagItem> tagsUnmatched = new List<TagItem>();
List<TagItemOrdered> srcUnmatched = new List<TagItemOrdered>(tags);
foreach (TagItem tagItem in Items)
{
// Find matching tag for this row
TagItemOrdered tagMatch = null;
foreach (TagItemOrdered tag in tags)
{
if (tag.Item.Name == tagItem.Name)
{
if ((tag.Layer == null) && (tagItem.Layer?.Name == defaultLayer))
tagMatch = tag;
else if ((tag.Layer != null) && (tagItem.Layer?.Name == tag.Layer.Name))
tagMatch = tag;
}
}
if (tagMatch != null)
{
tagsMatched[tagItem] = tagMatch; // This row has a matching tag
srcUnmatched.Remove(tagMatch); // This tag is no longer unmatched
}
else
{
tagsUnmatched.Add(tagItem); // No matches found
}
}
// Process the matched tags
foreach (var tagPair in tagsMatched)
{
TagItem currentTag = tagPair.Key;
if (tagPair.Value.NewName != null)
currentTag = Rename(currentTag, tagPair.Value.NewName); // Rename replaces the tag, so bound-area updates below must target the new one
if (tagPair.Value.BoundArea != null)
SetBoundArea(currentTag, tagPair.Value.BoundArea);
SetWeight(currentTag, tagPair.Value.Weight);
}
// Erase missing tags on defaultLayer only
if (modePruneDefault)
{
foreach (TagItem tag in tagsUnmatched)
{
if (tag.Layer?.Name == defaultLayer)
Remove(tag);
}
}
// Erase missing tags
if (modePrune)
{
foreach (TagItem tag in tagsUnmatched)
{
Remove(tag);
}
}
// Add in new tags
if (modeAdd)
{
foreach (TagItemOrdered tag in srcUnmatched)
{
string layerName = defaultLayer;
if (tag.Layer != null)
layerName = tag.Layer.Name;
// item.Tags only has ParentImageItem set (not ParentTagLayer), so check both.
ProjectInstance project = this.ParentTagLayer?.Project ?? this.ParentImageItem?.Project;
TagItem tagItem = null;
if (project != null)
tagItem = project.IntroduceTag(tag.Item.Name, layerName);
else
tagItem = new TagItem(tag.Item.Name, layerName);
if (tagItem == null)
throw new InvalidOperationException($"Tag '{tag.Item.Name}' could not be automatically introduced to layer '{layerName}'.");
Add(tagItem, weight: tag.Weight);
if (tag.BoundArea != null)
SetBoundArea(tagItem, tag.BoundArea);
}
}
}
public string SerializeToString()
{
// Convert to newline delimited string
List<string> tagList = new List<string>();
foreach (TagItem tag in Tags)
{
string areaStr = GetBoundArea(tag)?.ToCompactString() ?? "";
// An empty layer field means the tag has no layer, DeserializeFromString reads it back as such
tagList.Add($"{tag.Name}\b{tag.Layer?.Name}\b{GetWeight(tag).ToString(System.Globalization.CultureInfo.InvariantCulture)}\b{areaStr}");
}
return string.Join("\n", tagList);
}
public string SerializeToCleanString()
{
// Convert to newline delimited string
List<string> tagList = new List<string>();
foreach (TagItem tag in Tags)
{
tagList.Add($"{tag.Name}");
}
return string.Join("\r\n", tagList);
}
public void DeserializeFromString(string str, LayerStack layers=null)
{
string[] linesData = str.Split('\n');
foreach (string line in linesData)
{
try
{
string[] parts = line.Split('\b');
if (parts.Count() >= 3)
{
// Advanced format that packs all of the info
double weight = double.Parse(parts[2], System.Globalization.CultureInfo.InvariantCulture);
TagItem tag = string.IsNullOrEmpty(parts[1])
? new TagItem(parts[0]) // No layer name stored, so leave the tag layerless
: new TagItem(parts[0], parts[1]);
Add(tag, -1, weight);
if ((parts.Count() >= 4) && (parts[3].Length > 0))
{
BoundArea area = BoundArea.FromCompactString(parts[3]);
if (area != null)
SetBoundArea(tag, area);
}
}
else if (parts.Count() == 1)
{
// Simple newline separated list
string name = parts[0].Trim();
if (name == "")
continue; // Skip blank lines
TagLayer layer = layers?.GetLayerDefault();
TagItem tag = new TagItem(name, layer);
Add(tag);
}
}
catch { }
}
}
/// <summary>
/// Check if this collection contains any of the specified tags
/// </summary>
public bool FilterForAny(IEnumerable<TagItem> tags)
{
foreach (var tag in tags)
if (Tags.Contains(tag))
return true;
return false;
}
/// <summary>
/// Check if this collection contains all of the specified tags simultaneously
/// </summary>
public bool FilterForAll(IEnumerable<TagItem> tags)
{
foreach (var tag in tags)
if (!Tags.Contains(tag))
return false;
return true;
}
/// <summary>
/// Returns tags that contain the query string
/// </summary>
public List<TagItem> Autocomplete(string query)
{
List<TagItem> results = new List<TagItem>();
foreach (var tag in Tags)
{
string name = tag.Name;
int indexOf = name.IndexOf(query, StringComparison.OrdinalIgnoreCase);
if (indexOf < 0)
continue; // No match
if (indexOf > 0)
{
if (char.IsWhiteSpace(name[indexOf - 1]) == false)
continue; // Hit was in the middle of a word, so ignore
}
results.Add(tag);
}
return results;
}
public int TagCount()
{
return Tags.Count();
}
}
}