diff --git a/README.md b/README.md index 2194d09..add8ccb 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ **🎯 Selection & editing** - Lasso and rectangle select; move, resize, rotate, duplicate, recolor and change line width of the selection - Type text or paste images straight onto the page +- Convert handwriting to text: lasso it, check what was read, then swap the ink for a text box or copy the text - Stickers: save a lasso selection (a diagram, a stamp, a signature), optionally with the PDF behind it, or just a piece of a PDF, and drop a copy into any note - Screenshot tool: capture a region and copy, save or insert it into the page - Undo and redo for ink, page changes and templates @@ -58,6 +59,7 @@ - Share a note as a PDF or as images through the Windows share window (Mail, Teams, Nearby sharing, …) - Page templates: blank, grid, dots, lined, Cornell, with adjustable spacing - Widen a page to the left or right (it snaps to match neighbouring widened pages), or keep scrolling past the end to add a page +- Make room to write: with the Page size tool, drag down inside a page to open blank space at that line (the PDF below moves down with it, e.g. between two exercises), or drag up to close it again. Saved and exported PDFs keep the space, and the PDF text stays selectable - Page sorter: reorder, delete and jump between pages; bookmark pages - Autosave and version history: preview an earlier version next to the note, then restore it if you want - `.yunote` files are SQLite, so every stroke stays editable after you close and reopen @@ -72,6 +74,7 @@ - Home screen with folders (with colors), pinned notes, a "continue where you left off" row, and sorting by date, name or folder - Trash and Archive, with restore - Tabs: keep several notes open in one window (**Ctrl+T**, **Ctrl+W**, **Ctrl+Tab**, or Ctrl+click a note on Home); each tab keeps its own undo history +- Windows like a browser: drag tabs to reorder them, drag one out into its own window or onto another window's tabs, or right-click a tab to move it. Opening a note from File Explorer adds a tab to the YuNotes that's already open instead of starting a second copy - Side by side: open a second note read-only next to the one you're editing **🎤 Presenting** diff --git a/src/YuNotes/App.xaml.cs b/src/YuNotes/App.xaml.cs index 32000e6..1054cb7 100644 --- a/src/YuNotes/App.xaml.cs +++ b/src/YuNotes/App.xaml.cs @@ -9,7 +9,9 @@ namespace YuNotes; public partial class App : Application { - public static Window? MainWindow { get; private set; } + // The window the user last worked in (YuNotes can have several). + public static Window? MainWindow => YuNotes.MainWindow.Active; + private static Microsoft.UI.Dispatching.DispatcherQueue? s_ui; public static ServiceContainer Services { get; } = new(); public static string CrashLogPath { get; } = Path.Combine( @@ -47,35 +49,91 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) DebugSettings.BindingFailed += (_, ev) => Append($"[BindingFailed] {ev.Message}"); Services.Initialize(); - MainWindow = new MainWindow(); - MainWindow.Activate(); + s_ui = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); + var first = new MainWindow(); + first.Activate(); // If Explorer launched us via a file association (.pdf / .yunote), open // that file in the editor on top of the home page. - TryOpenActivationFile(); + try + { + var path = FileFromActivation(Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs()) + ?? FileFromCommandLine(Environment.GetCommandLineArgs(), skipFirst: true); + if (path is not null) YuNotes.MainWindow.OpenFile(path); + } + catch (Exception ex) { LogError(ex, "OnLaunched file activation"); } + + // Later launches hand their activation to this instance (see Program). + Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().Activated += (_, a) => + s_ui?.TryEnqueue(() => OnRedirected(a)); // Background update check (no-op when turned off in Settings). _ = YuNotes.Services.UpdateService.CheckOnStartupAsync(); } - // When the app is started by opening an associated file, Windows delivers the - // file through the AppLifecycle activation args (not OnLaunched's args). Read - // them and route the path through the normal editor-open flow. - private static void TryOpenActivationFile() + // Another launch of YuNotes: open its file as a tab in the window last + // used, or, for a plain launch, a new window (like a browser does). + private static void OnRedirected(Microsoft.Windows.AppLifecycle.AppActivationArguments args) { try { - var activation = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs(); - if (activation?.Kind == Microsoft.Windows.AppLifecycle.ExtendedActivationKind.File - && activation.Data is Windows.ApplicationModel.Activation.IFileActivatedEventArgs fileArgs - && fileArgs.Files.Count > 0 - && fileArgs.Files[0] is Windows.Storage.StorageFile file - && !string.IsNullOrEmpty(file.Path)) + var path = FileFromActivation(args); + if (path is not null) { YuNotes.MainWindow.OpenFile(path); return; } + var w = new MainWindow(); + w.Activate(); + w.BringToFront(); + } + catch (Exception ex) { LogError(ex, "Redirected activation"); } + } + + // When the app is started by opening an associated file, packaged YuNotes + // gets the file in File activation args; unpackaged YuNotes gets it on the + // command line (Launch activation). + private static string? FileFromActivation(Microsoft.Windows.AppLifecycle.AppActivationArguments? activation) + { + if (activation is null) return null; + if (activation.Kind == Microsoft.Windows.AppLifecycle.ExtendedActivationKind.File + && activation.Data is Windows.ApplicationModel.Activation.IFileActivatedEventArgs fileArgs + && fileArgs.Files.Count > 0 + && !string.IsNullOrEmpty(fileArgs.Files[0].Path)) + return fileArgs.Files[0].Path; + if (activation.Kind == Microsoft.Windows.AppLifecycle.ExtendedActivationKind.Launch + && activation.Data is Windows.ApplicationModel.Activation.ILaunchActivatedEventArgs launch + && !string.IsNullOrWhiteSpace(launch.Arguments)) + return FileFromCommandLine(SplitCommandLine(launch.Arguments), skipFirst: false); + return null; + } + + private static string? FileFromCommandLine(System.Collections.Generic.IEnumerable args, bool skipFirst) + { + foreach (var a in skipFirst ? System.Linq.Enumerable.Skip(args, 1) : args) + { + var p = a.Trim().Trim('"'); + if ((p.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase) || p.EndsWith(".yunote", StringComparison.OrdinalIgnoreCase)) + && File.Exists(p)) + return Path.GetFullPath(p); + } + return null; + } + + // Splits a command line into arguments, keeping quoted paths with spaces whole. + private static System.Collections.Generic.List SplitCommandLine(string line) + { + var result = new System.Collections.Generic.List(); + var cur = new System.Text.StringBuilder(); + bool quoted = false; + foreach (char c in line) + { + if (c == '"') { quoted = !quoted; continue; } + if (char.IsWhiteSpace(c) && !quoted) { - YuNotes.MainWindow.Navigate(file.Path); + if (cur.Length > 0) { result.Add(cur.ToString()); cur.Clear(); } + continue; } + cur.Append(c); } - catch (Exception ex) { LogError(ex, "OnLaunched file activation"); } + if (cur.Length > 0) result.Add(cur.ToString()); + return result; } private static void Append(string detail) diff --git a/src/YuNotes/Controls/InkCanvasControl.xaml.cs b/src/YuNotes/Controls/InkCanvasControl.xaml.cs index f9cb086..4a1a3cd 100644 --- a/src/YuNotes/Controls/InkCanvasControl.xaml.cs +++ b/src/YuNotes/Controls/InkCanvasControl.xaml.cs @@ -38,20 +38,6 @@ public sealed partial class InkCanvasControl : UserControl public event EventHandler? MomentaryToolStart; public event EventHandler? MomentaryToolEnd; public event EventHandler? ActivePageScrolled; - // True while any page is showing a live (uncommitted) stroke. - public event EventHandler? LiveInkActiveChanged; - // Pages currently showing live ink. A stroke handed between pages can - // raise the new page's start before the old page's end, so count instead - // of forwarding each page's flag. - private int _liveInkPages; - - private void OnPageLiveInkActiveChanged(object? sender, bool active) - { - bool was = _liveInkPages > 0; - _liveInkPages = Math.Max(0, _liveInkPages + (active ? 1 : -1)); - bool now = _liveInkPages > 0; - if (now != was) LiveInkActiveChanged?.Invoke(this, now); - } public InkCanvasControl() { @@ -288,12 +274,6 @@ public void Rebuild() { PagesPanel.Children.Clear(); _pageCanvases.Clear(); - // Discarded pages never report their live ink ending. - if (_liveInkPages > 0) - { - _liveInkPages = 0; - LiveInkActiveChanged?.Invoke(this, false); - } _pullZone = null; _pullRingHost = null; _addBtnWrapper = null; @@ -344,9 +324,9 @@ public void Rebuild() canvas.MomentaryToolStart += (_, kind) => MomentaryToolStart?.Invoke(this, kind); canvas.MomentaryToolEnd += (_, __) => MomentaryToolEnd?.Invoke(this, EventArgs.Empty); canvas.RectSelectionCompleted += (_, __) => RectSelectionCompleted?.Invoke(this, EventArgs.Empty); - canvas.LiveInkActiveChanged += OnPageLiveInkActiveChanged; canvas.SelectionDragDropped += OnSelectionDragDropped; canvas.ExtensionDragCompleted += OnExtensionDragCompleted; + canvas.SpaceDragCompleted += OnSpaceDragCompleted; canvas.ExtendModeActive = ExtendModeActive; PagesPanel.Children.Add(canvas); _pageCanvases.Add(canvas); @@ -1164,6 +1144,10 @@ public void SetRulerVisible(bool visible) public bool SelectionHasResizableWidth => ActivePageCanvas?.SelectionHasResizableWidth == true; public float? SelectionWidth() => ActivePageCanvas?.SelectionWidth(); public void SetSelectionWidth(float width) => ActivePageCanvas?.SetSelectionWidth(width); + public bool SelectionHasPenInk => ActivePageCanvas?.SelectionHasPenInk == true; + public List SelectedPenStrokes() => ActivePageCanvas?.SelectedPenStrokes() ?? new(); + public bool ReplaceSelectedPenInkWithText(string text, Windows.UI.Color color, float fontSize) => + ActivePageCanvas?.ReplaceSelectedPenInkWithText(text, color, fontSize) == true; public byte[]? RenderRegionOfCurrentPage(float x, float y, float w, float h) => ActivePageCanvas?.RenderRegionToPng(x, y, w, h); @@ -1653,6 +1637,19 @@ private void OnExtensionDragCompleted(object? sender, (ExtendSide Side, double A CommitPageExtension(pc.Page, args.Side, args.Amount, pc); } + // A Page size drag inside a page: open space below the row it started at + // (Delta > 0) or close inserted space above it (Delta < 0). One undo step. + private void OnSpaceDragCompleted(object? sender, (double Y, double Delta) args) + { + if (sender is not PageCanvas pc) return; + var page = pc.Page; + if (args.Delta > 0) PageGaps.Insert(page, args.Y, args.Delta); + else if (PageGaps.Remove(page, args.Y + args.Delta, args.Y) <= 0) return; + pc.ResizeCanvas(); + UpdateSeparators(); + DocumentMutated?.Invoke(this, page); + } + // Called by EditorPage when the dialog is used for precise control. public void CommitPageExtension(NotePage page, ExtendSide side, double amount) { diff --git a/src/YuNotes/Controls/LiquidGlassBackdrop.cs b/src/YuNotes/Controls/LiquidGlassBackdrop.cs index 6995693..6644891 100644 --- a/src/YuNotes/Controls/LiquidGlassBackdrop.cs +++ b/src/YuNotes/Controls/LiquidGlassBackdrop.cs @@ -28,18 +28,18 @@ namespace YuNotes.Controls; /// so the host keeps today's acrylic look. When activated it swaps the /// Background for a SpriteVisual whose effect brush samples the live backdrop: /// -/// backdrop → GaussianBlur → Saturation ┬→ tint overlay (glass body) -/// └→ Transform2D zoom → edge-masked (refraction) +/// backdrop → GaussianBlur → Saturation → tint overlay (glass body) +/// backdrop → lighter blur → edge-masked (clearer rim band) /// + Win2D-drawn rim/sheen surface, all alpha-masked to the rounded rect. /// /// The whole graph lives on the compositor thread: after setup there is no /// per-frame CPU work, and the GPU cost is in the same class as the in-app /// AcrylicBrush it replaces (one blur of a panel-sized region). The three mask /// surfaces are tiny and redrawn only on resize / theme / DPI changes. -/// True per-pixel displacement maps (the React lib's SVG feDisplacementMap) -/// aren't in the composition-supported effect set, so the edge refraction uses -/// the same approximation the lib's "standard" map encodes: edge pixels sample -/// toward the center (a magnifying rim), masked to a band along the border. +/// The rim band samples the live backdrop with less blur than the body. It +/// used to show a magnified live capture of the canvas instead, but that +/// capture didn't follow the canvas's scroll/zoom (it showed page that wasn't +/// behind the toolbar) and re-rendered on every ink change, so it was dropped. /// public sealed partial class LiquidGlassBackdrop : Grid { @@ -51,21 +51,16 @@ public sealed partial class LiquidGlassBackdrop : Grid // anchored dark even when floating over a white page, instead of flipping // to silver. Light theme keeps the unmodified backdrop. private const float DarkBackdropExposure = -1.8f; - private const float RefractionZoom = 1.22f; // edge band magnification private const float EdgeBandWidth = 15f; // refraction band along the rim private const float RimStrokeWidth = 1.5f; private bool _active; private Brush? _inactiveBackground; - private Vector2 _lastSourceOffset = new(float.NaN); private CanvasDevice? _device; private CompositionGraphicsDevice? _gfx; private SpriteVisual? _visual; private CompositionEffectBrush? _brush; - private CompositionVisualSurface? _visualSurface; // live capture feeding the refraction - private CompositionBrush? _refractionBrush; // zoomed brush over _visualSurface - private bool _refractionPaused; private CompositionDrawingSurface? _edgeSurface; // refraction band alpha private CompositionDrawingSurface? _rimSurface; // specular border + sheen @@ -83,37 +78,6 @@ public LiquidGlassBackdrop() Unloaded += OnUnloaded; } - /// - /// Element whose live rendering feeds the magnified edge-refraction band - /// (typically the canvas the glass floats over). Backdrop brushes cannot be - /// transformed by the compositor, so true refraction needs a - /// CompositionVisualSurface capture of the content behind the panel. When - /// null the edge band falls back to an untransformed, clearer backdrop. - /// Must not be an ancestor of this control. - /// - public UIElement? RefractionSource { get; set; } - - /// - /// Suspends the live refraction capture (e.g. while a stroke is being - /// drawn). The capture re-renders the whole source subtree whenever any of - /// it changes — ink drawn anywhere on the canvas, not just behind the - /// toolbar — which re-runs the edge blur every frame. That is invisible on - /// a desktop GPU but a steady per-frame cost on integrated laptop GPUs. - /// While paused the edge band samples the plain backdrop instead (the same - /// fallback used without a source), which the compositor only re-renders - /// when the region behind the toolbar itself changes. - /// - public bool RefractionPaused - { - get => _refractionPaused; - set - { - if (_refractionPaused == value) return; - _refractionPaused = value; - ApplyRefractionPause(); - } - } - /// Switches between the glass effect and the plain Background brush. public bool IsGlassActive { @@ -141,20 +105,16 @@ private void OnLoaded(object sender, RoutedEventArgs e) { _root = XamlRoot; if (_root is not null) _root.Changed += OnRootChanged; // DPI / monitor moves - LayoutUpdated += OnLayoutUpdated; // tracks toolbar drags Rebuild(); } private void OnUnloaded(object sender, RoutedEventArgs e) { if (_root is not null) { _root.Changed -= OnRootChanged; _root = null; } - LayoutUpdated -= OnLayoutUpdated; // Loaded/Unloaded can arrive out of order; only tear down when truly unloaded. if (!IsLoaded) ReleaseVisual(); } - private void OnLayoutUpdated(object? sender, object e) => UpdateRefractionOffset(); - private void OnRootChanged(XamlRoot sender, XamlRootChangedEventArgs args) => Rebuild(); private void Rebuild() @@ -238,7 +198,7 @@ private void DrawSurfaces(float w, float h, float scale, ElementTheme theme) _edgeSurface = CreateSurface(pw, ph); _rimSurface = CreateSurface(pw, ph); - // Refraction band: opaque at the rim, fading to 0 inland. Fill the pill, + // Edge band: opaque at the rim, fading to 0 inland. Fill the pill, // then carve out a blurred interior so the falloff is smooth. float band = MathF.Min(EdgeBandWidth * scale, MathF.Min(pw, ph) / 3f); using (var ds = CanvasComposition.CreateDrawingSession(_edgeSurface)) @@ -328,12 +288,8 @@ private void BuildBrush(Compositor compositor, float w, float h, ElementTheme th }, }; - // Edge refraction: the rim shows the content behind magnified toward the - // panel center, masked to a band along the border. Less blur than the - // body — a real glass rim bends light but stays clearer than the slab. - // The magnification lives on the brush bound to "backdrop2" (a scaled - // visual-surface brush), since the compositor rejects any Transform2D - // over a backdrop source. + // Edge band: the backdrop with less blur than the body, masked to a band + // along the border — a glass rim stays clearer than the slab. IGraphicsEffectSource edgeBackdrop = new GaussianBlurEffect { Source = new CompositionEffectSourceParameter("backdrop2"), @@ -365,69 +321,11 @@ private void BuildBrush(Compositor compositor, float w, float h, ElementTheme th _brush?.Dispose(); _brush = factory.CreateBrush(); _brush.SetSourceParameter("backdrop", compositor.CreateBackdropBrush()); - _refractionBrush = CreateRefractionBrush(compositor, w, h); - ApplyRefractionPause(); + _brush.SetSourceParameter("backdrop2", compositor.CreateBackdropBrush()); _brush.SetSourceParameter("edge", CreateMaskBrush(compositor, _edgeSurface!)); _brush.SetSourceParameter("rim", CreateMaskBrush(compositor, _rimSurface!)); } - /// - /// Brush feeding the magnified edge band: a live visual-surface capture of - /// aligned with this panel, zoomed toward the - /// center. Without a source, an unzoomed backdrop (the band then just shows - /// the backdrop with less blur — still glassy, no lens bend). - /// - private CompositionBrush CreateRefractionBrush(Compositor compositor, float w, float h) - { - _visualSurface?.Dispose(); _visualSurface = null; - if (RefractionSource is null) return compositor.CreateBackdropBrush(); - - _visualSurface = compositor.CreateVisualSurface(); - _visualSurface.SourceVisual = ElementCompositionPreview.GetElementVisual(RefractionSource); - _visualSurface.SourceSize = new Vector2(w, h); - _lastSourceOffset = new Vector2(float.NaN); - UpdateRefractionOffset(); - - var brush = compositor.CreateSurfaceBrush(_visualSurface); - brush.Stretch = CompositionStretch.None; // 1:1, centered by default ratios - brush.CenterPoint = new Vector2(w / 2f, h / 2f); - brush.Scale = new Vector2(RefractionZoom); - return brush; - } - - private void ApplyRefractionPause() - { - if (_brush is null || _refractionBrush is null) return; - bool live = !_refractionPaused && _visualSurface is not null; - if (_visualSurface is not null) - { - // Detaching the source stops the capture outright, rather than - // relying on an unbound surface not being re-rendered. - _visualSurface.SourceVisual = live && RefractionSource is not null - ? ElementCompositionPreview.GetElementVisual(RefractionSource) - : null; - } - _brush.SetSourceParameter("backdrop2", live - ? _refractionBrush - : _brush.Compositor.CreateBackdropBrush()); - if (live) UpdateRefractionOffset(); - } - - /// - /// Keeps the captured region aligned with the panel as it is dragged or - /// re-docked. Called from LayoutUpdated; the transform compare makes the - /// no-change case (e.g. layout passes caused by unrelated elements) cheap. - /// - private void UpdateRefractionOffset() - { - if (_visualSurface is null || RefractionSource is null || !IsLoaded || _refractionPaused) return; - var origin = TransformToVisual(RefractionSource).TransformPoint(new Point(0, 0)); - var offset = new Vector2((float)origin.X, (float)origin.Y); - if (offset == _lastSourceOffset) return; - _lastSourceOffset = offset; - _visualSurface.SourceOffset = offset; - } - private static CompositionSurfaceBrush CreateMaskBrush(Compositor compositor, CompositionDrawingSurface surface) { var brush = compositor.CreateSurfaceBrush(surface); @@ -442,8 +340,6 @@ private void ReleaseVisual() ElementCompositionPreview.SetElementChildVisual(this, null); _visual?.Dispose(); _visual = null; _brush?.Dispose(); _brush = null; - _visualSurface?.Dispose(); _visualSurface = null; - _refractionBrush = null; DisposeSurfaces(); _builtSize = default; } diff --git a/src/YuNotes/Controls/PageCanvas.Space.cs b/src/YuNotes/Controls/PageCanvas.Space.cs new file mode 100644 index 0000000..036f730 --- /dev/null +++ b/src/YuNotes/Controls/PageCanvas.Space.cs @@ -0,0 +1,142 @@ +using System; +using System.Linq; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Shapes; +using Windows.UI; +using YuNotes.Models; + +namespace YuNotes.Controls; + +// ─── Insert space ─────────────────────────────────────────────────────────── +// With the Page size tool, dragging down inside a page opens blank space at +// that line: everything below (the PDF too) moves down and the page grows, so +// there's room to write between two questions. Dragging up over space opened +// earlier closes it again. The page itself changes on release +// (InkCanvasControl.OnSpaceDragCompleted); while dragging, a band shows what +// will be added (blue) or removed (red). +public sealed partial class PageCanvas +{ + // Fired on release: (page row the drag started at, how far it went — + // positive opens space below that row, negative closes space above it). + public event EventHandler<(double Y, double Delta)>? SpaceDragCompleted; + + private bool _spacing; + private double _spaceStartY; + private double _spaceDelta; + private Rectangle? _spaceBand; + private Line? _spaceLine; + private Border? _spaceLabelBorder; + private TextBlock? _spaceLabel; + + // Drags shorter than this are taps, not space. + private const double MinSpace = 6; + + private static readonly Color SpaceAddColor = Color.FromArgb(255, 91, 107, 255); + private static readonly Color SpaceRemoveColor = Color.FromArgb(255, 220, 60, 60); + + private void BeginSpace(System.Numerics.Vector2 p) + { + _spacing = true; + _spaceStartY = Math.Clamp(p.Y, 0, Page.Height); + _spaceDelta = 0; + EnsureSpaceOverlay(); + UpdateSpacePreview(); + } + + private void ContinueSpace(System.Numerics.Vector2 p) + { + // Whole units, so the band doesn't shimmer under a pen. + _spaceDelta = Math.Round(p.Y - _spaceStartY); + UpdateSpacePreview(); + } + + // How much inserted space the band between `top` and `bottom` covers — + // what dragging up over it would close. + private double RemovableSpace(double top, double bottom) + { + double total = 0; + foreach (var (gy, gh) in PageGaps.GapRows(Page)) + total += Math.Max(0, Math.Min(bottom, gy + gh) - Math.Max(top, gy)); + return total; + } + + private void EndSpace(bool commit) + { + if (!_spacing) return; + _spacing = false; + double delta = _spaceDelta; + TearDownSpaceOverlay(); + if (!commit || Math.Abs(delta) < MinSpace) return; + if (delta < 0 && RemovableSpace(_spaceStartY + delta, _spaceStartY) < 0.5) return; + SpaceDragCompleted?.Invoke(this, (_spaceStartY, delta)); + } + + private void EnsureSpaceOverlay() + { + if (_spaceBand is not null) return; + _spaceBand = new Rectangle { IsHitTestVisible = false, StrokeThickness = 0 }; + _spaceLine = new Line + { + IsHitTestVisible = false, + StrokeThickness = 2, + StrokeDashArray = new DoubleCollection { 4, 3 }, + }; + _spaceLabel = new TextBlock + { + FontSize = 13, + Foreground = new SolidColorBrush(Microsoft.UI.Colors.White), + IsHitTestVisible = false, + }; + _spaceLabelBorder = new Border + { + Child = _spaceLabel, + Padding = new Thickness(10, 4, 10, 4), + CornerRadius = new CornerRadius(12), + IsHitTestVisible = false, + }; + foreach (var el in new UIElement[] { _spaceBand, _spaceLine, _spaceLabelBorder }) + { + Canvas.SetZIndex(el, 60); + _overlay.Children.Add(el); + } + } + + private void UpdateSpacePreview() + { + if (_spaceBand is null || _spaceLine is null || _spaceLabel is null || _spaceLabelBorder is null) return; + double w = Page.Width, d = _spaceDelta, y = _spaceStartY; + bool adding = d >= 0; + double removable = adding ? 0 : RemovableSpace(y + d, y); + var color = adding ? SpaceAddColor : SpaceRemoveColor; + + _spaceBand.Width = w; + _spaceBand.Height = Math.Abs(d); + _spaceBand.Fill = new SolidColorBrush(Color.FromArgb(48, color.R, color.G, color.B)); + Canvas.SetLeft(_spaceBand, 0); + Canvas.SetTop(_spaceBand, adding ? y : y + d); + + _spaceLine.X1 = 0; _spaceLine.X2 = w; + _spaceLine.Y1 = _spaceLine.Y2 = y; + _spaceLine.Stroke = new SolidColorBrush(color); + + _spaceLabel.Text = adding + ? (d < MinSpace ? "Drag down to add space, up to remove it" : $"+ {d:0} space") + : removable < 0.5 ? "No added space here to remove" + : $"− {removable:0} space"; + _spaceLabelBorder.Background = new SolidColorBrush(color); + Canvas.SetLeft(_spaceLabelBorder, 16); + Canvas.SetTop(_spaceLabelBorder, adding ? y + Math.Max(d, 0) + 6 : y + d - 34); + } + + private void TearDownSpaceOverlay() + { + foreach (var el in new UIElement?[] { _spaceBand, _spaceLine, _spaceLabelBorder }) + if (el is not null) _overlay.Children.Remove(el); + _spaceBand = null; + _spaceLine = null; + _spaceLabelBorder = null; + _spaceLabel = null; + } +} diff --git a/src/YuNotes/Controls/PageCanvas.cs b/src/YuNotes/Controls/PageCanvas.cs index 2114b78..d789bd9 100644 --- a/src/YuNotes/Controls/PageCanvas.cs +++ b/src/YuNotes/Controls/PageCanvas.cs @@ -40,7 +40,7 @@ public sealed class SelectionDropEventArgs : EventArgs public bool Transferred { get; set; } } -public sealed class PageCanvas : ContentControl +public sealed partial class PageCanvas : ContentControl { public NotePage Page { get; } public TemplateSettings PageTemplate { get; set; } @@ -76,7 +76,6 @@ public sealed class PageCanvas : ContentControl // window per frame (~half the drawing-time GPU cost; see // prototypes/InkPerfLab). private LiveInkSurface? _liveInk; - private bool _liveInkActive; // last value raised through LiveInkActiveChanged // ── Hi-res PDF background (zoomed in) ─────────────────────────────────── // The imported background PNG is rasterized at 300 DPI (2× the coord @@ -146,7 +145,7 @@ private void EnsureContentBounds() public void InvalidateContentBounds() => _contentBoundsDirty = true; // Drag modes when interacting with selection - private enum DragMode { None, Move, ResizeNW, ResizeNE, ResizeSW, ResizeSE, Rotate } + private enum DragMode { None, Move, ResizeNW, ResizeNE, ResizeSW, ResizeSE, ResizeW, ResizeE, ResizeN, ResizeS, Rotate } private DragMode _drag = DragMode.None; private Bbox _dragStartBbox; private Vector2 _dragStartCenter; @@ -171,6 +170,11 @@ private enum DragMode { None, Move, ResizeNW, ResizeNE, ResizeSW, ResizeSE, Rota // the model mutates ONCE on release. private Image? _dragGhost; private Rectangle? _dragGhostBorder; + // While resizing a selection with text in it, the text is drawn here at its + // new size and wrapping on every move (see UpdateTextResizeGhost), not + // stretched with the rest of the ghost — so the preview matches the result. + private Image? _textResizeGhost; + private readonly Dictionary _origTextFont = new(); private RotateTransform? _dragGhostRotate; private RotateTransform? _dragGhostBorderRotate; private Bbox _dragGhostBbox; // padded doc-space rect the ghost image covers @@ -189,7 +193,7 @@ private enum DragMode { None, Move, ResizeNW, ResizeNE, ResizeSW, ResizeSE, Rota // Snapshot of original element transforms at drag start, keyed by id private readonly Dictionary _origImageBoxes = new(); private readonly Dictionary _origTextBoxes = new(); - private readonly Dictionary _origShapePoints = new(); + private readonly Dictionary _origShapePoints = new(); private readonly Dictionary _origImageRot = new(); private readonly Dictionary _origTextRot = new(); @@ -277,11 +281,6 @@ public PageCanvas( public event EventHandler? MomentaryToolEnd; public event EventHandler? RectSelectionCompleted; - // Raised when a live stroke starts (true) and when it is committed, - // cancelled or dropped (false). EditorPage pauses the toolbar's live glass - // refraction in between so drawing doesn't re-blur it every frame. - public event EventHandler? LiveInkActiveChanged; - // Raised when a Move drag is released. InkCanvasControl uses it to hand the // selection to whichever page the pointer ended over (a cross-page move); // the handler sets Transferred=true if it did, so this page skips its own @@ -495,15 +494,6 @@ private void TearDownLiveInk() { CancelLiveInkSync(); _liveInk?.Clear(); - ReportLiveInkActive(); - } - - private void ReportLiveInkActive() - { - bool active = _liveInk?.IsActive == true; - if (active == _liveInkActive) return; - _liveInkActive = active; - LiveInkActiveChanged?.Invoke(this, active); } private void SyncLiveInkSurface(Stroke s) @@ -521,7 +511,6 @@ private void SyncLiveInkSurface(Stroke s) alpha = (byte)Math.Min(140, alpha == 255 ? 110 : alpha); _liveInk.Sync(s, Color.FromArgb(alpha, s.Color.R, s.Color.G, s.Color.B), (float)Page.Width, (float)Page.Height); - ReportLiveInkActive(); // also catches a device-lost Clear inside Sync } // Prediction lead: extrapolate up to TWO samples ahead (never less than @@ -815,7 +804,16 @@ public void UpdateHiResBackground(byte[] sourcePdf, int sourcePageIndex, ? Page.BackgroundContentWidth : Page.Width - bgLeft; if (bgW <= 0) { ClearHiResBackground(); return; } - var bgRect = new Windows.Foundation.Rect(bgLeft, 0, bgW, Page.Height); + // The crop is worked out in background rows (as imported, before any + // inserted space); the renderer places each piece. Without gaps these + // are the same as page rows. + var bgRect = new Windows.Foundation.Rect(bgLeft, 0, bgW, PageGaps.BackgroundHeight(Page)); + if (PageGaps.Any(Page)) + { + double vt = PageGaps.ToBackground(Page, viewRect.Y); + double vb = PageGaps.ToBackground(Page, viewRect.Bottom); + viewRect = new Windows.Foundation.Rect(viewRect.X, vt, viewRect.Width, Math.Max(0, vb - vt)); + } // Keep the current crop while it still covers the view at this scale. if (_bgHiRes is not null && Math.Abs(_bgHiResScale - backingScale) < 0.01f) @@ -858,7 +856,7 @@ private void QueueHiResRender(byte[] sourcePdf, int sourcePageIndex, Windows.Foundation.Rect want, float backingScale, int gen, Windows.Foundation.Rect? followUp) { - double pageH = Page.Height; + double pageH = PageGaps.BackgroundHeight(Page); double bgLeft = Page.BackgroundLeft; double bgW = Page.BackgroundContentWidth > 0 ? Page.BackgroundContentWidth @@ -928,6 +926,11 @@ private void QueueHiResRender(byte[] sourcePdf, int sourcePageIndex, _bgHiResScale = backingScale; var dirty = want; if (old is not null) { old.Dispose(); dirty.Union(oldRect); } + if (PageGaps.Any(Page)) + { + double top = PageGaps.ToPage(Page, dirty.Y), bottom = PageGaps.ToPage(Page, dirty.Bottom); + dirty = new Windows.Foundation.Rect(dirty.X, top, dirty.Width, Math.Max(0, bottom - top)); + } _canvas.Invalidate(dirty); // Tight pass is on screen — widen to the scroll-headroom crop. if (followUp is { } inflated) @@ -1255,8 +1258,21 @@ private void DrawSelectionVisuals(CanvasDrawingSession ds) // Corner handles + (single-element only) rotate handle var handles = HandlePositions(outer); - foreach (var (_, pos) in handles) + foreach (var (mode, pos) in handles) { + if (mode is DragMode.ResizeW or DragMode.ResizeE or DragMode.ResizeN or DragMode.ResizeS) + { + // Edge handles are pills along their edge: tall on the sides + // (width only), wide on top and bottom (height only). + bool side = mode is DragMode.ResizeW or DragMode.ResizeE; + float hw = side ? HandleSize * 0.32f : HandleSize * 0.8f; + float hh = side ? HandleSize * 0.8f : HandleSize * 0.32f; + var r = new Windows.Foundation.Rect(pos.X - hw, pos.Y - hh, hw * 2, hh * 2); + float rr = Math.Min(hw, hh); + ds.FillRoundedRectangle(r, rr, rr, Colors.White); + ds.DrawRoundedRectangle(r, rr, rr, Color.FromArgb(255, 91, 107, 255), 2f); + continue; + } ds.FillCircle(pos, HandleSize * 0.5f, Colors.White); ds.DrawCircle(pos, HandleSize * 0.5f, Color.FromArgb(255, 91, 107, 255), 2f); } @@ -1271,15 +1287,31 @@ private void DrawSelectionVisuals(CanvasDrawingSession ds) private List<(DragMode mode, Vector2 pos)> HandlePositions(Bbox b) { - return new() + var list = new List<(DragMode, Vector2)> { (DragMode.ResizeNW, new Vector2(b.X, b.Y)), (DragMode.ResizeNE, new Vector2(b.Right, b.Y)), (DragMode.ResizeSW, new Vector2(b.X, b.Bottom)), (DragMode.ResizeSE, new Vector2(b.Right, b.Bottom)), }; + // Side handles change only the width (text rewraps at the same size); + // top/bottom handles change only the height. Text boxes get no + // top/bottom handles: their height always fits their text. + list.Add((DragMode.ResizeW, new Vector2(b.X, b.Y + b.H / 2))); + list.Add((DragMode.ResizeE, new Vector2(b.Right, b.Y + b.H / 2))); + if (!SelectionIsTextOnly) + { + list.Add((DragMode.ResizeN, new Vector2(b.X + b.W / 2, b.Y))); + list.Add((DragMode.ResizeS, new Vector2(b.X + b.W / 2, b.Bottom))); + } + return list; } + // Only text boxes are selected (no ink, shapes or images). + private bool SelectionIsTextOnly => + Context.SelectedTextIds.Count > 0 && Context.SelectedStrokeIds.Count == 0 + && Context.SelectedShapeIds.Count == 0 && Context.SelectedImageIds.Count == 0; + private bool TryRotateHandle(Bbox outer, out Vector2 pos) { pos = default; @@ -1658,7 +1690,7 @@ private void OnPointerPressedCore(object sender, PointerRoutedEventArgs e) if (Context.EditingSuspended) return; // A new press while a previous gesture is still marked in progress means // that gesture was interrupted without a release — finish it first. - if (_panning || _selectingText || _lasering || _tapeGesture || _drag != DragMode.None || _activeTool is not null) + if (_panning || _selectingText || _lasering || _spacing || _tapeGesture || _drag != DragMode.None || _activeTool is not null) ResetInputState(); Focus(FocusState.Pointer); var p = ToPageSpace(e); @@ -1683,6 +1715,17 @@ private void OnPointerPressedCore(object sender, PointerRoutedEventArgs e) return; } + // Page size tool: a drag inside the page opens (or closes) space. + if (tool is ExtendPageTool) + { + if (HasCommittedSelection()) ClearSelection(); + BeginSpace(p); + CapturePointer(e.Pointer); + _capturedPointerId = e.Pointer.PointerId; + e.Handled = true; + return; + } + // Laser pointer: points, never edits — so it skips selection handling // and leaves any committed selection alone. if (tool is LaserTool) @@ -2219,6 +2262,11 @@ private void OnPointerMovedCore(object sender, PointerRoutedEventArgs e) } return; } + if (_spacing) + { + ContinueSpace(p); + return; + } if (_lasering) { var pts = e.GetIntermediatePoints(this); @@ -2327,6 +2375,13 @@ private void OnPointerReleasedCore(object sender, PointerRoutedEventArgs e) EndLaser(); skipFullRedraw = true; } + else if (_spacing) + { + // The page is resized and repainted by InkCanvasControl if this + // drag changed anything. + EndSpace(commit: true); + skipFullRedraw = true; + } else if (_tapeGesture) { if (_tapeTap is { } t) ToggleTape(t); @@ -2394,6 +2449,7 @@ public void ResetInputState() _tapeGesture = false; _tapeTap = null; if (_lasering) EndLaser(); + EndSpace(commit: false); if (_drag != DragMode.None) EndDrag(); if (_activeTool is { } tool) { @@ -2418,6 +2474,7 @@ private void StartDrag(DragMode mode, Vector2 p, bool tapDismisses = false) _dragStartCenter = _dragStartBbox.Center; _origImageBoxes.Clear(); _origTextBoxes.Clear(); + _origTextFont.Clear(); _origShapePoints.Clear(); _origImageRot.Clear(); _origTextRot.Clear(); @@ -2434,13 +2491,14 @@ private void StartDrag(DragMode mode, Vector2 p, bool tapDismisses = false) var t = Page.Texts.FirstOrDefault(z => z.Id == id); if (t is null) continue; _origTextBoxes[id] = Bbox.Of(t); + _origTextFont[id] = t.FontSize; _origTextRot[id] = t.Rotation; } foreach (var id in Context.SelectedShapeIds) { var sh = Page.Shapes.FirstOrDefault(z => z.Id == id); if (sh is null) continue; - _origShapePoints[id] = (sh.X1, sh.Y1, sh.X2, sh.Y2); + _origShapePoints[id] = (sh.X1, sh.Y1, sh.X2, sh.Y2, sh.X3, sh.Y3); } _dragStartRotation = Math.Atan2(p.Y - _dragStartCenter.Y, p.X - _dragStartCenter.X); _dragStartPoint = p; @@ -2478,8 +2536,19 @@ private void ContinueDrag(Vector2 p) case DragMode.ResizeNE: case DragMode.ResizeSW: case DragMode.ResizeSE: + case DragMode.ResizeW: + case DragMode.ResizeE: + case DragMode.ResizeN: + case DragMode.ResizeS: { var nb = ResizedBox(_drag, p); + if (SelectionIsTextOnly) + { + // The outline follows the text as it will really be (its + // height fits the rewrapped text), not the dragged box. + if (UpdateTextResizeGhost(nb) is { } tb) PositionGhost(tb.X, tb.Y, tb.W, tb.H); + break; + } float sx = nb.W / Math.Max(1e-3f, _dragStartBbox.W); float sy = nb.H / Math.Max(1e-3f, _dragStartBbox.H); PositionGhost( @@ -2487,6 +2556,7 @@ private void ContinueDrag(Vector2 p) nb.Y + (_dragGhostBbox.Y - _dragStartBbox.Y) * sy, _dragGhostBbox.W * sx, _dragGhostBbox.H * sy); + UpdateTextResizeGhost(nb); break; } case DragMode.Rotate: @@ -2505,18 +2575,87 @@ private Bbox ResizedBox(DragMode mode, Vector2 p) { var orig = _dragStartBbox; float left = orig.X, top = orig.Y, right = orig.Right, bottom = orig.Bottom; + + // Text: corners scale the text as a whole (box and font together), so + // the box keeps its shape and the width alone decides the size. + if (SelectionIsTextOnly && mode is DragMode.ResizeNW or DragMode.ResizeNE + or DragMode.ResizeSW or DragMode.ResizeSE) + { + bool fromLeft = mode is DragMode.ResizeNW or DragMode.ResizeSW; + bool fromTop = mode is DragMode.ResizeNW or DragMode.ResizeNE; + float w = Math.Max(24, fromLeft ? orig.Right - p.X : p.X - orig.X); + float h = orig.H * w / Math.Max(1e-3f, orig.W); + float x = fromLeft ? orig.Right - w : orig.X; + float y = fromTop ? orig.Bottom - h : orig.Y; + return new Bbox(x, y, w, h); + } + switch (mode) { case DragMode.ResizeNW: left = p.X; top = p.Y; break; case DragMode.ResizeNE: right = p.X; top = p.Y; break; case DragMode.ResizeSW: left = p.X; bottom = p.Y; break; case DragMode.ResizeSE: right = p.X; bottom = p.Y; break; + case DragMode.ResizeW: left = p.X; break; + case DragMode.ResizeE: right = p.X; break; + case DragMode.ResizeN: top = p.Y; break; + case DragMode.ResizeS: bottom = p.Y; break; + } + float minW = mode is DragMode.ResizeW or DragMode.ResizeE ? 24 : 8; + if (right - left < minW) + { + if (mode is DragMode.ResizeW or DragMode.ResizeNW or DragMode.ResizeSW) left = right - minW; + else right = left + minW; + } + if (bottom - top < 8) + { + if (mode is DragMode.ResizeN or DragMode.ResizeNW or DragMode.ResizeNE) top = bottom - 8; + else bottom = top + 8; } - if (right - left < 8) right = left + 8; - if (bottom - top < 8) bottom = top + 8; return new Bbox(left, top, right - left, bottom - top); } + // A selected text box as a resize to selection box `nb` leaves it: + // side handles — new width, text rewraps, font unchanged; + // corners on text only — box and font scale together; + // corners on a mixed selection — scaled with the rest, font by the + // smaller of the two scales so it never overflows. + // The height always fits the text, so nothing is cut off and there is no + // empty space left at the bottom. + private TextElement ResizedText(TextElement t, Bbox ob, float origFont, Bbox nb, DragMode mode) + { + var orig = _dragStartBbox; + float sx = nb.W / Math.Max(1e-3f, orig.W); + float sy = nb.H / Math.Max(1e-3f, orig.H); + bool sides = mode is DragMode.ResizeW or DragMode.ResizeE or DragMode.ResizeN or DragMode.ResizeS; + float font = sides ? origFont + : Math.Clamp(origFont * (SelectionIsTextOnly ? sx : Math.Min(sx, sy)), 6f, 400f); + var r = new TextElement + { + X = nb.X + (ob.X - orig.X) * sx, + Y = nb.Y + (ob.Y - orig.Y) * sy, + Width = Math.Max(font * 1.2, ob.W * sx), + Height = ob.H, + FontSize = font, + Rotation = t.Rotation, Text = t.Text, Color = t.Color, + FontFamily = t.FontFamily, Bold = t.Bold, Italic = t.Italic, + }; + r.Height = FitTextHeight(r); + return r; + } + + // Height a text box needs for its text at its width (at least one line). + private static double FitTextHeight(TextElement t) + { + var probe = new TextElement + { + Width = t.Width, Height = t.Height, FontSize = t.FontSize, FontFamily = t.FontFamily, + Bold = t.Bold, Italic = t.Italic, + Text = string.IsNullOrEmpty(t.Text) ? "Ag" : t.Text, + }; + return Math.Max(t.FontSize * 1.3, PageRenderer.MeasureTextHeight(probe) + 4); + } + private void ApplyResize(DragMode mode, Vector2 p) { var orig = _dragStartBbox; @@ -2542,11 +2681,8 @@ private void ApplyResize(DragMode mode, Vector2 p) if (!_origTextBoxes.TryGetValue(id, out var ob)) continue; var t = Page.Texts.FirstOrDefault(z => z.Id == id); if (t is null) continue; - t.X = newBox.X + (ob.X - orig.X) * sx; - t.Y = newBox.Y + (ob.Y - orig.Y) * sy; - t.Width = ob.W * sx; - t.Height = ob.H * sy; - t.FontSize = Math.Max(6f, t.FontSize * Math.Min(sx, sy)); + var r = ResizedText(t, ob, _origTextFont.TryGetValue(id, out var f) ? f : t.FontSize, newBox, mode); + t.X = r.X; t.Y = r.Y; t.Width = r.Width; t.Height = r.Height; t.FontSize = r.FontSize; } // Shapes: scale each endpoint relative to the original selection bbox. foreach (var id in Context.SelectedShapeIds) @@ -2558,6 +2694,11 @@ private void ApplyResize(DragMode mode, Vector2 p) sh.Y1 = newBox.Y + (op.Y1 - orig.Y) * sy; sh.X2 = newBox.X + (op.X2 - orig.X) * sx; sh.Y2 = newBox.Y + (op.Y2 - orig.Y) * sy; + if (sh.Kind == ShapeKind.Triangle) + { + sh.X3 = newBox.X + (op.X3 - orig.X) * sx; + sh.Y3 = newBox.Y + (op.Y3 - orig.Y) * sy; + } } // Strokes: scale all points relative to original bbox. foreach (var id in Context.SelectedStrokeIds) @@ -2630,7 +2771,8 @@ private void BeginDragGhost() ds.Transform = Matrix3x2.CreateTranslation(-box.X, -box.Y); Renderer.DrawElements(ds, Page, Context.SelectedStrokeIds, Context.SelectedShapeIds, - Context.SelectedTextIds, Context.SelectedImageIds, _imageCache); + IsResizeDrag(_drag) ? new List() : Context.SelectedTextIds, + Context.SelectedImageIds, _imageCache); } _dragGhostRotate = new RotateTransform(); @@ -2667,6 +2809,7 @@ private void BeginDragGhost() _overlay.Children.Add(_dragGhostBorder); _dragGhostBbox = box; + if (IsResizeDrag(_drag)) UpdateTextResizeGhost(_dragStartBbox); // Hide the originals (and the Win2D chrome — DrawSelectionVisuals // skips while _drag is set) with one partial redraw. @@ -2700,8 +2843,82 @@ private void PositionGhost(float x, float y, float w, float h) _dragGhostBorder.Height = h; } + private static bool IsResizeDrag(DragMode m) => + m is DragMode.ResizeNW or DragMode.ResizeNE or DragMode.ResizeSW or DragMode.ResizeSE + or DragMode.ResizeW or DragMode.ResizeE or DragMode.ResizeN or DragMode.ResizeS; + + // Draws the selected text boxes as ApplyResize will leave them for the + // selection box `nb`: same position/size/font-size formula, text laid out + // and wrapped for real rather than stretched. + // Returns the resized text boxes' outline (null if nothing to draw). + private Bbox? UpdateTextResizeGhost(Bbox nb) + { + if (Context.SelectedTextIds.Count == 0) return null; + var texts = new List(); + foreach (var id in Context.SelectedTextIds) + { + if (!_origTextBoxes.TryGetValue(id, out var ob)) continue; + var t = Page.Texts.FirstOrDefault(z => z.Id == id); + if (t is null) continue; + float font = _origTextFont.TryGetValue(id, out var f) ? f : t.FontSize; + texts.Add(ResizedText(t, ob, font, nb, _drag)); + } + if (texts.Count == 0) return null; + var outline = Bbox.Of(texts[0]); + foreach (var t in texts.Skip(1)) outline = Bbox.Union(outline, Bbox.Of(t)); + + // Area to draw into: the boxes, grown for rotation and for text that + // runs past the bottom of its box. + float minX = float.MaxValue, minY = float.MaxValue, maxX = float.MinValue, maxY = float.MinValue; + foreach (var t in texts) + { + float r = t.Rotation != 0 ? 0.5f * MathF.Sqrt((float)(t.Width * t.Width + t.Height * t.Height)) : 0f; + float cx = (float)(t.X + t.Width / 2), cy = (float)(t.Y + t.Height / 2); + minX = Math.Min(minX, Math.Min((float)t.X, cx - r)); + minY = Math.Min(minY, Math.Min((float)t.Y, cy - r)); + maxX = Math.Max(maxX, Math.Max((float)(t.X + t.Width), cx + r)); + maxY = Math.Max(maxY, Math.Max((float)(t.Y + t.Height), cy + r)); + } + var box = new Bbox(minX - 4, minY - 4, maxX - minX + 8, maxY - minY + 8); + if (box.W < 1 || box.H < 1) return outline; + + try + { + var device = TryGetCanvasDevice() ?? CanvasDevice.GetSharedDevice(); + float scale = Math.Clamp(_canvas.DpiScale, 1f, 4f); + const float maxPixels = 8_000_000f; + if (box.W * box.H * scale * scale > maxPixels) + scale = Math.Max(0.25f, MathF.Sqrt(maxPixels / (box.W * box.H))); + var src = new CanvasImageSource(device, box.W, box.H, 96f * scale); + using (var ds = src.CreateDrawingSession(Colors.Transparent)) + { + ds.Transform = Matrix3x2.CreateTranslation(-box.X, -box.Y); + foreach (var t in texts) Renderer.DrawTextElement(ds, t); + } + if (_textResizeGhost is null) + { + _textResizeGhost = new Image { Stretch = Stretch.Fill, IsHitTestVisible = false }; + Canvas.SetZIndex(_textResizeGhost, 10); + _overlay.Children.Add(_textResizeGhost); + } + _textResizeGhost.Source = src; + _textResizeGhost.Width = box.W; + _textResizeGhost.Height = box.H; + Canvas.SetLeft(_textResizeGhost, box.X); + Canvas.SetTop(_textResizeGhost, box.Y); + } + catch (Exception ex) + { + // Preview only: the resize still applies on release. + App.LogError(ex, "UpdateTextResizeGhost"); + } + return outline; + } + private void TearDownDragGhost() { + if (_textResizeGhost is not null) _overlay.Children.Remove(_textResizeGhost); + _textResizeGhost = null; if (_dragGhost is not null) _overlay.Children.Remove(_dragGhost); if (_dragGhostBorder is not null) _overlay.Children.Remove(_dragGhostBorder); _dragGhost = null; @@ -2771,6 +2988,10 @@ private void EndDrag() case DragMode.ResizeNE: case DragMode.ResizeSW: case DragMode.ResizeSE: + case DragMode.ResizeW: + case DragMode.ResizeE: + case DragMode.ResizeN: + case DragMode.ResizeS: ApplyResize(mode, _lastDragPoint); break; case DragMode.Rotate: @@ -2938,6 +3159,60 @@ public void SetSelectionWidth(float width) Context.SelectionChanged?.Invoke(); } + // True when the selection holds handwriting that can be turned into text. + public bool SelectionHasPenInk + { + get + { + if (Context.SelectedStrokeIds.Count == 0) return false; + var sel = new HashSet(Context.SelectedStrokeIds); + return Page.Strokes.Any(s => s.Kind == StrokeKind.Pen && sel.Contains(s.Id)); + } + } + + // The selected pen strokes, in the order they were written (the handwriting + // recognizer relies on that order). Highlighter strokes are left out. + public List SelectedPenStrokes() + { + var sel = new HashSet(Context.SelectedStrokeIds); + return Page.Strokes.Where(s => s.Kind == StrokeKind.Pen && sel.Contains(s.Id)).ToList(); + } + + // Swaps the selected pen ink for a text box holding `text`, placed where the + // ink was. Other selected items (highlighter, shapes, text, images) stay. + // One undoable mutation; the new text box ends up selected. + public bool ReplaceSelectedPenInkWithText(string text, Color color, float fontSize) + { + var pen = SelectedPenStrokes(); + if (pen.Count == 0 || string.IsNullOrWhiteSpace(text)) return false; + bool hadOld = SelectionBbox(out var oldRegion); + + var ink = Bbox.Of(pen[0]); + foreach (var s in pen.Skip(1)) ink = Bbox.Union(ink, Bbox.Of(s)); + + var ids = new HashSet(pen.Select(s => s.Id)); + Page.Strokes.RemoveAll(s => ids.Contains(s.Id)); + Context.SelectedStrokeIds.RemoveAll(ids.Contains); + + var t = new TextElement + { + X = ink.X, Y = ink.Y, + Width = Math.Max(ink.W + 24, 160), + Text = text.Trim(), Color = color, + FontSize = Math.Clamp(fontSize, 10f, 96f), + }; + t.Height = Math.Max(PageRenderer.MeasureTextHeight(t) + 8, t.FontSize * 1.5); + Page.Texts.Add(t); + Context.SelectedTextIds.Add(t.Id); + + Context.Mutated?.Invoke(); + Context.SelectionChanged?.Invoke(); + var dirty = Bbox.Of(t); + if (hadOld) dirty = Bbox.Union(dirty, oldRegion); + InvalidateSelectionRegion(dirty, pen.Max(s => s.Width)); + return true; + } + public void DuplicateSelection(float offsetX = 24, float offsetY = 24) { var newStrokeIds = new List(); @@ -3389,9 +3664,11 @@ public void EndInlineTextEdit(bool commit) var t = Page.Texts.FirstOrDefault(x => x.Id == _editorTextId); if (commit && t is not null) { - t.Text = _editor.Text ?? ""; + t.Text = (_editor.Text ?? "").Replace("\r\n", "\n").Replace('\r', '\n'); t.Width = Math.Max(_editor.ActualWidth, t.Width); - t.Height = Math.Max(_editor.ActualHeight, t.Height); + // Fit the height to the text: grows for new lines, shrinks when + // text was deleted or the font made smaller. + t.Height = FitTextHeight(t); } if (commit && t is not null && string.IsNullOrWhiteSpace(t.Text)) { @@ -4064,19 +4341,26 @@ private void UpdateExtTooltip(double amount) // to resize all internal canvases to the new page dimensions. public void ResizeCanvas() { - double newW = Page.Width; + double newW = Page.Width, newH = Page.Height; _canvas.Width = newW; _overlay.Width = newW; + _canvas.Height = newH; + _overlay.Height = newH; var root = (Grid)Content; root.Width = newW; + root.Height = newH; Width = newW; + Height = newH; // Background placement changed — the hi-res crop rect is stale. ClearHiResBackground(); - // Reposition right handle for new width. + // Reposition right handle for new width; both stay centred vertically. if (_rightExtHandle is not null) Canvas.SetLeft(_rightExtHandle, newW - ExtHandleWidth); + double centerY = (newH - ExtHandleHeight) / 2; + if (_leftExtHandle is not null) Canvas.SetTop(_leftExtHandle, centerY); + if (_rightExtHandle is not null) Canvas.SetTop(_rightExtHandle, centerY); _canvas.Invalidate(); } diff --git a/src/YuNotes/MainWindow.xaml b/src/YuNotes/MainWindow.xaml index 939ca3e..5f376c1 100644 --- a/src/YuNotes/MainWindow.xaml +++ b/src/YuNotes/MainWindow.xaml @@ -4,6 +4,6 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> - + diff --git a/src/YuNotes/MainWindow.xaml.cs b/src/YuNotes/MainWindow.xaml.cs index 93cbc1e..157a72d 100644 --- a/src/YuNotes/MainWindow.xaml.cs +++ b/src/YuNotes/MainWindow.xaml.cs @@ -1,5 +1,8 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Runtime.InteropServices; using Microsoft.UI; using Microsoft.UI.Composition.SystemBackdrops; using Microsoft.UI.Windowing; @@ -16,8 +19,59 @@ public sealed partial class MainWindow : Window { private readonly AppWindow _appWindow; - public MainWindow() + // ─── Windows ──────────────────────────────────────────────────────────────── + // YuNotes can have several windows, each with its own set of editor tabs. + // A note is open in at most one window: opening it again (from Home, the + // + menu or Explorer) switches to the window and tab that already has it. + + private static readonly List s_windows = new(); + + // Every open window, most recently used last. + public static IReadOnlyList All => s_windows; + + // The window the user last worked in. + public static MainWindow? Active => s_windows.Count > 0 ? s_windows[^1] : null; + + // This window's editor tabs. They outlive the editor page, so going Home + // and back keeps them. + internal EditorTabs Tabs { get; } + + // The window an element (or a page, through its frame) belongs to. + public static MainWindow? Of(UIElement? element) { + if (element is Microsoft.UI.Xaml.Controls.Page { Frame: { } f } + && s_windows.FirstOrDefault(w => ReferenceEquals(w.RootFrame, f)) is { } byFrame) + return byFrame; + if (element?.XamlRoot is { } root + && s_windows.FirstOrDefault(w => ReferenceEquals(w.Content?.XamlRoot, root)) is { } byRoot) + return byRoot; + return Active; + } + + // The window and tab holding `path`, if any window has it open. + internal static (MainWindow Window, OpenTab Tab)? FindOpenTab(string path) + { + foreach (var w in s_windows) + if (w.Tabs.Find(path) is { } t) return (w, t); + return null; + } + + public MainWindow() : this(null) { } + + // `tabs`: start in the editor with these tabs (a tab dragged out of another + // window), instead of on Home. + internal MainWindow(EditorTabs? tabs) + { + Tabs = tabs ?? new EditorTabs(); + s_windows.Add(this); + Activated += (_, e) => + { + if (e.WindowActivationState == WindowActivationState.Deactivated) return; + s_windows.Remove(this); + s_windows.Add(this); + }; + Closed += (_, __) => s_windows.Remove(this); + InitializeComponent(); Title = "YuNotes"; @@ -68,9 +122,60 @@ public MainWindow() e.Handled = true; }; - RootFrame.Navigate(typeof(HomePage)); + if (tabs is not null && tabs.List.Count > 0) RootFrame.Navigate(typeof(EditorPage), EditorResume.Instance); + else RootFrame.Navigate(typeof(HomePage)); } + // Opens a note file (from Explorer or a second launch of YuNotes): switches + // to it where it is already open, otherwise adds it as a tab in the window + // last used. + public static void OpenFile(string path) + { + if (FindOpenTab(path) is { } open) + { + open.Window.ShowTab(open.Tab.Path); + return; + } + var w = Active ?? new MainWindow(); + if (w.RootFrame.Content is EditorPage editor) _ = editor.OpenInNewTabAsync(path); + else w.NavigateTo(new EditorTabRequest(path), new SuppressNavigationTransitionInfo()); + w.BringToFront(); + } + + // Brings this window forward and shows the tab holding `path`. + internal void ShowTab(string path) + { + if (RootFrame.Content is EditorPage editor) _ = editor.SwitchToPathAsync(path); + else NavigateTo(new EditorTabRequest(path), new SuppressNavigationTransitionInfo()); + BringToFront(); + } + + public void BringToFront() + { + if (_appWindow.Presenter is OverlappedPresenter { State: OverlappedPresenterState.Minimized } op) op.Restore(); + Activate(); + SetForegroundWindow(WindowNative.GetWindowHandle(this)); + } + + // Places the window with its top-left corner near the mouse pointer (a tab + // dragged out lands where it was dropped), at the given size. + internal void PlaceAtCursor(Windows.Graphics.SizeInt32 size) + { + if (size.Width > 200 && size.Height > 200) _appWindow.Resize(size); + if (GetCursorPos(out var p)) _appWindow.Move(new Windows.Graphics.PointInt32(p.X - 120, p.Y - 16)); + } + + internal Windows.Graphics.SizeInt32 Size => _appWindow.Size; + + [StructLayout(LayoutKind.Sequential)] + private struct POINT { public int X, Y; } + + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out POINT p); + + [DllImport("user32.dll")] + private static extern bool SetForegroundWindow(IntPtr hwnd); + // Set once the user has resolved the unsaved-changes prompt (Save or Don't save), // so the re-issued Close() sails through instead of re-prompting. private bool _closeConfirmed; @@ -112,15 +217,25 @@ private void ApplyThemeFromSettings() // it (NavigationThemeTransition reverses it for NavigationMode.Back). private readonly System.Collections.Generic.Stack _transitionStack = new(); - public static void Navigate(object? parameter = null, NavigationTransitionInfo? transition = null) + // Navigates the window `owner` sits in. + public static void Navigate(UIElement owner, object? parameter = null, NavigationTransitionInfo? transition = null) + where T : Microsoft.UI.Xaml.Controls.Page + => Of(owner)?.NavigateTo(parameter, transition); + + public void NavigateTo(object? parameter = null, NavigationTransitionInfo? transition = null) where T : Microsoft.UI.Xaml.Controls.Page { - if (App.MainWindow is MainWindow mw) + // A note that is already open in another window: go there instead of + // opening a second, separately edited copy. + if (typeof(T) == typeof(EditorPage) && EditorPage.PathOf(parameter) is { } path + && FindOpenTab(path) is { } open && !ReferenceEquals(open.Window, this)) { - mw._navTheme.DefaultNavigationTransitionInfo = transition ?? new EntranceNavigationTransitionInfo(); - mw._transitionStack.Push(transition); - mw.RootFrame.Navigate(typeof(T), parameter); + open.Window.ShowTab(open.Tab.Path); + return; } + _navTheme.DefaultNavigationTransitionInfo = transition ?? new EntranceNavigationTransitionInfo(); + _transitionStack.Push(transition); + RootFrame.Navigate(typeof(T), parameter); } // The system caption buttons are drawn over our content; keep their chrome @@ -151,7 +266,7 @@ private void UpdateCaptionButtonColors() // as the window drag region while that page is shown. public static void SetDragRegion(UIElement element) { - if (App.MainWindow is MainWindow mw) mw.SetTitleBar(element); + if (Of(element) is MainWindow mw) mw.SetTitleBar(element); } // Carves interactive rects out of the SetTitleBar drag region so they get @@ -160,9 +275,9 @@ public static void SetDragRegion(UIElement element) // AppWindow resolved from this window's HWND in the constructor: going // through App.MainWindow.AppWindow instead threw a NullReferenceException // on every editor open, leaving the title unclickable. - public static void SetTitleBarPassthrough(params Windows.Graphics.RectInt32[] rects) + public static void SetTitleBarPassthrough(UIElement owner, params Windows.Graphics.RectInt32[] rects) { - if (App.MainWindow is not MainWindow mw) return; + if (Of(owner) is not MainWindow mw) return; var src = Microsoft.UI.Input.InputNonClientPointerSource.GetForWindowId(mw._appWindow.Id) ?? throw new InvalidOperationException( $"InputNonClientPointerSource.GetForWindowId returned null for window {mw._appWindow.Id.Value}"); @@ -172,29 +287,26 @@ public static void SetTitleBarPassthrough(params Windows.Graphics.RectInt32[] re // Presentation mode: full screen hides the taskbar and caption buttons; // switching back to the overlapped presenter restores the previous size // and maximized state. - public static void SetFullScreen(bool on) + public static void SetFullScreen(UIElement owner, bool on) { - if (App.MainWindow is not MainWindow mw) return; + if (Of(owner) is not MainWindow mw) return; mw._appWindow.SetPresenter(on ? AppWindowPresenterKind.FullScreen : AppWindowPresenterKind.Overlapped); } // Width in DIPs the caption buttons occupy at the window's top-right. Pages // pad their top bars by this so content doesn't sit under min/max/close. - public static double CaptionButtonInset + public static double CaptionButtonInset(UIElement owner) { - get - { - if (App.MainWindow is not MainWindow mw) return 138; - var tb = mw._appWindow.TitleBar; - double scale = mw.RootGrid.XamlRoot?.RasterizationScale ?? 1.0; - if (tb is null || tb.RightInset <= 0 || scale <= 0) return 138; - return tb.RightInset / scale; - } + if (Of(owner) is not MainWindow mw) return 138; + var tb = mw._appWindow.TitleBar; + double scale = mw.RootGrid.XamlRoot?.RasterizationScale ?? 1.0; + if (tb is null || tb.RightInset <= 0 || scale <= 0) return 138; + return tb.RightInset / scale; } - public static void GoBack() + public static void GoBack(UIElement owner) { - if (App.MainWindow is MainWindow mw) + if (Of(owner) is MainWindow mw) { if (mw.RootFrame.CanGoBack) { diff --git a/src/YuNotes/Models/Document.cs b/src/YuNotes/Models/Document.cs index e1e1d35..d1951d3 100644 --- a/src/YuNotes/Models/Document.cs +++ b/src/YuNotes/Models/Document.cs @@ -80,6 +80,8 @@ public sealed class NotePage public int? SourcePageIndex { get; set; } // Bookmark label ("Theorem", "Exam", …) shown in the page panel; null = none. public string? Bookmark { get; set; } + // Blank space inserted into the page (see PageGaps). Empty = none. + public List Gaps { get; } = new(); public List Strokes { get; } = new(); public List Shapes { get; } = new(); public List Texts { get; } = new(); diff --git a/src/YuNotes/Models/PageGaps.cs b/src/YuNotes/Models/PageGaps.cs new file mode 100644 index 0000000..48f5d66 --- /dev/null +++ b/src/YuNotes/Models/PageGaps.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace YuNotes.Models; + +// Blank space inserted into a page, e.g. between two questions on an imported +// exercise sheet so there is room to write the answer. The page grows by +// Size; the background (PDF) is split at At and the part below moves down. +// +// At is measured on the background as it was imported (before any space was +// inserted), so a gap stays at the same line of the PDF however many other +// gaps are added above it. +public sealed class PageGap +{ + public double At { get; set; } + public double Size { get; set; } +} + +public static class PageGaps +{ + // Below this a gap is treated as gone. + private const double MinSize = 0.5; + + public static bool Any(NotePage p) => p.Gaps.Count > 0; + + public static double Total(NotePage p) + { + double t = 0; + foreach (var g in p.Gaps) t += g.Size; + return t; + } + + // Height of the background without the inserted space. + public static double BackgroundHeight(NotePage p) => Math.Max(1, p.Height - Total(p)); + + private static IEnumerable Ordered(NotePage p) => p.Gaps.OrderBy(g => g.At); + + // Pieces of the background and where each is drawn: background rows + // SrcY..SrcY+SrcH go to page rows DstY..DstY+SrcH. One piece when the page + // has no gaps. + public static List<(double SrcY, double SrcH, double DstY)> Segments(NotePage p) + { + var list = new List<(double, double, double)>(); + double h = BackgroundHeight(p), src = 0, shift = 0; + foreach (var g in Ordered(p)) + { + double at = Math.Clamp(g.At, 0, h); + if (at > src) list.Add((src, at - src, src + shift)); + src = Math.Max(src, at); + shift += g.Size; + } + if (h > src) list.Add((src, h - src, src + shift)); + return list; + } + + // The inserted space, as page rows. + public static List<(double Y, double H)> GapRows(NotePage p) + { + var list = new List<(double, double)>(); + double shift = 0; + foreach (var g in Ordered(p)) + { + list.Add((g.At + shift, g.Size)); + shift += g.Size; + } + return list; + } + + // Background row → page row. + public static double ToPage(NotePage p, double bgY) + { + double shift = 0; + foreach (var g in Ordered(p)) + { + if (g.At > bgY) break; + shift += g.Size; + } + return bgY + shift; + } + + // Page row → background row. A row inside inserted space maps to the line + // the space was opened at. + public static double ToBackground(NotePage p, double pageY) + { + double shift = 0; + foreach (var g in Ordered(p)) + { + double top = g.At + shift; + if (pageY < top) break; + if (pageY < top + g.Size) return g.At; + shift += g.Size; + } + return pageY - shift; + } + + // Opens `amount` of blank space at page row `pageY`: everything below moves + // down and the page grows. Space opened inside existing space widens it. + public static void Insert(NotePage p, double pageY, double amount) + { + if (!(amount > 0)) return; + double at = ToBackground(p, pageY); + var same = p.Gaps.FirstOrDefault(g => Math.Abs(g.At - at) < 0.5); + if (same is not null) same.Size += amount; + else p.Gaps.Add(new PageGap { At = at, Size = amount }); + p.Height += amount; + ShiftElements(p, y => y >= pageY ? amount : 0); + foreach (var r in p.TextRuns) + if (r.Y >= pageY) r.Y += amount; + } + + // Removes inserted space between page rows `top` and `bottom` (only space, + // never the background). Things below move up; anything that was written + // inside the removed space moves up to where it started. Returns how much + // was removed. + public static double Remove(NotePage p, double top, double bottom) + { + if (bottom < top) (top, bottom) = (bottom, top); + var removed = new List<(double Y, double H)>(); + double shift = 0; + foreach (var g in Ordered(p).ToList()) + { + double gTop = g.At + shift, gBottom = gTop + g.Size; + shift += g.Size; + double a = Math.Max(top, gTop), b = Math.Min(bottom, gBottom); + if (b - a <= 0) continue; + removed.Add((a, b - a)); + g.Size -= b - a; + if (g.Size < MinSize) p.Gaps.Remove(g); + } + double total = removed.Sum(r => r.H); + if (total <= 0) return 0; + + double RemovedAbove(double y) + { + double s = 0; + foreach (var (ry, rh) in removed) + if (y > ry) s += Math.Min(rh, y - ry); + return s; + } + p.Height = Math.Max(1, p.Height - total); + ShiftElements(p, y => -RemovedAbove(y)); + foreach (var r in p.TextRuns) r.Y -= RemovedAbove(r.Y); + return total; + } + + // Moves each element down by dy(its vertical centre). Elements move whole, + // so ink that crosses the line keeps its shape. + private static void ShiftElements(NotePage p, Func dy) + { + foreach (var s in p.Strokes) + { + if (s.Points.Count == 0) continue; + float min = float.MaxValue, max = float.MinValue; + foreach (var pt in s.Points) { if (pt.Y < min) min = pt.Y; if (pt.Y > max) max = pt.Y; } + float d = (float)dy((min + max) / 2.0); + if (d == 0) continue; + for (int i = 0; i < s.Points.Count; i++) + { + var pt = s.Points[i]; + s.Points[i] = new InkPoint(pt.X, pt.Y + d, pt.Pressure); + } + } + foreach (var sh in p.Shapes) + { + double min = Math.Min(sh.Y1, sh.Y2), max = Math.Max(sh.Y1, sh.Y2); + if (sh.Kind == ShapeKind.Triangle) { min = Math.Min(min, sh.Y3); max = Math.Max(max, sh.Y3); } + float d = (float)dy((min + max) / 2.0); + if (d == 0) continue; + sh.Y1 += d; sh.Y2 += d; + if (sh.Kind == ShapeKind.Triangle) sh.Y3 += d; + } + foreach (var t in p.Texts) + t.Y += dy(t.Y + t.Height / 2); + foreach (var im in p.Images) + im.Y += dy(im.Y + im.Height / 2); + } + + public static List Clone(IEnumerable gaps) => + gaps.Select(g => new PageGap { At = g.At, Size = g.Size }).ToList(); + + public static string? ToJson(NotePage p) => + p.Gaps.Count == 0 ? null : System.Text.Json.JsonSerializer.Serialize(p.Gaps); + + public static void FromJson(NotePage p, string? json) + { + p.Gaps.Clear(); + if (string.IsNullOrEmpty(json)) return; + try + { + var list = System.Text.Json.JsonSerializer.Deserialize>(json); + if (list is not null) + p.Gaps.AddRange(list.Where(g => double.IsFinite(g.At) && double.IsFinite(g.Size) && g.Size >= MinSize)); + } + catch { } + } +} diff --git a/src/YuNotes/Program.cs b/src/YuNotes/Program.cs new file mode 100644 index 0000000..343cd36 --- /dev/null +++ b/src/YuNotes/Program.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.Windows.AppLifecycle; + +namespace YuNotes; + +// Single instance: the first YuNotes registers itself; any later launch +// (opening a .pdf / .yunote from Explorer, or starting YuNotes again) hands its +// activation to that one and exits. The running YuNotes then opens the file as +// a tab, or opens a new window for a plain launch (see App.OnRedirected). +public static class Program +{ + private const string InstanceKey = "YuNotes.Main"; + + [STAThread] + private static int Main(string[] args) + { + WinRT.ComWrappersSupport.InitializeComWrappers(); + if (TryRedirectToRunningInstance()) return 0; + + Application.Start(p => + { + var context = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread()); + SynchronizationContext.SetSynchronizationContext(context); + _ = new App(); + }); + return 0; + } + + // True when another YuNotes is running and has taken this activation. + private static bool TryRedirectToRunningInstance() + { + AppInstance key; + AppActivationArguments args; + try + { + args = AppInstance.GetCurrent().GetActivatedEventArgs(); + key = AppInstance.FindOrRegisterForKey(InstanceKey); + } + catch { return false; } // can't tell: just run normally + if (key.IsCurrent) return false; + + try + { + // Let the running instance bring its window to the front. + AllowSetForegroundWindow(key.ProcessId); + // Redirecting is async and this is an STA thread: wait on a + // separate thread while still pumping COM calls here. + var done = CreateEvent(IntPtr.Zero, true, false, null); + Task.Run(() => + { + try { key.RedirectActivationToAsync(args).AsTask().Wait(); } + catch { } + SetEvent(done); + }); + const uint CWMO_DEFAULT = 0, INFINITE = 0xFFFFFFFF; + CoWaitForMultipleObjects(CWMO_DEFAULT, INFINITE, 1, new[] { done }, out _); + CloseHandle(done); + return true; + } + catch { return false; } + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr CreateEvent(IntPtr attributes, bool manualReset, bool initialState, string? name); + + [DllImport("kernel32.dll")] + private static extern bool SetEvent(IntPtr handle); + + [DllImport("kernel32.dll")] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("ole32.dll")] + private static extern uint CoWaitForMultipleObjects(uint flags, uint timeout, ulong count, IntPtr[] handles, out uint index); + + [DllImport("user32.dll")] + private static extern bool AllowSetForegroundWindow(uint processId); +} diff --git a/src/YuNotes/Rendering/PageRenderer.cs b/src/YuNotes/Rendering/PageRenderer.cs index 24fdb50..9388abd 100644 --- a/src/YuNotes/Rendering/PageRenderer.cs +++ b/src/YuNotes/Rendering/PageRenderer.cs @@ -170,18 +170,45 @@ public void DrawPage(CanvasDrawingSession ds, ICanvasResourceCreator dev, NotePa // when it fully covers the dirty region the base blit underneath is // entirely painted over — skip the expensive cubic upscale of the // full-page bitmap. - bool hiResCoversClip = hiResBackground is not null && hiResRect is { } cover && + bool gaps = PageGaps.Any(page); + bool hiResCoversClip = !gaps && hiResBackground is not null && hiResRect is { } cover && clip is { } cr && cover.X <= cr.X + 0.01 && cover.Y <= cr.Y + 0.01 && cover.Right >= cr.Right - 0.01 && cover.Bottom >= cr.Bottom - 0.01; + // Inserted space splits the background into pieces, each drawn + // at its own row; without gaps this is one piece, the whole page. + var segments = PageGaps.Segments(page); + double bgH = PageGaps.BackgroundHeight(page); if (!hiResCoversClip) { - // Cubic resampling keeps PDF text edges noticeably cleaner than - // the default linear filter when the bitmap is scaled. - ds.DrawImage(backgroundBitmap, new Rect(bgLeft, 0, bgW, page.Height), - backgroundBitmap.Bounds, 1f, CanvasImageInterpolation.HighQualityCubic); + var bmpH = backgroundBitmap.Bounds.Height; + var bmpW = backgroundBitmap.Bounds.Width; + foreach (var (srcY, srcH, dstY) in segments) + { + if (clip is { } sc && (dstY > sc.Bottom || dstY + srcH < sc.Y)) continue; + // Cubic resampling keeps PDF text edges noticeably cleaner than + // the default linear filter when the bitmap is scaled. + ds.DrawImage(backgroundBitmap, new Rect(bgLeft, dstY, bgW, srcH), + new Rect(0, srcY / bgH * bmpH, bmpW, srcH / bgH * bmpH), + 1f, CanvasImageInterpolation.HighQualityCubic); + } } - if (hiResBackground is not null && hiResRect is { } hr) + if (hiResBackground is not null && hiResRect is { } hg && gaps) + { + // The crop covers background rows hg.Y..hg.Bottom: draw the part + // of it that falls in each piece. + var px = hiResBackground.Bounds; + foreach (var (srcY, srcH, dstY) in segments) + { + double a = Math.Max(hg.Y, srcY), b = Math.Min(hg.Bottom, srcY + srcH); + if (b <= a) continue; + ds.DrawImage(hiResBackground, + new Rect(hg.X, dstY + (a - srcY), hg.Width, b - a), + new Rect(0, (a - hg.Y) / hg.Height * px.Height, px.Width, (b - a) / hg.Height * px.Height), + 1f, CanvasImageInterpolation.HighQualityCubic); + } + } + else if (hiResBackground is not null && hiResRect is { } hr) { // The crop is rendered at the backing-store scale, so this blit // is normally ~1:1, where linear is visually identical to (and @@ -210,6 +237,10 @@ clip is { } cr && if (totalWidth - pdfRight > 0.5f) using (ds.CreateLayer(1f, new Rect(pdfRight, 0, totalWidth - pdfRight, page.Height))) _templates.DrawTemplate(ds, totalWidth, page.Height, template); + // Inserted space is YuNotes' own too. + foreach (var (gy, gh) in PageGaps.GapRows(page)) + using (ds.CreateLayer(1f, new Rect(pdfLeft, gy, Math.Max(0, pdfRight - pdfLeft), gh))) + _templates.DrawTemplate(ds, totalWidth, page.Height, template); } else { @@ -752,6 +783,20 @@ private static CanvasTextFormat CreateTextFormat(TextElement t) }; } + // Height the text box needs to show all of its text at its current width, + // laid out exactly as DrawText lays it out. + public static double MeasureTextHeight(TextElement t) + { + if (!IsFinite(t.Width) || t.Width <= 0) return t.Height; + try + { + using var fmt = CreateTextFormat(t); + using var layout = new CanvasTextLayout(CanvasDevice.GetSharedDevice(), t.Text ?? "", fmt, (float)t.Width, 100000f); + return layout.LayoutBounds.Height; + } + catch { return t.Height; } + } + private void DrawText(CanvasDrawingSession ds, TextElement t) { if (!IsDrawableText(t)) return; diff --git a/src/YuNotes/Rendering/PdfVectorWriter.cs b/src/YuNotes/Rendering/PdfVectorWriter.cs index 2b302fb..f86cbc7 100644 --- a/src/YuNotes/Rendering/PdfVectorWriter.cs +++ b/src/YuNotes/Rendering/PdfVectorWriter.cs @@ -109,7 +109,22 @@ private static void DrawBackground(XGraphics gfx, PageVectorExport e) double bgLeft = page.BackgroundLeft; double bgW = page.BackgroundContentWidth > 0 ? page.BackgroundContentWidth : w - bgLeft; if (page.BackgroundPng is { Length: > 0 } bg && bgW > 0) - DrawPng(gfx, bg, bgLeft, 0, bgW, h); + { + if (!PageGaps.Any(page)) DrawPng(gfx, bg, bgLeft, 0, bgW, h); + else + { + // Inserted space: draw the background once per piece, shifted + // to its row and clipped to it. + double bgH = PageGaps.BackgroundHeight(page); + foreach (var (srcY, srcH, dstY) in PageGaps.Segments(page)) + { + var st = gfx.Save(); + gfx.IntersectClip(new XRect(bgLeft, dstY, bgW, srcH)); + DrawPng(gfx, bg, bgLeft, dstY - srcY, bgW, bgH); + gfx.Restore(st); + } + } + } var t = e.Template; if (t.SkipImportedPdf && PageRenderer.HasImportedPdf(page)) @@ -119,6 +134,8 @@ private static void DrawBackground(XGraphics gfx, PageVectorExport e) double pdfRight = bgLeft + bgW; if (bgLeft > 0.5) DrawTemplateClipped(gfx, w, h, t, new XRect(0, 0, bgLeft, h)); if (w - pdfRight > 0.5) DrawTemplateClipped(gfx, w, h, t, new XRect(pdfRight, 0, w - pdfRight, h)); + foreach (var (gy, gh) in PageGaps.GapRows(page)) + DrawTemplateClipped(gfx, w, h, t, new XRect(bgLeft, gy, bgW, gh)); } else { @@ -126,6 +143,30 @@ private static void DrawBackground(XGraphics gfx, PageVectorExport e) } } + // On a page rebuilt from an imported PDF page (widened, or with space + // inserted): the template on the parts YuNotes added — the strips beside + // the PDF and the inserted space — never over the PDF itself, matching + // what the editor shows. Drawn under the notes. + public static void DrawOwnedTemplate(XGraphics gfx, NotePage page, TemplateSettings t, + double targetWidth, double targetHeight) + { + double w = page.Width, h = page.Height; + if (t.Kind == TemplateKind.Blank || !(w > 0) || !(h > 0) || !IsFinite(w) || !IsFinite(h)) return; + double bgLeft = page.BackgroundLeft; + double bgW = page.BackgroundContentWidth > 0 ? page.BackgroundContentWidth : w - bgLeft; + double pdfRight = bgLeft + bgW; + var state = gfx.Save(); + try + { + gfx.ScaleTransform(targetWidth / w, targetHeight / h); + if (bgLeft > 0.5) DrawTemplateClipped(gfx, w, h, t, new XRect(0, 0, bgLeft, h)); + if (w - pdfRight > 0.5) DrawTemplateClipped(gfx, w, h, t, new XRect(pdfRight, 0, w - pdfRight, h)); + foreach (var (gy, gh) in PageGaps.GapRows(page)) + DrawTemplateClipped(gfx, w, h, t, new XRect(bgLeft, gy, bgW, gh)); + } + finally { gfx.Restore(state); } + } + private static void DrawTemplateClipped(XGraphics gfx, double w, double h, TemplateSettings t, XRect clip) { var s = gfx.Save(); diff --git a/src/YuNotes/Services/DocumentService.cs b/src/YuNotes/Services/DocumentService.cs index 051fc2e..b55c45b 100644 --- a/src/YuNotes/Services/DocumentService.cs +++ b/src/YuNotes/Services/DocumentService.cs @@ -195,7 +195,7 @@ private static void WritePdf(Document doc, YuNotes.Rendering.PageVectorExport?[] var srcIdx = new int?[doc.Pages.Count]; for (int i = 0; i < doc.Pages.Count; i++) srcIdx[i] = doc.Pages[i].SourcePageIndex; container.WriteWithSource(pages, widths, heights, srcIdx, src, blob, pdfPath, - reusePageIndices, previousContainer); + reusePageIndices, previousContainer, new List(doc.Pages)); } else { @@ -238,6 +238,7 @@ public static Document CloneForSave(Document d) TemplateOverride = CloneTemplate(p.TemplateOverride), Bookmark = p.Bookmark }; + np.Gaps.AddRange(PageGaps.Clone(p.Gaps)); foreach (var st in p.Strokes) { var sc = new Stroke { Id = st.Id, Kind = st.Kind, Color = st.Color, Width = st.Width, PressureMode = st.PressureMode }; @@ -521,8 +522,8 @@ public Document Open(string path, bool forIndex = false) using (var cmd = conn.CreateCommand()) { cmd.CommandText = forIndex - ? "SELECT id,idx,width,height,NULL AS background_png,template_json,source_page_index,background_left,background_width,bookmark FROM page ORDER BY idx" - : "SELECT id,idx,width,height,background_png,template_json,source_page_index,background_left,background_width,bookmark FROM page ORDER BY idx"; + ? "SELECT id,idx,width,height,NULL AS background_png,template_json,source_page_index,background_left,background_width,bookmark,gaps_json FROM page ORDER BY idx" + : "SELECT id,idx,width,height,background_png,template_json,source_page_index,background_left,background_width,bookmark,gaps_json FROM page ORDER BY idx"; using var r = cmd.ExecuteReader(); while (r.Read()) { @@ -543,6 +544,7 @@ public Document Open(string path, bool forIndex = false) if (!r.IsDBNull(7)) p.BackgroundLeft = r.GetDouble(7); if (!r.IsDBNull(8)) p.BackgroundContentWidth = r.GetDouble(8); if (!r.IsDBNull(9)) p.Bookmark = r.GetString(9); + if (!r.IsDBNull(10)) PageGaps.FromJson(p, r.GetString(10)); doc.Pages.Add(p); pagesById[p.Id] = p; } @@ -676,8 +678,8 @@ private static void WriteAll(SqliteConnection conn, Document doc) p.Index = i; using (var cmd = conn.CreateCommand()) { - cmd.CommandText = @"INSERT INTO page(id,idx,width,height,background_png,template_json,source_page_index,background_left,background_width,bookmark) - VALUES($id,$i,$w,$h,$bg,$tpl,$src,$bl,$bw,$bm)"; + cmd.CommandText = @"INSERT INTO page(id,idx,width,height,background_png,template_json,source_page_index,background_left,background_width,bookmark,gaps_json) + VALUES($id,$i,$w,$h,$bg,$tpl,$src,$bl,$bw,$bm,$gaps)"; cmd.Parameters.AddWithValue("$id", p.Id); cmd.Parameters.AddWithValue("$i", p.Index); cmd.Parameters.AddWithValue("$w", p.Width); @@ -689,6 +691,7 @@ private static void WriteAll(SqliteConnection conn, Document doc) cmd.Parameters.AddWithValue("$bl", p.BackgroundLeft); cmd.Parameters.AddWithValue("$bw", p.BackgroundContentWidth); cmd.Parameters.AddWithValue("$bm", (object?)p.Bookmark ?? DBNull.Value); + cmd.Parameters.AddWithValue("$gaps", (object?)PageGaps.ToJson(p) ?? DBNull.Value); cmd.ExecuteNonQuery(); } foreach (var s in p.Strokes) @@ -766,6 +769,7 @@ private static void EnsureSchema(SqliteConnection c) try { Exec(c, "ALTER TABLE page ADD COLUMN background_left REAL DEFAULT 0"); } catch { } try { Exec(c, "ALTER TABLE page ADD COLUMN background_width REAL DEFAULT 0"); } catch { } try { Exec(c, "ALTER TABLE page ADD COLUMN bookmark TEXT"); } catch { } + try { Exec(c, "ALTER TABLE page ADD COLUMN gaps_json TEXT"); } catch { } Exec(c, @"CREATE TABLE IF NOT EXISTS stroke( id TEXT PRIMARY KEY, page_id TEXT, data BLOB)"); Exec(c, @"CREATE INDEX IF NOT EXISTS idx_stroke_page ON stroke(page_id)"); diff --git a/src/YuNotes/Services/HistoryService.cs b/src/YuNotes/Services/HistoryService.cs index ae8ea4e..5aa5194 100644 --- a/src/YuNotes/Services/HistoryService.cs +++ b/src/YuNotes/Services/HistoryService.cs @@ -189,6 +189,7 @@ public static DocSnapshot From(Document d, DocSnapshot? prev = null, NotePage? c BackgroundContentWidth = p.BackgroundContentWidth, TemplateOverride = CloneTemplate(p.TemplateOverride), Bookmark = p.Bookmark, + Gaps = PageGaps.Clone(p.Gaps), }; foreach (var st in p.Strokes) { @@ -279,6 +280,8 @@ public bool ApplyTo(Document d) p.BackgroundContentWidth = ps.BackgroundContentWidth; p.TemplateOverride = CloneTemplate(ps.TemplateOverride); p.Bookmark = ps.Bookmark; + p.Gaps.Clear(); + p.Gaps.AddRange(PageGaps.Clone(ps.Gaps)); p.Strokes.Clear(); foreach (var st in ps.Strokes) @@ -341,6 +344,7 @@ internal sealed class PageSnapshot public double BackgroundContentWidth; public TemplateSettings? TemplateOverride; public string? Bookmark; + public List Gaps = new(); public List Strokes = new(); public List Shapes = new(); public List Texts = new(); diff --git a/src/YuNotes/Services/PdfContainerService.cs b/src/YuNotes/Services/PdfContainerService.cs index 6d4292d..08804cd 100644 --- a/src/YuNotes/Services/PdfContainerService.cs +++ b/src/YuNotes/Services/PdfContainerService.cs @@ -26,7 +26,10 @@ static PdfContainerService() // Pages are only cloned for reuse from a container written the same way — // an older file's full-page raster flattens get re-written as vectors once. private const string FlattenFormatKey = "/YuNotesFlatten"; - private const string FlattenFormat = "vector-1"; + // vector-2: widened imported pages are written at their full width (they + // were squeezed into the original page size before), so pages saved by + // vector-1 are re-rendered once instead of reused. + private const string FlattenFormat = "vector-2"; // Each pages entry is drawn as vectors onto a white page (PdfVectorWriter); a // null entry yields a blank white page. @@ -61,20 +64,37 @@ public void Write(PageVectorExport?[] pages, double[] widths, double[] heights, public void WriteWithSource(PageVectorExport?[] overlays, double[] widths, double[] heights, int?[] sourceIndices, byte[] sourcePdfBytes, byte[]? embeddedData, string outputPath, - int?[]? reuseIndices = null, byte[]? previousContainer = null) + int?[]? reuseIndices = null, byte[]? previousContainer = null, + System.Collections.Generic.IReadOnlyList? notePages = null) { using var prev = OpenPrevious(previousContainer, reuseIndices); using var source = OpenSource(sourcePdfBytes); using var doc = new PdfDocument(); + // Opened only if a page was widened or had space inserted (see AddRebuiltSourcePage). + MemoryStream? formStream = null; + XPdfForm? form = null; for (int i = 0; i < overlays.Length; i++) { if (TryReusePage(doc, prev, reuseIndices, i)) continue; PdfPage page; var srcIdx = sourceIndices[i]; - if (srcIdx is int idx && idx >= 0 && idx < source.PageCount) + if (srcIdx is int idx && idx >= 0 && idx < source.PageCount + && notePages is not null && i < notePages.Count && NeedsRebuiltPage(notePages[i])) { - page = doc.AddPage(source.Pages[idx]); // clones the source page's vector content + formStream ??= new MemoryStream(sourcePdfBytes, 0, sourcePdfBytes.Length, writable: false, publiclyVisible: true); + form ??= XPdfForm.FromStream(formStream); + page = AddRebuiltSourcePage(doc, source.Pages[idx], form, idx, notePages[i]); + if (overlays[i] is { } withTemplate) + { + using var tg = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append); + PdfVectorWriter.DrawOwnedTemplate(tg, notePages[i], withTemplate.Template, + page.Width.Point, page.Height.Point); + } + } + else if (srcIdx is int idx2 && idx2 >= 0 && idx2 < source.PageCount) + { + page = doc.AddPage(source.Pages[idx2]); // clones the source page's vector content } else { @@ -92,6 +112,50 @@ public void WriteWithSource(PageVectorExport?[] overlays, double[] widths, doubl } Finish(doc, embeddedData, sourcePdfBytes, outputPath); + form?.Dispose(); + formStream?.Dispose(); + } + + // A source page that no longer has the original's size: widened to the + // left/right, or with blank space inserted. Cloning the original page + // would keep its old size and squeeze the notes into it, so these get a + // new page at the same scale as the original — wider and/or taller. + private static bool NeedsRebuiltPage(YuNotes.Models.NotePage note) + { + if (YuNotes.Models.PageGaps.Any(note)) return true; + if (note.BackgroundLeft > 0.5) return true; + return note.BackgroundContentWidth > 0 + && note.Width - note.BackgroundLeft - note.BackgroundContentWidth > 0.5; + } + + // The new page for NeedsRebuiltPage: the original page is drawn onto it + // (still as vectors, so its text stays selectable) at the PDF's place in + // the widened page, once per piece when space was inserted — each piece + // shifted down past the space above it and clipped to its own rows. + private static PdfPage AddRebuiltSourcePage(PdfDocument doc, PdfPage src, XPdfForm form, int srcIndex, + YuNotes.Models.NotePage note) + { + double srcW = src.Width.Point, srcH = src.Height.Point; + double bgLeft = note.BackgroundLeft; + double bgW = note.BackgroundContentWidth > 0 ? note.BackgroundContentWidth : note.Width - bgLeft; + double bgH = YuNotes.Models.PageGaps.BackgroundHeight(note); + if (!(bgW > 0) || !(bgH > 0)) return doc.AddPage(src); + double sx = srcW / bgW, sy = srcH / bgH; // points per page unit + + var page = doc.AddPage(); + page.Width = XUnit.FromPoint(note.Width * sx); + page.Height = XUnit.FromPoint(note.Height * sy); + form.PageIndex = srcIndex; + using var gfx = XGraphics.FromPdfPage(page); + gfx.DrawRectangle(XBrushes.White, 0, 0, page.Width.Point, page.Height.Point); + foreach (var (segY, segH, dstY) in YuNotes.Models.PageGaps.Segments(note)) + { + var st = gfx.Save(); + gfx.IntersectClip(new XRect(bgLeft * sx, dstY * sy, bgW * sx, segH * sy)); + gfx.DrawImage(form, bgLeft * sx, (dstY - segY) * sy, srcW, srcH); + gfx.Restore(st); + } + return page; } private static void Finish(PdfDocument doc, byte[]? embeddedData, byte[]? sourcePdfBytes, string outputPath) diff --git a/src/YuNotes/Services/SearchIndex.cs b/src/YuNotes/Services/SearchIndex.cs index 216b8db..b663d19 100644 --- a/src/YuNotes/Services/SearchIndex.cs +++ b/src/YuNotes/Services/SearchIndex.cs @@ -489,7 +489,7 @@ public async Task EnsureIndexedAsync(IEnumerable paths) if (readInk) page.Boxes.AddRange(await HandwritingRecognizer.RecognizeAsync(p.Strokes).ConfigureAwait(false)); if (p.SourcePageIndex is int si && si >= 0 && si < pdfPages.Count) - page.Boxes.AddRange(PdfBoxes(pdfPages[si], p.BackgroundLeft)); + page.Boxes.AddRange(PdfBoxes(pdfPages[si], p.BackgroundLeft, p)); page.Boxes.AddRange(TypedBoxes(p.Texts)); if (BookmarkBox(p) is { } bm) page.Boxes.Add(bm); entry.Pages.Add(page); @@ -497,11 +497,15 @@ public async Task EnsureIndexedAsync(IEnumerable paths) return entry; } - public static List PdfBoxes(IEnumerable runs, double shiftX) => + // `page`: place the words where the page shows them, below any space + // inserted above them. + public static List PdfBoxes(IEnumerable runs, double shiftX, NotePage? page = null) => runs.Select(r => new TextBox { T = r.Text, K = TextSource.Pdf, - X = (float)(r.X + shiftX), Y = (float)r.Y, W = (float)r.Width, H = (float)r.Height, + X = (float)(r.X + shiftX), + Y = (float)(page is not null && page.Gaps.Count > 0 ? PageGaps.ToPage(page, r.Y) : r.Y), + W = (float)r.Width, H = (float)r.Height, }).ToList(); // A page's bookmark label is searchable too; its match marks the page's diff --git a/src/YuNotes/Views/EditorPage.InkToText.cs b/src/YuNotes/Views/EditorPage.InkToText.cs new file mode 100644 index 0000000..fde7be3 --- /dev/null +++ b/src/YuNotes/Views/EditorPage.InkToText.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media; +using HandwritingRecognizer = YuNotes.Services.HandwritingRecognizer; +using RecognizedWord = YuNotes.Services.TextBox; +using DataPackage = Windows.ApplicationModel.DataTransfer.DataPackage; +using Clipboard = Windows.ApplicationModel.DataTransfer.Clipboard; + +namespace YuNotes.Views; + +public sealed partial class EditorPage +{ + // ─── Ink to text ──────────────────────────────────────────────────────────── + // Lasso some handwriting and choose "Convert to text" in the selection bar. + // Windows' handwriting recognizer (the one search already uses) reads it; + // the result opens in a dialog to fix up, then either replaces the ink with + // a text box in the same place (undoable) or goes to the clipboard. + + private bool _convertingInk; + + private void InitInkToText() + { + SelToTextBtn.Click += async (_, __) => await ConvertSelectionToTextAsync(); + } + + private async Task ConvertSelectionToTextAsync() + { + if (_doc is null || _convertingInk || !Canvas.SelectionHasPenInk) return; + var strokes = Canvas.SelectedPenStrokes(); + if (strokes.Count == 0) return; + + _convertingInk = true; + SelToTextBtn.IsEnabled = false; + List words; + try + { + if (!await Task.Run(() => HandwritingRecognizer.IsAvailable)) + { + await Notify("Handwriting recognition isn't available", + "Add a language with handwriting support in Windows Settings → Time & language → Language & region, then try again."); + return; + } + words = await HandwritingRecognizer.RecognizeAsync(strokes); + } + catch (Exception ex) + { + App.LogError(ex, "Converting handwriting to text"); + await Notify("Couldn't read the handwriting", ex.Message); + return; + } + finally + { + _convertingInk = false; + SelToTextBtn.IsEnabled = true; + } + + if (words.Count == 0) + { + await Notify("No words found", "The handwriting recognizer couldn't read any words in the selection."); + return; + } + + var text = JoinIntoLines(words); + var edited = await AskConvertedTextAsync(text); + if (edited is null) return; + + if (edited.Value.replace) + { + var color = strokes[0].Color; + float fontSize = EstimateFontSize(words); + if (Canvas.ReplaceSelectedPenInkWithText(edited.Value.text, color, fontSize)) + UpdateSelectionUi(); + } + else + { + var dp = new DataPackage(); + dp.SetText(edited.Value.text); + Clipboard.SetContent(dp); + ShowToast("Text copied"); + } + } + + // Returns the (possibly edited) text and whether to replace the ink with it + // (true) or copy it (false); null = cancelled or emptied. + private async Task<(string text, bool replace)?> AskConvertedTextAsync(string text) + { + var box = new TextBox + { + Text = text, + AcceptsReturn = true, + TextWrapping = TextWrapping.Wrap, + MinHeight = 120, + MaxHeight = 320, + IsSpellCheckEnabled = true, + }; + ScrollViewer.SetVerticalScrollBarVisibility(box, ScrollBarVisibility.Auto); + var panel = new StackPanel { Spacing = 10, MinWidth = 380 }; + panel.Children.Add(box); + panel.Children.Add(new TextBlock + { + Text = "Fix anything the recognizer misread. Replacing swaps the ink for a text box; Undo brings the ink back.", + TextWrapping = TextWrapping.Wrap, FontSize = 12, + Foreground = (Brush)Application.Current.Resources["AppTextSecondaryBrush"], + }); + var dlg = new ContentDialog + { + Title = "Convert to text", + Content = panel, + PrimaryButtonText = "Replace ink", + SecondaryButtonText = "Copy text", + CloseButtonText = "Cancel", + DefaultButton = ContentDialogButton.Primary, + XamlRoot = XamlRoot, + }; + box.TextChanged += (_, __) => + { + bool any = !string.IsNullOrWhiteSpace(box.Text); + dlg.IsPrimaryButtonEnabled = any; + dlg.IsSecondaryButtonEnabled = any; + }; + box.Loaded += (_, __) => box.Focus(FocusState.Programmatic); + + var result = await dlg.ShowAsync(); + // The TextBox uses \r for new lines; keep \n so other apps and PDF + // export see ordinary line breaks. + var final = (box.Text ?? "").Replace("\r\n", "\n").Replace('\r', '\n').Trim(); + if (final.Length == 0) return null; + return result switch + { + ContentDialogResult.Primary => (final, true), + ContentDialogResult.Secondary => (final, false), + _ => null, + }; + } + + // Puts recognized words back into lines of writing: words whose vertical + // centers fall inside a line's band join it, lines read top to bottom and + // words left to right. + internal static string JoinIntoLines(IReadOnlyList words) + { + var lines = new List<(float top, float bottom, List words)>(); + foreach (var w in words.OrderBy(w => w.Y + w.H / 2)) + { + float cy = w.Y + w.H / 2; + int hit = lines.FindIndex(l => cy >= l.top && cy <= l.bottom); + if (hit < 0) lines.Add((w.Y, w.Y + w.H, new List { w })); + else + { + var l = lines[hit]; + l.words.Add(w); + // Only stretch the band a little, so a tall word doesn't swallow + // the next line. + lines[hit] = (Math.Min(l.top, w.Y + w.H * 0.25f), Math.Max(l.bottom, w.Y + w.H * 0.75f), l.words); + } + } + var sb = new StringBuilder(); + foreach (var l in lines.OrderBy(l => l.top)) + { + if (sb.Length > 0) sb.Append('\n'); + sb.Append(string.Join(" ", l.words.OrderBy(w => w.X).Select(w => w.T.Trim()))); + } + return sb.ToString(); + } + + // A word's ink box spans ascenders to descenders, roughly one em, so the + // typed text comes out about as big as the writing was. + private static float EstimateFontSize(IReadOnlyList words) + { + var heights = words.Select(w => w.H).Where(h => h > 1).OrderBy(h => h).ToList(); + if (heights.Count == 0) return 18f; + return Math.Clamp(heights[heights.Count / 2] * 0.8f, 12f, 72f); + } +} diff --git a/src/YuNotes/Views/EditorPage.Pages.cs b/src/YuNotes/Views/EditorPage.Pages.cs index dd467c5..6a3815c 100644 --- a/src/YuNotes/Views/EditorPage.Pages.cs +++ b/src/YuNotes/Views/EditorPage.Pages.cs @@ -857,6 +857,7 @@ private static NotePage DeepClonePage(NotePage src, int newIndex) SkipImportedPdf = t.SkipImportedPdf } : null }; + clone.Gaps.AddRange(PageGaps.Clone(src.Gaps)); foreach (var s in src.Strokes) { diff --git a/src/YuNotes/Views/EditorPage.Presentation.cs b/src/YuNotes/Views/EditorPage.Presentation.cs index 7512d44..f93ebe4 100644 --- a/src/YuNotes/Views/EditorPage.Presentation.cs +++ b/src/YuNotes/Views/EditorPage.Presentation.cs @@ -69,7 +69,7 @@ private void EnterPresentation() KeyboardAccelerators.Add(a); } - MainWindow.SetFullScreen(true); + MainWindow.SetFullScreen(this, true); Canvas.AddPagesAllowed = false; // no "+" or pull-to-add while presenting SelectTool(ToolKind.Laser); UpdatePresentPageLabel(page); @@ -95,7 +95,7 @@ private void ExitPresentation() Canvas.ClearLaser(); Canvas.AddPagesAllowed = true; - MainWindow.SetFullScreen(false); + MainWindow.SetFullScreen(this, false); SelectTool(_toolBeforePresent); // Back to the zoom the user had, on the page they ended on. diff --git a/src/YuNotes/Views/EditorPage.Share.cs b/src/YuNotes/Views/EditorPage.Share.cs index 40bc1ac..22a8fd4 100644 --- a/src/YuNotes/Views/EditorPage.Share.cs +++ b/src/YuNotes/Views/EditorPage.Share.cs @@ -23,7 +23,7 @@ private enum ShareKind { Pdf, CurrentPagePng, AllPagesPng } // DataTransferManager is per window: hook DataRequested once, and hand it // whatever the latest Share prepared. - private static bool s_shareHooked; + private static readonly HashSet s_shareHooked = new(); private static (string Title, IReadOnlyList Files)? s_pendingShare; private bool _sharing; @@ -100,12 +100,11 @@ private async Task ShareAsync(ShareKind kind) foreach (var p in paths) files.Add(await StorageFile.GetFileFromPathAsync(p)); s_pendingShare = (title, files); - var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow); - if (!s_shareHooked) + var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(MainWindow.Of(this)); + if (s_shareHooked.Add(hwnd)) { var dtm = DataTransferManagerInterop.GetForWindow(hwnd); dtm.DataRequested += OnShareDataRequested; - s_shareHooked = true; } DataTransferManagerInterop.ShowShareUIForWindow(hwnd); } diff --git a/src/YuNotes/Views/EditorPage.Tabs.cs b/src/YuNotes/Views/EditorPage.Tabs.cs index 14f3bc5..ca9660a 100644 --- a/src/YuNotes/Views/EditorPage.Tabs.cs +++ b/src/YuNotes/Views/EditorPage.Tabs.cs @@ -7,6 +7,7 @@ using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Media; +using Microsoft.UI.Xaml.Media.Animation; using YuNotes.Models; namespace YuNotes.Views; @@ -15,11 +16,37 @@ namespace YuNotes.Views; // the note in the current tab. public sealed record EditorTabRequest(string Path); +// Shows the window's tabs as they are (a window made from a dragged-out tab). +public sealed class EditorResume +{ + public static readonly EditorResume Instance = new(); + private EditorResume() { } +} + +internal sealed class OpenTab +{ + public string Path = ""; + public string Title = ""; + public Document? Doc; +} + +// One window's editor tabs and which one is showing. +internal sealed class EditorTabs +{ + public readonly List List = new(); + public int Active = -1; + + public OpenTab? Find(string path) => + List.FirstOrDefault(t => t.Path.Length > 0 && string.Equals(t.Path, path, StringComparison.OrdinalIgnoreCase)); +} + public sealed partial class EditorPage { // ─── Tabs ──────────────────────────────────────────────────────────────────── - // Several notes open in one window. The tab list is static so it survives - // going back to Home and opening the editor again. Opening a note from Home + // Several notes open in one window. The tab list belongs to the window + // (MainWindow.Tabs) so it survives going back to Home and opening the + // editor again; each window has its own. Tabs can be reordered, dragged + // out into a new window, or dropped onto another window's tab strip. Opening a note from Home // replaces the current tab (as before tabs existed); new tabs come from the // + at the end of the tab strip, Ctrl+T, Ctrl+click on Home, or "Open to // edit" in side by side. The strip is always shown, even with one tab. @@ -29,41 +56,61 @@ public sealed partial class EditorPage // Their loaded Document is kept, with its own undo history, so switching // back is instant. - private sealed class OpenTab - { - public string Path = ""; - public string Title = ""; - public Document? Doc; - } - - private static readonly List s_tabs = new(); - private static int s_activeTab = -1; + private EditorTabs _tabSet = new(); + private List _tabs => _tabSet.List; + private int _activeTab { get => _tabSet.Active; set => _tabSet.Active = value; } private bool _suppressTabEvents; private bool _switchingTab; - private OpenTab? ActiveTab => s_activeTab >= 0 && s_activeTab < s_tabs.Count ? s_tabs[s_activeTab] : null; + private OpenTab? ActiveTab => _activeTab >= 0 && _activeTab < _tabs.Count ? _tabs[_activeTab] : null; private static bool SamePath(string a, string b) => a.Length > 0 && string.Equals(a, b, StringComparison.OrdinalIgnoreCase); private void InitTabs() { + // Tabs are matched by their Tag, not their position: while a tab is + // being dragged to a new place the strip's order runs ahead of ours. TabStrip.SelectionChanged += (sender, e) => { if (_suppressTabEvents) return; - _ = SwitchTabAsync(TabStrip.SelectedIndex); + if (TabStrip.SelectedItem is TabViewItem { Tag: OpenTab t } && _tabs.IndexOf(t) is var idx and >= 0) + _ = SwitchTabAsync(idx); }; TabStrip.TabCloseRequested += (sender, args) => { - int idx = TabStrip.TabItems.IndexOf(args.Tab); - if (idx >= 0) _ = CloseTabAsync(idx); + if (args.Tab.Tag is OpenTab t && _tabs.IndexOf(t) is var idx and >= 0) _ = CloseTabAsync(idx); }; + TabStrip.TabItemsChanged += (_, __) => { if (!_suppressTabEvents) SyncOrderFromStrip(); }; + TabStrip.TabDragStarting += OnTabDragStarting; + TabStrip.TabDragCompleted += (_, __) => s_drag = null; + TabStrip.TabDroppedOutside += OnTabDroppedOutside; + TabStrip.TabStripDragOver += OnTabStripDragOver; + TabStrip.TabStripDrop += OnTabStripDrop; TabAddFlyout.Opening += (_, __) => RebuildNewTabFlyout(TabAddFlyout); } + // The note a navigation to the editor would open, if it names one. + internal static string? PathOf(object? param) => param switch + { + Document d => d.Info.FilePath, + string p => p, + EditorOpenRequest r => r.Path, + EditorTabRequest t => t.Path, + _ => null, + }; + // Called from OnNavigatedTo with the navigation parameter. private void OpenFromNavigation(object? param) { + _tabSet = MainWindow.Of(this)?.Tabs ?? new EditorTabs(); + if (param is EditorResume) + { + PruneMissingTabs(); + if (_activeTab < 0 && _tabs.Count > 0) _activeTab = 0; + if (_activeTab >= 0) ActivateTab(_activeTab); + return; + } string? path = null; Document? doc = null; bool newTab = false; @@ -77,10 +124,22 @@ private void OpenFromNavigation(object? param) PruneMissingTabs(); if (path is null) return; - int idx = s_tabs.FindIndex(t => SamePath(t.Path, path)); + // Coming back (e.g. from Settings) to a note that has since moved to + // another window: show this window's tabs instead of a second copy. + if (_tabs.FindIndex(t => SamePath(t.Path, path)) < 0 + && MainWindow.FindOpenTab(path) is { } elsewhere + && !ReferenceEquals(elsewhere.Window, MainWindow.Of(this))) + { + if (_tabs.Count == 0) { MainWindow.GoBack(this); return; } + if (_activeTab < 0) _activeTab = 0; + ActivateTab(_activeTab); + return; + } + + int idx = _tabs.FindIndex(t => SamePath(t.Path, path)); if (idx >= 0) { - if (doc is not null) s_tabs[idx].Doc = doc; + if (doc is not null) _tabs[idx].Doc = doc; } else { @@ -92,40 +151,40 @@ private void OpenFromNavigation(object? param) }; if (newTab || ActiveTab is null) { - s_tabs.Add(tab); - idx = s_tabs.Count - 1; + _tabs.Add(tab); + idx = _tabs.Count - 1; } else { // Replace the note in the current tab. It was already saved or // discarded when the editor was left. if (ActiveTab!.Doc is { } old) App.Services.History.Forget(old); - s_tabs[s_activeTab] = tab; - idx = s_activeTab; + _tabs[_activeTab] = tab; + idx = _activeTab; } } ActivateTab(idx); } // Tabs whose note was moved, trashed or deleted from Home are closed. - private static void PruneMissingTabs() + private void PruneMissingTabs() { - var active = s_activeTab >= 0 && s_activeTab < s_tabs.Count ? s_tabs[s_activeTab] : null; - foreach (var t in s_tabs.Where(t => t.Path.Length > 0 && !File.Exists(t.Path)).ToList()) + var active = _activeTab >= 0 && _activeTab < _tabs.Count ? _tabs[_activeTab] : null; + foreach (var t in _tabs.Where(t => t.Path.Length > 0 && !File.Exists(t.Path)).ToList()) { if (t.Doc is { } d) App.Services.History.Forget(d); - s_tabs.Remove(t); + _tabs.Remove(t); } - s_activeTab = active is null ? -1 : s_tabs.IndexOf(active); - if (s_activeTab < 0 && s_tabs.Count > 0) s_activeTab = s_tabs.Count - 1; + _activeTab = active is null ? -1 : _tabs.IndexOf(active); + if (_activeTab < 0 && _tabs.Count > 0) _activeTab = _tabs.Count - 1; } // Shows tab `idx` without asking anything (the caller already left the // previous tab). private void ActivateTab(int idx) { - s_activeTab = idx; - var tab = s_tabs[idx]; + _activeTab = idx; + var tab = _tabs[idx]; RebuildTabStrip(); if (tab.Doc is { } d) { Load(d); RunPendingSearch(); } else _ = LoadFromPathAsync(tab.Path); @@ -149,10 +208,11 @@ private void RebuildTabStrip() { TabStrip.TabItems.Clear(); var res = Application.Current.Resources; - foreach (var t in s_tabs) + foreach (var t in _tabs) { var item = new TabViewItem { + Tag = t, Header = string.IsNullOrEmpty(t.Title) ? "Untitled" : t.Title, IsClosable = true, IconSource = new FontIconSource @@ -162,17 +222,18 @@ private void RebuildTabStrip() }, }; ToolTipService.SetToolTip(item, t.Path); + item.ContextFlyout = BuildTabContextMenu(t); TabStrip.TabItems.Add(item); } - TabStrip.SelectedIndex = s_activeTab; - TabStrip.Visibility = s_tabs.Count > 0 ? Visibility.Visible : Visibility.Collapsed; + TabStrip.SelectedIndex = _activeTab; + TabStrip.Visibility = _tabs.Count > 0 ? Visibility.Visible : Visibility.Collapsed; } finally { _suppressTabEvents = false; } } private async Task SwitchTabAsync(int idx) { - if (_switchingTab || idx == s_activeTab || idx < 0 || idx >= s_tabs.Count) return; + if (_switchingTab || idx == _activeTab || idx < 0 || idx >= _tabs.Count) return; _switchingTab = true; try { @@ -184,8 +245,8 @@ private async Task SwitchTabAsync(int idx) private Task CycleTabAsync(int dir) { - if (s_tabs.Count < 2) return Task.CompletedTask; - return SwitchTabAsync(((s_activeTab + dir) % s_tabs.Count + s_tabs.Count) % s_tabs.Count); + if (_tabs.Count < 2) return Task.CompletedTask; + return SwitchTabAsync(((_activeTab + dir) % _tabs.Count + _tabs.Count) % _tabs.Count); } // Saves (or asks about) the active note before another one takes the tab @@ -227,48 +288,50 @@ private void DropActiveTabDocument() private async Task CloseTabAsync(int idx) { - if (_switchingTab || idx < 0 || idx >= s_tabs.Count) return; + if (_switchingTab || idx < 0 || idx >= _tabs.Count) return; _switchingTab = true; try { - if (idx == s_activeTab) + if (idx == _activeTab) { if (!await LeaveActiveTabAsync()) { RebuildTabStrip(); return; } - if (s_tabs[idx].Doc is { } d) App.Services.History.Forget(d); - s_tabs.RemoveAt(idx); - if (s_tabs.Count == 0) + if (_tabs[idx].Doc is { } d) App.Services.History.Forget(d); + _tabs.RemoveAt(idx); + if (_tabs.Count == 0) { - s_activeTab = -1; + _activeTab = -1; _doc = null; - MainWindow.GoBack(); + MainWindow.GoBack(this); return; } - ActivateTab(Math.Min(idx, s_tabs.Count - 1)); + ActivateTab(Math.Min(idx, _tabs.Count - 1)); } else { // Background tabs are always saved, so closing one asks nothing. - if (s_tabs[idx].Doc is { } d) App.Services.History.Forget(d); - s_tabs.RemoveAt(idx); - if (idx < s_activeTab) s_activeTab--; + if (_tabs[idx].Doc is { } d) App.Services.History.Forget(d); + _tabs.RemoveAt(idx); + if (idx < _activeTab) _activeTab--; RebuildTabStrip(); } } finally { _switchingTab = false; } } - // Opens `path` in a new tab, or switches to it if it is already open. - private async Task OpenInNewTabAsync(string path) + // Opens `path` in a new tab, or switches to it if it is already open + // (here or in another window). + internal async Task OpenInNewTabAsync(string path) { if (_switchingTab) return; - int existing = s_tabs.FindIndex(t => SamePath(t.Path, path)); + int existing = _tabs.FindIndex(t => SamePath(t.Path, path)); if (existing >= 0) { await SwitchTabAsync(existing); return; } + if (MainWindow.FindOpenTab(path) is { } elsewhere) { elsewhere.Window.ShowTab(elsewhere.Tab.Path); return; } _switchingTab = true; try { if (!await LeaveActiveTabAsync()) return; - s_tabs.Add(new OpenTab { Path = path, Title = System.IO.Path.GetFileNameWithoutExtension(path) }); - ActivateTab(s_tabs.Count - 1); + _tabs.Add(new OpenTab { Path = path, Title = System.IO.Path.GetFileNameWithoutExtension(path) }); + ActivateTab(_tabs.Count - 1); } finally { _switchingTab = false; } } @@ -308,7 +371,7 @@ private static string NoteMenuLabel(string path) private void RebuildNewTabFlyout(MenuFlyout flyout) { flyout.Items.Clear(); - var open = CandidateNotePaths(p => s_tabs.Any(t => SamePath(t.Path, p))); + var open = CandidateNotePaths(p => _tabs.Any(t => SamePath(t.Path, p))); flyout.Items.Add(new MenuFlyoutItem { Text = "Open in a new tab:", IsEnabled = false }); foreach (var p in open) { @@ -319,11 +382,11 @@ private void RebuildNewTabFlyout(MenuFlyout flyout) } if (open.Count == 0) flyout.Items.Add(new MenuFlyoutItem { Text = "No other notes to open", IsEnabled = false }); - if (s_tabs.Count > 0) + if (_tabs.Count > 0) { flyout.Items.Add(new MenuFlyoutSeparator()); var close = new MenuFlyoutItem { Text = "Close this tab (Ctrl+W)" }; - close.Click += async (_, __) => await CloseTabAsync(s_activeTab); + close.Click += async (_, __) => await CloseTabAsync(_activeTab); flyout.Items.Add(close); } } @@ -334,13 +397,210 @@ private void ShowNewTabPicker() TabAddBtn.Flyout?.ShowAt(TabAddBtn); } + // Shows the tab holding `path` (another window asked, e.g. for a file + // opened from Explorer that this window already has). + internal async Task SwitchToPathAsync(string path) + { + int idx = _tabs.FindIndex(t => SamePath(t.Path, path)); + if (idx >= 0) await SwitchTabAsync(idx); + } + // A restored version replaces the note on disk: any copy held by a tab is stale. private static void DropCachedTab(string path) { - foreach (var t in s_tabs.Where(t => SamePath(t.Path, path))) + foreach (var w in MainWindow.All) + foreach (var t in w.Tabs.List.Where(t => SamePath(t.Path, path))) + { + if (t.Doc is { } d) App.Services.History.Forget(d); + t.Doc = null; + } + } + + // ─── Moving tabs between windows ──────────────────────────────────────────── + + // The tab being dragged and the editor it came from. Drags only happen + // within this one process, so a static is enough to hand it over. + private static (EditorPage Source, OpenTab Tab)? s_drag; + + private MenuFlyout BuildTabContextMenu(OpenTab tab) + { + var menu = new MenuFlyout(); + var toNew = new MenuFlyoutItem { - if (t.Doc is { } d) App.Services.History.Forget(d); - t.Doc = null; + Text = "Move to new window", + Icon = new FontIcon { Glyph = "\ue89e", FontFamily = (FontFamily)Application.Current.Resources["MaterialIconsFamily"] }, + }; + toNew.Click += async (_, __) => await MoveTabToNewWindowAsync(tab); + menu.Opening += (_, __) => toNew.IsEnabled = _tabs.Count > 1; + menu.Items.Add(toNew); + + var toWindow = new MenuFlyoutSubItem { Text = "Move to window" }; + menu.Opening += (_, __) => + { + toWindow.Items.Clear(); + var mine = MainWindow.Of(this); + foreach (var w in MainWindow.All.Where(w => !ReferenceEquals(w, mine)).Reverse()) + { + var label = w.Tabs.List.Count > 0 && w.Tabs.Active >= 0 && w.Tabs.Active < w.Tabs.List.Count + ? $"{w.Tabs.List[w.Tabs.Active].Title}" + (w.Tabs.List.Count > 1 ? $" and {w.Tabs.List.Count - 1} more" : "") + : "Home"; + var item = new MenuFlyoutItem { Text = label }; + var target = w; + item.Click += async (_, __) => await MoveTabToWindowAsync(tab, target); + toWindow.Items.Add(item); + } + toWindow.Visibility = toWindow.Items.Count > 0 ? Visibility.Visible : Visibility.Collapsed; + }; + menu.Items.Add(toWindow); + + menu.Items.Add(new MenuFlyoutSeparator()); + var close = new MenuFlyoutItem { Text = "Close tab" }; + close.Click += async (_, __) => { if (_tabs.IndexOf(tab) is var i and >= 0) await CloseTabAsync(i); }; + menu.Items.Add(close); + return menu; + } + + // After the user drags a tab to a new place in the strip, take that order. + // Mid-drag the strip can be one tab short; wait until it is whole again. + private void SyncOrderFromStrip() + { + var order = TabStrip.TabItems.OfType().Select(i => i.Tag as OpenTab).ToList(); + if (order.Count != _tabs.Count || order.Any(t => t is null || !_tabs.Contains(t))) return; + var active = ActiveTab; + _tabs.Clear(); + _tabs.AddRange(order!); + _activeTab = active is null ? -1 : _tabs.IndexOf(active); + } + + private void OnTabDragStarting(TabView sender, TabViewTabDragStartingEventArgs args) + { + if (args.Tab.Tag is not OpenTab tab) { args.Cancel = true; return; } + s_drag = (this, tab); + args.Data.Properties["YuNotesTab"] = tab.Path; + args.Data.RequestedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move; + } + + // Dropped somewhere that isn't a tab strip: the tab gets its own window, + // where it was dropped. The last tab stays (its window is already "its own"). + private void OnTabDroppedOutside(TabView sender, TabViewTabDroppedOutsideEventArgs args) + { + s_drag = null; + if (args.Tab.Tag is OpenTab tab && _tabs.Count > 1) _ = MoveTabToNewWindowAsync(tab, atCursor: true); + } + + // Another window's tab dragged over this strip: offer to take it. + private void OnTabStripDragOver(object sender, DragEventArgs e) + { + if (s_drag is { } d && !ReferenceEquals(d.Source, this)) + { + e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move; + e.DragUIOverride.Caption = "Move tab here"; + e.DragUIOverride.IsGlyphVisible = false; + } + } + + private void OnTabStripDrop(object sender, DragEventArgs e) + { + if (s_drag is not { } d || ReferenceEquals(d.Source, this)) return; + s_drag = null; + // Insert before the first tab whose middle is right of the drop point. + int index = _tabs.Count; + for (int i = 0; i < TabStrip.TabItems.Count; i++) + { + if (TabStrip.ContainerFromIndex(i) is TabViewItem item + && e.GetPosition(item).X < item.ActualWidth / 2) + { index = i; break; } + } + _ = ReceiveTabAsync(d.Source, d.Tab, index); + } + + private async Task MoveTabToNewWindowAsync(OpenTab tab, bool atCursor = false) + { + if (_tabs.Count < 2) return; + var size = MainWindow.Of(this)?.Size ?? default; + if (!await DetachTabAsync(tab)) return; + var set = new EditorTabs(); + set.List.Add(tab); + set.Active = 0; + var w = new MainWindow(set); + if (atCursor) w.PlaceAtCursor(size); + w.Activate(); + } + + private async Task MoveTabToWindowAsync(OpenTab tab, MainWindow target) + { + if (target.RootFrame.Content is EditorPage editor) + { + await editor.ReceiveTabAsync(this, tab, editor._tabs.Count); + return; + } + // The other window is on Home or Settings: hand it the tab and show it there. + var mine = MainWindow.Of(this); + bool last = _tabs.Count == 1; + if (!await DetachTabAsync(tab)) return; + target.Tabs.List.Add(tab); + target.Tabs.Active = target.Tabs.List.Count - 1; + target.NavigateTo(EditorResume.Instance, new SuppressNavigationTransitionInfo()); + target.BringToFront(); + if (last) mine?.Close(); + } + + // Takes `tab` from `source` (another window's editor) and shows it here at + // `index`. The window it came from closes if that was its last tab. + private async Task ReceiveTabAsync(EditorPage source, OpenTab tab, int index) + { + if (_switchingTab) return; + _switchingTab = true; + try + { + // Save this window's note first; it stays loaded if the move fails. + if (!await LeaveActiveTabAsync()) return; } + finally { _switchingTab = false; } + + var sourceWindow = MainWindow.Of(source); + bool sourceEmpties = source._tabs.Count == 1; + if (!await source.DetachTabAsync(tab)) return; + if (sourceEmpties) sourceWindow?.Close(); + + index = Math.Clamp(index, 0, _tabs.Count); + _tabs.Insert(index, tab); + ActivateTab(index); + MainWindow.Of(this)?.BringToFront(); + } + + // Takes `tab` out of this window, saving it first if it is the one showing. + // False = it stays (the user cancelled, or saving failed). When it was the + // last tab the editor is left empty; the caller closes the window. + private async Task DetachTabAsync(OpenTab tab) + { + if (_switchingTab) return false; + int idx = _tabs.IndexOf(tab); + if (idx < 0) return false; + _switchingTab = true; + try + { + if (idx == _activeTab) + { + if (!await LeaveActiveTabAsync()) { RebuildTabStrip(); return false; } + _tabs.RemoveAt(idx); + if (_tabs.Count == 0) + { + _activeTab = -1; + _doc = null; + RebuildTabStrip(); + return true; + } + ActivateTab(Math.Min(idx, _tabs.Count - 1)); + } + else + { + _tabs.RemoveAt(idx); + if (idx < _activeTab) _activeTab--; + RebuildTabStrip(); + } + return true; + } + finally { _switchingTab = false; } } } diff --git a/src/YuNotes/Views/EditorPage.Toolbar.cs b/src/YuNotes/Views/EditorPage.Toolbar.cs index ba4add4..1a544f7 100644 --- a/src/YuNotes/Views/EditorPage.Toolbar.cs +++ b/src/YuNotes/Views/EditorPage.Toolbar.cs @@ -673,6 +673,7 @@ private void UpdateSelectionUi() if (Canvas.HasSelection) { SyncSelectionColorPicker(); + SelToTextBtn.Visibility = Canvas.SelectionHasPenInk ? Visibility.Visible : Visibility.Collapsed; SelectionActions.Visibility = Visibility.Visible; PositionSelectionActions(); } diff --git a/src/YuNotes/Views/EditorPage.Versions.cs b/src/YuNotes/Views/EditorPage.Versions.cs index 4a1fbeb..2d60037 100644 --- a/src/YuNotes/Views/EditorPage.Versions.cs +++ b/src/YuNotes/Views/EditorPage.Versions.cs @@ -128,8 +128,8 @@ private async Task RestoreVersionAsync(Services.VersionHistory.Version chosen) await Task.Run(() => App.Services.Versions.Restore(path, version)); // Reopen the note fresh from the restored file (in this same tab). DropCachedTab(path); - if (ActiveTab is not null) ActivateTab(s_activeTab); - else { MainWindow.GoBack(); MainWindow.Navigate(path); } + if (ActiveTab is not null) ActivateTab(_activeTab); + else { MainWindow.GoBack(this); MainWindow.Navigate(this, path); } } catch (Exception ex) { await Notify("Restore failed", ex.Message); } } diff --git a/src/YuNotes/Views/EditorPage.xaml b/src/YuNotes/Views/EditorPage.xaml index 3c216b3..bdd1d14 100644 --- a/src/YuNotes/Views/EditorPage.xaml +++ b/src/YuNotes/Views/EditorPage.xaml @@ -496,7 +496,7 @@ + ToolTipService.ToolTip="Page size — drag a side handle to widen a page; drag down inside a page to add writing space, up to remove it"> @@ -572,6 +572,11 @@ +