Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/Files.App/Data/Items/ListedItem.FileTags.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

using Files.App.Utils.FileTags;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Files.App.Utils
{
public partial class ListedItem
{
private long fileTagsRevision;
public long FileTagsRevision => Interlocked.Read(ref fileTagsRevision);

private string[]? fileTags;
[DisallowNull]
public string[]? FileTags
{
get => fileTags;
set
{
#if !WINDOWS
if (fileTags is not null && fileTags.SequenceEqual(value, StringComparer.Ordinal))
return;
#endif
// fileTags is null when the item is first created
#if WINDOWS
var fileTagsInitialized = fileTags is not null;
#else
// Tags are loaded lazily, so an item that was never loaded counts as untagged and its first edit must still be saved
const bool fileTagsInitialized = true;
#endif
if (SetProperty(ref fileTags, value))
{
Interlocked.Increment(ref fileTagsRevision);
// only set the tags if the file tags have been changed
if (fileTagsInitialized)
{
var path = this.GetRequiredPath();
#if WINDOWS
var dbInstance = FileTagsHelper.GetDbInstance();
dbInstance.SetTags(path, FileFRN, value);
#endif
_ = FileTagsHelper.WriteFileTagAsync(path, value);
}

HasTags = value is { Length: > 0 };
OnPropertyChanged(nameof(FileTagsUI));
}
}
}

/// <summary>
/// Applies tags read from storage; unlike <see cref="FileTags"/> it never writes them back.
/// </summary>
public void SetLoadedFileTags(string[] tags, long? expectedRevision = null)
{
if (expectedRevision is not null && expectedRevision != FileTagsRevision)
return;

#if WINDOWS
FileTags = tags;
#else
if (fileTags is not null && fileTags.SequenceEqual(tags, StringComparer.Ordinal))
return;

if (SetProperty(ref fileTags, tags, nameof(FileTags)))
{
HasTags = tags.Length > 0;
OnPropertyChanged(nameof(FileTagsUI));
}
#endif
}

/// <summary>
/// Applies an edit against the latest tags in the serialized storage queue.
/// </summary>
public async Task EditFileTagsAsync(Func<string[], string[]> edit)
{
#if WINDOWS
if (fileTags is null)
SetLoadedFileTags(FileTagsHelper.ReadFileTag(this.GetRequiredPath()));
FileTags = edit(fileTags ?? []);
await Task.CompletedTask;
#else
var revision = Interlocked.Increment(ref fileTagsRevision);
var tags = await FileTagsHelper.EditFileTagsAsync(this.GetRequiredPath(), edit);
if (tags is not null)
SetLoadedFileTags(tags, revision);
#endif
}
}
}
33 changes: 0 additions & 33 deletions src/Files.App/Data/Items/ListedItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using FluentFTP;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Media.Imaging;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using Windows.Storage;
Expand Down Expand Up @@ -109,38 +108,6 @@ public BitmapImage? CustomIcon

public ulong? FileFRN { get; set; }

private string[]? fileTags;
[DisallowNull]
public string[]? FileTags
{
get => fileTags;
set
{
#if !WINDOWS
if (fileTags is not null && fileTags.SequenceEqual(value, StringComparer.Ordinal))
return;
#endif
// fileTags is null when the item is first created
var fileTagsInitialized = fileTags is not null;
if (SetProperty(ref fileTags, value))
{
// only set the tags if the file tags have been changed
if (fileTagsInitialized)
{
var path = this.GetRequiredPath();
#if WINDOWS
var dbInstance = FileTagsHelper.GetDbInstance();
dbInstance.SetTags(path, FileFRN, value);
#endif
_ = FileTagsHelper.WriteFileTagAsync(path, value);
}

HasTags = !value.IsEmpty();
OnPropertyChanged(nameof(FileTagsUI));
}
}
}

