Repository navigation
Expand file tree
/
Copy pathProjectInstance.cs
More file actions
492 lines (440 loc) · 19 KB
/
Copy pathProjectInstance.cs
File metadata and controls
492 lines (440 loc) · 19 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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace SharpTagManager
{
class ProjectInstance
{
// File paths
public string ProjectPath;
public string ProjectFilename;
// Project contents
public Dictionary<string, ImageItem> ImageItems = new Dictionary<string, ImageItem>();
public Dictionary<string,ImageFolder> Folders = new Dictionary<string, ImageFolder>();
public LayerStack Layers = null;
public Queue<string> ItemsToBeLoaded = null;
public bool HasUnsavedChanges = false;
public FileUtility.Json.JsonStructures.ExportSettings ExportSettings = new FileUtility.Json.JsonStructures.ExportSettings();
public FileUtility.Json.JsonStructures.ViewSettings ViewSettings = new FileUtility.Json.JsonStructures.ViewSettings();
private ProjectInstance(string filename)
{
ProjectFilename = filename;
ProjectPath = Path.GetDirectoryName(filename);
Layers = new LayerStack(this);
}
public TagItem IntroduceTag(string name, string layerName = "Uncategorised")
{
TagLayer layer = IntroduceLayer(layerName);
return IntroduceTag(name, layer);
}
public TagItem IntroduceTag(string name, TagLayer layer)
{
if(layer == null)
layer = IntroduceLayer("Uncategorised");
if(layer?.Tags?.ReadOnly == true)
layer = IntroduceLayer("Uncategorised");
return layer.IntroduceTag(name);
}
public TagLayer IntroduceLayer(string name, Type layerType=null, bool autogenerated=false)
{
return Layers.IntroduceLayer(name, this, layerType, autogenerated);
}
public TagLayer GetLayer(string name)
{
return Layers.GetLayer(name);
}
public ImageFolder IntroduceFolder(string name, bool createIfMissing)
{
// Try direct match
if (Folders.ContainsKey(name))
return Folders[name];
if (name == "")
{
// Special handling of root folder
name = "<root>";
if (Folders.ContainsKey(name))
return Folders[name];
ImageFolder folder = new ImageFolder();
folder.Name = name;
Folders[name] = folder;
return folder;
}
else
{
// Express the name as a path relative to the project, so the same directory always maps to the same key
name = ToRelativePath(ToFullPath(name));
if (name == "")
return IntroduceFolder("", createIfMissing); // Path pointed at the project root
// Try relative directory match
if (Folders.ContainsKey(name))
return Folders[name];
// Try case insensitive match
foreach (var folder in Folders)
if (folder.Key.ToLower() == name.ToLower())
return folder.Value;
// Try direct match in filesystem
if (Directory.Exists(ToFullPath(name)))
{
ImageFolder folder = new ImageFolder();
folder.Name = name;
Folders[name] = folder;
return folder;
}
}
// Create it if none exists
if (createIfMissing)
{
string pathFull = ToFullPath(name);
Directory.CreateDirectory(pathFull);
ImageFolder folder = new ImageFolder();
folder.Name = name;
Folders[name] = folder;
return folder;
}
return null;
}
public void Add_ImageItem(ImageItem item)
{
// Make sure it has an image
if ((item.PathSourceImage == null) || (item.PathSourceImage == ""))
throw new Exception("ImageItem has no source image");
// Make sure the image is located inside the project
string pathImageFull = ToFullPath(item.PathSourceImage);
if (!File.Exists(pathImageFull))
throw new Exception($"ImageItem at '{pathImageFull}' does not exist");
// Make sure there is a folder for it
string folderName = Path.GetDirectoryName(item.PathSourceImage);
item.Folder = IntroduceFolder(folderName, createIfMissing:false);
if ((item.Folder != null) && !item.Folder.Items.Contains(item))
item.Folder.Items.Add(item);
// Must be set before building tagsManaged below, so tags actually get linked to this image
item.Project = this;
// Translate all the tags into proper managed tags, preserving per-tag data
TagCollection tagsManaged = new TagCollection(item, item.Name);
foreach (TagItem tag in item.Tags.Items)
{
TagItem managedTag = IntroduceTag(tag.Name, tag.Layer.Name);
double weight = item.Tags.GetWeight(tag);
BoundArea boundArea = item.Tags.GetBoundArea(tag);
tagsManaged.Add(managedTag, weight: weight);
if (boundArea != null)
tagsManaged.SetBoundArea(managedTag, boundArea);
}
item.Tags = tagsManaged;
// Add it to the project
ImageItem itemExisting = null;
if (ImageItems.TryGetValue(item.Name, out itemExisting))
{
// Item is already there, if it is the same one then we don't need to do anything
if (itemExisting != item)
{
// We need to replace an existing one, old one has to be removed first to clean up any dangling references.
Remove_ImageItem(item.Name);
ImageItems.Add(item.Name, item);
}
}
else
{
// Item does not exist yet, so add it
ImageItems.Add(item.Name, item);
}
}
public bool Remove_ImageItem(string itemName, bool deleteFiles=false)
{
ImageItem itemGet = null;
if (ImageItems.TryGetValue(itemName, out itemGet))
{
itemGet.Tags.Clear();
if (itemGet.Folder != null)
itemGet.Folder.Items.Remove(itemGet);
if (deleteFiles)
DeleteImageFiles(itemGet);
ImageItems.Remove(itemGet.Name);
return true;
}
return false; // Item not found
}
public void SaveAll()
{
FileUtility.Json.ProjectToFile(this.ProjectFilename, this);
foreach (ImageItem item in ImageItems.Values)
{
Save(item);
}
foreach (TagLayer layer in Layers.Items)
if (layer.Tags != null)
layer.Tags.HasChanged = false;
HasUnsavedChanges = false;
}
public void Save(ImageItem item)
{
string imagePath = ToFullPath(item.Name);
string jsonPath = imagePath + ".json";
string directory = Path.GetDirectoryName(jsonPath);
Directory.CreateDirectory(directory);
FileUtility.Json.ImageItemToFile(jsonPath, item, this);
if (item?.Tags != null)
item.Tags.HasChanged = false;
}
public ImageItem Revert(ImageItem item)
{
string imagePath = ToFullPath(item.PathSourceImage);
ImageItem itemFromDisk = ImageItem.LoadUnmanaged(imagePath, ProjectPath);
if (itemFromDisk != null)
{
Add_ImageItem(itemFromDisk);
itemFromDisk.Tags.HasChanged = false;
}
return itemFromDisk;
}
public void DeleteImageFiles(ImageItem item)
{
// Check where the files are
string pathImage = ToFullPath(item.PathSourceImage);
string pathJson = ToFullPath(Path.ChangeExtension(item.PathSourceImage,".json"));
if (!File.Exists(pathImage))
pathImage = null;
if (!File.Exists(pathJson))
pathJson = null;
// Perform removal
if (AppSettings.Instance.UI_DeleteIntoFolder)
{
// Move to .delete folder
string pathDelete = ToFullPath(".delete");
// The synthetic "<root>" folder name contains characters that are illegal in paths, so map it to the root
string subFolder = item.Folder?.Name;
if (string.IsNullOrEmpty(subFolder) || subFolder == "<root>")
subFolder = "";
pathDelete = Path.Combine(pathDelete, subFolder);
Directory.CreateDirectory(pathDelete);
SafeMove(pathImage, pathDelete);
SafeMove(pathJson, pathDelete);
}
else
{
// Normal deletion
if(pathImage != null)
File.Delete(pathImage);
if (pathJson != null)
File.Delete(pathJson);
}
void SafeMove(string source, string dest)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(dest) || !File.Exists(source))
return;
// Get the file name and its extension
string fileName = Path.GetFileName(source);
string filePath = Path.Combine(dest, fileName);
// Check if a file with the same name already exists in the destination folder
int counter = 1;
while (File.Exists(filePath))
{
// Add (1), (2), etc. to the file name if it already exists
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
string extension = Path.GetExtension(fileName);
filePath = Path.Combine(dest, $"{fileNameWithoutExtension} ({counter}){extension}");
counter++;
}
// Move the file to the destination with the new name
File.Move(source, filePath);
}
}
public static ProjectInstance Load(string filename)
{
ProjectInstance project = LoadAsync(filename);
string fileLoading;
while (project.LoadContinue(out fileLoading))
{ }
return project;
}
public static ProjectInstance LoadAsync(string filename)
{
// If a directory was given try to find the project file in there
if (Directory.Exists(filename))
{
var fileCandidates = Directory.GetFiles(filename, "*.SharpTag");
if(fileCandidates.Length > 0)
filename = fileCandidates.First();
}
// Make sure the project file exists
if (File.Exists(filename) == false)
{
throw new FileNotFoundException("Project file not found", filename);
}
// Create a brand new project instance and load it from disk
ProjectInstance project = new ProjectInstance(filename);
FileUtility.Json.ProjectFromFile(project.ProjectFilename, project);
// Index the project directory for images
project.ItemsToBeLoaded = new Queue<string>();
string[] files = Directory.GetFiles(project.ProjectPath, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
string folder = project.ToRelativePath(file);
if (folder.StartsWith("."))
continue; // Folders that start with . are ignored
if (IsImageFile(file))
project.ItemsToBeLoaded.Enqueue(file);
}
return project;
}
private static readonly string[] ImageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".tif", ".tiff", ".bmp" };
public static bool IsImageFile(string path)
{
return ImageExtensions.Contains(Path.GetExtension(path).ToLower());
}
// Removes any ImageItems whose source file is no longer present on disk
public int RemoveMissingImageItems()
{
List<string> missing = ImageItems.Values
.Where(item => !File.Exists(ToFullPath(item.PathSourceImage)))
.Select(item => item.Name)
.ToList();
foreach (string name in missing)
Remove_ImageItem(name);
return missing.Count;
}
// Queues up (into ItemsToBeLoaded) any image files on disk that aren't tracked as an ImageItem yet.
// Drive the queue with LoadContinue(), same as the initial project load.
public int ScanForNewImageFiles()
{
var knownFiles = new HashSet<string>(ImageItems.Values.Select(item => ToFullPath(item.PathSourceImage)), StringComparer.OrdinalIgnoreCase);
ItemsToBeLoaded = new Queue<string>();
string[] files = Directory.GetFiles(ProjectPath, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
string folder = ToRelativePath(file);
if (folder.StartsWith("."))
continue; // Folders that start with . are ignored
if (!IsImageFile(file))
continue;
if (!knownFiles.Contains(Path.GetFullPath(file)))
ItemsToBeLoaded.Enqueue(file);
}
return ItemsToBeLoaded.Count;
}
// Refreshes cached Resolution for images modified on disk. Returns the updated items.
public List<ImageItem> RescanModifiedImageFiles()
{
List<ImageItem> updated = new List<ImageItem>();
foreach (ImageItem item in ImageItems.Values)
{
string imagePath = ToFullPath(item.PathSourceImage);
FileInfo info = new FileInfo(imagePath);
if (!info.Exists || ((item.Resolution != default) && (item.TimestampImage == info.LastWriteTimeUtc)))
continue;
try
{
using (Image image = Image.FromFile(imagePath))
item.Resolution = image.Size;
item.TimestampImage = info.LastWriteTimeUtc;
updated.Add(item);
}
catch (Exception) { }
}
return updated;
}
public bool LoadContinue(out string file)
{
file = null;
if (ItemsToBeLoaded.Count == 0)
return false;
file = ItemsToBeLoaded.Dequeue();
ImageItem.Load(this, file);
return true;
}
public void RefreshTagDatabaseAssignment()
{
foreach (TagLayer layer in Layers.Items)
{
if (layer.Tags != null)
{
foreach (TagItem tag in layer.Tags.Items)
{
tag.DatabaseEntry = FormTagSelector.TagMatchToDatabase(tag.Name);
}
}
}
}
public static bool CheckProjectExists(string path)
{
// If a directory was given try to find the project file in there
if (Directory.Exists(path))
{
var fileCandidates = Directory.GetFiles(path, "*.SharpTag");
if (fileCandidates.Length > 0)
path = fileCandidates.First();
}
// Make sure the project file exists
return File.Exists(path);
}
public static void CreateNew(string path)
{
// If a directory was given generate a name for the project file
if (Directory.Exists(path))
{
string dirName = Path.GetFileName(path);
path = Path.Combine(path, $"{dirName}.SharpTag");
}
// Create an empty project file
File.WriteAllText(path, String.Empty);
}
public string ToRelativePath(string path)
{
return GetRelativePath(path, ProjectPath);
}
public string ToFullPath(string path)
{
return GetFullPath(path, ProjectPath);
}
public static string GetRelativePath(string fullPath, string basePath)
{
// Empty paths are just simply equal to the basePath
if (fullPath == "")
return basePath;
// Ensure paths are in absolute form
string fullPathMod = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
basePath = Path.GetFullPath(basePath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// Case-insensitive, matching the prefix check below
if (string.Equals(fullPathMod, basePath, StringComparison.OrdinalIgnoreCase))
return ""; //Path is identical so relative path is an empty string
// Ensure basePath ends with a directory separator
if (!basePath.EndsWith(Path.DirectorySeparatorChar.ToString()) &&
!basePath.EndsWith(Path.AltDirectorySeparatorChar.ToString()))
{
basePath += Path.DirectorySeparatorChar;
}
// Check if the fullPath starts with the basePath
if (fullPathMod.StartsWith(basePath, StringComparison.OrdinalIgnoreCase))
{
// Create the relative path
string relativePath = fullPathMod.Substring(basePath.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
return relativePath;
}
// If the path does not start with basePath, return the original fullPath
return fullPath;
}
public static string GetFullPath(string path, string basePath)
{
if (basePath == null)
return path;
// Ensure basePath is absolute
basePath = Path.GetFullPath(basePath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// Check if the path is already absolute
if (Path.IsPathRooted(path))
{
return Path.GetFullPath(path); // Return the full path if it's already absolute
}
else
{
// Combine the basePath with the relative path
string fullPath = Path.Combine(basePath, path);
return Path.GetFullPath(fullPath); // Return the absolute path
}
}
}
}