diff --git a/src/App.Commands.cs b/src/App.Commands.cs index ad92a5755..4693ffc96 100644 --- a/src/App.Commands.cs +++ b/src/App.Commands.cs @@ -41,8 +41,10 @@ public static bool IsCheckForUpdateCommandVisible { if (Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime { MainWindow: { } owner }) { + WindowTrace.Write($"Preferences open(menu): ownerState={owner.WindowState} ownerBounds={owner.Bounds} ownerClient={owner.ClientSize}"); var dialog = new Views.Preferences(); await dialog.ShowDialog(owner); + WindowTrace.Write($"Preferences closed(menu): ownerState={owner.WindowState} ownerBounds={owner.Bounds} ownerClient={owner.ClientSize}"); } }); diff --git a/src/App.JsonCodeGen.cs b/src/App.JsonCodeGen.cs index c63fccc29..ed2614ed5 100644 --- a/src/App.JsonCodeGen.cs +++ b/src/App.JsonCodeGen.cs @@ -73,6 +73,7 @@ public override void Write(Utf8JsonWriter writer, GridLength value, JsonSerializ [JsonSerializable(typeof(List))] [JsonSerializable(typeof(ViewModels.Preferences))] [JsonSerializable(typeof(ViewModels.RepositoryNodeMinimalInfo))] + [JsonSerializable(typeof(Models.ProjectsSaveModel))] [JsonSerializable(typeof(List))] internal partial class JsonCodeGen : JsonSerializerContext { } } diff --git a/src/App.axaml.cs b/src/App.axaml.cs index 818a6b26d..64d1b5c51 100644 --- a/src/App.axaml.cs +++ b/src/App.axaml.cs @@ -25,6 +25,10 @@ public static void Main(string[] args) { Native.OS.SetupBasicDirectories(); + var scanLogFromEnv = Environment.GetEnvironmentVariable("SOURCEGIT_SCAN_LOG"); + if (!string.IsNullOrEmpty(scanLogFromEnv)) + Models.ScanLog.Open(scanLogFromEnv); + AppDomain.CurrentDomain.UnhandledException += (_, e) => { Native.OS.LogException(e.ExceptionObject as Exception); @@ -37,7 +41,9 @@ public static void Main(string[] args) try { - if (TryLaunchAsRebaseTodoEditor(args, out int exitTodo)) + if (TryRunScanCommand(args, out int exitScan)) + Environment.Exit(exitScan); + else if (TryLaunchAsRebaseTodoEditor(args, out int exitTodo)) Environment.Exit(exitTodo); else if (TryLaunchAsRebaseMessageEditor(args, out int exitMessage)) Environment.Exit(exitMessage); @@ -58,7 +64,7 @@ public static AppBuilder BuildAvaloniaApp() builder.WithInterFont(); builder.With(new FontManagerOptions() { - DefaultFamilyName = "fonts:Inter#Inter" + DefaultFamilyName = Models.PlatformFonts.PrimaryFamily }); builder.ConfigureFonts(manager => { @@ -183,6 +189,12 @@ public static void SetFonts(string defaultFont, string monospaceFont) defaultFont = StringExtensions.FormatFontNames(defaultFont); monospaceFont = StringExtensions.FormatFontNames(monospaceFont); + // An empty preference means "use the platform default", not "use Inter for everything": + // Inter has no CJK glyphs, so leaving it in place lets the platform fallback pick an + // arbitrary Chinese font and mixed lines end up with a mismatched baseline. + if (string.IsNullOrEmpty(defaultFont)) + defaultFont = Models.PlatformFonts.DefaultFamily; + var resDic = new ResourceDictionary(); if (!string.IsNullOrEmpty(defaultFont)) resDic.Add("Fonts.Default", new FontFamily(defaultFont)); @@ -191,7 +203,7 @@ public static void SetFonts(string defaultFont, string monospaceFont) { if (!string.IsNullOrEmpty(defaultFont)) { - monospaceFont = $"fonts:SourceGit#JetBrains Mono NL,{defaultFont}"; + monospaceFont = $"fonts:SourceGit#JetBrains Mono NL,{Models.PlatformFonts.MonospaceFallback},{defaultFont}"; resDic.Add("Fonts.Monospace", FontFamily.Parse(monospaceFont)); } } @@ -278,6 +290,52 @@ public override void OnFrameworkInitializationCompleted() } #endregion + #region Scan Diagnostics + /// + /// Headless diagnostic entry: `SourceGit --scan-log [--log ]` scans the + /// directory with the exact scanner used by the project tree, writes a trace and + /// exits. Used to tell a "slow scan" apart from a "scan finds nothing" failure. + /// + private static bool TryRunScanCommand(string[] args, out int exitCode) + { + exitCode = 0; + + if (args == null || args.Length < 2 || !args[0].Equals("--scan-log", StringComparison.Ordinal)) + return false; + + var target = args[1]; + var logPath = Path.Combine(Path.GetTempPath(), "sourcegit_scan.log"); + if (args.Length >= 4 && args[2].Equals("--log", StringComparison.Ordinal)) + logPath = args[3]; + + Models.ScanLog.Open(logPath); + Models.ScanLog.Write($"headless scan: target='{target}' log='{logPath}'"); + + // In GUI mode this is assigned while loading preferences. Headless runs must do + // it explicitly, otherwise every git process fails to start and is dropped. + Native.OS.GitExecutable = Native.OS.FindGitExecutable(); + Models.ScanLog.Write($"headless scan: git executable='{Native.OS.GitExecutable}'"); + + try + { + var repos = Models.RepositoryScanner.ScanAsync(target, new Models.ScanLogProgress(), new Models.ScanLogProgress()) + .GetAwaiter() + .GetResult(); + + Models.ScanLog.Write($"headless scan: RESULT {repos.Count} repositories"); + foreach (var repo in repos) + Models.ScanLog.Write($"headless scan: {repo}"); + } + catch (Exception e) + { + Models.ScanLog.Write($"headless scan: EXCEPTION {e}"); + exitCode = 2; + } + + return true; + } + #endregion + #region Launch Ways private static bool TryLaunchAsRebaseTodoEditor(string[] args, out int exitCode) { diff --git a/src/Models/PlatformFonts.cs b/src/Models/PlatformFonts.cs new file mode 100644 index 000000000..25aebf1db --- /dev/null +++ b/src/Models/PlatformFonts.cs @@ -0,0 +1,72 @@ +using System; + +namespace SourceGit.Models +{ + /// + /// Per-platform font defaults. + /// + /// The embedded Inter font is used so every build renders western text identically, but it + /// carries no CJK coverage: Chinese characters are then filled in by whatever family the + /// platform happens to fall back to, which leaves mixed-script lines with a mismatched + /// baseline and weight. Naming an explicit CJK family per platform fixes that without + /// embedding a CJK font (which would add 8-15 MB to every build). + /// + /// Only used when the corresponding preference is empty, so whatever the user typed in + /// Preferences > Appearance always wins. + /// + public static class PlatformFonts + { + /// UI font for western text, followed by the CJK family to fall back to. + public static string DefaultFamily + { + get + { + if (OperatingSystem.IsWindows()) + return "Segoe UI,Microsoft YaHei UI"; + + if (OperatingSystem.IsMacOS()) + return "Helvetica Neue,PingFang SC"; + + return "Noto Sans,Noto Sans CJK SC,Source Han Sans SC,DejaVu Sans"; + } + } + + /// + /// Tail of the monospace list: JetBrains Mono NL is embedded and comes first, these only + /// cover the characters it does not have (CJK, and a last-resort system fallback). + /// + public static string MonospaceFallback + { + get + { + if (OperatingSystem.IsWindows()) + return "Cascadia Mono,Consolas,Microsoft YaHei UI"; + + if (OperatingSystem.IsMacOS()) + return "Menlo,Monaco,PingFang SC"; + + return "Noto Sans Mono CJK SC,DejaVu Sans Mono"; + } + } + + /// + /// Family used for controls that do not set a font themselves (Avalonia's + /// FontManagerOptions only takes a single name, so this is the first family above). + /// + public static string PrimaryFamily + { + get + { + var comma = DefaultFamily.IndexOf(','); + return comma < 0 ? DefaultFamily : DefaultFamily.Substring(0, comma).Trim(); + } + } + + /// + /// Same DIP size reads larger on Linux: fontconfig resolves a slightly bigger x-height + /// than DirectWrite, so 13 there looks like 14+ does on Windows. 12 keeps both builds + /// visually similar at the default 100% scaling. + /// + public static double DefaultFontSize => OperatingSystem.IsLinux() ? 12.0 : 13.0; + } +} diff --git a/src/Models/Project.cs b/src/Models/Project.cs new file mode 100644 index 000000000..e09efa8bb --- /dev/null +++ b/src/Models/Project.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; + +namespace SourceGit.Models +{ + /// + /// A "project" is a user-defined container that owns one or more directories. + /// Repositories are discovered by scanning those directories and are NOT stored + /// here - they are rebuilt on every scan so that the file system stays the source + /// of truth. + /// + public class Project + { + public string Name { get; set; } = string.Empty; + public List Directories { get; set; } = new List(); + } + + /// + /// Root object persisted to projects.json. + /// Nodes are expanded by default, so only the paths the user collapsed are stored. + /// + public class ProjectsSaveModel + { + public List Projects { get; set; } = new List(); + public List Collapsed { get; set; } = new List(); + } +} diff --git a/src/Models/RepositoryScanner.cs b/src/Models/RepositoryScanner.cs new file mode 100644 index 000000000..25711dd46 --- /dev/null +++ b/src/Models/RepositoryScanner.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace SourceGit.Models +{ + /// + /// Filesystem scanner that discovers git repositories under a root directory. + /// It is intentionally free of side effects: it does not touch Preferences and + /// does not register anything, unlike ViewModels.ScanRepositories which both + /// scans and imports. It is safe to call from a background thread. + /// + /// Unlike the upstream implementation, it does NOT spawn one `git` process per + /// subdirectory to detect bare repositories. That made a scan of a few thousand + /// folders take minutes. A bare repository is recognised by its layout instead + /// (HEAD + objects/ + refs/), and only real candidates are verified by git. + /// + public static class RepositoryScanner + { + public const int MAX_DEPTH = 5; + public const int VERIFY_CONCURRENCY = 4; + + /// + /// Returns absolute paths (forward-slash normalized) of the repositories found + /// under , including rootDir itself when it is one. + /// reports the directory currently being inspected; + /// is called as soon as a repository is + /// confirmed, so the caller can render it incrementally. + /// + public static async Task> ScanAsync(string rootDir, + IProgress progress = null, + IProgress repositoryFound = null, + CancellationToken token = default) + { + var found = new List(); + if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir)) + { + ScanLog.Write($"scan: root not found '{rootDir}'"); + return found; + } + + ScanLog.Write($"scan: begin root='{rootDir}'"); + + var root = new DirectoryInfo(rootDir); + var opts = new EnumerationOptions + { + AttributesToSkip = FileAttributes.Hidden | FileAttributes.System, + IgnoreInaccessible = true, + }; + + var seen = new HashSet(); + var gate = new SemaphoreSlim(VERIFY_CONCURRENCY); + progress?.Report(root.FullName); + + if (await IsRepositoryAsync(root.FullName)) + { + var normalized = Normalize(root.FullName); + seen.Add(Key(normalized)); + found.Add(normalized); + repositoryFound?.Report(normalized); + ScanLog.Write($"scan: root itself is a repository '{normalized}'"); + return found; + } + + await ScanChildrenAsync(root, found, seen, opts, gate, progress, repositoryFound, 0, token); + ScanLog.Write($"scan: done, {found.Count} repositories"); + return found; + } + + public static string Normalize(string path) + { + return path.Replace('\\', '/').TrimEnd('/'); + } + + public static string Key(string path) + { + return OperatingSystem.IsLinux() ? Normalize(path) : Normalize(path).ToLower(CultureInfo.CurrentCulture); + } + + private static bool HasGitEntry(DirectoryInfo dir) + { + var gitDir = Path.Combine(dir.FullName, ".git"); + return Directory.Exists(gitDir) || File.Exists(gitDir); + } + + /// + /// Cheap layout check for a bare repository: `HEAD` file plus `objects/` and + /// `refs/` directories. This replaces a `git rev-parse` call per directory; + /// only directories passing this check are verified by git afterwards. + /// + private static bool LooksLikeBareRepository(DirectoryInfo dir) + { + return File.Exists(Path.Combine(dir.FullName, "HEAD")) && + Directory.Exists(Path.Combine(dir.FullName, "objects")) && + Directory.Exists(Path.Combine(dir.FullName, "refs")); + } + + private static async Task IsRepositoryAsync(string dir) + { + var gitDir = Path.Combine(dir, ".git"); + if (!Directory.Exists(gitDir) && !File.Exists(gitDir)) + return false; + return await TryGetRepositoryRootAsync(dir) != null; + } + + /// + /// Runs `git rev-parse --show-toplevel` to make sure the directory is really a + /// repository root (a plain .git folder is not enough, e.g. worktrees and + /// submodules report a different top level). + /// + private static async Task TryGetRepositoryRootAsync(string dir) + { + var test = await new Commands.QueryRepositoryRootPath(dir).GetResultAsync().ConfigureAwait(false); + if (!test.IsSuccess || string.IsNullOrEmpty(test.StdOut)) + { + ScanLog.Write($"verify: NOT a repository '{dir}' (exitOk={test.IsSuccess}) stderr='{test.StdErr?.Trim()}'"); + return null; + } + + return Normalize(test.StdOut.Trim()); + } + + private static async Task ScanChildrenAsync(DirectoryInfo dir, List outs, HashSet seen, EnumerationOptions opts, + SemaphoreSlim gate, IProgress progress, IProgress repositoryFound, int depth, CancellationToken token) + { + if (token.IsCancellationRequested) + return; + + var candidates = new List(); + var bareCandidates = new List(); + var pending = new List(); + + foreach (var subdir in dir.GetDirectories("*", opts)) + { + if (token.IsCancellationRequested) + return; + + // Same pruning rules as ViewModels.ScanRepositories: hidden folders and + // node_modules never contain repositories worth listing. + if (subdir.Name.StartsWith(".", StringComparison.Ordinal) || + subdir.Name.Equals("node_modules", StringComparison.Ordinal)) + continue; + + progress?.Report(subdir.FullName); + + if (HasGitEntry(subdir)) + { + ScanLog.Write($"visit: '{subdir.FullName}' has .git entry"); + candidates.Add(subdir); + } + else if (LooksLikeBareRepository(subdir)) + { + ScanLog.Write($"visit: '{subdir.FullName}' looks like a bare repository"); + bareCandidates.Add(subdir); + } + else + { + pending.Add(subdir); + } + } + + if (candidates.Count > 0) + { + var tasks = new Task[candidates.Count]; + for (var i = 0; i < candidates.Count; i++) + { + var path = candidates[i].FullName; + tasks[i] = Task.Run(async () => + { + await gate.WaitAsync(token).ConfigureAwait(false); + try + { + return await TryGetRepositoryRootAsync(path).ConfigureAwait(false); + } + finally + { + gate.Release(); + } + }, token); + } + + await Task.WhenAll(tasks).ConfigureAwait(false); + + // Read results in index order so the output stays deterministic. + for (var i = 0; i < tasks.Length; i++) + { + var repo = tasks[i].Result; + if (repo != null && seen.Add(Key(repo))) + { + ScanLog.Write($"found: '{repo}' (root was '{candidates[i].FullName}')"); + outs.Add(repo); + repositoryFound?.Report(repo); + } + else if (repo != null) + { + ScanLog.Write($"found: duplicate skipped '{repo}'"); + } + } + } + + foreach (var bare in bareCandidates) + { + if (token.IsCancellationRequested) + return; + + if (!await new Commands.IsBareRepository(bare.FullName).GetResultAsync().ConfigureAwait(false)) + continue; + + var normalized = Normalize(bare.FullName); + if (seen.Add(Key(normalized))) + { + outs.Add(normalized); + repositoryFound?.Report(normalized); + } + } + + if (depth >= MAX_DEPTH) + return; + + foreach (var subdir in pending) + { + if (token.IsCancellationRequested) + return; + + // Do not descend into a repository: nested repositories are a separate + // concern and would produce a confusing tree. + await ScanChildrenAsync(subdir, outs, seen, opts, gate, progress, repositoryFound, depth + 1, token).ConfigureAwait(false); + } + } + } +} diff --git a/src/Models/RepositoryStatusScanner.cs b/src/Models/RepositoryStatusScanner.cs new file mode 100644 index 000000000..fcd1c45a1 --- /dev/null +++ b/src/Models/RepositoryStatusScanner.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace SourceGit.Models +{ + /// + /// Answers "does this repository have local changes?" for repositories that are not + /// open in a tab, so the project tree can show a status without opening anything. + /// + /// Only the working copy is asked about, and untracked files are deliberately left + /// out (`status -uno`): a tree root like C:/docs contains repositories with + /// node_modules and build outputs, and counting those would mark every node dirty + /// while telling the user nothing useful. + /// + public static class RepositoryStatusScanner + { + public const int Concurrency = 4; + + /// + /// Queries the given repositories concurrently and returns, for the ones with local + /// changes, the number of changed files keyed by . + /// + public static async Task> QueryDirtyAsync(IList repositories, CancellationToken token) + { + var result = new Dictionary(); + if (repositories == null || repositories.Count == 0) + return result; + + var dirty = new ConcurrentDictionary(); + var cursor = -1; + + async Task Worker() + { + while (!token.IsCancellationRequested) + { + var index = Interlocked.Increment(ref cursor); + if (index >= repositories.Count) + return; + + var path = repositories[index]; + try + { + var changes = await new Commands.QueryLocalChanges(path, false, true) + .WithCancellation(token) + .GetResultAsync() + .ConfigureAwait(false); + + if (changes.Count > 0) + dirty[RepositoryScanner.Key(path)] = changes.Count; + } + catch (OperationCanceledException) + { + return; + } + catch + { + // One unreadable repository must not abort the whole pass. + } + } + } + + var workers = Math.Min(Concurrency, repositories.Count); + var tasks = new List(workers); + for (var i = 0; i < workers; i++) + tasks.Add(Task.Run(Worker, token)); + + await Task.WhenAll(tasks).ConfigureAwait(false); + + foreach (var pair in dirty) + result[pair.Key] = pair.Value; + + return result; + } + } +} diff --git a/src/Models/ScanLog.cs b/src/Models/ScanLog.cs new file mode 100644 index 000000000..6ca60365d --- /dev/null +++ b/src/Models/ScanLog.cs @@ -0,0 +1,72 @@ +using System; +using System.IO; + +namespace SourceGit.Models +{ + /// + /// Minimal append-only diagnostic log for repository scanning. Only enabled when a + /// log file has been opened (either by the `--scan-log` command line switch or the + /// SOURCEGIT_SCAN_LOG environment variable), so it costs nothing in normal use. + /// + public static class ScanLog + { + private static readonly object _lock = new object(); + private static StreamWriter _writer = null; + + public static bool Enabled + { + get + { + lock (_lock) + return _writer != null; + } + } + + public static void Open(string path) + { + lock (_lock) + { + try + { + _writer = new StreamWriter(path, false); + _writer.AutoFlush = true; + _writer.WriteLine($"# scan log opened at {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}"); + } + catch + { + _writer = null; + } + } + } + + public static void Write(string message) + { + lock (_lock) + { + if (_writer == null) + return; + + try + { + _writer.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {message}"); + } + catch + { + // Never let diagnostics break the scan. + } + } + } + } + + /// + /// IProgress implementation that writes straight into instead + /// of marshalling to a UI thread. Used by the headless `--scan-log` mode. + /// + public class ScanLogProgress : IProgress + { + public void Report(string value) + { + ScanLog.Write($"progress: {value}"); + } + } +} diff --git a/src/Native/WindowTrace.cs b/src/Native/WindowTrace.cs new file mode 100644 index 000000000..2a4013680 --- /dev/null +++ b/src/Native/WindowTrace.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; + +namespace SourceGit +{ + /// + /// Diagnostic trace for the launcher window geometry/state, used to investigate why a + /// maximized window changes size around the preferences dialog. Writes one line per + /// event into "window-trace.log" inside the config directory; failures are swallowed so + /// tracing can never break the app. Remove this class once the issue is settled. + /// + public static class WindowTrace + { + private static readonly object _lock = new object(); + private static string _file = null; + + public static void Write(string message) + { + try + { + lock (_lock) + { + if (_file == null) + { + var dir = Native.OS.BasicDirectories?.ConfigDir; + if (string.IsNullOrEmpty(dir)) + dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + + if (string.IsNullOrEmpty(dir)) + return; + + _file = Path.Combine(dir, "window-trace.log"); + File.AppendAllText(_file, $"==== session start {DateTime.Now:yyyy-MM-dd HH:mm:ss} pid={Environment.ProcessId} ===={Environment.NewLine}"); + } + + File.AppendAllText(_file, $"{DateTime.Now:HH:mm:ss.fff} {message}{Environment.NewLine}"); + } + } + catch + { + // Diagnostics must never affect the app. + } + } + } +} diff --git a/src/ViewModels/Preferences.cs b/src/ViewModels/Preferences.cs index 9d9fb3f9f..4f1226629 100644 --- a/src/ViewModels/Preferences.cs +++ b/src/ViewModels/Preferences.cs @@ -794,7 +794,7 @@ private bool RemoveInvalidRepositoriesRecursive(List collection) private string _themeOverrides = string.Empty; private string _defaultFontFamily = string.Empty; private string _monospaceFontFamily = string.Empty; - private double _defaultFontSize = 13; + private double _defaultFontSize = Models.PlatformFonts.DefaultFontSize; private double _editorFontSize = 13; private int _editorTabWidth = 4; private double _zoom = 1.0; diff --git a/src/ViewModels/ProjectTreeNode.cs b/src/ViewModels/ProjectTreeNode.cs new file mode 100644 index 000000000..4d3570183 --- /dev/null +++ b/src/ViewModels/ProjectTreeNode.cs @@ -0,0 +1,182 @@ +using System.IO; + +using Avalonia.Collections; + +using CommunityToolkit.Mvvm.ComponentModel; + +namespace SourceGit.ViewModels +{ + /// + /// Node of the left-side project tree. Three kinds of nodes exist: + /// project (container), directory (only kept when it leads to repositories) and + /// repository (double-click opens a regular repository tab). + /// + public class ProjectTreeNode : ObservableObject + { + public string Name + { + get => _name; + set => SetProperty(ref _name, value); + } + + public string FullPath + { + get => _fullPath; + set => SetProperty(ref _fullPath, value); + } + + public bool IsProject + { + get; + set; + } = false; + + public bool IsRepository + { + get => _isRepository; + set + { + if (SetProperty(ref _isRepository, value)) + { + OnPropertyChanged(nameof(IsDirectory)); + OnPropertyChanged(nameof(IsRepositoryDirty)); + OnPropertyChanged(nameof(HasDirtyChildren)); + } + } + } + + /// + /// An intermediate directory: neither the project container nor a repository. + /// Used by the view to pick the folder icon instead of the repository icon. + /// + public bool IsDirectory + { + get => !IsProject && !_isRepository; + } + + public bool IsExpanded + { + get => _isExpanded; + set => SetProperty(ref _isExpanded, value); + } + + public ProjectTreeNode Parent + { + get; + set; + } = null; + + public Models.Project Project + { + get; + set; + } = null; + + public AvaloniaList Children + { + get; + } = new AvaloniaList(); + + public bool IsMissing + { + get => _isRepository && !Directory.Exists(_fullPath); + } + + /// + /// Working copy status of a repository node. Mirrors the state the repository tab + /// already computes, and is filled in by the background scan for repositories that + /// are not open. Directory and project nodes never carry a state of their own. + /// + public Models.DirtyState Status + { + get => _status; + set + { + if (SetProperty(ref _status, value)) + { + OnPropertyChanged(nameof(IsRepositoryDirty)); + OnPropertyChanged(nameof(HasPendingPullOrPush)); + OnPropertyChanged(nameof(PendingText)); + } + } + } + + /// Repositories with local changes below this node (itself included). + public int DirtyRepositories + { + get => _dirtyRepositories; + set + { + if (SetProperty(ref _dirtyRepositories, value)) + { + OnPropertyChanged(nameof(HasDirtyChildren)); + OnPropertyChanged(nameof(DirtyCountText)); + } + } + } + + /// + /// Number of changed files reported by the last status query. Only meaningful for repository + /// nodes; directory nodes show how many repositories below them are dirty instead. + /// + public int LocalChanges + { + get => _localChanges; + set + { + if (SetProperty(ref _localChanges, value)) + OnPropertyChanged(nameof(LocalChangesText)); + } + } + + public string LocalChangesText + { + get => _localChanges > 0 ? $"{_localChanges} 处改动" : string.Empty; + } + + public bool IsRepositoryDirty + { + get => _isRepository && _status != Models.DirtyState.None; + } + + /// True when the repository has commits to push or pull. + public bool HasPendingPullOrPush + { + get => _isRepository && _status.HasFlag(Models.DirtyState.HasPendingPullOrPush); + } + + public string PendingText + { + get => HasPendingPullOrPush ? "待推拉" : string.Empty; + } + + public bool HasDirtyChildren + { + get => !_isRepository && _dirtyRepositories > 0; + } + + public string DirtyCountText + { + get => _dirtyRepositories > 0 ? $"{_dirtyRepositories} 个仓库有改动" : string.Empty; + } + + /// + /// Opens the repository in a regular tab. The upstream implementation already + /// deduplicates by path, so double-clicking an already opened repository just + /// activates its tab instead of creating a second one. + /// + public void Open() + { + if (_isRepository && Directory.Exists(_fullPath)) + App.GetLauncher().OpenRepositoryInTab(_fullPath, null); + } + + private string _name = string.Empty; + private string _fullPath = string.Empty; + private bool _isRepository = false; + private bool _isExpanded = false; + private Models.DirtyState _status = Models.DirtyState.None; + private int _dirtyRepositories = 0; + private int _localChanges = 0; + } +} diff --git a/src/ViewModels/Projects.cs b/src/ViewModels/Projects.cs new file mode 100644 index 000000000..a6b9c596c --- /dev/null +++ b/src/ViewModels/Projects.cs @@ -0,0 +1,843 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +using Avalonia.Collections; + +using CommunityToolkit.Mvvm.ComponentModel; + +namespace SourceGit.ViewModels +{ + /// + /// Owns the user's projects and the left-side tree built from them. + /// Persisted to its own projects.json so that the big Preferences class (and + /// therefore the most conflict-prone file with upstream) is not touched. + /// + public class Projects : ObservableObject + { + public static Projects Instance + { + get; + } = new Projects(); + + public AvaloniaList Roots + { + get; + } = new AvaloniaList(); + + public string StatusText + { + get => _statusText; + set => SetProperty(ref _statusText, value); + } + + public bool IsScanning + { + get => _isScanning; + private set => SetProperty(ref _isScanning, value); + } + + public ProjectTreeNode CreateProject(IEnumerable directories) + { + var dirs = directories.Select(Models.RepositoryScanner.Normalize).Where(d => !string.IsNullOrEmpty(d)).ToList(); + if (dirs.Count == 0) + return null; + + // Reuse a project that covers exactly the same directories: pressing "+ 工程" twice + // on the same folder used to produce "docs", "docs 2", "docs 3". + var existing = Roots.FirstOrDefault(r => r.Project != null && + r.Project.Directories.Count == dirs.Count && + r.Project.Directories.All(d => dirs.Contains(d, StringComparer.OrdinalIgnoreCase))); + if (existing != null) + { + Models.ScanLog.Write($"projects: reuse existing project '{existing.Name}'"); + return existing; + } + + var baseName = Path.GetFileName(dirs[0]); + if (string.IsNullOrEmpty(baseName)) + baseName = dirs[0]; + + var project = new Models.Project { Name = MakeUniqueName(baseName, null) }; + project.Directories.AddRange(dirs); + _projects.Add(project); + + var node = new ProjectTreeNode + { + Name = project.Name, + FullPath = string.Empty, + IsProject = true, + IsExpanded = true, + Project = project, + }; + node.PropertyChanged += OnNodePropertyChanged; + + Roots.Add(node); + Save(); + return node; + } + + public bool AddDirectories(ProjectTreeNode projectNode, IEnumerable directories) + { + if (projectNode?.Project == null) + return false; + + var added = false; + foreach (var dir in directories.Select(Models.RepositoryScanner.Normalize)) + { + if (string.IsNullOrEmpty(dir)) + continue; + + var existing = projectNode.Project.Directories.FirstOrDefault(d => string.Equals(d, dir, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + continue; + + projectNode.Project.Directories.Add(dir); + added = true; + } + + if (added) + Save(); + + return added; + } + + public void RenameProject(ProjectTreeNode projectNode, string newName) + { + if (projectNode?.Project == null) + return; + + var name = (newName ?? string.Empty).Trim(); + if (name.Length == 0 || string.Equals(name, projectNode.Project.Name, StringComparison.Ordinal)) + return; + + projectNode.Project.Name = MakeUniqueName(name, projectNode); + projectNode.Name = projectNode.Project.Name; + Save(); + } + + public void RemoveProject(ProjectTreeNode projectNode) + { + if (projectNode?.Project == null) + return; + + projectNode.PropertyChanged -= OnNodePropertyChanged; + _projects.Remove(projectNode.Project); + Roots.Remove(projectNode); + Save(); + } + + /// + /// Removes one configured directory from a project. + /// must be the tree node created for that directory (a direct child of the + /// project node), not an intermediate directory node. + /// + public void RemoveDirectory(ProjectTreeNode projectNode, ProjectTreeNode rootNode) + { + if (projectNode?.Project == null || rootNode?.Parent != projectNode) + return; + + var index = projectNode.Project.Directories.FindIndex(d => string.Equals(Models.RepositoryScanner.Key(d), Models.RepositoryScanner.Key(rootNode.FullPath), StringComparison.Ordinal)); + if (index < 0) + return; + + projectNode.Project.Directories.RemoveAt(index); + projectNode.Children.Remove(rootNode); + Save(); + UpdateAggregates(); + } + + public void CancelScan() + { + _scanCts?.Cancel(); + } + + /// + /// Removes one discovered node (a repository, or a directory below the configured + /// ones) from the current tree only. Nothing is persisted, so the next scan brings + /// it back. That is intentional: a permanent exclusion list would make a mistake + /// hard to undo, and adding the same path back is a normal thing to want. + /// Directories left empty by the removal are dropped as well, so the tree does not + /// keep a dead branch around. + /// + public void RemoveNode(ProjectTreeNode node) + { + if (node == null || node.Parent == null || node.IsProject) + return; + + node.PropertyChanged -= OnNodePropertyChanged; + node.Parent.Children.Remove(node); + + var parent = node.Parent; + while (parent != null && !parent.IsProject && parent.Children.Count == 0) + { + parent.PropertyChanged -= OnNodePropertyChanged; + + var grandParent = parent.Parent; + if (grandParent == null) + break; + + grandParent.Children.Remove(parent); + parent = grandParent; + } + + UpdateAggregates(); + } + + /// + /// Finds the repository node that represents the given absolute path. + /// Paths are compared with the same normalisation the scanner uses, so a + /// tab opened from a path with a different slash style or casing still matches. + /// Returns null when the repository does not belong to any project. + /// + public ProjectTreeNode FindRepository(string path) + { + if (string.IsNullOrEmpty(path)) + return null; + + var key = Models.RepositoryScanner.Key(path); + foreach (var root in Roots) + { + var found = FindRepository(root, key); + if (found != null) + return found; + } + + return null; + } + + /// + /// Expands every ancestor of the given node so that it becomes visible. + /// The expansion is deliberately kept out of the persisted collapsed set: + /// it follows the active tab, it is not a preference of the user. + /// + public void RevealRepository(ProjectTreeNode repositoryNode) + { + if (repositoryNode == null) + return; + + _suppressCollapseSave = true; + try + { + var parent = repositoryNode.Parent; + while (parent != null) + { + parent.IsExpanded = true; + parent = parent.Parent; + } + } + finally + { + _suppressCollapseSave = false; + } + } + + /// + /// Recomputes the status shown on the tree: repositories that are open in a tab + /// contribute the state the repository page already tracks (which updates on every + /// git operation), the rest are queried in the background with a working-copy-only + /// `git status`. Runs are serialised: a second request cancels the previous one. + /// + public async Task RefreshStatusAsync() + { + HookLauncher(); + + // Cancel only: disposing the source while a query may still hold its token would + // throw on the cancelled path. + _statusCts?.Cancel(); + + var cts = new CancellationTokenSource(); + _statusCts = cts; + + var repositories = new List(); + foreach (var root in Roots) + CollectRepositories(root, repositories); + + if (repositories.Count == 0) + return; + + Dictionary dirty; + try + { + dirty = await Models.RepositoryStatusScanner.QueryDirtyAsync(repositories.Select(n => n.FullPath).ToList(), cts.Token); + } + catch (OperationCanceledException) + { + return; + } + finally + { + if (ReferenceEquals(_statusCts, cts)) + _statusCts = null; + } + + if (cts.IsCancellationRequested) + return; + + foreach (var node in repositories) + { + var count = dirty.TryGetValue(Models.RepositoryScanner.Key(node.FullPath), out var changes) ? changes : 0; + node.LocalChanges = count; + node.Status = count > 0 ? Models.DirtyState.HasLocalChanges : Models.DirtyState.None; + } + + // Open pages win over the scan: they know about pending pushes and pulls too. + MirrorOpenPages(); + UpdateAggregates(); + } + + /// + /// Mirrors the state of a repository page onto its tree node. Called whenever a page + /// reports a new dirty state, so a commit/stage/pull in a tab shows up in the tree + /// immediately instead of waiting for the next scan. + /// + public void MirrorPageStatus(LauncherPage page) + { + if (page?.Node == null) + return; + + var node = FindRepository(page.Node.Id); + if (node == null) + return; + + if (page.Data is Repository repository) + node.LocalChanges = repository.LocalChangesCount; + + node.Status = page.DirtyState; + UpdateAggregates(); + } + + /// + /// Subscribes to the launcher's pages once, so status changes made in a tab reach the + /// tree. Safe to call repeatedly: it is a no-op once the current launcher is hooked. + /// + public void HookLauncher() + { + var launcher = App.GetLauncher(); + if (launcher == null || ReferenceEquals(_hookedLauncher, launcher)) + return; + + if (_hookedLauncher != null) + { + _hookedLauncher.Pages.CollectionChanged -= OnPagesChanged; + foreach (var page in _hookedLauncher.Pages) + page.PropertyChanged -= OnPagePropertyChanged; + } + + _hookedLauncher = launcher; + _hookedLauncher.Pages.CollectionChanged += OnPagesChanged; + foreach (var page in _hookedLauncher.Pages) + page.PropertyChanged += OnPagePropertyChanged; + } + + private void OnPagesChanged(object sender, NotifyCollectionChangedEventArgs e) + { + if (e.OldItems != null) + { + foreach (var item in e.OldItems) + if (item is LauncherPage removed) + removed.PropertyChanged -= OnPagePropertyChanged; + } + + if (e.NewItems != null) + { + foreach (var item in e.NewItems) + if (item is LauncherPage added) + added.PropertyChanged += OnPagePropertyChanged; + } + + // A closed tab no longer updates its node, so re-query everything below. + _ = RefreshStatusAsync(); + } + + private void OnPagePropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(LauncherPage.DirtyState) && sender is LauncherPage page) + MirrorPageStatus(page); + } + + private void MirrorOpenPages() + { + var launcher = _hookedLauncher; + if (launcher == null) + return; + + foreach (var page in launcher.Pages) + MirrorPageStatus(page); + } + + private static void CollectRepositories(ProjectTreeNode node, List result) + { + if (node.IsRepository) + { + result.Add(node); + return; + } + + foreach (var child in node.Children) + CollectRepositories(child, result); + } + + private void UpdateAggregates() + { + foreach (var root in Roots) + UpdateAggregates(root); + } + + private int UpdateAggregates(ProjectTreeNode node) + { + if (node.IsRepository) + { + node.DirtyRepositories = node.IsRepositoryDirty ? 1 : 0; + return node.DirtyRepositories; + } + + var count = 0; + foreach (var child in node.Children) + count += UpdateAggregates(child); + + node.DirtyRepositories = count; + return count; + } + + private static ProjectTreeNode FindRepository(ProjectTreeNode node, string key) + { + if (node.IsRepository && string.Equals(Models.RepositoryScanner.Key(node.FullPath), key, StringComparison.Ordinal)) + return node; + + foreach (var child in node.Children) + { + var found = FindRepository(child, key); + if (found != null) + return found; + } + + return null; + } + + /// + /// Rebuilds one project's subtree. Scanning runs on the thread pool while the tree + /// is updated as repositories are found, so this must be called from the UI thread. + /// A running scan of the previous request is cancelled. + /// + public async Task RebuildAsync(ProjectTreeNode projectNode) + { + if (projectNode?.Project == null) + return; + + var previous = _scanCts; + var cts = new CancellationTokenSource(); + _scanCts = cts; + previous?.Cancel(); + previous?.Dispose(); + + var token = cts.Token; + var dirs = projectNode.Project.Directories.ToArray(); + var entries = new List(); + IsScanning = true; + Models.ScanLog.Write($"projects: rebuild '{projectNode.Name}' dirs={dirs.Length}"); + + try + { + projectNode.Children.Clear(); + + for (var i = 0; i < dirs.Length; i++) + { + if (token.IsCancellationRequested) + return; + + var index = i + 1; + var total = dirs.Length; + var dir = dirs[i]; + StatusText = $"{projectNode.Name}: 扫描 ({index}/{total}) {dir}"; + + if (!Directory.Exists(dir)) + { + var missing = new ProjectTreeNode + { + Name = $"{dir} (不存在)", + FullPath = dir, + Parent = projectNode, + }; + projectNode.Children.Add(missing); + continue; + } + + // The directory node is added before scanning starts, so the user sees the + // tree structure immediately and repositories appear under it as they are + // confirmed instead of all at once at the end. + var entry = new ScanEntry(dir, new ProjectTreeNode + { + // The first level under a project is the configured directory itself, + // named by its full path: using only the last segment made it collide + // with the project name ("docs → docs"). + Name = Models.RepositoryScanner.Normalize(dir), + FullPath = dir, + Parent = projectNode, + IsExpanded = !_collapsed.Contains(Models.RepositoryScanner.Key(dir)), + }); + entry.Node.PropertyChanged += OnNodePropertyChanged; + projectNode.Children.Add(entry.Node); + entries.Add(entry); + + var found = new Progress(repo => + { + if (!entry.Reconciled && Roots.Contains(projectNode)) + InsertRepository(entry.Node, dir, repo); + }); + + var progress = new Progress(current => + StatusText = $"{projectNode.Name}: 扫描 ({index}/{total}) {Shorten(current)}"); + + entry.Repositories = await Task.Run(() => Models.RepositoryScanner.ScanAsync(dir, progress, found, token), token); + Models.ScanLog.Write($"projects: dir '{dir}' returned {entry.Repositories.Count} repositories"); + } + } + catch (OperationCanceledException) + { + return; + } + catch (Exception e) + { + Native.OS.LogException(e); + StatusText = $"扫描失败: {e.Message}"; + return; + } + finally + { + if (ReferenceEquals(_scanCts, cts)) + { + _scanCts = null; + IsScanning = false; + } + } + + // Drop the result when the project was removed while the scan was running. + if (token.IsCancellationRequested || !Roots.Contains(projectNode)) + return; + + FinalizeTree(projectNode, entries, dirs.Length); + + // Repositories known now: fetch their working copy state once, in the background. + await RefreshStatusAsync(); + } + + /// + /// Rebuilds every project once, so that the tree appears without the user + /// having to press 扫描 on every project after a restart. + /// + public void StartRestore() + { + if (_restored) + return; + + _restored = true; + _ = RestoreAllAsync(); + } + + private async Task RestoreAllAsync() + { + // Sequentially, not concurrently: RebuildAsync cancels the previous scan of the + // same instance, so firing them all at once would cancel every one but the last. + foreach (var root in Roots.ToList()) + { + await RebuildAsync(root); + await Task.Yield(); + } + } + + private Projects() + { + Load(); + } + + /// + /// Makes sure the incremental insertions are complete (progress callbacks can + /// still be queued when the scan task returns), applies the "directory itself is + /// a repository" case, sorts children and refreshes the status line. + /// + private void FinalizeTree(ProjectTreeNode projectNode, List entries, int totalDirs) + { + _suppressCollapseSave = true; + try + { + var total = 0; + foreach (var entry in entries) + { + entry.Reconciled = true; + total += entry.Repositories.Count; + + foreach (var repo in entry.Repositories) + InsertRepository(entry.Node, entry.Dir, repo); + + if (entry.Repositories.Count == 1 && + string.Equals(entry.Repositories[0], Models.RepositoryScanner.Normalize(entry.Dir), StringComparison.OrdinalIgnoreCase)) + { + entry.Node.IsRepository = true; + } + + SortChildren(entry.Node); + } + + StatusText = $"{projectNode.Name}: {entries.Count}/{totalDirs} 个目录 / {total} 个仓库"; + Models.ScanLog.Write($"projects: finalize '{projectNode.Name}' dirs={entries.Count}/{totalDirs} repos={total} topChildren={projectNode.Children.Count}"); + } + finally + { + _suppressCollapseSave = false; + } + } + + private static string Shorten(string path) + { + var normalized = Models.RepositoryScanner.Normalize(path); + var index = normalized.LastIndexOf('/'); + return index < 0 || index + 1 >= normalized.Length ? normalized : normalized.Substring(index + 1); + } + + private string MakeUniqueName(string baseName, ProjectTreeNode except) + { + var name = baseName; + var i = 2; + while (_projects.Any(p => !ReferenceEquals(p, except?.Project) && string.Equals(p.Name, name, StringComparison.CurrentCultureIgnoreCase))) + name = $"{baseName} {i++}"; + return name; + } + + private void InsertRepository(ProjectTreeNode rootNode, string rootDir, string repoPath) + { + Models.ScanLog.Write($"projects: insert '{repoPath}' under '{rootDir}'"); + + var normalizedRoot = Models.RepositoryScanner.Normalize(rootDir); + if (string.Equals(repoPath, normalizedRoot, StringComparison.OrdinalIgnoreCase)) + { + rootNode.IsRepository = true; + return; + } + + var relative = Path.GetRelativePath(rootDir, repoPath.Replace('/', Path.DirectorySeparatorChar)); + var segments = relative.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + if (segments.Length == 0) + return; + + var cursor = rootNode; + for (var i = 0; i < segments.Length; i++) + { + if (string.IsNullOrEmpty(segments[i])) + continue; + + var isLeaf = i == segments.Length - 1; + var full = Models.RepositoryScanner.Normalize(Path.Combine(Path.Combine(new[] { rootDir }.Concat(segments.Take(i + 1)).ToArray()))); + + var child = cursor.Children.FirstOrDefault(c => string.Equals(c.Name, segments[i], StringComparison.CurrentCultureIgnoreCase)); + if (child == null) + { + child = new ProjectTreeNode + { + Name = segments[i], + FullPath = full, + Parent = cursor, + IsRepository = isLeaf, + IsExpanded = !_collapsed.Contains(Models.RepositoryScanner.Key(full)), + }; + child.PropertyChanged += OnNodePropertyChanged; + cursor.Children.Add(child); + } + else if (isLeaf) + { + child.IsRepository = true; + } + + cursor = child; + } + } + + private static void SortChildren(ProjectTreeNode node) + { + var sorted = node.Children.OrderBy(c => c.IsRepository ? 1 : 0) + .ThenBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase) + .ToList(); + + node.Children.Clear(); + foreach (var child in sorted) + node.Children.Add(child); + + foreach (var child in node.Children) + SortChildren(child); + } + + /// + /// Expands or collapses the whole tree at once. Each node change is kept out of the + /// persisted collapsed set while it happens, then the set is rewritten once — otherwise + /// "collapse all" would write projects.json once per node. + /// + public void SetAllExpanded(bool expanded) + { + if (Roots.Count == 0) + return; + + _suppressCollapseSave = true; + try + { + foreach (var root in Roots) + ApplyExpandedRecursive(root, expanded); + } + finally + { + _suppressCollapseSave = false; + } + + _collapsed.Clear(); + if (!expanded) + { + foreach (var root in Roots) + CollectCollapsedRecursive(root, _collapsed); + } + + Save(); + } + + private static void ApplyExpandedRecursive(ProjectTreeNode node, bool expanded) + { + foreach (var child in node.Children) + { + child.IsExpanded = expanded; + ApplyExpandedRecursive(child, expanded); + } + } + + private static void CollectCollapsedRecursive(ProjectTreeNode node, HashSet keys) + { + foreach (var child in node.Children) + { + if (!string.IsNullOrEmpty(child.FullPath)) + keys.Add(Models.RepositoryScanner.Key(child.FullPath)); + + CollectCollapsedRecursive(child, keys); + } + } + + private void OnNodePropertyChanged(object sender, PropertyChangedEventArgs e) + { + if (e.PropertyName != nameof(ProjectTreeNode.IsExpanded) || _suppressCollapseSave) + return; + + if (sender is not ProjectTreeNode node || string.IsNullOrEmpty(node.FullPath)) + return; + + var key = Models.RepositoryScanner.Key(node.FullPath); + if (node.IsExpanded) + _collapsed.Remove(key); + else + _collapsed.Add(key); + + Save(); + } + + private string StorePath + { + get => Path.Combine(Native.OS.BasicDirectories.ConfigDir, "projects.json"); + } + + private void Load() + { + try + { + var path = StorePath; + if (!File.Exists(path)) + return; + + var model = JsonSerializer.Deserialize(File.ReadAllText(path), JsonCodeGen.Default.ProjectsSaveModel); + if (model?.Projects == null) + return; + + foreach (var key in model.Collapsed ?? new List()) + { + if (!string.IsNullOrEmpty(key)) + _collapsed.Add(key); + } + + foreach (var project in model.Projects) + { + if (string.IsNullOrEmpty(project.Name)) + continue; + + _projects.Add(project); + + var node = new ProjectTreeNode + { + Name = project.Name, + FullPath = string.Empty, + IsProject = true, + IsExpanded = true, + Project = project, + }; + node.PropertyChanged += OnNodePropertyChanged; + Roots.Add(node); + } + } + catch (Exception e) + { + Native.OS.LogException(e); + } + } + + public void Save() + { + try + { + var model = new Models.ProjectsSaveModel + { + Projects = _projects, + Collapsed = _collapsed.ToList(), + }; + + var text = JsonSerializer.Serialize(model, JsonCodeGen.Default.ProjectsSaveModel); + + var finalFile = StorePath; + var tmpFile = Path.Combine(Native.OS.BasicDirectories.ConfigDir, "projects_tmp.json"); + File.WriteAllText(tmpFile, text); + + if (File.Exists(finalFile)) + File.Delete(finalFile); + + File.Move(tmpFile, finalFile); + } + catch (Exception e) + { + Native.OS.LogException(e); + } + } + + private sealed class ScanEntry + { + public ScanEntry(string dir, ProjectTreeNode node) + { + Dir = dir; + Node = node; + Repositories = new List(); + } + + public string Dir { get; } + public ProjectTreeNode Node { get; } + public List Repositories { get; set; } + public bool Reconciled { get; set; } + } + + private readonly List _projects = new List(); + private readonly HashSet _collapsed = new HashSet(); + private CancellationTokenSource _scanCts = null; + private CancellationTokenSource _statusCts = null; + private Launcher _hookedLauncher = null; + private bool _suppressCollapseSave = false; + private bool _restored = false; + private string _statusText = string.Empty; + private bool _isScanning = false; + } +} diff --git a/src/Views/Launcher.axaml b/src/Views/Launcher.axaml index ced304b54..a8b803718 100644 --- a/src/Views/Launcher.axaml +++ b/src/Views/Launcher.axaml @@ -150,13 +150,17 @@ - - - - - - - + + + + + + + + + + + {state}, bounds={Bounds} client={ClientSize} explicitSize=({Width}x{Height})"); + + if (state != oldState && !_revertingState) + { + _pendingStateNew = state; + _pendingStateOld = oldState; + var generation = ++_stateCheckGeneration; + _ = ConfirmStateTransitionAsync(generation); + } + else if (_revertingState) + { + PersistWindowState(state); + } } else if (change.Property == IsActiveProperty) { + WindowTrace.Write($"IsActive: {change.OldValue} -> {change.NewValue}, state={WindowState} bounds={Bounds}"); + if (!IsActive && DataContext is ViewModels.Launcher { CommandPalette: { } } vm) vm.CommandPalette = null; + + // Re-activated means the modal dialog that produced the phantom restore is gone; + // only now is it safe to put the owner back, otherwise the WM would keep flipping + // it to Normal for every re-maximize and we would end up in a 2Hz tug of war. + if (IsActive && _phantomRestoreTo.HasValue) + ApplyPhantomRestore(); } if (OperatingSystem.IsMacOS() && WindowState != WindowState.FullScreen) @@ -118,11 +151,32 @@ protected override void OnSizeChanged(SizeChangedEventArgs e) { base.OnSizeChanged(e); + WindowTrace.Write($"SizeChanged: {e.PreviousSize} -> {e.NewSize}, state={WindowState} bounds={Bounds} " + + $"client={ClientSize} explicitSize=({Width}x{Height}) workArea={Screens?.ScreenFromWindow(this)?.WorkingArea}"); + + // A real resize proves the pending state transition came from an actual user + // maximize/restore rather than from a modal dialog stealing activation. + if (_pendingStateNew.HasValue && e.NewSize != e.PreviousSize) + { + var state = _pendingStateNew.Value; + _pendingStateNew = null; + _phantomRestoreTo = null; + ++_stateCheckGeneration; + PersistWindowState(state); + } + else if (_phantomRestoreTo.HasValue) + { + // The user resized the window themselves; the queued phantom undo is stale. + _phantomRestoreTo = null; + } + if (WindowState == WindowState.Normal) { + // Store what the window really is; "Width"/"Height" may still carry the + // maximized geometry, which must not pollute the restore size. var layout = ViewModels.Preferences.Instance.Layout; - layout.LauncherWidth = Width; - layout.LauncherHeight = Height; + layout.LauncherWidth = e.NewSize.Width; + layout.LauncherHeight = e.NewSize.Height; } } @@ -149,7 +203,11 @@ protected override async void OnKeyDown(KeyEventArgs e) { if (e is { KeyModifiers: KeyModifiers.Control, Key: Key.OemComma }) { + WindowTrace.Write($"Preferences open(cmd): state={WindowState} bounds={Bounds} client={ClientSize}"); await this.ShowDialogAsync(new Preferences()); + WindowTrace.Write($"Preferences closed(cmd): state={WindowState} bounds={Bounds} client={ClientSize} " + + $"layout=({ViewModels.Preferences.Instance.Layout.LauncherWidth}x{ViewModels.Preferences.Instance.Layout.LauncherHeight}, " + + $"{ViewModels.Preferences.Instance.Layout.LauncherWindowState})"); e.Handled = true; return; } @@ -343,6 +401,8 @@ protected override void OnClosed(EventArgs e) { base.OnClosed(e); + WindowTrace.Write($"OnClosed: state={WindowState} bounds={Bounds} client={ClientSize} explicitSize=({Width}x{Height})"); + if (!Design.IsDesignMode) ViewModels.Preferences.Instance.Save(); @@ -351,7 +411,11 @@ protected override void OnClosed(EventArgs e) private void OnPositionChanged(object sender, PixelPointEventArgs e) { - if (WindowState == WindowState.Normal) + WindowTrace.Write($"PositionChanged: {e.Point}, state={WindowState} bounds={Bounds}"); + + // While a state transition is unconfirmed the window may be in the middle of a + // phantom restore; the position reported here is not the user's layout yet. + if (WindowState == WindowState.Normal && _pendingStateNew == null) { var layout = ViewModels.Preferences.Instance.Layout; layout.LauncherPositionX = Position.X; @@ -359,6 +423,72 @@ private void OnPositionChanged(object sender, PixelPointEventArgs e) } } + /// + /// A transition is only trusted once it is followed by a real resize. Modal dialogs on + /// X11 flip the owner from Maximized to Normal without resizing it, and persisting that + /// phantom state made a maximized window restart at its old, smaller size. + /// + private async Task ConfirmStateTransitionAsync(int generation) + { + await Task.Delay(PhantomStateWindowMs); + + if (generation != _stateCheckGeneration || !_pendingStateNew.HasValue) + return; + + var oldState = _pendingStateOld; + var newState = _pendingStateNew.Value; + _pendingStateNew = null; + + if (newState == WindowState.Normal && oldState == WindowState.Maximized) + { + // Queue the undo instead of applying it now: while the modal dialog is still open + // the WM turns every re-maximize straight back into a Normal flip, so acting here + // produces an endless Maximized/Normal oscillation. It is applied once the owner + // is re-activated after the dialog closes. + WindowTrace.Write($"phantom transition ignored: {oldState} -> {newState} without a resize, queued restore to {oldState}"); + _phantomRestoreTo = oldState; + PersistWindowState(oldState); + return; + } + + if (newState != WindowState.Maximized) + _phantomRestoreTo = null; + + PersistWindowState(newState); + } + + private void ApplyPhantomRestore() + { + var target = _phantomRestoreTo!.Value; + _phantomRestoreTo = null; + + if (WindowState == target) + return; + + WindowTrace.Write($"apply queued restore: {WindowState} -> {target}"); + _revertingState = true; + try + { + WindowState = target; + } + finally + { + _revertingState = false; + } + + PersistWindowState(target); + } + + private void PersistWindowState(WindowState state) + { + var layout = ViewModels.Preferences.Instance.Layout; + if (layout.LauncherWindowState != state) + { + layout.LauncherWindowState = state; + WindowTrace.Write($"persist state={state}"); + } + } + private void OnOpenWorkspaceMenu(object sender, RoutedEventArgs e) { if (sender is Button btn && DataContext is ViewModels.Launcher launcher) @@ -449,6 +579,19 @@ private async void OnShowNewVersion(object sender, RoutedEventArgs e) private GridLength _captionHeight = new(32); private WindowState _lastWindowState = WindowState.Normal; + + // How long a WindowState change may wait for its resize before being treated as the + // phantom flip a modal dialog causes on X11. + private const int PhantomStateWindowMs = 400; + + private WindowState? _pendingStateNew = null; + private WindowState _pendingStateOld = WindowState.Normal; + private int _stateCheckGeneration = 0; + private bool _revertingState = false; + + // A phantom restore detected while a modal dialog held the owner: applied once the + // dialog closes and the owner is activated again. + private WindowState? _phantomRestoreTo = null; } } diff --git a/src/Views/LauncherTabBar.axaml b/src/Views/LauncherTabBar.axaml index 76b4f7ddf..a744d040f 100644 --- a/src/Views/LauncherTabBar.axaml +++ b/src/Views/LauncherTabBar.axaml @@ -38,18 +38,42 @@ - - - + + + @@ -107,6 +131,7 @@ Fill="{Binding DirtyState, Converter={x:Static c:DirtyStateConverters.ToBrush}}"/> barLeft) + { + var barRect = new Rect(barLeft + 1, height - 2, Math.Max(0, barRight - barLeft - 2), 2); + context.DrawRectangle(GetHighlightBrush(), null, barRect); + } + } + + /// + /// Fixed red instead of the system accent colour: the accent follows the OS theme and on + /// Windows resolves to a blue that reads as "not highlighted at all" against the title + /// bar. Cached so repeated layout passes hand out the same instance. + /// + private IBrush GetHighlightBrush() + { + var color = ActualThemeVariant == ThemeVariant.Light ? Color.FromRgb(0xC5, 0x2F, 0x2F) : Colors.Red; + if (_highlightBrush == null || _highlightBrushColor != color) + { + _highlightBrushColor = color; + _highlightBrush = new SolidColorBrush(color); + _highlightTint = new SolidColorBrush(color, 0.16); + } + + return _highlightBrush; + } + + private ISolidColorBrush GetHighlightTint() + { + GetHighlightBrush(); + return _highlightTint; + } + + /// + /// The active tab used to be filled with Brush.ToolBar. On themes where the title bar and + /// the tool bar resolve to the same colour the shape was drawn on top of itself and + /// disappeared, so fall back to the window brush whenever the two are close. + /// + private IBrush GetActiveTabFill() + { + var toolbar = this.FindResource("Brush.ToolBar") as ISolidColorBrush; + if (toolbar == null) + return Brushes.Transparent; + + var titleBar = this.FindResource("Brush.TitleBar") as ISolidColorBrush; + if (titleBar != null && AreClose(titleBar.Color, toolbar.Color)) + { + var window = this.FindResource("Brush.Window") as ISolidColorBrush; + if (window != null && !AreClose(window.Color, titleBar.Color)) + return window; + } + + return toolbar; + } + + private static bool AreClose(Color a, Color b) + { + const byte tolerance = 8; + return Math.Abs(a.R - b.R) <= tolerance && + Math.Abs(a.G - b.G) <= tolerance && + Math.Abs(a.B - b.B) <= tolerance && + Math.Abs(a.A - b.A) <= tolerance; } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) @@ -204,14 +274,144 @@ private void ScrollTabsRight(object _, RoutedEventArgs e) private void OnTabsLayoutUpdated(object _1, EventArgs _2) { IsScrollButtonVisible = LauncherTabsScroller.Extent.Width > LauncherTabsScroller.Viewport.Width; + ScheduleActiveSync(); InvalidateVisual(); } private void OnTabsSelectionChanged(object _1, SelectionChangedEventArgs _2) { + ScheduleActiveSync(); InvalidateVisual(); } + /// + /// Never decorates the tab bar synchronously from a layout callback: touching the item + /// containers there re-enters layout, and the UI thread can end up looping until the + /// window stops responding. The work is posted at background priority and coalesced, + /// so at most one decoration pass is pending at any time. + /// + private void ScheduleActiveSync() + { + if (_activeSyncPending) + return; + + _activeSyncPending = true; + Dispatcher.UIThread.Post(() => + { + _activeSyncPending = false; + SyncActiveClass(); + }, DispatcherPriority.Background); + } + + /// + /// Applies the active-page decoration directly, as local values on the item container and + /// on the title TextBlock. + /// + /// Every style-based route was either invisible on Windows or impossible to verify from + /// here: a ListBoxItem:selected style has to reach into the item template, and a + /// descendant selector has to cross the DataTemplate boundary, while the class-keyed + /// styles still depend on where the styles collection is applied. Local values outrank + /// theme, application and control setters alike, so what is computed here is exactly + /// what gets rendered on every platform. + /// + private void SyncActiveClass() + { + if (LauncherTabsList == null) + return; + + var selected = LauncherTabsList.SelectedIndex; + var count = LauncherTabsList.ItemCount; + var highlightBrush = GetHighlightBrush(); + var tint = GetHighlightTint(); + var realized = 0; + var titles = 0; + + for (var i = 0; i < count; i++) + { + var container = LauncherTabsList.ContainerFromIndex(i) as ContentControl; + if (container == null) + continue; + + realized++; + + var active = i == selected; + container.Classes.Set("active", active); + if (active) + { + // Render-only properties: no measured size changes, so this cannot start a + // layout loop. The bottom bar is painted by Render(). + if (!ReferenceEquals(container.Background, tint)) + container.Background = tint; + + if (!ReferenceEquals(container.BorderBrush, highlightBrush)) + container.BorderBrush = highlightBrush; + + if (container.Opacity != 1) + container.Opacity = 1; + } + else + { + if (container.Background != null) + container.ClearValue(TemplatedControl.BackgroundProperty); + + if (container.BorderBrush != null) + container.ClearValue(TemplatedControl.BorderBrushProperty); + + if (container.BorderThickness != default(Thickness)) + container.ClearValue(TemplatedControl.BorderThicknessProperty); + + container.ClearValue(Visual.OpacityProperty); + } + + foreach (var title in container.GetVisualDescendants().OfType()) + { + if (!title.Classes.Contains("tab_title")) + continue; + + titles++; + title.Classes.Set("active", active); + if (active) + { + if (title.FontWeight != FontWeight.Bold) + title.FontWeight = FontWeight.Bold; + + if (!ReferenceEquals(title.Foreground, highlightBrush)) + title.Foreground = highlightBrush; + } + else + { + title.ClearValue(TextBlock.FontWeightProperty); + title.ClearValue(TextBlock.ForegroundProperty); + } + } + } + + TraceActiveSync(selected, count, realized, titles); + } + + /// + /// Writes one line per distinct outcome, so a report of "nothing changed" can be turned + /// into a fact: either no container was realized (containers == 0) or the decoration was + /// applied and the problem lies elsewhere. + /// + private void TraceActiveSync(int selected, int count, int realized, int titles) + { + var state = $"{selected}/{count}/{realized}/{titles}"; + if (state == _lastActiveTrace) + return; + + _lastActiveTrace = state; + try + { + File.AppendAllText(_activeTraceFile, + $"{DateTime.Now:HH:mm:ss.fff} tab=active selected={selected} items={count} containers={realized} titles={titles}{Environment.NewLine}"); + } + catch + { + // Tracing must never break the UI. + } + } + private void OnPointerPressedTab(object sender, PointerPressedEventArgs e) { if (sender is Border border) @@ -428,5 +628,11 @@ private void OnCloseTab(object sender, RoutedEventArgs e) private PointerPressedEventArgs _pressedTabEvent = null; private bool _startDragTab = false; private readonly DataFormat _dndMainTabFormat = DataFormat.CreateStringApplicationFormat("sourcegit-dnd-main-tab"); + private readonly string _activeTraceFile = Path.Combine(Native.OS.BasicDirectories.ConfigDir, "tabbar-trace.log"); + private string _lastActiveTrace = null; + private bool _activeSyncPending; + private IBrush _highlightBrush; + private ISolidColorBrush _highlightTint; + private Color _highlightBrushColor; } } diff --git a/src/Views/Preferences.axaml b/src/Views/Preferences.axaml index 6b3aa863c..e10466705 100644 --- a/src/Views/Preferences.axaml +++ b/src/Views/Preferences.axaml @@ -213,6 +213,7 @@ + + + + + + + + + + + + + + + + + + + +