public IList<TagViewModel>? FileTagsUI
{
get => fileTagsSettingsService.GetTagsByIds(FileTags);
Expand Down
38 changes: 38 additions & 0 deletions src/Files.App/Helpers/Navigation/InFlightOpenGate.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading;

namespace Files.App.Helpers
{
/// <summary>
/// Lets one open of a given target run at a time. A double click can raise the open command twice before the first
/// navigation finishes, which would push the same location onto the back stack twice.
/// </summary>
internal sealed class InFlightOpenGate
{
private readonly object gate = new();
private readonly HashSet<string> inFlight = new(StringComparer.Ordinal);

/// <summary>Returns a lease to dispose when the open finished, or null when the same target is already being opened.</summary>
public IDisposable? TryEnter(string key)
{
lock (gate)
return inFlight.Add(key) ? new Lease(this, key) : null;
}

private sealed class Lease(InFlightOpenGate owner, string key) : IDisposable
{
private int disposed;

public void Dispose()
{
if (Interlocked.Exchange(ref disposed, 1) == 0)
lock (owner.gate)
owner.inFlight.Remove(key);
}
}
}
}
8 changes: 8 additions & 0 deletions src/Files.App/Helpers/Navigation/NavigationHelpers.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.Extensions.Logging;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;

namespace Files.App.Helpers
{
Expand All @@ -22,6 +23,9 @@ public static partial class NavigationHelpers
{
private static ILauncherService LinuxLauncher => Ioc.Default.GetRequiredService<ILauncherService>();

// A double click can raise the open command twice; a second navigation to the archive would need two Back presses
private static readonly InFlightOpenGate archiveOpenGate = new();

private static IMimeTypeService LinuxMimeTypes => Ioc.Default.GetRequiredService<IMimeTypeService>();

private static async Task<bool> OpenPathLinuxAsync(string path, IShellPage associatedInstance, bool openViaApplicationPicker, IEnumerable<string>? selectItems, bool forceOpenInNewTab)
Expand All @@ -37,6 +41,10 @@ private static async Task<bool> OpenPathLinuxAsync(string path, IShellPage assoc

var archiveService = Ioc.Default.GetRequiredService<IArchiveService>();
var isArchiveRoot = !openViaApplicationPicker && File.Exists(path) && archiveService.IsArchiveFileName(path);
using var archiveOpenLease = isArchiveRoot ? archiveOpenGate.TryEnter($"{RuntimeHelpers.GetHashCode(associatedInstance)}:{path}") : null;
if (isArchiveRoot && archiveOpenLease is null)
return true;

if (isArchiveRoot)
{
// Archive navigation must not launch executables, desktop entries, or editors.
Expand Down
31 changes: 9 additions & 22 deletions src/Files.App/UserControls/Menus/FileTagsContextMenu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using Microsoft.UI.Xaml.Markup;
using Microsoft.UI.Xaml.Media;
using WinRT;
using static Files.App.Helpers.MenuFlyoutHelper;

Check warning on line 9 in src/Files.App/UserControls/Menus/FileTagsContextMenu.cs

View workflow job for this annotation

GitHub Actions / build-linux

'MenuFlyoutHelper' is obsolete: 'Must not use this helper to generate menu flyout any longer.'

Check warning on line 9 in src/Files.App/UserControls/Menus/FileTagsContextMenu.cs

View workflow job for this annotation

GitHub Actions / build-linux-x64

'MenuFlyoutHelper' is obsolete: 'Must not use this helper to generate menu flyout any longer.'

namespace Files.App.UserControls.Menus
{
Expand Down Expand Up @@ -94,16 +94,16 @@
}

[DynamicWindowsRuntimeCast(typeof(ToggleMenuFlyoutItem))]
private void TagItem_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
private async void TagItem_Click(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
{
var tagItem = (ToggleMenuFlyoutItem)sender;
if (tagItem.IsChecked)
{
AddFileTag(SelectedItems, (TagViewModel)tagItem.Tag);
await AddFileTagAsync(SelectedItems, (TagViewModel)tagItem.Tag);
}
else
{
RemoveFileTag(SelectedItems, (TagViewModel)tagItem.Tag);
await RemoveFileTagAsync(SelectedItems, (TagViewModel)tagItem.Tag);
}
}

Expand Down Expand Up @@ -137,30 +137,17 @@
removeItem.IsEnabled = SelectedItems.Any(item => item?.FileTags is { Length: > 0 });
}

private void RemoveFileTag(IEnumerable<ListedItem> selectedListedItems, TagViewModel removed)
private async Task RemoveFileTagAsync(IEnumerable<ListedItem> selectedListedItems, TagViewModel removed)
{
foreach (var selectedItem in selectedListedItems)
{
var existingTags = selectedItem.FileTags ?? [];
if (existingTags.Contains(removed.Uid))
{
var tagList = existingTags.Except(new[] { removed.Uid }).ToArray();
selectedItem.FileTags = tagList;
}
}
await Task.WhenAll(selectedListedItems.ToList().Select(item =>
item.EditFileTagsAsync(tags => tags.Where(uid => uid != removed.Uid).ToArray())));
TagsChanged?.Invoke(this, EventArgs.Empty);
}

private void AddFileTag(IEnumerable<ListedItem> selectedListedItems, TagViewModel added)
private async Task AddFileTagAsync(IEnumerable<ListedItem> selectedListedItems, TagViewModel added)
{
foreach (var selectedItem in selectedListedItems)
{
var existingTags = selectedItem.FileTags ?? [];
if (!existingTags.Contains(added.Uid))
{
selectedItem.FileTags = [.. existingTags, added.Uid];
}
}
await Task.WhenAll(selectedListedItems.ToList().Select(item =>
item.EditFileTagsAsync(tags => tags.Contains(added.Uid) ? tags : [.. tags, added.Uid])));
TagsChanged?.Invoke(this, EventArgs.Empty);
}

Expand Down
12 changes: 12 additions & 0 deletions src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ public static Task<bool> WriteFileTagAsync(string filePath, string[] tag, Cancel
return EnqueueWrite(() => !cancellationToken.IsCancellationRequested && WriteTags(filePath, tags, names, store), false);
}

public static Task<string[]?> EditFileTagsAsync(string filePath, Func<string[], string[]> edit)
{
var store = Ioc.Default.GetService<IFileTagsStore>();
var settings = Ioc.Default.GetRequiredService<IFileTagsSettingsService>();
return EnqueueWrite<string[]?>(() =>
{
var tags = edit(ReadFileTag(filePath)).Distinct(StringComparer.Ordinal).ToArray();
var names = settings.GetTagsByIds(tags)?.Select(x => x.Name).ToArray() ?? [];
return WriteTags(filePath, tags, names, store) ? tags : null;
}, null);
}

public static Task<bool> UntagAllFilesAsync(string uid)
{
var store = Ioc.Default.GetService<IFileTagsStore>();
Expand Down
3 changes: 1 addition & 2 deletions src/Files.App/Utils/FileTags/FileTagsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,7 @@ public static async Task<bool> RemoveTagsAsync(IEnumerable<ListedItem> items)
if (!confirmed)
return false;

foreach (var item in itemsWithTags)
item.FileTags = [];
await Task.WhenAll(itemsWithTags.Select(item => item.EditFileTagsAsync(_ => [])));

return true;
}
Expand Down
9 changes: 6 additions & 3 deletions src/Files.App/ViewModels/ShellViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1702,6 +1702,7 @@ public async Task LoadExtendedItemPropertiesAsync(ListedItem item)
// A network share is never a cloud placeholder root, so skip that round-trip
var syncStatus = isItemNetwork ? CloudDriveSyncStatus.Unknown : await CheckCloudDriveSyncStatusAsync(matchingStorageFile);
var fileFRN = await FileTagsHelper.GetFileFRN(matchingStorageFile);
var tagRevision = item.FileTagsRevision;
var fileTag = await ReadFileTagAsync(item.GetRequiredPath());

// Extended properties open each file; load them in the background on a share
Expand All @@ -1721,7 +1722,7 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() =>
item.FolderRelativeId = matchingStorageFile.FolderRelativeId;
item.SyncStatusUI = syncStatusUI;
item.FileFRN = fileFRN;
item.FileTags = fileTag;
item.SetLoadedFileTags(fileTag, tagRevision);
item.IsElevationRequired = isElevationRequired;
item.ImageDimensions = properties?["System.Image.Dimensions"]?.ToString() ?? string.Empty;
item.FileVersion = properties?["System.FileVersion"]?.ToString() ?? string.Empty;
Expand Down Expand Up @@ -1784,6 +1785,7 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() =>
// A network share is never a cloud placeholder root, so skip that round-trip
var syncStatus = isItemNetwork ? CloudDriveSyncStatus.Unknown : await CheckCloudDriveSyncStatusAsync(matchingStorageFolder);
var fileFRN = await FileTagsHelper.GetFileFRN(matchingStorageFolder);
var tagRevision = item.FileTagsRevision;
var fileTag = await ReadFileTagAsync(item.GetRequiredPath());

// Folder extended properties only carry drive storage details, irrelevant on a network subfolder
Expand All @@ -1796,7 +1798,7 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() =>
item.FolderRelativeId = matchingStorageFolder.FolderRelativeId;
item.SyncStatusUI = CloudDriveSyncStatusUI.FromCloudDriveSyncStatus(syncStatus);
item.FileFRN = fileFRN;
item.FileTags = fileTag;
item.SetLoadedFileTags(fileTag, tagRevision);

if (extraProperties is not null)
{
Expand Down Expand Up @@ -1834,14 +1836,15 @@ await dispatcherQueue.EnqueueOrInvokeAsync(() =>
token.ThrowIfCancellationRequested();
await FilesystemTasks.Wrap(async () =>
{
var tagRevision = item.FileTagsRevision;
var fileTag = await ReadFileTagAsync(item.GetRequiredPath());

await dispatcherQueue.EnqueueOrInvokeAsync(() =>
{
// Reset cloud sync status icon
item.SyncStatusUI = new CloudDriveSyncStatusUI();

item.FileTags = fileTag;
item.SetLoadedFileTags(fileTag, tagRevision);
},
Microsoft.UI.Dispatching.DispatcherQueuePriority.Low);

Expand Down
Loading
Loading