diff --git a/docs/development/architecture-audit-20261116.txt b/docs/development/architecture-audit-20261116.txt new file mode 100644 index 00000000..820f35e2 --- /dev/null +++ b/docs/development/architecture-audit-20261116.txt @@ -0,0 +1,380 @@ +BusyMark architecture audit disposition — audit 2026-11-16, verification 2026-11-17 + +Input and scope +--------------- +Read all 14 pages of /home/albert/Downloads/busymark-architecture-audit.pdf. +SHA-256: 789adc28ccf7a9b51e579783a9e160a36d9064a551a8a533032caca0d5d04121. +The requested /home/albert/busystack/busymark directory does not exist. Work was +performed in the supplied checkout, /mnt/Media/busystack/busymark. +The starting revision was 0623104, rather than the PDF's archived 9f6aa57. +Each finding was checked against that current production code before correction. +The official Flutter 3.47.5 / Dart 3.13.4 toolchain and dependency locks are retained. +No third-party source, SDK, tool implementation, or shared dependency was changed. + +Disposition of every numbered finding +------------------------------------ +A1 — CORRECTED IN SOURCE; final verification recorded below. +Independent evidence in the starting revision: +* workspace_service.dart saveFormattedText checked expectedSnapshot and then + renamed a temporary file, leaving the final check/publication race. +* workspace_controller.dart Save All and autosave called unconditional saveText. +* Writerside _replaceAtomically and HTML publishSite exchanged again on rejected + displaced state, followed by ordinary temporary-path cleanup. +* saveFormattedTextBatch read/stat'ed displaced data before adding to committed. +Corrections: +* workspace_service.dart:1387 resolves the normal-save referent and delegates + conditional writes to the existing saveFormattedTextReplacingPath publisher. + The ordinary unconditional API remains for callers without an expected version. +* workspace_controller.dart:6803,7036,9222 passes the captured disk snapshot on + manual Save, Save All and autosave. Save All classifies publication conflicts + as conflicts, not ordinary failures; all three retain the unsaved buffer. +* workspace_message.dart and workspace_safety.dart retain/show a recovery path, + including in the overwrite prompt, instead of translating it away. +* workspace_service.dart:1524 registers exchange ownership before fallible + validation. The existing checked batch rollback handles every later exception. +* writerside_topic_removal_service.dart:2634 retains displaced state on every + post-exchange rejection/read/cleanup failure, without a blind second exchange. + Existing rollback-failed reporting includes both paths and triggers rollback + of earlier successful domain edits; it does not claim the current file restored. + Recovery paths also survive an exception during rollback of an earlier file. +* html_export_publisher.dart:138 uses the existing retained-stage exception on + failed displaced-directory validation; html_export_service.dart already keeps + that stage. Publication may have happened; the wording now says so explicitly. +* Integration review found that workspace_file_monitor.dart recognized only + the basename of a save staging directory, not its contents child. The real + inotify regression reproduced a leaked .busymark-save-*/contents path; endpoint + tests reproduced both erroneous move directions. The existing temporary-path + predicate now recognizes save staging ancestors, including batch saves. + A controller regression verifies that exchange notifications cannot retarget + the authoring buffer. No watcher or file-decoration subsystem was replaced. +Removed: the normal conditional check-then-rename path, blind Writerside/HTML +recovery exchanges and unsafe batch cleanup before exchange registration. +Retained: symlink referent versus Save As entry semantics; BOM/newlines/mode; +anchored paths; live authorization; manifests; multi-file domain rollback; +checked conditional Save As/batch rollback; non-Git document recovery comparison. +Regression evidence: workspace_service_test final-window symlink/format/mode, +second-writer recovery, injected post-exchange validation errors with and without +a newer destination; workspace_controller_test manual/all/auto dirty-buffer and +recovery-path cases; Writerside post-exchange A/B preservation and truthful partial +failure; HTML service-level retained-stage cleanup test. Existing multi-file, +permissions, recovery, search replacement and refactoring suites also run. +The Local History recorder now observes the conditional-save API with its +expected snapshot; its original source/empty-write assertions remain unchanged. + +A2 — CORRECTED IN SOURCE; final verification recorded below. +Independent evidence: separate application processes used the same SQLite path, +while repository guards compared process-local caches and store UPSERTs compared +no persisted input. Startup unconditionally reclassified every syncing note. +Corrections in nextcloud_notes/data/notes_store.dart: +* SQLite transaction ownership now includes expected storage generations for + account/note/attachment mutations, removal cascades, import and offline state. + Generation changes commit atomically with durable rows; failure advances neither + durable content nor the owning cache's expectation. Tombstones fence reuse. +* Observational reads do not silently reauthorize an older repository cache. + Even no-op editor saves validate their durable identity before claiming success. +* Network workflows acquire an account request claim before sending requests. + Claims include the cached identities deleted by another process, as well as + current rows. Stale caches cannot issue a remote delete before validation. +* Session identity includes process ID and Linux process start identity, so + process ID reuse cannot establish live ownership. Closed sessions release their + claims; dead sessions are retired. Startup leaves live requests alone and + recovers interrupted syncing state only when no live request owns it. +* Nested/overlapping request counts live in the SQLite claim transaction; a + queued begin cannot lose ownership when an earlier request ends. +* Store close drains active requests before releasing ownership. HTTP operations + never hold a SQLite transaction across a network await. +* Expected-state capture belongs inside the existing startup transaction and + error handler. Invalid generation metadata now rolls back migration and + session registration, closes SQLite and reports failure instead of leaving + open() waiting for an unreported worker failure. The new regression verifies + the unchanged schema/outbox after failure, immediate lock reuse, repair and + successful reopen. +Repository synchronize/settings/reconciliation/conflict-resolution/deletion and +attachment-deletion routes use that existing store boundary. This is necessary +ownership state; it replaces neither the repository nor SQLite worker/scheduler. +Behavioral limit: a competing window receives an explicit conflict, keeps its +editor text dirty, and does not automatically rebase or retry the rejected write. +The message directs the user to preserve edits with existing Save As before +reopening the window to reload its cache. New recovery UI or a competing save +engine was not introduced. Uncertain process-identity I/O fails closed, rather than declaring a live owner +dead. Process-start liveness is tested for the supported +Linux desktop, not asserted for other platforms or mixed old/new binaries. +Regression evidence: notes_process_ownership_test uses independent repositories +and actual Dart processes, stale content and same-revision acknowledgment changes, +live-request startup, killed-owner recovery, deleted identities before network +I/O, queued request overlap, attachment/removal/transaction fences and close +during an active request. +Settings widget fixtures explicitly let real SQLite initialization complete +before advancing the fake clock to visual quiescence; existing assertions and +timeout limits remain. The existing Notes suites exercise edits during HTTP acknowledgment, metadata, +settings, creation evidence, uploads, imports, restart, rollback and recovery. + +A3 — CORRECTED. +Independent evidence: shared_git_integration.dart bound session-capturing +callbacks but its route disposal never cleared the persistent controller source. +GitController.releaseSharedStatusSource (git_controller.dart:142) checks exact +owner identity, clears the source, invalidates pending refreshes and schedules the +existing fallback. The scope captures release callbacks at bind time and runs +them before session/client disposal (shared_git_integration.dart:263,278). +An old release cannot detach a replacement session. The existing lazy session, +watcher handoff, trust checks and document-tab responsibilities remain. +Regression: git_controller_test exact-owner release, replacement binding, late +retired result and real fallback status; existing Files watcher and host tests. + +A4 — CORRECTED. +Independent evidence: AssetIngestionService used openSync/lockSync with a +blockingExclusive OS lock on the caller's isolate. +asset_ingestion_service.dart:352 now awaits open/lock/unlock/close inside the +same local queue and exception-safe ownership boundary. No worker or queue added. +Regression: an actual Python process holds the production lock while a Dart timer +must fire before lock release; publication waits, then succeeds, and another +operation verifies release. Existing adoption/rollback/process tests remain. + +A5 — CORRECTED. +Independent evidence: writersideEditorIndex unconditionally loaded every module +and called withModule repeatedly, separately from withDocumentSources. +workspace_controller.dart:6084 now captures the complete buffer map and obtains +the index from WorkspaceService.withDocumentSources. No state is published by +this read-only preparation. Removed the separate module-load/withModule loop. +Retained discovery and disk freshness, removal of closed-buffer overrides, +inactive dirty dependencies, module/instance selection and stale-result guards. +Regression: unsaved inactive dependency rename/undo integration additionally +asserts that preparation leaves workspace state unchanged with validation off; +existing discovery/overlay/reference/controller tests exercise the reused path. +No wall-clock performance improvement is claimed. + +A6 — CORRECTED. +Independent evidence: repository-wide production search found outbox writes and +schema maintenance, but no reader. Pending selection and exact creation evidence +already came from the authoritative notes records. +Schema 7 drops outbox inside the migration/recovery transaction and fences older +clients. Removed mirror creation, writes/deletes, repeated note serialization, +and six redundant per-note commit payload values. No replacement queue added. +Actual notes, creation attempts, pending state, attachments and atomicity remain. +Regression: v2–v6 legacy fixtures retain exact pending JSON/bytes while dropping +the mirror; malformed recovery rolls back the fence and table drop; v8 is rejected. +Existing rollback/retry/restart assertions now check authoritative pending state, +not a write-only mirror. Acceptance criteria were not relaxed. + +A7 — CORRECTED. +Independent evidence: PDF export allocated unique export:block request keys and +only detached cancellation in finally; the coordinator retained revision entries. +markdown_visualization_export.dart:87 now cancels every temporary key and clears +its last successful result in finally, on completion/failure/cancellation. +The content-addressed render cache and coordinator scheduling remain. +Regression: mixed successful/failed exports leave no retained successful results +for temporary keys; cancellation retires all selected keys; existing real Typst +and visualization tests run with the local pinned binary enabled. + +A8 — CORRECTED (optional local optimization implemented). +Independent evidence: with no hidden ranges, visibleText equals fullText and the +index consumers query immutable coordinates. Two identical indexes and a second +changed-range scan were unnecessary. +source_document.dart:36,62 shares the full index only when current hidden ranges +are empty. Folded coordinates retain their separate index. Net benefit is the +removed duplicate allocation/update/scan with a small local branch; no editor +redesign or speculative performance infrastructure was added. +Regression: empty/unfolded identity, folded-to-unfolded edits, subsequent edits, +existing CRLF/randomized mapping, line index, gutter and editor/search suites. + +No numbered finding was disproven or intentionally ignored. Source corrections +are distinct from full installed-application acceptance; see verification below. + +Deliberately retained / unnumbered audit observations +--------------------------------------------------- +The page 9 unopened-reference reread cost remains unchanged: freshness is real, +but there is no latency measurement or demonstrated equivalent invalidation +scheme. Adding another indexing service would increase the correctness burden. +reference_controller.dart:189 still rereads unopened sources before comparing +the captured document with its cached index input. +The page 10–13 retention recommendations remain intact: DocumentBuffer authority +and two editor projections; shared undo and stale-revision guards; bounded +workspace preparation; undo/recovery/session/local-history distinctions; lossless +Markdown and authored/resolved Writerside models; operation-specific Writerside +services; Notes repository/store/scheduler and exact uncertain-request evidence; +search/reference/FTS/comparison distinctions; file observation; Git host/session/ +engine handoff; spelling projections/coordinator/isolate/native dictionaries; +diagram/math scheduling and content caches; Dart/native/JS/D2 execution; SVG and +OpenAPI dependency policies; PDF/HTML pipelines; native integration and pinned +qualification tools; AI protocol adapters/guarded application; asset provisional +ownership; clipboard/feedback; commands/routing/settings/localization/design. +None is replaced, merged, or split merely because of file size or line count. +Shared Git UI ownership, focus/sidebar contracts, canonical worktree attachment, +trust/read-only rules and document lifetimes are retained. Shared pins/archives +are unchanged because no shared implementation was changed; the exact archive +check is part of verification, rather than inventing a new shared revision. + +Verification +------------ +Evidence directory: build/architecture-audit-20261116/. +Source correction and regression verification do not constitute completed +installed-application acceptance. The independent gates below remain explicit. + +Source and artifact identity: +* Final production change: 81afc3e. The previous 631128d build and its native + captures are superseded by this integration correction. 365bc2a changes only + app test fixture cleanup. BusyMark production hash v2, 434 files: + 68c30695dbcdb366c2e9762b3a84539eb93d095a3fea4f7a95a4be5be36eb09a. +* The final official release build passed and sealed all 1,474 bundle payload + files in build-recovery-source.json. Only lib/libapp.so differs from the + previous bundle; its new SHA-256 is + 92623c9d3d08208e9a882448c9a39b61f13654f1178eeef57145d72471cd6a02. + This whole-payload receipt, not the runner executable hash alone, binds the + actual application compiled by the official SDK. Verification against current + production source and every sealed payload passed again after native testing. +* final-source-verification.json records the repeated binding, exact shared pins, + archive/tree hashes, unchanged dependency inputs and clean official SDK Git + status. Neither shared package changed, so no shared pin refresh was warranted. + +Completed checks: +* Official Flutter analyzer: no issues (analyze-disposal-final.log). +* Tracked Dart formatting: 667 files, zero changes (format-integration-final.log; final app fixture formatted separately). +* Shared localization synchronization and exact vendored archive checks pass. +* Shared engine: 142 tests and supported-runtime check; shared Flutter UI: 489; + shared native accessibility: 2; native spelling package: 14. All pass. +* Resolved native Git presentation audit and adversarial self-tests pass. + All three BusyMark source audits (Git scope, general design, sidebar) and + their adversarial self-tests pass. No audit or acceptance criteria changed. + All eight commands were repeated on the final sources and exit zero + (final-audit-results.json and final-audit-*.log). +* All 134 Python verification-tool tests pass (python-private-final.log). +* The six production native helper suites pass: GTK accent lookup, accent host + lifecycle, shortcut metadata, credential namespace, Notes libsecret and the + complete demand-driven WebKit host lifecycle suite (native-driver.log). +* Official Writerside builder conformance passes all 181 semantic checks in + each of ten invocations, including reference/property/default/list variants + (writerside-conformance-unsandboxed.log). No builder or fixture was changed. +* The final affected Notes run passes all 147 cases (notes-overlap-final.log), + including real independent processes, crash recovery and queued ownership. + After startup integration correction, the entire Notes directory passes all + 301 tests (notes-startup-final.log). +* The final controller/watcher/endpoint group passes all 217 cases, including + the document-identity regression (save-watcher-controller-final.log). The + combined Local History/controller/watcher group passes all 394 cases before + that last additional controller assertion case was added. +* The final fixture integration run passes all 201 cases across Notes settings, + Local History workspace and actual PDF options rendering + (integration-fixtures-verified.log). + +Full BusyMark corpus: +* Final execution PASSES: full-corpus-disposal/receipt.json records all 244 + discovered test files, 5,737 passing cases, zero failed and zero skipped. + The frozen implementation/test revision is 365bc2a. All 21 invocations use + complete test files, --no-pub, --concurrency=2 and --reporter=expanded, without + test-name filters. Actual Typst/D2 rendering and native dictionary resources + are enabled. Every file occurs exactly once in this final receipt. +* full-corpus-integrity.json records independent verification of the discovered + file set, unchanged test/production inputs, complete commands, all original + output hashes and the actual passing counts. Exact shared archive/tree + verification also passes; their test fixtures were not modified. +* Canonical packaging qualification remains BLOCKED: the unmodified + tools/verify_flutter_test_corpus.py:37 calls git diff using the literal + revision "materialized source archive" inside shared directories with no + .git repository. Git exits 129 at that call and the verifier exits 1 + (corpus-canonical-verifier.log). + It does not reach its output checks. The independent integrity checks above + are execution evidence, not a waiver or replacement of that packaging gate. + No acceptance tool, criteria, assertion or dependency was changed to pass it. +* An earlier completed run recorded 5,729 passes and one autosave deadline + failure. Its unmodified receipt/logs remain in full-corpus-acceptance/. The + incomplete full-corpus-confirmation/ run reproduced that timeout in batch 11 + before the startup/watcher integration corrections. Diagnostic complete-file + runs passed, without reproducing it. The exact original interleaving was not + captured; a passing repeat alone is not claimed to explain or correct it. +* Integration review separately demonstrated the watcher staging defect with + failing endpoint tests and real inotify events (save-staging-*-red.log), then + corrected its source predicate and verified authoring-buffer identity. The + final full batch containing the autosave case passes all 381 cases with the + original three-second deadline and all original assertions. Failure diagnostics + now include settings, buffer path, current/saved text, disk state and error. +* full-corpus-recovery/ was stopped after five app fixture timer failures and + before changing its frozen inputs. Those tests unmounted an + UncontrolledProviderScope while its manually owned ProviderContainer remained + alive through Flutter's timer invariants. 365bc2a disposes that container on + fixture unmount, exercising production timer cancellation. Every original + editor/save/reopen and timer assertion remains. All 299 app cases pass in + app-fixture-cleanup.log and again in the final complete corpus. + +Native final-production bundle verification: +* All 16 final-production Git cases complete their driver checks: light/dark, + en/de/ja/ar, text scale 1.0/1.5 (native-git-postcorpus/). Every receipt records + natural application exit, unchanged disposable repository, ready credential + service and a mapped engine matching the official SDK. DesktopRun.close in + tools/git_native_smoke.py:548 requires each driver to exit zero and checks + those fields before the loop can print its final completion message. That + message is present after every case. No case was skipped or filtered. +* The outer run-postcorpus-native.py orchestration session nevertheless reports + SIGTERM/143. A clean aggregate exit is NOT claimed. Its exact cause has not + been established; the process waited for the corpus before the long matrix. + This remains a separately recorded orchestration failure, rather than being + rewritten as exit zero. The complete per-case evidence is independently + checked against current source/payloads in final-source-verification.json. +* All 220 named original captures were visually reviewed through 26 contact + sheets. All six popups extending beyond the parent window were also reviewed + at full display size (two duplicate pairs verified byte-identical). Menus fit + the display; no new visible regression was identified. The final + native-postcorpus-review/reviewed.json binds every reviewed original by hash. +* The final plain shipping application close passes: one run, clean durable + shutdown, no surviving children, exact official mapped engine + (native-close-recovery/summary.json). The --plain harness executes only that + case; this does not claim native dirty Save/Discard/Cancel coverage. Document + lifetime flows remain covered by the complete 299-case app widget suite. +* Final compiled X11 spelling/editor/history and visualization/math/PDF/HTML + paths pass (x11-recovery/results.json). Final compiled Wayland spelling/editor, + visualization/PDF and the complete real renderer corpus pass under an owned + Weston display (wayland-recovery/wayland-results.json). +* The separate complete X11 renderer corpus passes (renderer-x11-qualified.log). + Its first launch lacked GTK's Cairo Python bridge; supplying the existing + unmodified prerequisite tree through PYTHONPATH fixes that environment failure. + The compiled smoke PDF is byte-identical before/after the final Notes/watcher + integration changes (SHA-256 e6ed565492758ab3994a3854aa2cab476cde8e01062c437bd2423dc9d4e6086a). +* Earlier native-git-recovery/ completed one case, then refused startup of the + next because its source binding differed momentarily during Flutter work. + Current hashes matched again afterward, but the exact transient was not + identified. That partial attempt is retained and not accepted. The complete + post-corpus case collection ran after the Flutter test processes finished. +* These rebuilt-bundle checks do not certify installed Snap confinement, offline + network-namespace restart, physical printing, or the independent multi-engine + Wayland lifecycle gate. + +Qualification limitations and remaining failures: +* Canonical packaging qualification fails at the materialized-archive Git check + described above. The native matrix outer wrapper reports SIGTERM/143 despite + completed, independently validated case checks. Neither failure is hidden, + waived, or converted to a passing command exit. +* The final complete test execution has no failures. The exact interleaving of + the earlier autosave timeouts remains unobserved; the final pass does not + retrospectively establish their cause. Failed/interrupted runs are retained. +* Installed BusyMark still contains an older payload. sudo -n requires a password; + administrator authentication was unavailable. BusyFiles checkout and installed + application are absent. Corrected installed-payload binding and both-consumer + installed-app acceptance are therefore blocked. Older installed binaries and + unchanged shared revisions are not accepted as evidence for this correction. +* The separately documented official Wayland multi-engine lifecycle problem + has not been resolved or waived. The missing BusyFiles checkout also prevents + executing its maintained standalone upstream probe here. Passing the compiled + single-application smoke paths does not close that gate. +* Relocated HTML verification through both installed browser engines is not + available: Selenium is absent. The browsers themselves are present. No package + was added, upgraded or patched to obtain a pass. Actual compiled exports and + the real PDF-rendering tests remain independent passing evidence. +* No application was pushed, published, released or installed. All first-party + implementation changes are local commits; the final report is committed too. + +Local implementation commits: +ffd3e26 Correct audited publication, Notes ownership, and resource lifetimes +fd97b85 Fence deleted Notes identities before remote requests +ce1d245 Preserve recovery evidence through nested rollback and liveness errors +5fe8432 Keep rollback regression compliant with analyzer style +631128d Count overlapping Notes requests inside the ownership transaction +0b30b52 Align integration fixtures with conditional saves and real Notes initialization +81afc3e Keep Notes startup transactional and conditional save staging private +365bc2a Dispose owned app test containers before timer invariant checks + +Further simplification +---------------------- +No broader architectural reduction is supported by this audit or these changes. +The useful deletions are the outbox mirror, duplicate index preparation and +unfolded duplicate indexes. Other fixes restore ownership and recovery rather +than reduce line count. Additional simplification needs an equivalent production +path and demonstrable total benefit, especially around concurrency and recovery. diff --git a/docs/development/architecture-simplification-lines.csv b/docs/development/architecture-simplification-lines.csv new file mode 100644 index 00000000..9c109f38 --- /dev/null +++ b/docs/development/architecture-simplification-lines.csv @@ -0,0 +1,96 @@ +scope,file,before_lines,after_lines,delta +entrypoint,lib/main.dart,80,80,0 +production,lib/src/app/busymark_app.dart,1608,1463,-145 +production,lib/src/app/busymark_dialogs.dart,2209,2091,-118 +production,lib/src/editor/source/source_controller.dart,25,23,-2 +production,lib/src/editor/source/source_search.dart,637,587,-50 +production,lib/src/editor/source_highlighter.dart,2516,2192,-324 +production,lib/src/editor/wysiwyg/wysiwyg_editor.dart,11291,10824,-467 +production,lib/src/export/export_options_editor.dart,756,753,-3 +production,lib/src/export/html_export_ui.dart,307,302,-5 +production,lib/src/export/markdown_pdf_export_ui.dart,422,408,-14 +production,lib/src/export/writerside_pdf_export_service.dart,700,680,-20 +production,lib/src/export/writerside_pdf_export_ui.dart,337,326,-11 +production,lib/src/feedback/presentation/feedback_dialog.dart,424,419,-5 +production,lib/src/git/application/git_controller.dart,2439,769,-1670 +production,lib/src/git/application/git_gateway.dart,123,21,-102 +production,lib/src/git/application/git_use_cases.dart,80,33,-47 +production,lib/src/git/application/shared_git_integration.dart,1200,1184,-16 +production,lib/src/git/data/git_cli_gateway.dart,2,0,-2 +production,lib/src/git/data/git_executable_locator.dart,148,0,-148 +production,lib/src/git/data/git_process_runner.dart,162,0,-162 +production,lib/src/git/data/git_shared_gateway.dart,949,204,-745 +production,lib/src/git/domain/git_diff_parser.dart,368,0,-368 +production,lib/src/git/domain/git_log_parser.dart,50,0,-50 +production,lib/src/git/domain/git_models.dart,507,284,-223 +production,lib/src/git/domain/git_status_parser.dart,218,0,-218 +production,lib/src/local_history/local_history_controller.dart,6663,6615,-48 +production,lib/src/local_history/local_history_panel.dart,462,426,-36 +production,lib/src/platform/header_bar_configuration.dart,671,0,-671 +production,lib/src/platform/linux_header_bar_service.dart,433,0,-433 +production,lib/src/references/markdown_references.dart,252,255,3 +production,lib/src/references/reference_controller.dart,322,370,48 +production,lib/src/references/reference_index.dart,366,367,1 +production,lib/src/spellcheck/spelling_release_smoke.dart,705,704,-1 +production,lib/src/workspace/document_navigation.dart,17,15,-2 +production,lib/src/workspace/presentation/settings_screen.dart,2478,2408,-70 +production,lib/src/workspace/presentation/welcome_screen.dart,921,852,-69 +production,lib/src/workspace/presentation/workspace_screen.dart,16606,16443,-163 +production,lib/src/workspace/presentation/writerside_instance_dialog.dart,655,652,-3 +production,lib/src/workspace/workspace_controller.dart,9785,9726,-59 +production,lib/src/workspace/workspace_model.dart,531,501,-30 +production,lib/src/workspace/workspace_safety.dart,649,640,-9 +production,lib/src/workspace/workspace_service.dart,2821,2751,-70 +production,lib/src/workspace/workspace_tab_actions.dart,293,289,-4 +production,lib/src/workspace/workspace_tabs.dart,123,111,-12 +production,lib/src/writerside/writerside_topic_file_editor.dart,2752,2538,-214 +test,test/src/app_router_test.dart,269,245,-24 +test,test/src/app_smoke_test.dart,24130,23747,-383 +test,test/src/busymark_dialogs_test.dart,748,482,-266 +test,test/src/busymark_document_test.dart,7889,7905,16 +test,test/src/git/git_cli_gateway_integration_test.dart,1199,187,-1012 +test,test/src/git/git_controller_test.dart,2106,954,-1152 +test,test/src/git/git_diff_parser_test.dart,165,0,-165 +test,test/src/git/git_log_parser_test.dart,65,0,-65 +test,test/src/git/git_process_runner_test.dart,400,0,-400 +test,test/src/git/git_status_parser_test.dart,153,0,-153 +test,test/src/git/shared_gateway_identity_test.dart,66,107,41 +test,test/src/git/shared_git_decorations_test.dart,122,121,-1 +test,test/src/header_bar_configuration_test.dart,549,0,-549 +test,test/src/html_export_ui_test.dart,294,288,-6 +test,test/src/linux_accent_provider_test.dart,407,401,-6 +test,test/src/linux_header_bar_service_test.dart,198,0,-198 +test,test/src/local_history_controller_test.dart,6367,6365,-2 +test,test/src/markdown_pdf_export_test.dart,358,352,-6 +test,test/src/modal_barrier_test.dart,44,38,-6 +test,test/src/nextcloud_notes/notes_workspace_workflows_test.dart,2012,2047,35 +test,test/src/pdf_title_page_ui_test.dart,435,429,-6 +test,test/src/references/reference_controller_test.dart,216,299,83 +test,test/src/source_audit_test.dart,2074,2079,5 +test,test/src/source_highlighter_test.dart,778,686,-92 +test,test/src/source_search_test.dart,265,248,-17 +test,test/src/spelling_editor_integration_test.dart,1170,1259,89 +test,test/src/spelling_service_test.dart,6170,6103,-67 +test,test/src/spelling_workspace_test.dart,2048,2007,-41 +test,test/src/validation_problems_ui_test.dart,347,337,-10 +test,test/src/visualization_card_test.dart,526,514,-12 +test,test/src/workspace_controller_test.dart,7411,7405,-6 +test,test/src/workspace_safety_test.dart,2287,2303,16 +test,test/src/writerside_authoring_ui_test.dart,2110,2352,242 +test,test/src/writerside_toc_regressions_test.dart,851,838,-13 +test,test/src/writerside_topic_file_editor_test.dart,2521,2266,-255 +test,test/src/wysiwyg_clipboard_test.dart,5017,5104,87 +test,test/src/wysiwyg_math_test.dart,1242,1266,24 +test,test/src/wysiwyg_selection_lifecycle_test.dart,3810,3771,-39 +test,test/src/wysiwyg_session_test.dart,938,933,-5 +test,test/src/wysiwyg_structured_regression_test.dart,2809,3171,362 +test,test/support/document_history_harness.dart,70,85,15 +test,test/support/shared_git_read_fixture.dart,198,166,-32 +test,test/support/writerside_authoring_native_smoke.dart,5200,5198,-2 +test,test/support/wysiwyg_editable_harness.dart,131,160,29 +tool,tools/focus_restoration_smoke.dart,524,494,-30 +tool,tools/history_visual_smoke.dart,1129,1127,-2 +tool,tools/nextcloud_notes_desktop_acceptance.dart,3369,3367,-2 +tool,tools/sidebar_search_smoke.dart,2884,2896,12 +tool,tools/writerside_toc_visual_smoke.dart,1294,1292,-2 +tool,tools/wysiwyg_selection_smoke.dart,1695,1766,71 diff --git a/docs/development/architecture-simplification.md b/docs/development/architecture-simplification.md new file mode 100644 index 00000000..e08d469c --- /dev/null +++ b/docs/development/architecture-simplification.md @@ -0,0 +1,352 @@ +# Architecture simplification against the v0.7.2 review + +The cleanup removes **6,757 production lines (2.99%) and eight source files**. +It retires alternate native-header, Git, undo and property-panel owners, +redundant workspace state and unnecessary derived work. All nine numbered +findings are resolved below; the broader tab-state deletion is bounded and the +conditional worker merger is rejected with source-based reasons. Native release +and installed-app acceptance remain open as detailed in the verification record. + +The complete eleven-page review at +`/home/albert/Downloads/BusyMark-v0.7.2-Architecture-Review.pdf` was checked against +the source, callers, tests, native runner and exact bundled shared packages. +The starting tree was clean at +`fb66d1ca922bc64e8ffe3e9b0f044f8957b8d61b`, the review's own snapshot. The code +changes are committed locally as `0c648f9`, `0137003` (remaining editor-history +fixtures) and `5ad719b` (Files-only linked-worktree invalidation). Nothing was +pushed or published. + +Native fixture corrections are committed as `09bb425`, `c81c5c3` and `f6ff558`: +they check restored buffer selections, instrument the existing batch history +reader, and exercise fixed selector mnemonics independently of direct key +assignments. Final test-only corrections are committed as `e17a502`; they await +observable Notes state and check retained search, staging and history behavior. +That first verification phase used production inputs frozen at `5ad719b`. +The bounded follow-up below records the later source revisions and new results. + +The official Flutter 3.47.5 / Dart 3.13.4 SDK and all dependency locks remain +unchanged. The shared engine remains pinned to +`7d8e55d8034aeb85cddac1c0f498b0f3cc33105b`; the shared UI remains pinned to +`0a2434964ea44fbd9d8c06e73cc3b0fc7c7642e8`. Their archives were materialized and +checked with `tools/checkout_shared_dependencies.py --check`. No shared source, +third-party software, archive, consumer pin or dependency version was changed. + +## Resolution of every finding + +| PDF finding | Verified resolution and retained owner | Principal changed files and coverage | +| --- | --- | --- | +| 1. Retired native header protocol | Deleted both protocol/configuration files, app/page publishers, defaults, action/search listeners, service arguments and native modal-depth queue/maps. The Linux runner has no receiver for this protocol. Current Flutter/Yaru headers, command registry, actual modal routes, barriers, shortcut boundaries, focus restoration, GTK menus and native services remain. | Deleted `platform/linux_header_bar_service.dart` and `platform/header_bar_configuration.dart`. Removed wiring from `app/busymark_app.dart`, `app/busymark_dialogs.dart`, workspace/welcome/settings, export and feedback surfaces. Protocol-only suites were deleted; modal/focus tests remain. `app_smoke_test.dart` uses actual search controls and `LinuxPageFrame`. The sidebar and focus smoke entrypoints use current controls and routes. | +| 2. Retired Git ownership | Deleted the unused executable/process/status/log cluster, old history/commit/diff/branch/mutation methods, epochs and models. Narrowed the existing gateway to identity discovery, status projection and staged AI patch access. Removed unused repository metadata, error variants and operation/message state, including the write-only running-state bridge. Discovery no longer performs a status scan solely to populate unused metadata. The empty CLI-gateway re-export was removed. | `git/application/git_controller.dart`, `git_gateway.dart`, `git_use_cases.dart`, `shared_git_integration.dart`, `git/data/git_shared_gateway.dart`, `git/domain/git_models.dart`; deleted five execution/parser files and the two-line re-export. Retained tests use the shared engine and canonical shared fixtures. Root/trust, byte paths, stale repository identities, Files staging and AI fingerprint tests remain. The active document-versus-disk `GitDiffViewer` recovery route remains in `workspace_screen.dart`. | +| 3. Second editor undo owner | Deleted internal undo/redo stacks, deep-copy snapshots, snapshot traversal/restoration, the history-mode flag and discarded snapshot construction. Existing pre-mutation session reporting, Flutter field undo controllers, transaction guards and the authoritative synchronization path remain. | `editor/wysiwyg/wysiwyg_editor.dart` and its host wiring. Existing `DocumentHistoryHarness` / `WysiwygEditableHarness`, structured, clipboard, selection, spelling and native selection fixtures now use real buffer/workspace history. Removed assertions solely about the deleted private stack and the obsolete local/external test dimension. Exact source, undo/redo, grouping, selection, composition, stale edits and field disposal checks remain. | +| 4. Fallback property-panel owner | Deleted the editor's separate property session, draft/snapshot state, panel construction/layout and mutation callbacks. The workspace inspector/session and existing property controls are the sole owner; editor inspection and video/insertion callbacks remain. | `wysiwyg_editor.dart`, `workspace_screen.dart`, `writerside_authoring_ui_test.dart`. Panel cases mount a real disposable Writerside project in `WorkspaceScreen`; retained assertions cover quoted properties, inline links/shortcuts, video cancellation/insertion, code attributes, stale drafts, undo/reopening, RTL and scaled/narrow controls. Standalone native-menu/navigation cases retain their supplied editor contexts. | +| 5. Duplicate workspace state | Deleted `Workspace.activeFileSnapshot` / `activeFileModifiedAt`, propagation and the three byte reads used only to populate them. Deleted legacy text/dirty storage and parameters from `WorkspaceState`. Authoring tab entries require buffers and use buffer IDs; the unused path-only tab fallback was removed. `DocumentBuffer.diskSnapshot`, content loads, save/conflict checks and separate comparison/history lifetimes remain. | `workspace_model.dart`, `workspace_controller.dart`, `workspace_service.dart`, `workspace_tabs.dart`, `workspace_tab_actions.dart`, `workspace_safety.dart`, navigation and host callers. Snapshot assertions now inspect the buffer baseline. Fixtures construct real buffers with the appropriate view mode and retain active document buffers while adding dirty project files. | +| 6. Irrelevant refreshes | Same-owner attachment now returns without scheduling Git status or publishing duplicate state. Files-only updates use the existing shared engine watcher before the lazy shared session exists; binding the session cancels that subscription. Workspace filesystem events detect repositories before discovery. Removed remotes queries and `hasRemote`. References compare content/identity/project inputs, ignore editor state, use existing filesystem/Notes events, and compare retained source strings rather than cache-only hashes. Move destinations are considered. | `git_controller.dart`, `git_gateway.dart`, `shared_git_integration.dart`, `git_shared_gateway.dart`, `git_models.dart`, `references/reference_controller.dart`. A regression fails on the old reference implementation and passes after the change: caret/scroll/folding preserve the index; content and an unopened file edit refresh it. Real ordinary/linked-worktree regressions verify zero repeated-attachment scans, external index-only staging before a shared session opens, and cancellation on trust revocation. | +| 7. Repeated parsing / retrieval | Reference indexing parses once and passes that document to the existing reference extractor. Hidden/unrelated inspector paths check need/visibility/type before obtaining a rich projection. AI accesses the existing shared patch API directly. PDF composition reuses each loaded topic's source and semantic document. | `references/reference_index.dart`, `markdown_references.dart`, `workspace_screen.dart`, `git_shared_gateway.dart`, `export/writerside_pdf_export_service.dart`; deleted the now-unused application `git_diff_parser.dart`. Actual Git command recording verifies staged bytes, no discovery status scan, and no viewer content/remotes commands. Reference, PDF/export and actual-host inspector regressions exercise retained implementations. Navigation digests, useful projection caches, include resolution, limits, cancellation, asset staging and the PDF backend remain. | +| 8. Retired modes / algorithms | Deleted the source highlighter's visual-only mode/helpers, obsolete topic-delete implementation/result/exclusive helpers, unreachable Local History document-browsing mode/list/sort, retired workspace-source search algorithm/model, unused workspace search controller, topic-rename affected-path helper, modification-time helper and path-only history selector. | `editor/source_highlighter.dart`, `source/source_controller.dart`, `source/source_search.dart`, `writerside_topic_file_editor.dart`, `local_history_controller.dart`, `local_history_panel.dart`, `workspace_controller.dart`, `workspace_service.dart`. Only tests unique to deleted implementations were removed. Active highlighting, rename/removal service protections, retained-history search/inspection, current search, comparison and restore tests remain. | +| 9. Search-worker consolidation (conditional) | Retained, with source-based justification below. No replacement worker framework was introduced. | `editor/source/source_search.dart` (`SourceSearchWorker`) and `search/search_replace_service.dart` (`SearchReplacementWorker`) retain their actual production behavior and behavioral suites. | + +Paths in the table are relative to `lib/src` unless a test/tool is named. +The accompanying [line inventory](architecture-simplification-lines.csv) gives before/after +physical counts for all 95 changed Dart files, with production, entrypoint, test +and tool scopes separated. Forty-four are production files under `lib/src`. +The entrypoint's direct gateway import changes no line count. Test/tool +reductions are excluded from the production metric. + +## Recommendations retained or bounded after checking the source + +The wider removal of `Workspace.openFilePaths` / `activeFilePath` was deliberately +bounded. UI tab construction now derives from buffers. `_openActiveFile` and +`_closeOpenFileTab` still coordinate requested path lists across asynchronous +loads, while service results and `resolveWorkspaceDocumentContext` need the +parsed active path before/independently of a loaded buffer. Replacing all of that +with buffer-derived lists would erase pending navigation or require new state. +The PDF itself cautions against unconditional removal. No new tab coordinator +or compatibility fallback was added. + +`SourceSearchWorker.search` accepts an already prepared `SourceDocument`. +`SourceDocument` prepares indexes/visible text on the caller isolate. Replacement +prepares raw source inside its worker and also performs direct exact-span +validation. A substitution must retain that background preparation, Unicode and +grapheme boundaries, independent cancellation, and the distinction between +exactly 5,000 replacements and a refused 5,001-match truncated preview. Existing +replacement code already reuses `searchSourceDocument` for literal matching. +No smaller equivalent lifecycle/mapping change was established, so the +conditional recommendation was rejected rather than introducing a generic +worker API or moving preparation back to the UI isolate. + +The retained cases in `source_search_test.dart` check sequential reuse, active +and superseded-request cancellation, Unicode/combining boundaries and source +mapping. `search_replace_service_test.dart` checks the 4,999/5,000/5,001 boundary, +asynchronous preview cancellation and stale replacement plans. These behaviors +remain attached to their production workers. + +History assertions now reflect the retained production owner. Buffer history +reconstructs authored source through the existing parser; it does not restore +an obsolete private deep copy of temporary empty paragraphs or boundary-space +inline nodes. Tests still check exact whitespace/source bytes, live paste +semantics/carets before traversal, parsed replay semantics and real input after +traversal. Table Undo restores the captured table selection, followed by a real +cell caret when the selection is collapsed. The workspace's final-newline policy +is preserved. Inspector tests use the host's authored Markdown-title target and +logical XML-topic behavior instead of the fallback panel's private state. + +The review's explicit retain decisions were respected: recovery and Local +History durability, offline Notes/outbox/attachment ownership, distinct authored +and resolved representations, manual/Save All/autosave policies, native services, +rendering/visualization scheduling, AI provider boundaries, spelling, clipboard, +settings, feedback, active dependencies and acceptance tooling remain. Large +files were not split or moved merely to reduce their apparent size. + +Manual Save, Save All and autosave already share `saveFormattedText` and +`_enqueueBufferWrite`; their overwrite review, batch reporting, cadence and +history-record policies differ. The small repetition in saved-buffer updates +does not justify another policy framework. The deliberate focus-primitive +duplication across the app/shared UI boundary also remains: adding a package +solely to share roughly 126 lines is not a demonstrated improvement. Existing +semantic focus controls and their native behavior are preserved. + +## Measured code reduction + +Counts use `len(file.read_text().splitlines())` for every Dart file in `lib/src`, +including comments and the same generated adapter/data files on both sides. +Translations, tests, assets, tools, shared/third-party packages and moved code are +excluded from the production reduction. No production files were moved. + +| Scope | Before | After | Net change | +| --- | ---: | ---: | ---: | +| Dart files under `lib/src` | 361 | 353 | -8 | +| Physical production lines under `lib/src` | 226,164 | 219,407 | **-6,757 (2.99%)** | +| Git controller | 2,439 | 769 | -1,670 | +| Shared Git host gateway | 949 | 204 | -745 | +| Rich editor | 11,291 | 10,824 | -467 | +| Workspace screen | 16,606 | 16,443 | -163 | + +The eight deleted files comprise the six unconditional files in the review, the +368-line diff parser unlocked by the AI change and the two-line gateway export. +They account for 2,052 lines. Other reductions remove active alternate owners, +state propagation and execution steps. Reference invalidation adds a small +amount of necessary wiring to the existing filesystem monitor, preserving +external changes while removing editor-state-triggered work. No runtime latency, +CPU, allocation or binary-size improvement is claimed without a benchmark. + +| Deleted production file (`lib/src/`) | Before | After | +| --- | ---: | ---: | +| `platform/linux_header_bar_service.dart` | 433 | 0 | +| `platform/header_bar_configuration.dart` | 671 | 0 | +| `git/data/git_executable_locator.dart` | 148 | 0 | +| `git/data/git_process_runner.dart` | 162 | 0 | +| `git/domain/git_status_parser.dart` | 218 | 0 | +| `git/domain/git_log_parser.dart` | 50 | 0 | +| `git/domain/git_diff_parser.dart` | 368 | 0 | +| `git/data/git_cli_gateway.dart` | 2 | 0 | + +Deleted test files certify only removed implementations: +`header_bar_configuration_test.dart`, `linux_header_bar_service_test.dart`, +`git/git_process_runner_test.dart`, `git/git_status_parser_test.dart`, +`git/git_log_parser_test.dart` and `git/git_diff_parser_test.dart`. Actual native +headers/modal controls, the shared engine and the narrowed host adapter retain +behavioral coverage. The inventory includes every modified test/support/tool +file and its before/after count; their deleted lines do not inflate the +application-code reduction. + +Using only the workspace directory monitor for Git was rejected during +verification: linked worktrees store their index and common metadata outside +that directory. The retained shared engine already implements the required +repository watcher, including metadata coverage and reconciliation. The host +adds one subscription through its narrowed gateway, retires it on owner, +repository or trust changes/disposal, and hands ownership to the existing shared +session when bound. This is necessary invalidation, not a second watcher +implementation or a new coordination framework. + +The remaining 16,443-line workspace screen and 9,726-line workspace controller +still concentrate real product responsibilities. Their size is documented, +not presented as solved by deleting unrelated behavior or adding abstractions. + +## Verification and acceptance + +**BusyMark is not release-qualified.** The architectural deletion and bounded +follow-up are implemented, but native shutdown, two native read-only selection +checks, full focus transitions and installed-application acceptance remain open. +Baseline reproduction and passing unrelated tests do not waive those gates or +prove that the cleanup has no effect on them. + +The official Flutter 3.47.5 / Dart 3.13.4 SDK is unchanged at +`6a19cca56475dbfba1478ee68d7bd0c2ef891da1`. The mapped release engine SHA-256 is +`d57449a5c2ee39e77b9e3488f0703b165c67e0b3c554089f388db96484ae62f1`. +All dependency manifests/locks and both exact shared pins/archives are unchanged +from the original reviewed commit. No third-party or shared source was patched. +The raw records below are relative to `build/architecture-review/`. + +### Baseline established before changes + +The original clean tree's analyzer passed. Its first complete Flutter run had +**5,732 passed, 68 skipped and 37 failed** (`baseline-tests.log`). Thirty-five +failures lacked the native Git supervisor. Two save/reopen timeouts passed on +unchanged code in isolation after prerequisites were supplied. This baseline is +not green. The original release also failed **27 of 100 natural-close runs with +SIGSEGV** (`close-baseline-release/summary.json`). All 444 tracked production/lock +inputs matched the reviewed original commit (`baseline-native-integrity.json`). + +Official bundled Typst/D2, fonts, spelling dictionaries, the native Git +supervisor and owned Xvfb/private desktops were prepared with existing tooling. +Incomplete, failed and superseded attempts are retained with their original +logs. The previous report's final source had **5,706 passed, 0 skipped, 1 failed** +across all 243 entry files (`full-corpus-isolated/receipt.json`): Chromium exceeded +its unchanged five-second retirement deadline in the CRLF CSS case. The complete +unchanged HTML-options file subsequently passed all 16 cases on both original +and changed production. That isolated comparison never qualified the failed +full run. Its packaging helper correctly refused it. + +### Bounded follow-up changes + +`15ac993` requires the file-tab buffer ID and deletes the path-only identity +fallback. The kind prefix and separate comparison/history IDs remain. It also +deletes both empty `if (mounted)` blocks, the empty spelling teardown and both +no-op spelling callback invocations. No replacement callback or compatibility +mechanism was added. All **92 affected safety/spelling cases passed before and +after** (`followup-20261115/remnants-{baseline-ready,after}.log`). The first +mistaken invocation naming a nonexistent test file is retained separately. + +`665b105` fixes a verified native host allocation defect. The sidebar preserves +its selected view by workspace ID, while its parent allocation also required +`openedAt`. A same-root refresh changed that timestamp without remounting the +sidebar. The live snapshot showed Git requiring **396 pixels inside a 300-pixel +slot**, with the branch action at x=312 outside the slot. Resizing did not help; +reselecting Commit did (`followup-20261115/layout-state-control/`). Allocation +now uses the sidebar's existing `(workspace ID, view)` identity; initial view +publication also clears stale allocation after a real remount. Document, +repository and asynchronous lifetime timestamps/guards remain unchanged. This +adds six net production lines and no new owner or framework. + +The real application regression covers Japanese 1.5x text, same-root refresh, +full unmount/remount and unchanged buffer identity/source. It fails with the +old allocation and passes with the correction (`sidebar-lifetime-{before,green}.log`). +All **299 application smoke cases pass**. Earlier invalid fixture attempts and +the inadequate initial native candidate remain recorded, without qualification. + +`6cd76cb` corrects the Files-only watcher's test readiness. The pinned shared +`repository_watch.dart` deliberately invalidates after installing its watches +to close the initial status/watch gap. Under load this legitimate refresh landed +inside the fixture's measurement after a fixed one-second sleep (one status +call became two). The existing counting gateway now observes initial watch +invalidation and its completed status read before measuring editor attachments. +The strict zero-extra-scans assertion for ten repeated attachments, ordinary and +linked-worktree staging checks, trust-revocation assertion and staging deadline +remain. All **21 cases pass** in both an isolated diagnostic and the actual file; +analysis is clean. The first ignored diagnostic's void-event compilation error +is retained separately. No production Git or shared watcher code changed. + +### Current source and verification results + +The shipping source is production SHA-256 +`793dcf728362205bece6bc7dee445dca9c968fa59c0fb9b68d44b0a708b63a56`, with AOT SHA-256 +`cd1a1caf26f04c6089ab4b09320b3b1188517c2745bb40a1309f9fb073a52aa1`. +The producer receipt was captured before building at `15ac993` with the explicit +two-file changes later committed as `665b105`; those bytes match that committed +source. The subsequent fixture-only commit changes no production input. +The preserved 1,473-payload shipping bundle is +`followup-20261115/final-sidebar-release/bundle/`; all native matrix receipts +bind to it and the official mapped engine. Probe bundles separately identify +and hash their diagnostic entrypoints; they are not shipping executables. + +| Verification | Result and raw evidence | +| --- | --- | +| Complete final Flutter corpus | All **243 entry files exactly once**, 22 complete-file batches: **5,706 passed, 0 skipped, 2 failed**. Autosave-after-branch deadline and RTL template-dialog initial settle timeout; `followup-20261115/complete-corpus/receipt.json`. The existing qualifier rejects it with `Full test corpus has not passed`; no waiver. | +| Official analyzer | Clean after the final fixture change: `followup-20261115/final-fixture-analyze.log`. | +| Maintained Dart formatting | All 665 tracked Dart files pass; verification copies/build outputs excluded. | +| Current archive/consumer/resolved audits | Exact shared trees, host consumer, resolved native audit and adversarial tests, all three host/design/sidebar audits and self-tests pass: `followup-20261115/current-audits.json`. | +| Unchanged shared suites | Engine **142**, shared UI **489**, native spelling **14**, Python **134**, shared native CTest **2** passed in the first verification phase. Their source/pinned inputs remain unchanged; see `shared-engine-serial.log`, `shared-ui-serial.log`, `spellcheck-native-tests-ready.log`, `python-suite-private.log`, `git-accessibility-tests.log`. | +| Localization/native services | Synchronization check and accent, credential policy, shortcut metadata, GTK host and libsecret scripts passed in the first phase; localization/editor/navigation cases are retained in the final corpus. | +| Actual shipping X11 presentation | **All 16** theme/locale/scale cases pass, including both Japanese 1.5x failures from the earlier build: `followup-20261115/final-native-matrix.json`. All **236** retained captures inspected in **30** labelled grids with full-resolution Japanese branches, narrow history, RTL and focused-filter checks; original hashes verified in `followup-20261115/final-native-review/`. | +| Shipping 100-natural-close gate | **Failed:** 76 exit zero, **23 SIGSEGV + 1 abort**; all 100 records/raw logs and zero unresolved descendants: `followup-20261115/final-natural-close/summary.json`. | +| Final-source native selection | **80/82 pass**. `10-drag-with-scroll`: clipboard; `12-cell-local-drag`: local range/clipboard. All editing/composition/retained-buffer Undo/Redo cases complete. Full fresh report, clipboard evidence and captures: `followup-20261115/final-selection-native/`. | +| Final-source actual application selection/history | **All 52 checks pass**, with clean ownership: `followup-20261115/final-application-selection-result.json`. Uses the real `application.main`, workspace buffers, tab restoration, Linux clipboard, composition and Undo/Redo; framework-dispatched keys/input, separately from physical pointer and shipping close gates. All 52 captures inspected in seven labelled grids; original hashes verified. | +| Final-source native focus | Wayland **Alt-Tab all 13 checks pass**, including the owned supervisor without cleanup/survivors: `followup-20261115/final-focus-native/`. X11 readiness fails; full Wayland minimize/restore times out waiting for resumed lifecycle after restore. Both failed gates remain under `followup-20261115/final-focus-x11/` and `followup-20261115/final-focus-full-wayland/`. | +| Installed BusyMark | Older **0.7.1 Snap revision 31**; changed payload not installed or accepted. Administrator authentication is unavailable. No install, push or publication occurred. | + +The first follow-up corpus stopped after 14 passing batches when subsequent +source changes superseded it. A later frozen run ended with outer exit 143 after +19 complete batches, one watcher-fixture failure and interrupted batch 20. All +243 entry hashes matched before applying the fixture correction. Its incomplete +receipt remains at `followup-20261115/final-corpus/receipt.json`; the termination +cause was not isolated. The final run uses a new receipt and bounded groups of +complete files. No interrupted or changed-input output is used to qualify it. + +The complete final run exposes a three-second autosave-after-history-branch +deadline failure, followed by a teardown/write race. The entire test file and +durable history store are byte-identical to the reviewed original; autosave code +is identical except for removal of the obsolete Workspace snapshot assignment +(`followup-20261115/autosave-source-comparison.json`). All 444 original baseline +production/lock inputs were verified again. The complete unchanged file passes +**178 cases on original and 178 on current production** serially, with the same +assertions and deadline (`history-autosave-comparison.json`). These repeats support +a timing concern, not a resolved root cause or proof of non-regression. The failed +full batch remains failed; no timeout, test or functionality was weakened. + +The second full-run failure is the RTL template-creation dialog's initial +`pumpAndSettle` timeout. The test, production dialog and catalog service are all +byte-identical to the reviewed original (`template-dialog-source-comparison.json`). +The fixture advances real I/O for a fixed interval before settling; the exact +cause of this timeout remains unisolated. Complete serial original/current file +comparisons each pass all **14 cases**, with original assertions and timing +(`template-dialog-comparison.json`). They do not qualify the failed full batch. + +### What remains unaccepted + +The previous shipping build failed 32 natural closes with SIGSEGV and one with +a mutex abort in 100 runs. The original failed 27; the constructor-cleanup build +failed 18. The corrected shipping build still fails 24. A separate unchanged +SDK-template counter also fails one of 100 natural closes on the same official +engine (`followup-20261115/sdk-counter-natural-close/`). Different observed rates +do not establish improvement, non-regression, a common cause or an upstream fault. + +Debugger traces on old and changed shipping builds show native rendering/driver +teardown while engine workers remain active: LLVM/Mesa cleanup in one capture +and EGL/NVIDIA loader cleanup in another. No root cause is claimed. Debugger-only +callback-drain, early-disposal and application-hold experiments failed to prove +a safe fix and were rejected (`followup-20261115/gdb-*`). No lifecycle workaround, +forced exit, delay, engine patch or retained closed engine was shipped. + +The fresh selection report preserves the two failing assertions. The older +`selection-comparison.json` references two missing `/tmp` reports; those raw old +reports are explicitly missing, not reconstructed. The new complete 82-case +report is included in the handoff. Passing Alt-Tab focus does not qualify X11, +full minimize/restore, the independent official-SDK Wayland multi-engine gate, +or installed behavior. A first full-focus setup closed the ownership supervisor's +required input lease; its cancelled output contains no product assertion. +All recorded follow-up ownership cleanups leave zero unresolved descendants. + +Earlier production native WebKit/renderers, large 10,001-note/30-cycle sidebar +workflow, X11 and Wayland spelling/editor-history/PDF/HTML exports passed; their +records remain in `web-render-native.log`, `visualization-native-ready.log`, +`sidebar-native-final.log`, `final-x11/` and `final-wayland/`. They are historical +coverage of that earlier source. The earlier compiled dirty-close/video fixture +still contains readiness failures and a visualization abort; its dependent +reopen was missing. None substitutes for final complete native acceptance. + +The remaining failures need causal native investigation and actual payload-bound +installed acceptance. They do not justify restoring deleted implementations or +adding another architecture. This is a BusyMark-only follow-up; shared pins and +archives are unchanged, and no other consumer change is required. + +### Portable evidence handoff + +The separate local artifact is +`build/architecture-review/busymark-architecture-evidence-20261115.tar.gz`, with +an adjacent `.sha256` checksum. Include this artifact with a source handoff: +ordinary source exports omit the ignored `build/` directory. Its internal +`README.txt` explains path mapping and the historical missing reports. +`followup-20261115/final-evidence-integrity.json` verifies all 243 entry hashes, +all 22 raw-log hashes, current production/shared hashes and all 95 original/current +line rows. That check establishes the integrity of a complete **failed** run. + +The separate archive includes raw passed/failed/incomplete logs, receipts, +original captures and inspection records, full debugger stacks, SDK counter +control source, exact source patches, toolchain/pin hashes, this report and the +95-file line inventory. `MANIFEST.json` records original paths, lengths and +SHA-256 for every included file. Private profiles, caches, downloaded +prerequisites, SDK/build binaries and source checkout copies are excluded. + +Reading the records and verifying their hashes requires no Flutter/Dart SDK. +Re-executing the checks requires the pinned official toolchain and native +prerequisites. Hash integrity does not qualify failed or incomplete acceptance. diff --git a/lib/l10n/app_ar.arb b/lib/l10n/app_ar.arb index ae7778f9..4a4076c0 100644 --- a/lib/l10n/app_ar.arb +++ b/lib/l10n/app_ar.arb @@ -361,6 +361,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "جديد", "open": "فتح", "@open": { "description": "Open action label." @@ -598,15 +599,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "إنشاء", + "home": "الرئيسية", + "openMenu": "قائمة فتح", + "newNextcloudNote": "ملاحظة Nextcloud جديدة", + "shortcutNewDocument": "قائمة جديد", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "إنشاء ملف Markdown أو مشروع Writerside", + "shortcutNewDocumentDescription": "افتح قائمة إنشاء الموارد", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "فتح ملف Markdown أو مجلد أو مشروع Writerside", + "shortcutOpenDescription": "افتح قائمة فتح الموارد", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -956,11 +960,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "مسح أذونات الصور البعيدة", + "clearRemoteImagePermissions": "مسح أذونات الصور لمساحات العمل", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "نسيان مساحات العمل التي سُمح لها بتحميل الصور البعيدة.", + "clearRemoteImagePermissionsDescription": "نسيان جميع أذونات الصور البعيدة لمساحات العمل.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1330,7 +1334,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "اختر ما إذا كان بإمكان BusyMark تحميل الصور البعيدة.", + "remoteImageBlockedTooltip": "تم حظر الصورة البعيدة. انقر لعرض خيارات التحميل.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1342,7 +1346,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "تحميل لمساحة العمل هذه", + "loadThisRemoteImage": "تحميل هذه الصورة", + "remoteImageMoreOptions": "خيارات إضافية…", + "remoteImageMoreOptionsTitle": "أذونات الصور البعيدة", + "loadRemoteImagesInDocument": "تحميل الصور في هذا المستند", + "remoteImageUntilClose": "حتى إغلاق هذا المستند.", + "remoteImageWorkspacePermissionDetail": "يسمح بالصور البعيدة في ⁨{workspace}⁩ حتى تمسح أذونات مساحة العمل في إعدادات الخصوصية.", + "remoteImageGlobalPermissionDetail": "يسمح بالصور البعيدة في كل BusyMark حتى توقف هذا الخيار في إعدادات الخصوصية.", + "remoteImageGlobalSettingsDetail": "السماح بالصور البعيدة في كل BusyMark. تُدار أذونات مساحات العمل بشكل منفصل.", + "loadRemoteImagesForWorkspace": "السماح دائمًا في مساحة العمل هذه", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3639,7 +3651,7 @@ "searchTopicsCategory": "المواضيع", "searchCurrentDocument": "المستند الحالي", "searchCurrentWorkspace": "مساحة العمل الحالية", - "browseNotes": "تصفح الملاحظات", + "browseNotes": "تصفح ملاحظات Nextcloud", "searchActionsCommand": "البحث عن إجراءات", "searchDocumentsCommand": "البحث عن مستندات", "searchTopicsCommand": "البحث عن مواضيع", diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index bd206290..8466f323 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -361,6 +361,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Neu", "open": "Öffnen", "@open": { "description": "Open action label." @@ -598,15 +599,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Erstellen", + "home": "Startseite", + "openMenu": "Menü „Öffnen“", + "newNextcloudNote": "Neue Nextcloud-Notiz", + "shortcutNewDocument": "Menü „Neu“", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Markdown-Datei oder Writerside-Projekt erstellen", + "shortcutNewDocumentDescription": "Menü zum Erstellen von Ressourcen öffnen", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Markdown-Datei, Ordner oder Writerside-Projekt öffnen", + "shortcutOpenDescription": "Menü zum Öffnen von Ressourcen öffnen", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -956,11 +960,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Berechtigungen für externe Bilder löschen", + "clearRemoteImagePermissions": "Bildberechtigungen für Arbeitsbereiche löschen", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Arbeitsbereiche vergessen, denen das Laden externer Bilder erlaubt wurde.", + "clearRemoteImagePermissionsDescription": "Alle Arbeitsbereichsberechtigungen für entfernte Bilder löschen.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1330,7 +1334,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Festlegen, ob BusyMark externe Bilder laden darf.", + "remoteImageBlockedTooltip": "Externes Bild blockiert. Klicken für Ladeoptionen.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1342,7 +1346,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Für diesen Arbeitsbereich laden", + "loadThisRemoteImage": "Dieses Bild laden", + "remoteImageMoreOptions": "Weitere Optionen…", + "remoteImageMoreOptionsTitle": "Berechtigungen für entfernte Bilder", + "loadRemoteImagesInDocument": "Bilder in diesem Dokument laden", + "remoteImageUntilClose": "Bis dieses Dokument geschlossen wird.", + "remoteImageWorkspacePermissionDetail": "Erlaubt entfernte Bilder in {workspace}, bis Sie die Arbeitsbereichsberechtigungen in den Datenschutzeinstellungen löschen.", + "remoteImageGlobalPermissionDetail": "Erlaubt entfernte Bilder in ganz BusyMark, bis Sie dies in den Datenschutzeinstellungen deaktivieren.", + "remoteImageGlobalSettingsDetail": "Entfernte Bilder überall in BusyMark erlauben. Arbeitsbereichsberechtigungen werden separat verwaltet.", + "loadRemoteImagesForWorkspace": "In diesem Arbeitsbereich immer erlauben", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3639,7 +3651,7 @@ "searchTopicsCategory": "Themen", "searchCurrentDocument": "Aktuelles Dokument", "searchCurrentWorkspace": "Aktueller Arbeitsbereich", - "browseNotes": "Notizen durchsuchen", + "browseNotes": "Nextcloud-Notizen durchsuchen", "searchActionsCommand": "Aktionen suchen", "searchDocumentsCommand": "Dokumente suchen", "searchTopicsCommand": "Themen suchen", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 33d6af46..55c53c0a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -401,6 +401,8 @@ "@fullScreen": {"description": "Command that toggles full-screen window mode."}, "markdown": "Markdown", "@markdown": {"description": "Markdown format label."}, + "newResource": "New", + "@newResource": {"description": "Short tooltip for the header button that opens creation options."}, "open": "Open", "@open": {"description": "Open action label."}, "openInFiles": "Open in Files", @@ -523,11 +525,14 @@ "@shortcutDeleteTreeItemDescription": {"description": "Keyboard shortcut description for deleting the selected Files item or removing the selected topic from the table of contents."}, "shortcutGroupGeneral": "General", "@shortcutGroupGeneral": {"description": "Keyboard shortcut group for general application commands."}, - "shortcutNewDocument": "Create", + "home": "Home", + "openMenu": "Open Menu", + "newNextcloudNote": "New Nextcloud Note", + "shortcutNewDocument": "New Menu", "@shortcutNewDocument": {"description": "Keyboard shortcut label for opening the content creation chooser."}, - "shortcutNewDocumentDescription": "Create a Markdown file or Writerside project", + "shortcutNewDocumentDescription": "Show the menu for creating resources", "@shortcutNewDocumentDescription": {"description": "Keyboard shortcut description for creating Markdown files or Writerside projects."}, - "shortcutOpenDescription": "Open a Markdown file, folder, or Writerside project", + "shortcutOpenDescription": "Show the menu for opening resources", "@shortcutOpenDescription": {"description": "Keyboard shortcut description for opening content."}, "shortcutSaveDescription": "Save the current document", "@shortcutSaveDescription": {"description": "Keyboard shortcut description for saving content."}, @@ -638,11 +643,11 @@ "@sidebarViewMenu": { "description": "Tooltip for the sidebar view selector button." }, - "createMarkdownFile": "Create Markdown File", + "createMarkdownFile": "New Markdown File", "@createMarkdownFile": {"description": "Welcome screen action for creating a Markdown file."}, "createMarkdownFileDescription": "Start an unsaved local Markdown document", "@createMarkdownFileDescription": {"description": "Welcome screen subtitle for creating a Markdown file."}, - "createWritersideProject": "Create Writerside Project", + "createWritersideProject": "New Writerside Project", "@createWritersideProject": {"description": "Welcome screen action for creating a Writerside project."}, "createWritersideProjectDescription": "Start a local Writerside-compatible project", "@createWritersideProjectDescription": {"description": "Welcome screen subtitle for creating a Writerside project."}, @@ -712,9 +717,9 @@ "@allowRemoteImages": {"description": "Settings switch title for loading remote images."}, "allowRemoteImagesDescription": "Allow Markdown preview and editor images to load from http and https URLs.", "@allowRemoteImagesDescription": {"description": "Settings switch description for loading remote images."}, - "clearRemoteImagePermissions": "Clear remote image permissions", + "clearRemoteImagePermissions": "Clear workspace image permissions", "@clearRemoteImagePermissions": {"description": "Settings action label for clearing per-workspace remote image permissions."}, - "clearRemoteImagePermissionsDescription": "Forget workspaces that were allowed to load remote images.", + "clearRemoteImagePermissionsDescription": "Forget all workspace permissions for remote images.", "@clearRemoteImagePermissionsDescription": {"description": "Settings action description for clearing per-workspace remote image permissions."}, "clearGitWorkspaceTrust": "Clear trusted Git workspaces", "@clearGitWorkspaceTrust": {"description": "Settings action label for clearing trusted Git workspaces."}, @@ -929,13 +934,29 @@ "@noImageSource": {"description": "Placeholder shown when an image has no source."}, "remoteImageBlocked": "Remote image blocked", "@remoteImageBlocked": {"description": "Placeholder label shown when a remote image is blocked."}, - "remoteImageBlockedTooltip": "Choose whether BusyMark can load remote images.", + "remoteImageBlockedTooltip": "Remote image blocked. Click for loading options.", "@remoteImageBlockedTooltip": {"description": "Tooltip for a blocked remote image placeholder."}, "remoteImagesBlockedTitle": "Remote images are blocked", "@remoteImagesBlockedTitle": {"description": "Dialog title for remote image loading permission."}, "remoteImagesBlockedMessage": "This document references images from the internet. Loading them can reveal network information to the image host.", "@remoteImagesBlockedMessage": {"description": "Dialog message explaining the privacy risk of remote images."}, - "loadRemoteImagesForWorkspace": "Load for this workspace", + "loadThisRemoteImage": "Load this image", + "@loadThisRemoteImage": {"description": "Primary action on a blocked image."}, + "remoteImageMoreOptions": "More options…", + "@remoteImageMoreOptions": {"description": "Opens the additional remote image permission choices."}, + "remoteImageMoreOptionsTitle": "Remote image permissions", + "@remoteImageMoreOptionsTitle": {"description": "Title of the remote image permission dialog."}, + "loadRemoteImagesInDocument": "Load images in this document", + "@loadRemoteImagesInDocument": {"description": "Temporary permission for all images in a single document."}, + "remoteImageUntilClose": "Until this document closes.", + "@remoteImageUntilClose": {"description": "Lifetime of a temporary remote image permission."}, + "remoteImageWorkspacePermissionDetail": "Allows remote images in {workspace} until you clear workspace permissions in Privacy settings.", + "@remoteImageWorkspacePermissionDetail": {"description": "Shows the identity of the workspace and explains how to revoke the permission.", "placeholders": {"workspace": {"type": "String"}}}, + "remoteImageGlobalPermissionDetail": "Allows remote images throughout BusyMark until you turn this off in Privacy settings.", + "@remoteImageGlobalPermissionDetail": {"description": "Explains how to revoke the app-wide remote image permission."}, + "remoteImageGlobalSettingsDetail": "Allow remote images throughout BusyMark. Workspace permissions are managed separately.", + "@remoteImageGlobalSettingsDetail": {"description": "Description for the app-wide Privacy switch."}, + "loadRemoteImagesForWorkspace": "Always allow in this workspace", "@loadRemoteImagesForWorkspace": {"description": "Dialog button that allows remote images for the current workspace."}, "alwaysLoadRemoteImages": "Always load remote images", "@alwaysLoadRemoteImages": {"description": "Dialog button that enables remote images globally."}, @@ -3186,7 +3207,7 @@ "searchTopicsCategory": "Topics", "searchCurrentDocument": "Current document", "searchCurrentWorkspace": "Current workspace", - "browseNotes": "Browse Notes", + "browseNotes": "Browse Nextcloud Notes", "searchActionsCommand": "Search Actions", "searchDocumentsCommand": "Search Documents", "searchTopicsCommand": "Search Topics", diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index edfab100..f2f8d3a0 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Nuevo", "open": "Abrir", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Crear", + "home": "Inicio", + "openMenu": "Menú Abrir", + "newNextcloudNote": "Nueva nota de Nextcloud", + "shortcutNewDocument": "Menú Nuevo", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Crear un archivo Markdown o un proyecto de Writerside", + "shortcutNewDocumentDescription": "Mostrar el menú para crear recursos", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Abrir un archivo Markdown, una carpeta o un proyecto de Writerside", + "shortcutOpenDescription": "Mostrar el menú para abrir recursos", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Borrar permisos de imágenes remotas", + "clearRemoteImagePermissions": "Borrar permisos de imágenes de espacios de trabajo", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Olvida los espacios de trabajo autorizados a cargar imágenes remotas.", + "clearRemoteImagePermissionsDescription": "Olvidar todos los permisos de imágenes remotas de espacios de trabajo.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Elija si BusyMark puede cargar imágenes remotas.", + "remoteImageBlockedTooltip": "Imagen remota bloqueada. Haz clic para ver las opciones de carga.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Cargar en este espacio de trabajo", + "loadThisRemoteImage": "Cargar esta imagen", + "remoteImageMoreOptions": "Más opciones…", + "remoteImageMoreOptionsTitle": "Permisos de imágenes remotas", + "loadRemoteImagesInDocument": "Cargar imágenes en este documento", + "remoteImageUntilClose": "Hasta que se cierre este documento.", + "remoteImageWorkspacePermissionDetail": "Permite las imágenes remotas en {workspace} hasta que borres los permisos del espacio de trabajo en Privacidad.", + "remoteImageGlobalPermissionDetail": "Permite las imágenes remotas en todo BusyMark hasta que desactives esta opción en Privacidad.", + "remoteImageGlobalSettingsDetail": "Permite las imágenes remotas en todo BusyMark. Los permisos de los espacios de trabajo se administran por separado.", + "loadRemoteImagesForWorkspace": "Permitir siempre en este espacio de trabajo", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "Temas", "searchCurrentDocument": "Documento actual", "searchCurrentWorkspace": "Espacio de trabajo actual", - "browseNotes": "Explorar notas", + "browseNotes": "Explorar notas de Nextcloud", "searchActionsCommand": "Buscar acciones", "searchDocumentsCommand": "Buscar documentos", "searchTopicsCommand": "Buscar temas", diff --git a/lib/l10n/app_et.arb b/lib/l10n/app_et.arb index 1157edd7..ac2a69c8 100644 --- a/lib/l10n/app_et.arb +++ b/lib/l10n/app_et.arb @@ -447,6 +447,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Uus", "open": "Ava", "@open": { "description": "Open action label." @@ -684,15 +685,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Loo", + "home": "Avaleht", + "openMenu": "Avamismenüü", + "newNextcloudNote": "Uus Nextcloudi märge", + "shortcutNewDocument": "Uue ressursi menüü", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Loo Markdowni fail või Writerside’i projekt", + "shortcutNewDocumentDescription": "Kuva ressursside loomise menüü", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Ava Markdowni fail, kaust või Writerside’i projekt", + "shortcutOpenDescription": "Kuva ressursside avamise menüü", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1042,11 +1046,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Eemalda välispiltide laadimise load", + "clearRemoteImagePermissions": "Kustuta tööruumide pildiõigused", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Unusta tööruumid, millel oli lubatud välispilte laadida.", + "clearRemoteImagePermissionsDescription": "Unusta kõik tööruumide kaugpiltide õigused.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1416,7 +1420,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Vali, kas BusyMark võib välispilte laadida.", + "remoteImageBlockedTooltip": "Välispilt on blokeeritud. Laadimisvalikute nägemiseks klõpsa.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1428,7 +1432,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Laadi selles tööruumis", + "loadThisRemoteImage": "Laadi see pilt", + "remoteImageMoreOptions": "Rohkem valikuid…", + "remoteImageMoreOptionsTitle": "Kaugpiltide õigused", + "loadRemoteImagesInDocument": "Laadi selle dokumendi pildid", + "remoteImageUntilClose": "Kuni selle dokumendi sulgemiseni.", + "remoteImageWorkspacePermissionDetail": "Lubab kaugpildid tööruumis {workspace}, kuni kustutad tööruumide õigused privaatsusseadetes.", + "remoteImageGlobalPermissionDetail": "Lubab kaugpildid kogu BusyMarkis, kuni lülitad selle privaatsusseadetes välja.", + "remoteImageGlobalSettingsDetail": "Luba kaugpildid kogu BusyMarkis. Tööruumide õigusi hallatakse eraldi.", + "loadRemoteImagesForWorkspace": "Luba selles tööruumis alati", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -4087,7 +4099,7 @@ "searchTopicsCategory": "Teemad", "searchCurrentDocument": "Praegune dokument", "searchCurrentWorkspace": "Praegune tööruum", - "browseNotes": "Sirvi märkmeid", + "browseNotes": "Sirvi Nextcloudi märkmeid", "searchActionsCommand": "Otsi toiminguid", "searchDocumentsCommand": "Otsi dokumente", "searchTopicsCommand": "Otsi teemasid", diff --git a/lib/l10n/app_fa.arb b/lib/l10n/app_fa.arb index e410a54c..f6661857 100644 --- a/lib/l10n/app_fa.arb +++ b/lib/l10n/app_fa.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "جدید", "open": "باز کردن", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "ایجاد", + "home": "خانه", + "openMenu": "منوی باز کردن", + "newNextcloudNote": "یادداشت جدید Nextcloud", + "shortcutNewDocument": "منوی جدید", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "ایجاد فایل Markdown یا پروژهٔ Writerside", + "shortcutNewDocumentDescription": "نمایش منوی ایجاد منابع", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "باز کردن فایل Markdown، پوشه یا پروژهٔ Writerside", + "shortcutOpenDescription": "نمایش منوی باز کردن منابع", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "پاک کردن مجوزهای تصاویر راه دور", + "clearRemoteImagePermissions": "پاک کردن مجوزهای تصویر فضاهای کاری", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "فضاهای کاری‌ای را که اجازهٔ بارگیری تصاویر راه دور داشتند، فراموش کنید.", + "clearRemoteImagePermissionsDescription": "همهٔ مجوزهای تصاویر راه‌دور فضاهای کاری را فراموش کن.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1333,7 +1337,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "انتخاب کنید BusyMark اجازهٔ بارگیری تصاویر راه دور داشته باشد یا نه.", + "remoteImageBlockedTooltip": "تصویر راه دور مسدود شد. برای گزینه‌های بارگیری کلیک کنید.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1345,7 +1349,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "بارگیری برای این فضای کاری", + "loadThisRemoteImage": "بارگیری این تصویر", + "remoteImageMoreOptions": "گزینه‌های بیشتر…", + "remoteImageMoreOptionsTitle": "مجوزهای تصاویر راه‌دور", + "loadRemoteImagesInDocument": "بارگیری تصاویر این سند", + "remoteImageUntilClose": "تا زمان بسته شدن این سند.", + "remoteImageWorkspacePermissionDetail": "تصاویر راه‌دور در ⁨{workspace}⁩ مجاز هستند تا زمانی که مجوزهای فضای کاری را در تنظیمات حریم خصوصی پاک کنید.", + "remoteImageGlobalPermissionDetail": "تصاویر راه‌دور در سراسر BusyMark مجاز هستند تا زمانی که این گزینه را در تنظیمات حریم خصوصی خاموش کنید.", + "remoteImageGlobalSettingsDetail": "اجازهٔ بارگیری تصاویر راه‌دور در سراسر BusyMark. مجوزهای فضای کاری جداگانه مدیریت می‌شوند.", + "loadRemoteImagesForWorkspace": "همیشه در این فضای کاری مجاز باشد", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3669,7 +3681,7 @@ "searchTopicsCategory": "موضوع‌ها", "searchCurrentDocument": "سند کنونی", "searchCurrentWorkspace": "فضای کاری کنونی", - "browseNotes": "مرور یادداشت‌ها", + "browseNotes": "مرور یادداشت‌های Nextcloud", "searchActionsCommand": "جستجوی کنش‌ها", "searchDocumentsCommand": "جستجوی سندها", "searchTopicsCommand": "جستجوی موضوع‌ها", diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index db4b00e5..8a05c1f4 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Nouveau", "open": "Ouvrir", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Créer", + "home": "Accueil", + "openMenu": "Menu Ouvrir", + "newNextcloudNote": "Nouvelle note Nextcloud", + "shortcutNewDocument": "Menu Nouveau", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Créer un fichier Markdown ou un projet Writerside", + "shortcutNewDocumentDescription": "Afficher le menu de création de ressources", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Ouvrir un fichier Markdown, un dossier ou un projet Writerside", + "shortcutOpenDescription": "Afficher le menu d’ouverture de ressources", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Effacer les autorisations d’images distantes", + "clearRemoteImagePermissions": "Effacer les autorisations d’images des espaces de travail", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Oublier les espaces de travail autorisés à charger des images distantes.", + "clearRemoteImagePermissionsDescription": "Oublier toutes les autorisations d’images distantes des espaces de travail.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Choisissez si BusyMark peut charger des images distantes.", + "remoteImageBlockedTooltip": "Image distante bloquée. Cliquez pour voir les options de chargement.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Charger pour cet espace de travail", + "loadThisRemoteImage": "Charger cette image", + "remoteImageMoreOptions": "Plus d’options…", + "remoteImageMoreOptionsTitle": "Autorisations des images distantes", + "loadRemoteImagesInDocument": "Charger les images de ce document", + "remoteImageUntilClose": "Jusqu’à la fermeture de ce document.", + "remoteImageWorkspacePermissionDetail": "Autorise les images distantes dans {workspace} jusqu’à l’effacement des autorisations dans les paramètres de confidentialité.", + "remoteImageGlobalPermissionDetail": "Autorise les images distantes dans tout BusyMark jusqu’à la désactivation de cette option dans les paramètres de confidentialité.", + "remoteImageGlobalSettingsDetail": "Autorise les images distantes dans tout BusyMark. Les autorisations des espaces de travail sont gérées séparément.", + "loadRemoteImagesForWorkspace": "Toujours autoriser dans cet espace de travail", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "Rubriques", "searchCurrentDocument": "Document actuel", "searchCurrentWorkspace": "Espace de travail actuel", - "browseNotes": "Parcourir les notes", + "browseNotes": "Parcourir les notes Nextcloud", "searchActionsCommand": "Rechercher des actions", "searchDocumentsCommand": "Rechercher des documents", "searchTopicsCommand": "Rechercher des rubriques", diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index cd5cd329..f6ee91d7 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "नया", "open": "खोलें", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "बनाएँ", + "home": "होम", + "openMenu": "खोलें मेनू", + "newNextcloudNote": "नया Nextcloud नोट", + "shortcutNewDocument": "नया मेनू", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Markdown फ़ाइल या Writerside प्रोजेक्ट बनाएँ", + "shortcutNewDocumentDescription": "संसाधन बनाने का मेनू दिखाएँ", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Markdown फ़ाइल, फ़ोल्डर या Writerside प्रोजेक्ट खोलें", + "shortcutOpenDescription": "संसाधन खोलने का मेनू दिखाएँ", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "दूरस्थ छवि अनुमतियाँ साफ़ करें", + "clearRemoteImagePermissions": "कार्यस्थानों की छवि अनुमतियाँ हटाएँ", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "उन कार्यस्थानों को भूलें जिन्हें दूरस्थ छवियाँ लोड करने की अनुमति दी गई थी।", + "clearRemoteImagePermissionsDescription": "कार्यस्थानों की सभी दूरस्थ छवि अनुमतियाँ भूलें।", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "चुनें कि BusyMark दूरस्थ छवियाँ लोड कर सकता है या नहीं।", + "remoteImageBlockedTooltip": "दूरस्थ छवि अवरुद्ध है। लोड करने के विकल्पों के लिए क्लिक करें।", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "इस कार्यस्थान के लिए लोड करें", + "loadThisRemoteImage": "यह छवि लोड करें", + "remoteImageMoreOptions": "और विकल्प…", + "remoteImageMoreOptionsTitle": "दूरस्थ छवियों की अनुमतियाँ", + "loadRemoteImagesInDocument": "इस दस्तावेज़ की छवियाँ लोड करें", + "remoteImageUntilClose": "इस दस्तावेज़ के बंद होने तक।", + "remoteImageWorkspacePermissionDetail": "गोपनीयता सेटिंग में कार्यस्थान की अनुमतियाँ हटाने तक {workspace} में दूरस्थ छवियों की अनुमति देता है।", + "remoteImageGlobalPermissionDetail": "गोपनीयता सेटिंग में यह विकल्प बंद करने तक पूरे BusyMark में दूरस्थ छवियों की अनुमति देता है।", + "remoteImageGlobalSettingsDetail": "पूरे BusyMark में दूरस्थ छवियों की अनुमति दें। कार्यस्थानों की अनुमतियाँ अलग से प्रबंधित होती हैं।", + "loadRemoteImagesForWorkspace": "इस कार्यस्थान में हमेशा अनुमति दें", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "विषय", "searchCurrentDocument": "वर्तमान दस्तावेज़", "searchCurrentWorkspace": "वर्तमान कार्यक्षेत्र", - "browseNotes": "नोट ब्राउज़ करें", + "browseNotes": "Nextcloud नोट ब्राउज़ करें", "searchActionsCommand": "क्रियाएँ खोजें", "searchDocumentsCommand": "दस्तावेज़ खोजें", "searchTopicsCommand": "विषय खोजें", diff --git a/lib/l10n/app_id.arb b/lib/l10n/app_id.arb index 38a962de..9123a21c 100644 --- a/lib/l10n/app_id.arb +++ b/lib/l10n/app_id.arb @@ -474,6 +474,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Baru", "open": "Buka", "@open": { "description": "Open action label." @@ -714,15 +715,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Buat", + "home": "Beranda", + "openMenu": "Menu Buka", + "newNextcloudNote": "Catatan Nextcloud Baru", + "shortcutNewDocument": "Menu Baru", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "Buat file Markdown atau proyek Writerside", + "shortcutNewDocumentDescription": "Tampilkan menu untuk membuat sumber daya", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "Buka file Markdown, folder, atau proyek Writerside", + "shortcutOpenDescription": "Tampilkan menu untuk membuka sumber daya", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1072,11 +1076,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Hapus izin gambar jarak jauh", + "clearRemoteImagePermissions": "Hapus izin gambar ruang kerja", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Lupakan ruang kerja yang diizinkan memuat gambar jarak jauh.", + "clearRemoteImagePermissionsDescription": "Lupakan semua izin gambar jarak jauh untuk ruang kerja.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1492,7 +1496,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Pilih apakah BusyMark dapat memuat gambar jarak jauh.", + "remoteImageBlockedTooltip": "Gambar jarak jauh diblokir. Klik untuk opsi pemuatan.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1504,7 +1508,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Muat untuk ruang kerja ini", + "loadThisRemoteImage": "Muat gambar ini", + "remoteImageMoreOptions": "Opsi lainnya…", + "remoteImageMoreOptionsTitle": "Izin gambar jarak jauh", + "loadRemoteImagesInDocument": "Muat gambar di dokumen ini", + "remoteImageUntilClose": "Hingga dokumen ini ditutup.", + "remoteImageWorkspacePermissionDetail": "Mengizinkan gambar jarak jauh di {workspace} hingga izin ruang kerja dihapus di pengaturan Privasi.", + "remoteImageGlobalPermissionDetail": "Mengizinkan gambar jarak jauh di seluruh BusyMark hingga opsi ini dimatikan di pengaturan Privasi.", + "remoteImageGlobalSettingsDetail": "Izinkan gambar jarak jauh di seluruh BusyMark. Izin ruang kerja dikelola secara terpisah.", + "loadRemoteImagesForWorkspace": "Selalu izinkan di ruang kerja ini", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5157,7 +5169,7 @@ "searchTopicsCategory": "Topik", "searchCurrentDocument": "Dokumen saat ini", "searchCurrentWorkspace": "Ruang kerja saat ini", - "browseNotes": "Jelajahi catatan", + "browseNotes": "Jelajahi Catatan Nextcloud", "searchActionsCommand": "Cari tindakan", "searchDocumentsCommand": "Cari dokumen", "searchTopicsCommand": "Cari topik", diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb index b11695c7..88a341aa 100644 --- a/lib/l10n/app_it.arb +++ b/lib/l10n/app_it.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Nuovo", "open": "Apri", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Crea", + "home": "Pagina iniziale", + "openMenu": "Menu Apri", + "newNextcloudNote": "Nuova nota Nextcloud", + "shortcutNewDocument": "Menu Nuovo", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Crea un file Markdown o un progetto Writerside", + "shortcutNewDocumentDescription": "Mostra il menu per creare risorse", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Apri un file Markdown, una cartella o un progetto Writerside", + "shortcutOpenDescription": "Mostra il menu per aprire risorse", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Cancella autorizzazioni per immagini remote", + "clearRemoteImagePermissions": "Cancella le autorizzazioni delle immagini degli spazi di lavoro", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Dimentica le aree di lavoro autorizzate a caricare immagini remote.", + "clearRemoteImagePermissionsDescription": "Dimentica tutte le autorizzazioni per le immagini remote degli spazi di lavoro.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Scegli se BusyMark può caricare immagini remote.", + "remoteImageBlockedTooltip": "Immagine remota bloccata. Fai clic per le opzioni di caricamento.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Carica per quest’area di lavoro", + "loadThisRemoteImage": "Carica questa immagine", + "remoteImageMoreOptions": "Altre opzioni…", + "remoteImageMoreOptionsTitle": "Autorizzazioni per le immagini remote", + "loadRemoteImagesInDocument": "Carica le immagini in questo documento", + "remoteImageUntilClose": "Fino alla chiusura di questo documento.", + "remoteImageWorkspacePermissionDetail": "Consente le immagini remote in {workspace} finché non cancelli le autorizzazioni degli spazi di lavoro nelle impostazioni di privacy.", + "remoteImageGlobalPermissionDetail": "Consente le immagini remote in tutto BusyMark finché non disattivi questa opzione nelle impostazioni di privacy.", + "remoteImageGlobalSettingsDetail": "Consenti le immagini remote in tutto BusyMark. Le autorizzazioni degli spazi di lavoro si gestiscono separatamente.", + "loadRemoteImagesForWorkspace": "Consenti sempre in questo spazio di lavoro", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "Argomenti", "searchCurrentDocument": "Documento corrente", "searchCurrentWorkspace": "Area di lavoro corrente", - "browseNotes": "Sfoglia note", + "browseNotes": "Sfoglia le note Nextcloud", "searchActionsCommand": "Cerca azioni", "searchDocumentsCommand": "Cerca documenti", "searchTopicsCommand": "Cerca argomenti", diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb index 27c0bd20..af44683c 100644 --- a/lib/l10n/app_ja.arb +++ b/lib/l10n/app_ja.arb @@ -476,6 +476,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "新規作成", "open": "開く", "@open": { "description": "Open action label." @@ -716,15 +717,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "作成", + "home": "ホーム", + "openMenu": "開くメニュー", + "newNextcloudNote": "新しい Nextcloud ノート", + "shortcutNewDocument": "新規作成メニュー", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "Markdown ファイルまたは Writerside プロジェクトを作成", + "shortcutNewDocumentDescription": "リソースを作成するメニューを表示", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "Markdown ファイル、フォルダー、または Writerside プロジェクトを開く", + "shortcutOpenDescription": "リソースを開くメニューを表示", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1074,11 +1078,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "リモート画像の権限を消去", + "clearRemoteImagePermissions": "ワークスペースの画像の許可を消去", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "リモート画像の読み込みを許可したワークスペースの権限を忘れる", + "clearRemoteImagePermissionsDescription": "すべてのワークスペースのリモート画像の許可を消去します。", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1494,7 +1498,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "BusyMark にリモート画像の読み込みを許可するか選択", + "remoteImageBlockedTooltip": "リモート画像をブロックしました。クリックして読み込みオプションを表示します。", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1506,7 +1510,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "このワークスペースで読み込む", + "loadThisRemoteImage": "この画像を読み込む", + "remoteImageMoreOptions": "その他のオプション…", + "remoteImageMoreOptionsTitle": "リモート画像の許可", + "loadRemoteImagesInDocument": "この文書の画像を読み込む", + "remoteImageUntilClose": "この文書を閉じるまで有効です。", + "remoteImageWorkspacePermissionDetail": "プライバシー設定でワークスペースの許可を消去するまで、{workspace} のリモート画像を許可します。", + "remoteImageGlobalPermissionDetail": "プライバシー設定でこのオプションをオフにするまで、BusyMark 全体でリモート画像を許可します。", + "remoteImageGlobalSettingsDetail": "BusyMark 全体でリモート画像を許可します。ワークスペースの許可は個別に管理されます。", + "loadRemoteImagesForWorkspace": "このワークスペースでは常に許可する", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5169,7 +5181,7 @@ "searchTopicsCategory": "トピック", "searchCurrentDocument": "現在のドキュメント", "searchCurrentWorkspace": "現在のワークスペース", - "browseNotes": "ノートを参照", + "browseNotes": "Nextcloud ノートを参照", "searchActionsCommand": "アクションを検索", "searchDocumentsCommand": "ドキュメントを検索", "searchTopicsCommand": "トピックを検索", diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb index 60d3362b..ad89a933 100644 --- a/lib/l10n/app_ko.arb +++ b/lib/l10n/app_ko.arb @@ -474,6 +474,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "새로 만들기", "open": "열기", "@open": { "description": "Open action label." @@ -714,15 +715,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "만들기", + "home": "홈", + "openMenu": "열기 메뉴", + "newNextcloudNote": "새 Nextcloud 노트", + "shortcutNewDocument": "새로 만들기 메뉴", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "Markdown 파일 또는 Writerside 프로젝트 만들기", + "shortcutNewDocumentDescription": "리소스를 만드는 메뉴 표시", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "Markdown 파일, 폴더 또는 Writerside 프로젝트 열기", + "shortcutOpenDescription": "리소스를 여는 메뉴 표시", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1072,11 +1076,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "원격 이미지 권한 초기화", + "clearRemoteImagePermissions": "작업 공간의 이미지 권한 지우기", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "원격 이미지 로드 권한이 허용된 작업공간의 저장된 권한을 삭제합니다.", + "clearRemoteImagePermissionsDescription": "모든 작업 공간의 원격 이미지 권한을 지웁니다.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1492,7 +1496,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "BusyMark가 원격 이미지를 로드할 수 있는지 여부를 선택합니다.", + "remoteImageBlockedTooltip": "원격 이미지가 차단되었습니다. 클릭하여 불러오기 옵션을 확인하세요.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1504,7 +1508,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "이 작업공간에서 로드", + "loadThisRemoteImage": "이 이미지 불러오기", + "remoteImageMoreOptions": "추가 옵션…", + "remoteImageMoreOptionsTitle": "원격 이미지 권한", + "loadRemoteImagesInDocument": "이 문서의 이미지 불러오기", + "remoteImageUntilClose": "이 문서를 닫을 때까지 적용됩니다.", + "remoteImageWorkspacePermissionDetail": "개인정보 보호 설정에서 작업 공간 권한을 지울 때까지 {workspace}의 원격 이미지를 허용합니다.", + "remoteImageGlobalPermissionDetail": "개인정보 보호 설정에서 이 옵션을 끌 때까지 BusyMark 전체에서 원격 이미지를 허용합니다.", + "remoteImageGlobalSettingsDetail": "BusyMark 전체에서 원격 이미지를 허용합니다. 작업 공간 권한은 별도로 관리됩니다.", + "loadRemoteImagesForWorkspace": "이 작업 공간에서 항상 허용", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5157,7 +5169,7 @@ "searchTopicsCategory": "주제", "searchCurrentDocument": "현재 문서", "searchCurrentWorkspace": "현재 작업 공간", - "browseNotes": "노트 찾아보기", + "browseNotes": "Nextcloud 노트 찾아보기", "searchActionsCommand": "작업 검색", "searchDocumentsCommand": "문서 검색", "searchTopicsCommand": "주제 검색", diff --git a/lib/l10n/app_nb.arb b/lib/l10n/app_nb.arb index b3ae2fba..4b65b7e2 100644 --- a/lib/l10n/app_nb.arb +++ b/lib/l10n/app_nb.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Ny", "open": "Åpne", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Opprett", + "home": "Hjem", + "openMenu": "Åpne-meny", + "newNextcloudNote": "Nytt Nextcloud-notat", + "shortcutNewDocument": "Ny-meny", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Opprett en Markdown-fil eller et Writerside-prosjekt", + "shortcutNewDocumentDescription": "Vis menyen for å opprette ressurser", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Åpne en Markdown-fil, en mappe eller et Writerside-prosjekt", + "shortcutOpenDescription": "Vis menyen for å åpne ressurser", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Tøm tillatelser for eksterne bilder", + "clearRemoteImagePermissions": "Slett bildetillatelser for arbeidsområder", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Glem arbeidsområder som fikk tillatelse til å laste inn eksterne bilder.", + "clearRemoteImagePermissionsDescription": "Glem alle tillatelser for eksterne bilder i arbeidsområder.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Velg om BusyMark kan laste inn eksterne bilder.", + "remoteImageBlockedTooltip": "Eksternt bilde blokkert. Klikk for innlastingsvalg.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Last inn for dette arbeidsområdet", + "loadThisRemoteImage": "Last inn dette bildet", + "remoteImageMoreOptions": "Flere valg…", + "remoteImageMoreOptionsTitle": "Tillatelser for eksterne bilder", + "loadRemoteImagesInDocument": "Last inn bilder i dette dokumentet", + "remoteImageUntilClose": "Til dette dokumentet lukkes.", + "remoteImageWorkspacePermissionDetail": "Tillater eksterne bilder i {workspace} til du sletter arbeidsområdetillatelsene i personverninnstillingene.", + "remoteImageGlobalPermissionDetail": "Tillater eksterne bilder i hele BusyMark til du slår dette av i personverninnstillingene.", + "remoteImageGlobalSettingsDetail": "Tillat eksterne bilder i hele BusyMark. Tillatelser for arbeidsområder administreres separat.", + "loadRemoteImagesForWorkspace": "Tillat alltid i dette arbeidsområdet", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "Emner", "searchCurrentDocument": "Gjeldende dokument", "searchCurrentWorkspace": "Gjeldende arbeidsområde", - "browseNotes": "Bla gjennom notater", + "browseNotes": "Bla gjennom Nextcloud-notater", "searchActionsCommand": "Søk etter handlinger", "searchDocumentsCommand": "Søk etter dokumenter", "searchTopicsCommand": "Søk etter emner", diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 8bda1d74..1504f800 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -474,6 +474,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Nieuw", "open": "Openen", "@open": { "description": "Open action label." @@ -714,15 +715,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Maken", + "home": "Start", + "openMenu": "Menu Openen", + "newNextcloudNote": "Nieuwe Nextcloud-notitie", + "shortcutNewDocument": "Menu Nieuw", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "Maak een Markdown-bestand of Writerside-project", + "shortcutNewDocumentDescription": "Toon het menu om bronnen te maken", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "Open een Markdown-bestand, map of Writerside-project", + "shortcutOpenDescription": "Toon het menu om bronnen te openen", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1072,11 +1076,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Wis machtigingen voor externe afbeeldingen", + "clearRemoteImagePermissions": "Afbeeldingsmachtigingen voor werkruimten wissen", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Verwijder de opgeslagen rechten voor werkruimten die externe afbeeldingen mochten laden.", + "clearRemoteImagePermissionsDescription": "Vergeet alle machtigingen voor externe afbeeldingen in werkruimten.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1492,7 +1496,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Kies of BusyMark externe afbeeldingen kan laden.", + "remoteImageBlockedTooltip": "Externe afbeelding geblokkeerd. Klik voor laadopties.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1504,7 +1508,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Voor deze werkruimte laden", + "loadThisRemoteImage": "Deze afbeelding laden", + "remoteImageMoreOptions": "Meer opties…", + "remoteImageMoreOptionsTitle": "Machtigingen voor externe afbeeldingen", + "loadRemoteImagesInDocument": "Afbeeldingen in dit document laden", + "remoteImageUntilClose": "Totdat dit document wordt gesloten.", + "remoteImageWorkspacePermissionDetail": "Staat externe afbeeldingen in {workspace} toe totdat je de werkruimtemachtigingen wist in de privacyinstellingen.", + "remoteImageGlobalPermissionDetail": "Staat externe afbeeldingen in heel BusyMark toe totdat je dit uitschakelt in de privacyinstellingen.", + "remoteImageGlobalSettingsDetail": "Sta externe afbeeldingen in heel BusyMark toe. Werkruimtemachtigingen worden apart beheerd.", + "loadRemoteImagesForWorkspace": "Altijd toestaan in deze werkruimte", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5157,7 +5169,7 @@ "searchTopicsCategory": "Onderwerpen", "searchCurrentDocument": "Huidig document", "searchCurrentWorkspace": "Huidige werkruimte", - "browseNotes": "Notities bekijken", + "browseNotes": "Door Nextcloud-notities bladeren", "searchActionsCommand": "Acties zoeken", "searchDocumentsCommand": "Documenten zoeken", "searchTopicsCommand": "Onderwerpen zoeken", diff --git a/lib/l10n/app_pl.arb b/lib/l10n/app_pl.arb index ae5bc726..7b0dd025 100644 --- a/lib/l10n/app_pl.arb +++ b/lib/l10n/app_pl.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Nowy", "open": "Otwórz", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Utwórz", + "home": "Strona główna", + "openMenu": "Menu Otwórz", + "newNextcloudNote": "Nowa notatka Nextcloud", + "shortcutNewDocument": "Menu Nowy", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Utwórz plik Markdown lub projekt Writerside", + "shortcutNewDocumentDescription": "Pokaż menu tworzenia zasobów", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Otwórz plik Markdown, folder lub projekt Writerside", + "shortcutOpenDescription": "Pokaż menu otwierania zasobów", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Wyczyść uprawnienia do obrazów zdalnych", + "clearRemoteImagePermissions": "Wyczyść uprawnienia do obrazów w obszarach roboczych", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Zapomnij obszary robocze, którym zezwolono na wczytywanie obrazów zdalnych.", + "clearRemoteImagePermissionsDescription": "Usuń wszystkie uprawnienia obszarów roboczych do obrazów zdalnych.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Wybierz, czy BusyMark może wczytywać obrazy zdalne.", + "remoteImageBlockedTooltip": "Obraz zdalny zablokowany. Kliknij, aby wyświetlić opcje wczytywania.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Wczytaj w tym obszarze roboczym", + "loadThisRemoteImage": "Wczytaj ten obraz", + "remoteImageMoreOptions": "Więcej opcji…", + "remoteImageMoreOptionsTitle": "Uprawnienia do obrazów zdalnych", + "loadRemoteImagesInDocument": "Wczytaj obrazy w tym dokumencie", + "remoteImageUntilClose": "Do zamknięcia tego dokumentu.", + "remoteImageWorkspacePermissionDetail": "Zezwala na obrazy zdalne w {workspace} do czasu wyczyszczenia uprawnień obszarów roboczych w ustawieniach prywatności.", + "remoteImageGlobalPermissionDetail": "Zezwala na obrazy zdalne w całym BusyMark do czasu wyłączenia tej opcji w ustawieniach prywatności.", + "remoteImageGlobalSettingsDetail": "Zezwalaj na obrazy zdalne w całym BusyMark. Uprawnienia obszarów roboczych są zarządzane oddzielnie.", + "loadRemoteImagesForWorkspace": "Zawsze zezwalaj w tym obszarze roboczym", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3653,7 +3665,7 @@ "searchTopicsCategory": "Tematy", "searchCurrentDocument": "Bieżący dokument", "searchCurrentWorkspace": "Bieżący obszar roboczy", - "browseNotes": "Przeglądaj notatki", + "browseNotes": "Przeglądaj notatki Nextcloud", "searchActionsCommand": "Szukaj działań", "searchDocumentsCommand": "Szukaj dokumentów", "searchTopicsCommand": "Szukaj tematów", diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb index 02038672..d97d08b2 100644 --- a/lib/l10n/app_pt.arb +++ b/lib/l10n/app_pt.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Novo", "open": "Abrir", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Criar", + "home": "Início", + "openMenu": "Menu Abrir", + "newNextcloudNote": "Nova nota do Nextcloud", + "shortcutNewDocument": "Menu Novo", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Criar ficheiro Markdown ou projeto Writerside", + "shortcutNewDocumentDescription": "Mostrar o menu para criar recursos", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Abrir um ficheiro Markdown, uma pasta ou um projeto Writerside", + "shortcutOpenDescription": "Mostrar o menu para abrir recursos", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Limpar permissões de imagens remotas", + "clearRemoteImagePermissions": "Limpar permissões de imagens dos espaços de trabalho", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Esquecer os espaços de trabalho autorizados a carregar imagens remotas.", + "clearRemoteImagePermissionsDescription": "Esquecer todas as permissões dos espaços de trabalho para imagens remotas.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Escolha se o BusyMark pode carregar imagens remotas.", + "remoteImageBlockedTooltip": "Imagem remota bloqueada. Clique para ver as opções de carregamento.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Carregar neste espaço de trabalho", + "loadThisRemoteImage": "Carregar esta imagem", + "remoteImageMoreOptions": "Mais opções…", + "remoteImageMoreOptionsTitle": "Permissões de imagens remotas", + "loadRemoteImagesInDocument": "Carregar imagens neste documento", + "remoteImageUntilClose": "Até fechar este documento.", + "remoteImageWorkspacePermissionDetail": "Permite imagens remotas em {workspace} até limpar as permissões de espaços de trabalho nas definições de privacidade.", + "remoteImageGlobalPermissionDetail": "Permite imagens remotas em todo o BusyMark até desativar esta opção nas definições de privacidade.", + "remoteImageGlobalSettingsDetail": "Permitir imagens remotas em todo o BusyMark. As permissões dos espaços de trabalho são geridas separadamente.", + "loadRemoteImagesForWorkspace": "Permitir sempre neste espaço de trabalho", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "Tópicos", "searchCurrentDocument": "Documento atual", "searchCurrentWorkspace": "Área de trabalho atual", - "browseNotes": "Explorar notas", + "browseNotes": "Explorar notas do Nextcloud", "searchActionsCommand": "Pesquisar ações", "searchDocumentsCommand": "Pesquisar documentos", "searchTopicsCommand": "Pesquisar tópicos", diff --git a/lib/l10n/app_pt_BR.arb b/lib/l10n/app_pt_BR.arb index 3210b32c..f83c7e10 100644 --- a/lib/l10n/app_pt_BR.arb +++ b/lib/l10n/app_pt_BR.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Novo", "open": "Abrir", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Criar", + "home": "Início", + "openMenu": "Menu Abrir", + "newNextcloudNote": "Nova nota do Nextcloud", + "shortcutNewDocument": "Menu Novo", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Criar arquivo Markdown ou projeto Writerside", + "shortcutNewDocumentDescription": "Mostrar o menu para criar recursos", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Abrir um arquivo Markdown, uma pasta ou um projeto Writerside", + "shortcutOpenDescription": "Mostrar o menu para abrir recursos", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Limpar permissões de imagens remotas", + "clearRemoteImagePermissions": "Limpar permissões de imagens dos espaços de trabalho", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Esquecer os espaços de trabalho autorizados a carregar imagens remotas.", + "clearRemoteImagePermissionsDescription": "Esquecer todas as permissões de imagens remotas dos espaços de trabalho.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Escolha se o BusyMark pode carregar imagens remotas.", + "remoteImageBlockedTooltip": "Imagem remota bloqueada. Clique para ver as opções de carregamento.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Carregar neste espaço de trabalho", + "loadThisRemoteImage": "Carregar esta imagem", + "remoteImageMoreOptions": "Mais opções…", + "remoteImageMoreOptionsTitle": "Permissões de imagens remotas", + "loadRemoteImagesInDocument": "Carregar imagens neste documento", + "remoteImageUntilClose": "Até fechar este documento.", + "remoteImageWorkspacePermissionDetail": "Permite imagens remotas em {workspace} até limpar as permissões dos espaços de trabalho nas configurações de Privacidade.", + "remoteImageGlobalPermissionDetail": "Permite imagens remotas em todo o BusyMark até desativar esta opção nas configurações de Privacidade.", + "remoteImageGlobalSettingsDetail": "Permitir imagens remotas em todo o BusyMark. As permissões dos espaços de trabalho são gerenciadas separadamente.", + "loadRemoteImagesForWorkspace": "Sempre permitir neste espaço de trabalho", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3627,7 +3639,7 @@ "searchTopicsCategory": "Tópicos", "searchCurrentDocument": "Documento atual", "searchCurrentWorkspace": "Área de trabalho atual", - "browseNotes": "Explorar notas", + "browseNotes": "Explorar notas do Nextcloud", "searchActionsCommand": "Pesquisar ações", "searchDocumentsCommand": "Pesquisar documentos", "searchTopicsCommand": "Pesquisar tópicos", diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 761162b9..f170bf10 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Создать", "open": "Открыть", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Создать", + "home": "Главная", + "openMenu": "Меню «Открыть»", + "newNextcloudNote": "Новая заметка Nextcloud", + "shortcutNewDocument": "Меню «Создать»", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Создать файл Markdown или проект Writerside", + "shortcutNewDocumentDescription": "Показать меню создания ресурсов", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Открыть файл Markdown, папку или проект Writerside", + "shortcutOpenDescription": "Показать меню открытия ресурсов", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Сбросить разрешения на удалённые изображения", + "clearRemoteImagePermissions": "Очистить разрешения для изображений в рабочих пространствах", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Забыть рабочие области, которым было разрешено загружать удалённые изображения.", + "clearRemoteImagePermissionsDescription": "Забыть все разрешения рабочих пространств на загрузку удалённых изображений.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Выберите, может ли BusyMark загружать удалённые изображения.", + "remoteImageBlockedTooltip": "Удалённое изображение заблокировано. Нажмите, чтобы выбрать способ загрузки.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Загрузить для этой рабочей области", + "loadThisRemoteImage": "Загрузить это изображение", + "remoteImageMoreOptions": "Другие варианты…", + "remoteImageMoreOptionsTitle": "Разрешения для удалённых изображений", + "loadRemoteImagesInDocument": "Загрузить изображения в этом документе", + "remoteImageUntilClose": "До закрытия этого документа.", + "remoteImageWorkspacePermissionDetail": "Разрешает удалённые изображения в {workspace}, пока вы не очистите разрешения для рабочих пространств в настройках конфиденциальности.", + "remoteImageGlobalPermissionDetail": "Разрешает удалённые изображения во всём BusyMark, пока вы не отключите эту настройку в разделе конфиденциальности.", + "remoteImageGlobalSettingsDetail": "Разрешает удалённые изображения во всём BusyMark. Разрешения рабочих пространств настраиваются отдельно.", + "loadRemoteImagesForWorkspace": "Всегда разрешать в этом рабочем пространстве", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3653,7 +3665,7 @@ "searchTopicsCategory": "Темы", "searchCurrentDocument": "Текущий документ", "searchCurrentWorkspace": "Текущая рабочая область", - "browseNotes": "Обзор заметок", + "browseNotes": "Просмотр заметок Nextcloud", "searchActionsCommand": "Поиск действий", "searchDocumentsCommand": "Поиск документов", "searchTopicsCommand": "Поиск тем", diff --git a/lib/l10n/app_tr.arb b/lib/l10n/app_tr.arb index 3cfd1f77..7403ee96 100644 --- a/lib/l10n/app_tr.arb +++ b/lib/l10n/app_tr.arb @@ -474,6 +474,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Yeni", "open": "Aç", "@open": { "description": "Open action label." @@ -714,15 +715,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Oluştur", + "home": "Ana Sayfa", + "openMenu": "Aç Menüsü", + "newNextcloudNote": "Yeni Nextcloud Notu", + "shortcutNewDocument": "Yeni Menüsü", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "Markdown dosyası veya Writerside projesi oluştur", + "shortcutNewDocumentDescription": "Kaynak oluşturma menüsünü göster", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "Markdown dosyasını, klasörünü veya Writerside projesini açın", + "shortcutOpenDescription": "Kaynak açma menüsünü göster", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1072,11 +1076,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Harici görsel izinlerini temizle", + "clearRemoteImagePermissions": "Çalışma alanı resim izinlerini temizle", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Harici görsellerin yüklenmesine izin verilen çalışma alanlarını unutun.", + "clearRemoteImagePermissionsDescription": "Çalışma alanlarının tüm uzak resim izinlerini unut.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1492,7 +1496,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "BusyMark'ın harici görselleri yükleyip yükleyemeyeceğini seçin.", + "remoteImageBlockedTooltip": "Uzak görsel engellendi. Yükleme seçenekleri için tıklayın.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1504,7 +1508,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Bu çalışma alanı için yükleme", + "loadThisRemoteImage": "Bu resmi yükle", + "remoteImageMoreOptions": "Diğer seçenekler…", + "remoteImageMoreOptionsTitle": "Uzak resim izinleri", + "loadRemoteImagesInDocument": "Bu belgedeki resimleri yükle", + "remoteImageUntilClose": "Bu belge kapanana kadar.", + "remoteImageWorkspacePermissionDetail": "Gizlilik ayarlarında çalışma alanı izinlerini temizleyene kadar {workspace} içindeki uzak resimlere izin verir.", + "remoteImageGlobalPermissionDetail": "Gizlilik ayarlarında bu seçeneği kapatana kadar BusyMark genelinde uzak resimlere izin verir.", + "remoteImageGlobalSettingsDetail": "BusyMark genelinde uzak resimlere izin ver. Çalışma alanı izinleri ayrı yönetilir.", + "loadRemoteImagesForWorkspace": "Bu çalışma alanında her zaman izin ver", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5157,7 +5169,7 @@ "searchTopicsCategory": "Konular", "searchCurrentDocument": "Geçerli belge", "searchCurrentWorkspace": "Geçerli çalışma alanı", - "browseNotes": "Notlara göz at", + "browseNotes": "Nextcloud Notlarına Göz At", "searchActionsCommand": "Eylemleri ara", "searchDocumentsCommand": "Belgeleri ara", "searchTopicsCommand": "Konuları ara", diff --git a/lib/l10n/app_uk.arb b/lib/l10n/app_uk.arb index 01f3d568..09f37f0e 100644 --- a/lib/l10n/app_uk.arb +++ b/lib/l10n/app_uk.arb @@ -359,6 +359,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Створити", "open": "Відкрити", "@open": { "description": "Open action label." @@ -596,15 +597,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Створити", + "home": "Головна", + "openMenu": "Меню «Відкрити»", + "newNextcloudNote": "Нова нотатка Nextcloud", + "shortcutNewDocument": "Меню «Створити»", "@shortcutNewDocument": { "description": "Keyboard shortcut label for creating a document." }, - "shortcutNewDocumentDescription": "Створити файл Markdown або проєкт Writerside", + "shortcutNewDocumentDescription": "Показати меню створення ресурсів", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating a document." }, - "shortcutOpenDescription": "Відкрити файл Markdown, папку або проєкт Writerside", + "shortcutOpenDescription": "Показати меню відкриття ресурсів", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -954,11 +958,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Очистити дозволи для віддалених зображень", + "clearRemoteImagePermissions": "Очистити дозволи на зображення в робочих просторах", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Забути робочі області, яким було дозволено завантажувати віддалені зображення.", + "clearRemoteImagePermissionsDescription": "Забути всі дозволи робочих просторів для віддалених зображень.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1328,7 +1332,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Виберіть, чи може BusyMark завантажувати віддалені зображення.", + "remoteImageBlockedTooltip": "Віддалене зображення заблоковано. Натисніть, щоб переглянути параметри завантаження.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1340,7 +1344,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Завантажити для цієї робочої області", + "loadThisRemoteImage": "Завантажити це зображення", + "remoteImageMoreOptions": "Інші варіанти…", + "remoteImageMoreOptionsTitle": "Дозволи для віддалених зображень", + "loadRemoteImagesInDocument": "Завантажити зображення в цьому документі", + "remoteImageUntilClose": "До закриття цього документа.", + "remoteImageWorkspacePermissionDetail": "Дозволяє віддалені зображення в {workspace}, доки не очистите дозволи робочих просторів у налаштуваннях конфіденційності.", + "remoteImageGlobalPermissionDetail": "Дозволяє віддалені зображення в усьому BusyMark, доки не вимкнете цю опцію в налаштуваннях конфіденційності.", + "remoteImageGlobalSettingsDetail": "Дозволяє віддалені зображення в усьому BusyMark. Дозволи робочих просторів налаштовуються окремо.", + "loadRemoteImagesForWorkspace": "Завжди дозволяти в цьому робочому просторі", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -3653,7 +3665,7 @@ "searchTopicsCategory": "Теми", "searchCurrentDocument": "Поточний документ", "searchCurrentWorkspace": "Поточна робоча область", - "browseNotes": "Переглянути нотатки", + "browseNotes": "Переглянути нотатки Nextcloud", "searchActionsCommand": "Пошук дій", "searchDocumentsCommand": "Пошук документів", "searchTopicsCommand": "Пошук тем", diff --git a/lib/l10n/app_vi.arb b/lib/l10n/app_vi.arb index babce350..6ca2ff90 100644 --- a/lib/l10n/app_vi.arb +++ b/lib/l10n/app_vi.arb @@ -474,6 +474,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "Tạo mới", "open": "Mở", "@open": { "description": "Open action label." @@ -714,15 +715,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "Tạo", + "home": "Trang chủ", + "openMenu": "Menu Mở", + "newNextcloudNote": "Ghi chú Nextcloud mới", + "shortcutNewDocument": "Menu Tạo mới", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "Tạo tệp Markdown hoặc dự án Writerside", + "shortcutNewDocumentDescription": "Hiển thị menu tạo tài nguyên", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "Mở tệp Markdown, thư mục hoặc dự án Writerside", + "shortcutOpenDescription": "Hiển thị menu mở tài nguyên", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1072,11 +1076,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "Xóa quyền hình ảnh từ xa", + "clearRemoteImagePermissions": "Xóa quyền tải hình ảnh của không gian làm việc", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "Quên các không gian làm việc đã được cho phép tải hình ảnh từ xa.", + "clearRemoteImagePermissionsDescription": "Quên mọi quyền tải hình ảnh từ xa của các không gian làm việc.", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1492,7 +1496,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "Chọn xem BusyMark có thể tải hình ảnh từ xa hay không.", + "remoteImageBlockedTooltip": "Hình ảnh từ xa bị chặn. Nhấp để xem tùy chọn tải.", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1504,7 +1508,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "Tải cho không gian làm việc này", + "loadThisRemoteImage": "Tải hình ảnh này", + "remoteImageMoreOptions": "Tùy chọn khác…", + "remoteImageMoreOptionsTitle": "Quyền tải hình ảnh từ xa", + "loadRemoteImagesInDocument": "Tải hình ảnh trong tài liệu này", + "remoteImageUntilClose": "Cho đến khi đóng tài liệu này.", + "remoteImageWorkspacePermissionDetail": "Cho phép tải hình ảnh từ xa trong {workspace} cho đến khi bạn xóa quyền không gian làm việc trong phần Cài đặt quyền riêng tư.", + "remoteImageGlobalPermissionDetail": "Cho phép tải hình ảnh từ xa trong toàn bộ BusyMark cho đến khi bạn tắt tùy chọn này trong phần Cài đặt quyền riêng tư.", + "remoteImageGlobalSettingsDetail": "Cho phép tải hình ảnh từ xa trong toàn bộ BusyMark. Quyền của từng không gian làm việc được quản lý riêng.", + "loadRemoteImagesForWorkspace": "Luôn cho phép trong không gian làm việc này", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5157,7 +5169,7 @@ "searchTopicsCategory": "Chủ đề", "searchCurrentDocument": "Tài liệu hiện tại", "searchCurrentWorkspace": "Không gian làm việc hiện tại", - "browseNotes": "Duyệt ghi chú", + "browseNotes": "Duyệt ghi chú Nextcloud", "searchActionsCommand": "Tìm thao tác", "searchDocumentsCommand": "Tìm tài liệu", "searchTopicsCommand": "Tìm chủ đề", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 86a2406c..0992ed96 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -476,6 +476,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "新建", "open": "打开", "@open": { "description": "Open action label." @@ -716,15 +717,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "创建", + "home": "主页", + "openMenu": "打开菜单", + "newNextcloudNote": "新建 Nextcloud 笔记", + "shortcutNewDocument": "新建菜单", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "创建 Markdown 文件或 Writerside 项目", + "shortcutNewDocumentDescription": "显示用于新建资源的菜单", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "打开 Markdown 文件、文件夹或 Writerside 项目", + "shortcutOpenDescription": "显示用于打开资源的菜单", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1074,11 +1078,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "清除远程图像权限", + "clearRemoteImagePermissions": "清除工作区图片权限", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "忘记已获准加载远程图像的工作区。", + "clearRemoteImagePermissionsDescription": "忘记所有工作区的远程图片权限。", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1494,7 +1498,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "选择是否允许 BusyMark 加载远程图像。", + "remoteImageBlockedTooltip": "远程图像已阻止。点击查看加载选项。", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1506,7 +1510,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "为此工作区加载", + "loadThisRemoteImage": "加载此图片", + "remoteImageMoreOptions": "更多选项…", + "remoteImageMoreOptionsTitle": "远程图片权限", + "loadRemoteImagesInDocument": "加载此文档中的图片", + "remoteImageUntilClose": "在关闭此文档前有效。", + "remoteImageWorkspacePermissionDetail": "允许在 {workspace} 中加载远程图片,直至在隐私设置中清除工作区权限。", + "remoteImageGlobalPermissionDetail": "允许在整个 BusyMark 中加载远程图片,直至在隐私设置中关闭此选项。", + "remoteImageGlobalSettingsDetail": "允许在整个 BusyMark 中加载远程图片。工作区权限单独管理。", + "loadRemoteImagesForWorkspace": "在此工作区中始终允许", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5169,7 +5181,7 @@ "searchTopicsCategory": "主题", "searchCurrentDocument": "当前文档", "searchCurrentWorkspace": "当前工作区", - "browseNotes": "浏览笔记", + "browseNotes": "浏览 Nextcloud 笔记", "searchActionsCommand": "搜索操作", "searchDocumentsCommand": "搜索文档", "searchTopicsCommand": "搜索主题", diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index c507f2d4..d3157c1a 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -474,6 +474,7 @@ "@markdown": { "description": "Markdown format label." }, + "newResource": "新建", "open": "打开", "@open": { "description": "Open action label." @@ -714,15 +715,18 @@ "@shortcutGroupGeneral": { "description": "Keyboard shortcut group for general application commands." }, - "shortcutNewDocument": "创建", + "home": "主页", + "openMenu": "打开菜单", + "newNextcloudNote": "新建 Nextcloud 笔记", + "shortcutNewDocument": "新建菜单", "@shortcutNewDocument": { "description": "Keyboard shortcut label for opening the content creation chooser." }, - "shortcutNewDocumentDescription": "创建 Markdown 文件或 Writerside 项目", + "shortcutNewDocumentDescription": "显示用于新建资源的菜单", "@shortcutNewDocumentDescription": { "description": "Keyboard shortcut description for creating Markdown files or Writerside projects." }, - "shortcutOpenDescription": "打开 Markdown 文件、文件夹或 Writerside 项目", + "shortcutOpenDescription": "显示用于打开资源的菜单", "@shortcutOpenDescription": { "description": "Keyboard shortcut description for opening content." }, @@ -1072,11 +1076,11 @@ "@allowRemoteImagesDescription": { "description": "Settings switch description for loading remote images." }, - "clearRemoteImagePermissions": "清除远程图像权限", + "clearRemoteImagePermissions": "清除工作区图片权限", "@clearRemoteImagePermissions": { "description": "Settings action label for clearing per-workspace remote image permissions." }, - "clearRemoteImagePermissionsDescription": "忘记已获准加载远程图像的工作区。", + "clearRemoteImagePermissionsDescription": "忘记所有工作区的远程图片权限。", "@clearRemoteImagePermissionsDescription": { "description": "Settings action description for clearing per-workspace remote image permissions." }, @@ -1492,7 +1496,7 @@ "@remoteImageBlocked": { "description": "Placeholder label shown when a remote image is blocked." }, - "remoteImageBlockedTooltip": "选择是否允许 BusyMark 加载远程图像。", + "remoteImageBlockedTooltip": "远程图像已阻止。点击查看加载选项。", "@remoteImageBlockedTooltip": { "description": "Tooltip for a blocked remote image placeholder." }, @@ -1504,7 +1508,15 @@ "@remoteImagesBlockedMessage": { "description": "Dialog message explaining the privacy risk of remote images." }, - "loadRemoteImagesForWorkspace": "为此工作区加载", + "loadThisRemoteImage": "加载此图片", + "remoteImageMoreOptions": "更多选项…", + "remoteImageMoreOptionsTitle": "远程图片权限", + "loadRemoteImagesInDocument": "加载此文档中的图片", + "remoteImageUntilClose": "在关闭此文档前有效。", + "remoteImageWorkspacePermissionDetail": "允许在 {workspace} 中加载远程图片,直至在隐私设置中清除工作区权限。", + "remoteImageGlobalPermissionDetail": "允许在整个 BusyMark 中加载远程图片,直至在隐私设置中关闭此选项。", + "remoteImageGlobalSettingsDetail": "允许在整个 BusyMark 中加载远程图片。工作区权限单独管理。", + "loadRemoteImagesForWorkspace": "在此工作区中始终允许", "@loadRemoteImagesForWorkspace": { "description": "Dialog button that allows remote images for the current workspace." }, @@ -5157,7 +5169,7 @@ "searchTopicsCategory": "主题", "searchCurrentDocument": "当前文档", "searchCurrentWorkspace": "当前工作区", - "browseNotes": "浏览笔记", + "browseNotes": "浏览 Nextcloud 笔记", "searchActionsCommand": "搜索操作", "searchDocumentsCommand": "搜索文档", "searchTopicsCommand": "搜索主题", diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index da09a74e..d4d7fe2f 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -1411,6 +1411,12 @@ abstract class AppLocalizations { /// **'Markdown'** String get markdown; + /// Short tooltip for the header button that opens creation options. + /// + /// In en, this message translates to: + /// **'New'** + String get newResource; + /// Open action label. /// /// In en, this message translates to: @@ -1771,22 +1777,40 @@ abstract class AppLocalizations { /// **'General'** String get shortcutGroupGeneral; + /// No description provided for @home. + /// + /// In en, this message translates to: + /// **'Home'** + String get home; + + /// No description provided for @openMenu. + /// + /// In en, this message translates to: + /// **'Open Menu'** + String get openMenu; + + /// No description provided for @newNextcloudNote. + /// + /// In en, this message translates to: + /// **'New Nextcloud Note'** + String get newNextcloudNote; + /// Keyboard shortcut label for opening the content creation chooser. /// /// In en, this message translates to: - /// **'Create'** + /// **'New Menu'** String get shortcutNewDocument; /// Keyboard shortcut description for creating Markdown files or Writerside projects. /// /// In en, this message translates to: - /// **'Create a Markdown file or Writerside project'** + /// **'Show the menu for creating resources'** String get shortcutNewDocumentDescription; /// Keyboard shortcut description for opening content. /// /// In en, this message translates to: - /// **'Open a Markdown file, folder, or Writerside project'** + /// **'Show the menu for opening resources'** String get shortcutOpenDescription; /// Keyboard shortcut description for saving content. @@ -2104,7 +2128,7 @@ abstract class AppLocalizations { /// Welcome screen action for creating a Markdown file. /// /// In en, this message translates to: - /// **'Create Markdown File'** + /// **'New Markdown File'** String get createMarkdownFile; /// Welcome screen subtitle for creating a Markdown file. @@ -2116,7 +2140,7 @@ abstract class AppLocalizations { /// Welcome screen action for creating a Writerside project. /// /// In en, this message translates to: - /// **'Create Writerside Project'** + /// **'New Writerside Project'** String get createWritersideProject; /// Welcome screen subtitle for creating a Writerside project. @@ -2320,13 +2344,13 @@ abstract class AppLocalizations { /// Settings action label for clearing per-workspace remote image permissions. /// /// In en, this message translates to: - /// **'Clear remote image permissions'** + /// **'Clear workspace image permissions'** String get clearRemoteImagePermissions; /// Settings action description for clearing per-workspace remote image permissions. /// /// In en, this message translates to: - /// **'Forget workspaces that were allowed to load remote images.'** + /// **'Forget all workspace permissions for remote images.'** String get clearRemoteImagePermissionsDescription; /// Settings action label for clearing trusted Git workspaces. @@ -2938,7 +2962,7 @@ abstract class AppLocalizations { /// Tooltip for a blocked remote image placeholder. /// /// In en, this message translates to: - /// **'Choose whether BusyMark can load remote images.'** + /// **'Remote image blocked. Click for loading options.'** String get remoteImageBlockedTooltip; /// Dialog title for remote image loading permission. @@ -2953,10 +2977,58 @@ abstract class AppLocalizations { /// **'This document references images from the internet. Loading them can reveal network information to the image host.'** String get remoteImagesBlockedMessage; + /// Primary action on a blocked image. + /// + /// In en, this message translates to: + /// **'Load this image'** + String get loadThisRemoteImage; + + /// Opens the additional remote image permission choices. + /// + /// In en, this message translates to: + /// **'More options…'** + String get remoteImageMoreOptions; + + /// Title of the remote image permission dialog. + /// + /// In en, this message translates to: + /// **'Remote image permissions'** + String get remoteImageMoreOptionsTitle; + + /// Temporary permission for all images in a single document. + /// + /// In en, this message translates to: + /// **'Load images in this document'** + String get loadRemoteImagesInDocument; + + /// Lifetime of a temporary remote image permission. + /// + /// In en, this message translates to: + /// **'Until this document closes.'** + String get remoteImageUntilClose; + + /// Shows the identity of the workspace and explains how to revoke the permission. + /// + /// In en, this message translates to: + /// **'Allows remote images in {workspace} until you clear workspace permissions in Privacy settings.'** + String remoteImageWorkspacePermissionDetail(String workspace); + + /// Explains how to revoke the app-wide remote image permission. + /// + /// In en, this message translates to: + /// **'Allows remote images throughout BusyMark until you turn this off in Privacy settings.'** + String get remoteImageGlobalPermissionDetail; + + /// Description for the app-wide Privacy switch. + /// + /// In en, this message translates to: + /// **'Allow remote images throughout BusyMark. Workspace permissions are managed separately.'** + String get remoteImageGlobalSettingsDetail; + /// Dialog button that allows remote images for the current workspace. /// /// In en, this message translates to: - /// **'Load for this workspace'** + /// **'Always allow in this workspace'** String get loadRemoteImagesForWorkspace; /// Dialog button that enables remote images globally. @@ -9423,7 +9495,7 @@ abstract class AppLocalizations { /// No description provided for @browseNotes. /// /// In en, this message translates to: - /// **'Browse Notes'** + /// **'Browse Nextcloud Notes'** String get browseNotes; /// No description provided for @searchActionsCommand. diff --git a/lib/l10n/generated/app_localizations_ar.dart b/lib/l10n/generated/app_localizations_ar.dart index ecf399e3..0db6468b 100644 --- a/lib/l10n/generated/app_localizations_ar.dart +++ b/lib/l10n/generated/app_localizations_ar.dart @@ -717,6 +717,9 @@ class AppLocalizationsAr extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'جديد'; + @override String get open => 'فتح'; @@ -900,15 +903,22 @@ class AppLocalizationsAr extends AppLocalizations { String get shortcutGroupGeneral => 'عام'; @override - String get shortcutNewDocument => 'إنشاء'; + String get home => 'الرئيسية'; + + @override + String get openMenu => 'قائمة فتح'; @override - String get shortcutNewDocumentDescription => - 'إنشاء ملف Markdown أو مشروع Writerside'; + String get newNextcloudNote => 'ملاحظة Nextcloud جديدة'; @override - String get shortcutOpenDescription => - 'فتح ملف Markdown أو مجلد أو مشروع Writerside'; + String get shortcutNewDocument => 'قائمة جديد'; + + @override + String get shortcutNewDocumentDescription => 'افتح قائمة إنشاء الموارد'; + + @override + String get shortcutOpenDescription => 'افتح قائمة فتح الموارد'; @override String get shortcutSaveDescription => 'حفظ المستند الحالي'; @@ -1196,11 +1206,11 @@ class AppLocalizationsAr extends AppLocalizations { 'السماح بتحميل صور معاينة Markdown والمحرر من عناوين URL التي تستخدم http وhttps.'; @override - String get clearRemoteImagePermissions => 'مسح أذونات الصور البعيدة'; + String get clearRemoteImagePermissions => 'مسح أذونات الصور لمساحات العمل'; @override String get clearRemoteImagePermissionsDescription => - 'نسيان مساحات العمل التي سُمح لها بتحميل الصور البعيدة.'; + 'نسيان جميع أذونات الصور البعيدة لمساحات العمل.'; @override String get clearGitWorkspaceTrust => 'مسح مساحات عمل Git الموثوقة'; @@ -1560,7 +1570,7 @@ class AppLocalizationsAr extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'اختر ما إذا كان بإمكان BusyMark تحميل الصور البعيدة.'; + 'تم حظر الصورة البعيدة. انقر لعرض خيارات التحميل.'; @override String get remoteImagesBlockedTitle => 'الصور البعيدة محظورة'; @@ -1570,7 +1580,35 @@ class AppLocalizationsAr extends AppLocalizations { 'يشير هذا المستند إلى صور من الإنترنت. قد يكشف تحميلها معلومات عن الشبكة لمضيف الصورة.'; @override - String get loadRemoteImagesForWorkspace => 'تحميل لمساحة العمل هذه'; + String get loadThisRemoteImage => 'تحميل هذه الصورة'; + + @override + String get remoteImageMoreOptions => 'خيارات إضافية…'; + + @override + String get remoteImageMoreOptionsTitle => 'أذونات الصور البعيدة'; + + @override + String get loadRemoteImagesInDocument => 'تحميل الصور في هذا المستند'; + + @override + String get remoteImageUntilClose => 'حتى إغلاق هذا المستند.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'يسمح بالصور البعيدة في ⁨$workspace⁩ حتى تمسح أذونات مساحة العمل في إعدادات الخصوصية.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'يسمح بالصور البعيدة في كل BusyMark حتى توقف هذا الخيار في إعدادات الخصوصية.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'السماح بالصور البعيدة في كل BusyMark. تُدار أذونات مساحات العمل بشكل منفصل.'; + + @override + String get loadRemoteImagesForWorkspace => 'السماح دائمًا في مساحة العمل هذه'; @override String get alwaysLoadRemoteImages => 'تحميل الصور البعيدة دائمًا'; @@ -5537,7 +5575,7 @@ class AppLocalizationsAr extends AppLocalizations { String get searchCurrentWorkspace => 'مساحة العمل الحالية'; @override - String get browseNotes => 'تصفح الملاحظات'; + String get browseNotes => 'تصفح ملاحظات Nextcloud'; @override String get searchActionsCommand => 'البحث عن إجراءات'; diff --git a/lib/l10n/generated/app_localizations_de.dart b/lib/l10n/generated/app_localizations_de.dart index c97cca42..fd6d031b 100644 --- a/lib/l10n/generated/app_localizations_de.dart +++ b/lib/l10n/generated/app_localizations_de.dart @@ -732,6 +732,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Neu'; + @override String get open => 'Öffnen'; @@ -916,15 +919,23 @@ class AppLocalizationsDe extends AppLocalizations { String get shortcutGroupGeneral => 'Allgemein'; @override - String get shortcutNewDocument => 'Erstellen'; + String get home => 'Startseite'; + + @override + String get openMenu => 'Menü „Öffnen“'; + + @override + String get newNextcloudNote => 'Neue Nextcloud-Notiz'; + + @override + String get shortcutNewDocument => 'Menü „Neu“'; @override String get shortcutNewDocumentDescription => - 'Markdown-Datei oder Writerside-Projekt erstellen'; + 'Menü zum Erstellen von Ressourcen öffnen'; @override - String get shortcutOpenDescription => - 'Markdown-Datei, Ordner oder Writerside-Projekt öffnen'; + String get shortcutOpenDescription => 'Menü zum Öffnen von Ressourcen öffnen'; @override String get shortcutSaveDescription => 'Aktuelles Dokument speichern'; @@ -1230,11 +1241,11 @@ class AppLocalizationsDe extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Berechtigungen für externe Bilder löschen'; + 'Bildberechtigungen für Arbeitsbereiche löschen'; @override String get clearRemoteImagePermissionsDescription => - 'Arbeitsbereiche vergessen, denen das Laden externer Bilder erlaubt wurde.'; + 'Alle Arbeitsbereichsberechtigungen für entfernte Bilder löschen.'; @override String get clearGitWorkspaceTrust => @@ -1589,7 +1600,7 @@ class AppLocalizationsDe extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Festlegen, ob BusyMark externe Bilder laden darf.'; + 'Externes Bild blockiert. Klicken für Ladeoptionen.'; @override String get remoteImagesBlockedTitle => 'Externe Bilder sind blockiert'; @@ -1599,7 +1610,37 @@ class AppLocalizationsDe extends AppLocalizations { 'Dieses Dokument verweist auf Bilder aus dem Internet. Beim Laden können Netzwerkinformationen an den Bildhost übermittelt werden.'; @override - String get loadRemoteImagesForWorkspace => 'Für diesen Arbeitsbereich laden'; + String get loadThisRemoteImage => 'Dieses Bild laden'; + + @override + String get remoteImageMoreOptions => 'Weitere Optionen…'; + + @override + String get remoteImageMoreOptionsTitle => + 'Berechtigungen für entfernte Bilder'; + + @override + String get loadRemoteImagesInDocument => 'Bilder in diesem Dokument laden'; + + @override + String get remoteImageUntilClose => 'Bis dieses Dokument geschlossen wird.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Erlaubt entfernte Bilder in $workspace, bis Sie die Arbeitsbereichsberechtigungen in den Datenschutzeinstellungen löschen.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Erlaubt entfernte Bilder in ganz BusyMark, bis Sie dies in den Datenschutzeinstellungen deaktivieren.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Entfernte Bilder überall in BusyMark erlauben. Arbeitsbereichsberechtigungen werden separat verwaltet.'; + + @override + String get loadRemoteImagesForWorkspace => + 'In diesem Arbeitsbereich immer erlauben'; @override String get alwaysLoadRemoteImages => 'Externe Bilder immer laden'; @@ -5560,7 +5601,7 @@ class AppLocalizationsDe extends AppLocalizations { String get searchCurrentWorkspace => 'Aktueller Arbeitsbereich'; @override - String get browseNotes => 'Notizen durchsuchen'; + String get browseNotes => 'Nextcloud-Notizen durchsuchen'; @override String get searchActionsCommand => 'Aktionen suchen'; diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index ea6dd0b6..72174766 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -724,6 +724,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'New'; + @override String get open => 'Open'; @@ -908,15 +911,23 @@ class AppLocalizationsEn extends AppLocalizations { String get shortcutGroupGeneral => 'General'; @override - String get shortcutNewDocument => 'Create'; + String get home => 'Home'; + + @override + String get openMenu => 'Open Menu'; + + @override + String get newNextcloudNote => 'New Nextcloud Note'; + + @override + String get shortcutNewDocument => 'New Menu'; @override String get shortcutNewDocumentDescription => - 'Create a Markdown file or Writerside project'; + 'Show the menu for creating resources'; @override - String get shortcutOpenDescription => - 'Open a Markdown file, folder, or Writerside project'; + String get shortcutOpenDescription => 'Show the menu for opening resources'; @override String get shortcutSaveDescription => 'Save the current document'; @@ -1093,14 +1104,14 @@ class AppLocalizationsEn extends AppLocalizations { String get sidebarViewMenu => 'Sidebar view'; @override - String get createMarkdownFile => 'Create Markdown File'; + String get createMarkdownFile => 'New Markdown File'; @override String get createMarkdownFileDescription => 'Start an unsaved local Markdown document'; @override - String get createWritersideProject => 'Create Writerside Project'; + String get createWritersideProject => 'New Writerside Project'; @override String get createWritersideProjectDescription => @@ -1210,11 +1221,11 @@ class AppLocalizationsEn extends AppLocalizations { 'Allow Markdown preview and editor images to load from http and https URLs.'; @override - String get clearRemoteImagePermissions => 'Clear remote image permissions'; + String get clearRemoteImagePermissions => 'Clear workspace image permissions'; @override String get clearRemoteImagePermissionsDescription => - 'Forget workspaces that were allowed to load remote images.'; + 'Forget all workspace permissions for remote images.'; @override String get clearGitWorkspaceTrust => 'Clear trusted Git workspaces'; @@ -1566,7 +1577,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Choose whether BusyMark can load remote images.'; + 'Remote image blocked. Click for loading options.'; @override String get remoteImagesBlockedTitle => 'Remote images are blocked'; @@ -1576,7 +1587,35 @@ class AppLocalizationsEn extends AppLocalizations { 'This document references images from the internet. Loading them can reveal network information to the image host.'; @override - String get loadRemoteImagesForWorkspace => 'Load for this workspace'; + String get loadThisRemoteImage => 'Load this image'; + + @override + String get remoteImageMoreOptions => 'More options…'; + + @override + String get remoteImageMoreOptionsTitle => 'Remote image permissions'; + + @override + String get loadRemoteImagesInDocument => 'Load images in this document'; + + @override + String get remoteImageUntilClose => 'Until this document closes.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Allows remote images in $workspace until you clear workspace permissions in Privacy settings.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Allows remote images throughout BusyMark until you turn this off in Privacy settings.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Allow remote images throughout BusyMark. Workspace permissions are managed separately.'; + + @override + String get loadRemoteImagesForWorkspace => 'Always allow in this workspace'; @override String get alwaysLoadRemoteImages => 'Always load remote images'; @@ -5529,7 +5568,7 @@ class AppLocalizationsEn extends AppLocalizations { String get searchCurrentWorkspace => 'Current workspace'; @override - String get browseNotes => 'Browse Notes'; + String get browseNotes => 'Browse Nextcloud Notes'; @override String get searchActionsCommand => 'Search Actions'; diff --git a/lib/l10n/generated/app_localizations_es.dart b/lib/l10n/generated/app_localizations_es.dart index 47908095..ea8df515 100644 --- a/lib/l10n/generated/app_localizations_es.dart +++ b/lib/l10n/generated/app_localizations_es.dart @@ -728,6 +728,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Nuevo'; + @override String get open => 'Abrir'; @@ -912,15 +915,23 @@ class AppLocalizationsEs extends AppLocalizations { String get shortcutGroupGeneral => 'General'; @override - String get shortcutNewDocument => 'Crear'; + String get home => 'Inicio'; + + @override + String get openMenu => 'Menú Abrir'; + + @override + String get newNextcloudNote => 'Nueva nota de Nextcloud'; + + @override + String get shortcutNewDocument => 'Menú Nuevo'; @override String get shortcutNewDocumentDescription => - 'Crear un archivo Markdown o un proyecto de Writerside'; + 'Mostrar el menú para crear recursos'; @override - String get shortcutOpenDescription => - 'Abrir un archivo Markdown, una carpeta o un proyecto de Writerside'; + String get shortcutOpenDescription => 'Mostrar el menú para abrir recursos'; @override String get shortcutSaveDescription => 'Guardar el documento actual'; @@ -1227,11 +1238,11 @@ class AppLocalizationsEs extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Borrar permisos de imágenes remotas'; + 'Borrar permisos de imágenes de espacios de trabajo'; @override String get clearRemoteImagePermissionsDescription => - 'Olvida los espacios de trabajo autorizados a cargar imágenes remotas.'; + 'Olvidar todos los permisos de imágenes remotas de espacios de trabajo.'; @override String get clearGitWorkspaceTrust => @@ -1585,7 +1596,7 @@ class AppLocalizationsEs extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Elija si BusyMark puede cargar imágenes remotas.'; + 'Imagen remota bloqueada. Haz clic para ver las opciones de carga.'; @override String get remoteImagesBlockedTitle => @@ -1595,9 +1606,37 @@ class AppLocalizationsEs extends AppLocalizations { String get remoteImagesBlockedMessage => 'Este documento hace referencia a imágenes de Internet. Cargarlas puede revelar información de red al servidor que las aloja.'; + @override + String get loadThisRemoteImage => 'Cargar esta imagen'; + + @override + String get remoteImageMoreOptions => 'Más opciones…'; + + @override + String get remoteImageMoreOptionsTitle => 'Permisos de imágenes remotas'; + + @override + String get loadRemoteImagesInDocument => 'Cargar imágenes en este documento'; + + @override + String get remoteImageUntilClose => 'Hasta que se cierre este documento.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Permite las imágenes remotas en $workspace hasta que borres los permisos del espacio de trabajo en Privacidad.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Permite las imágenes remotas en todo BusyMark hasta que desactives esta opción en Privacidad.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Permite las imágenes remotas en todo BusyMark. Los permisos de los espacios de trabajo se administran por separado.'; + @override String get loadRemoteImagesForWorkspace => - 'Cargar en este espacio de trabajo'; + 'Permitir siempre en este espacio de trabajo'; @override String get alwaysLoadRemoteImages => 'Cargar siempre las imágenes remotas'; @@ -5563,7 +5602,7 @@ class AppLocalizationsEs extends AppLocalizations { String get searchCurrentWorkspace => 'Espacio de trabajo actual'; @override - String get browseNotes => 'Explorar notas'; + String get browseNotes => 'Explorar notas de Nextcloud'; @override String get searchActionsCommand => 'Buscar acciones'; diff --git a/lib/l10n/generated/app_localizations_et.dart b/lib/l10n/generated/app_localizations_et.dart index f7646e07..9bad7260 100644 --- a/lib/l10n/generated/app_localizations_et.dart +++ b/lib/l10n/generated/app_localizations_et.dart @@ -720,6 +720,9 @@ class AppLocalizationsEt extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Uus'; + @override String get open => 'Ava'; @@ -904,15 +907,22 @@ class AppLocalizationsEt extends AppLocalizations { String get shortcutGroupGeneral => 'Üldine'; @override - String get shortcutNewDocument => 'Loo'; + String get home => 'Avaleht'; + + @override + String get openMenu => 'Avamismenüü'; @override - String get shortcutNewDocumentDescription => - 'Loo Markdowni fail või Writerside’i projekt'; + String get newNextcloudNote => 'Uus Nextcloudi märge'; @override - String get shortcutOpenDescription => - 'Ava Markdowni fail, kaust või Writerside’i projekt'; + String get shortcutNewDocument => 'Uue ressursi menüü'; + + @override + String get shortcutNewDocumentDescription => 'Kuva ressursside loomise menüü'; + + @override + String get shortcutOpenDescription => 'Kuva ressursside avamise menüü'; @override String get shortcutSaveDescription => 'Salvesta praegune dokument'; @@ -1210,12 +1220,11 @@ class AppLocalizationsEt extends AppLocalizations { 'Luba Markdowni eelvaatel ja redaktoril laadida pilte HTTP- ja HTTPS-aadressidelt.'; @override - String get clearRemoteImagePermissions => - 'Eemalda välispiltide laadimise load'; + String get clearRemoteImagePermissions => 'Kustuta tööruumide pildiõigused'; @override String get clearRemoteImagePermissionsDescription => - 'Unusta tööruumid, millel oli lubatud välispilte laadida.'; + 'Unusta kõik tööruumide kaugpiltide õigused.'; @override String get clearGitWorkspaceTrust => @@ -1569,7 +1578,7 @@ class AppLocalizationsEt extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Vali, kas BusyMark võib välispilte laadida.'; + 'Välispilt on blokeeritud. Laadimisvalikute nägemiseks klõpsa.'; @override String get remoteImagesBlockedTitle => 'Välispildid on blokeeritud'; @@ -1579,7 +1588,35 @@ class AppLocalizationsEt extends AppLocalizations { 'See dokument viitab internetis olevatele piltidele. Nende laadimine võib avaldada pildi majutajale teie võrguteavet.'; @override - String get loadRemoteImagesForWorkspace => 'Laadi selles tööruumis'; + String get loadThisRemoteImage => 'Laadi see pilt'; + + @override + String get remoteImageMoreOptions => 'Rohkem valikuid…'; + + @override + String get remoteImageMoreOptionsTitle => 'Kaugpiltide õigused'; + + @override + String get loadRemoteImagesInDocument => 'Laadi selle dokumendi pildid'; + + @override + String get remoteImageUntilClose => 'Kuni selle dokumendi sulgemiseni.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Lubab kaugpildid tööruumis $workspace, kuni kustutad tööruumide õigused privaatsusseadetes.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Lubab kaugpildid kogu BusyMarkis, kuni lülitad selle privaatsusseadetes välja.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Luba kaugpildid kogu BusyMarkis. Tööruumide õigusi hallatakse eraldi.'; + + @override + String get loadRemoteImagesForWorkspace => 'Luba selles tööruumis alati'; @override String get alwaysLoadRemoteImages => 'Laadi välispildid alati'; @@ -5511,7 +5548,7 @@ class AppLocalizationsEt extends AppLocalizations { String get searchCurrentWorkspace => 'Praegune tööruum'; @override - String get browseNotes => 'Sirvi märkmeid'; + String get browseNotes => 'Sirvi Nextcloudi märkmeid'; @override String get searchActionsCommand => 'Otsi toiminguid'; diff --git a/lib/l10n/generated/app_localizations_fa.dart b/lib/l10n/generated/app_localizations_fa.dart index fbeb3405..d66d5bc2 100644 --- a/lib/l10n/generated/app_localizations_fa.dart +++ b/lib/l10n/generated/app_localizations_fa.dart @@ -722,6 +722,9 @@ class AppLocalizationsFa extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'جدید'; + @override String get open => 'باز کردن'; @@ -906,15 +909,22 @@ class AppLocalizationsFa extends AppLocalizations { String get shortcutGroupGeneral => 'عمومی'; @override - String get shortcutNewDocument => 'ایجاد'; + String get home => 'خانه'; + + @override + String get openMenu => 'منوی باز کردن'; @override - String get shortcutNewDocumentDescription => - 'ایجاد فایل Markdown یا پروژهٔ Writerside'; + String get newNextcloudNote => 'یادداشت جدید Nextcloud'; @override - String get shortcutOpenDescription => - 'باز کردن فایل Markdown، پوشه یا پروژهٔ Writerside'; + String get shortcutNewDocument => 'منوی جدید'; + + @override + String get shortcutNewDocumentDescription => 'نمایش منوی ایجاد منابع'; + + @override + String get shortcutOpenDescription => 'نمایش منوی باز کردن منابع'; @override String get shortcutSaveDescription => 'ذخیرهٔ سند فعلی'; @@ -1205,11 +1215,12 @@ class AppLocalizationsFa extends AppLocalizations { 'اجازه دهید تصاویر پیش‌نمایش و ویرایشگر Markdown از نشانی‌های http و https بارگیری شوند.'; @override - String get clearRemoteImagePermissions => 'پاک کردن مجوزهای تصاویر راه دور'; + String get clearRemoteImagePermissions => + 'پاک کردن مجوزهای تصویر فضاهای کاری'; @override String get clearRemoteImagePermissionsDescription => - 'فضاهای کاری‌ای را که اجازهٔ بارگیری تصاویر راه دور داشتند، فراموش کنید.'; + 'همهٔ مجوزهای تصاویر راه‌دور فضاهای کاری را فراموش کن.'; @override String get clearGitWorkspaceTrust => 'پاک کردن فضاهای کاری مورد اعتماد Git'; @@ -1585,7 +1596,7 @@ class AppLocalizationsFa extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'انتخاب کنید BusyMark اجازهٔ بارگیری تصاویر راه دور داشته باشد یا نه.'; + 'تصویر راه دور مسدود شد. برای گزینه‌های بارگیری کلیک کنید.'; @override String get remoteImagesBlockedTitle => 'تصاویر راه دور مسدود شده‌اند'; @@ -1595,7 +1606,35 @@ class AppLocalizationsFa extends AppLocalizations { 'این سند به تصاویری در اینترنت ارجاع می‌دهد. بارگیری آن‌ها ممکن است اطلاعات شبکه را برای میزبان تصویر آشکار کند.'; @override - String get loadRemoteImagesForWorkspace => 'بارگیری برای این فضای کاری'; + String get loadThisRemoteImage => 'بارگیری این تصویر'; + + @override + String get remoteImageMoreOptions => 'گزینه‌های بیشتر…'; + + @override + String get remoteImageMoreOptionsTitle => 'مجوزهای تصاویر راه‌دور'; + + @override + String get loadRemoteImagesInDocument => 'بارگیری تصاویر این سند'; + + @override + String get remoteImageUntilClose => 'تا زمان بسته شدن این سند.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'تصاویر راه‌دور در ⁨$workspace⁩ مجاز هستند تا زمانی که مجوزهای فضای کاری را در تنظیمات حریم خصوصی پاک کنید.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'تصاویر راه‌دور در سراسر BusyMark مجاز هستند تا زمانی که این گزینه را در تنظیمات حریم خصوصی خاموش کنید.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'اجازهٔ بارگیری تصاویر راه‌دور در سراسر BusyMark. مجوزهای فضای کاری جداگانه مدیریت می‌شوند.'; + + @override + String get loadRemoteImagesForWorkspace => 'همیشه در این فضای کاری مجاز باشد'; @override String get alwaysLoadRemoteImages => 'همیشه تصاویر راه دور بارگیری شوند'; @@ -5549,7 +5588,7 @@ class AppLocalizationsFa extends AppLocalizations { String get searchCurrentWorkspace => 'فضای کاری کنونی'; @override - String get browseNotes => 'مرور یادداشت‌ها'; + String get browseNotes => 'مرور یادداشت‌های Nextcloud'; @override String get searchActionsCommand => 'جستجوی کنش‌ها'; diff --git a/lib/l10n/generated/app_localizations_fr.dart b/lib/l10n/generated/app_localizations_fr.dart index f5750081..c9c47330 100644 --- a/lib/l10n/generated/app_localizations_fr.dart +++ b/lib/l10n/generated/app_localizations_fr.dart @@ -734,6 +734,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Nouveau'; + @override String get open => 'Ouvrir'; @@ -918,15 +921,24 @@ class AppLocalizationsFr extends AppLocalizations { String get shortcutGroupGeneral => 'Général'; @override - String get shortcutNewDocument => 'Créer'; + String get home => 'Accueil'; + + @override + String get openMenu => 'Menu Ouvrir'; + + @override + String get newNextcloudNote => 'Nouvelle note Nextcloud'; + + @override + String get shortcutNewDocument => 'Menu Nouveau'; @override String get shortcutNewDocumentDescription => - 'Créer un fichier Markdown ou un projet Writerside'; + 'Afficher le menu de création de ressources'; @override String get shortcutOpenDescription => - 'Ouvrir un fichier Markdown, un dossier ou un projet Writerside'; + 'Afficher le menu d’ouverture de ressources'; @override String get shortcutSaveDescription => 'Enregistrer le document actuel'; @@ -1232,11 +1244,11 @@ class AppLocalizationsFr extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Effacer les autorisations d’images distantes'; + 'Effacer les autorisations d’images des espaces de travail'; @override String get clearRemoteImagePermissionsDescription => - 'Oublier les espaces de travail autorisés à charger des images distantes.'; + 'Oublier toutes les autorisations d’images distantes des espaces de travail.'; @override String get clearGitWorkspaceTrust => @@ -1590,7 +1602,7 @@ class AppLocalizationsFr extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Choisissez si BusyMark peut charger des images distantes.'; + 'Image distante bloquée. Cliquez pour voir les options de chargement.'; @override String get remoteImagesBlockedTitle => 'Les images distantes sont bloquées'; @@ -1599,9 +1611,38 @@ class AppLocalizationsFr extends AppLocalizations { String get remoteImagesBlockedMessage => 'Ce document fait référence à des images sur Internet. Leur chargement peut révéler des informations réseau à l’hôte des images.'; + @override + String get loadThisRemoteImage => 'Charger cette image'; + + @override + String get remoteImageMoreOptions => 'Plus d’options…'; + + @override + String get remoteImageMoreOptionsTitle => + 'Autorisations des images distantes'; + + @override + String get loadRemoteImagesInDocument => 'Charger les images de ce document'; + + @override + String get remoteImageUntilClose => 'Jusqu’à la fermeture de ce document.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Autorise les images distantes dans $workspace jusqu’à l’effacement des autorisations dans les paramètres de confidentialité.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Autorise les images distantes dans tout BusyMark jusqu’à la désactivation de cette option dans les paramètres de confidentialité.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Autorise les images distantes dans tout BusyMark. Les autorisations des espaces de travail sont gérées séparément.'; + @override String get loadRemoteImagesForWorkspace => - 'Charger pour cet espace de travail'; + 'Toujours autoriser dans cet espace de travail'; @override String get alwaysLoadRemoteImages => 'Toujours charger les images distantes'; @@ -5567,7 +5608,7 @@ class AppLocalizationsFr extends AppLocalizations { String get searchCurrentWorkspace => 'Espace de travail actuel'; @override - String get browseNotes => 'Parcourir les notes'; + String get browseNotes => 'Parcourir les notes Nextcloud'; @override String get searchActionsCommand => 'Rechercher des actions'; diff --git a/lib/l10n/generated/app_localizations_hi.dart b/lib/l10n/generated/app_localizations_hi.dart index 1c1cf650..bfc996e8 100644 --- a/lib/l10n/generated/app_localizations_hi.dart +++ b/lib/l10n/generated/app_localizations_hi.dart @@ -727,6 +727,9 @@ class AppLocalizationsHi extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'नया'; + @override String get open => 'खोलें'; @@ -911,15 +914,22 @@ class AppLocalizationsHi extends AppLocalizations { String get shortcutGroupGeneral => 'सामान्य'; @override - String get shortcutNewDocument => 'बनाएँ'; + String get home => 'होम'; + + @override + String get openMenu => 'खोलें मेनू'; @override - String get shortcutNewDocumentDescription => - 'Markdown फ़ाइल या Writerside प्रोजेक्ट बनाएँ'; + String get newNextcloudNote => 'नया Nextcloud नोट'; @override - String get shortcutOpenDescription => - 'Markdown फ़ाइल, फ़ोल्डर या Writerside प्रोजेक्ट खोलें'; + String get shortcutNewDocument => 'नया मेनू'; + + @override + String get shortcutNewDocumentDescription => 'संसाधन बनाने का मेनू दिखाएँ'; + + @override + String get shortcutOpenDescription => 'संसाधन खोलने का मेनू दिखाएँ'; @override String get shortcutSaveDescription => 'मौजूदा दस्तावेज़ सहेजें'; @@ -1208,11 +1218,12 @@ class AppLocalizationsHi extends AppLocalizations { 'Markdown पूर्वावलोकन और संपादक की छवियों को http और https URL से लोड होने दें।'; @override - String get clearRemoteImagePermissions => 'दूरस्थ छवि अनुमतियाँ साफ़ करें'; + String get clearRemoteImagePermissions => + 'कार्यस्थानों की छवि अनुमतियाँ हटाएँ'; @override String get clearRemoteImagePermissionsDescription => - 'उन कार्यस्थानों को भूलें जिन्हें दूरस्थ छवियाँ लोड करने की अनुमति दी गई थी।'; + 'कार्यस्थानों की सभी दूरस्थ छवि अनुमतियाँ भूलें।'; @override String get clearGitWorkspaceTrust => 'विश्वसनीय Git कार्यस्थान साफ़ करें'; @@ -1567,7 +1578,7 @@ class AppLocalizationsHi extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'चुनें कि BusyMark दूरस्थ छवियाँ लोड कर सकता है या नहीं।'; + 'दूरस्थ छवि अवरुद्ध है। लोड करने के विकल्पों के लिए क्लिक करें।'; @override String get remoteImagesBlockedTitle => 'दूरस्थ छवियाँ अवरुद्ध हैं'; @@ -1577,7 +1588,36 @@ class AppLocalizationsHi extends AppLocalizations { 'यह दस्तावेज़ इंटरनेट की छवियों का संदर्भ देता है। उन्हें लोड करने पर छवि होस्ट को नेटवर्क की जानकारी मिल सकती है।'; @override - String get loadRemoteImagesForWorkspace => 'इस कार्यस्थान के लिए लोड करें'; + String get loadThisRemoteImage => 'यह छवि लोड करें'; + + @override + String get remoteImageMoreOptions => 'और विकल्प…'; + + @override + String get remoteImageMoreOptionsTitle => 'दूरस्थ छवियों की अनुमतियाँ'; + + @override + String get loadRemoteImagesInDocument => 'इस दस्तावेज़ की छवियाँ लोड करें'; + + @override + String get remoteImageUntilClose => 'इस दस्तावेज़ के बंद होने तक।'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'गोपनीयता सेटिंग में कार्यस्थान की अनुमतियाँ हटाने तक $workspace में दूरस्थ छवियों की अनुमति देता है।'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'गोपनीयता सेटिंग में यह विकल्प बंद करने तक पूरे BusyMark में दूरस्थ छवियों की अनुमति देता है।'; + + @override + String get remoteImageGlobalSettingsDetail => + 'पूरे BusyMark में दूरस्थ छवियों की अनुमति दें। कार्यस्थानों की अनुमतियाँ अलग से प्रबंधित होती हैं।'; + + @override + String get loadRemoteImagesForWorkspace => + 'इस कार्यस्थान में हमेशा अनुमति दें'; @override String get alwaysLoadRemoteImages => 'दूरस्थ छवियाँ हमेशा लोड करें'; @@ -5503,7 +5543,7 @@ class AppLocalizationsHi extends AppLocalizations { String get searchCurrentWorkspace => 'वर्तमान कार्यक्षेत्र'; @override - String get browseNotes => 'नोट ब्राउज़ करें'; + String get browseNotes => 'Nextcloud नोट ब्राउज़ करें'; @override String get searchActionsCommand => 'क्रियाएँ खोजें'; diff --git a/lib/l10n/generated/app_localizations_id.dart b/lib/l10n/generated/app_localizations_id.dart index 2ee89df6..a86339a3 100644 --- a/lib/l10n/generated/app_localizations_id.dart +++ b/lib/l10n/generated/app_localizations_id.dart @@ -725,6 +725,9 @@ class AppLocalizationsId extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Baru'; + @override String get open => 'Buka'; @@ -909,15 +912,24 @@ class AppLocalizationsId extends AppLocalizations { String get shortcutGroupGeneral => 'Umum'; @override - String get shortcutNewDocument => 'Buat'; + String get home => 'Beranda'; + + @override + String get openMenu => 'Menu Buka'; + + @override + String get newNextcloudNote => 'Catatan Nextcloud Baru'; + + @override + String get shortcutNewDocument => 'Menu Baru'; @override String get shortcutNewDocumentDescription => - 'Buat file Markdown atau proyek Writerside'; + 'Tampilkan menu untuk membuat sumber daya'; @override String get shortcutOpenDescription => - 'Buka file Markdown, folder, atau proyek Writerside'; + 'Tampilkan menu untuk membuka sumber daya'; @override String get shortcutSaveDescription => 'Simpan dokumen saat ini'; @@ -1214,11 +1226,11 @@ class AppLocalizationsId extends AppLocalizations { 'Izinkan pratinjau Markdown dan gambar editor dimuat dari URL http dan https.'; @override - String get clearRemoteImagePermissions => 'Hapus izin gambar jarak jauh'; + String get clearRemoteImagePermissions => 'Hapus izin gambar ruang kerja'; @override String get clearRemoteImagePermissionsDescription => - 'Lupakan ruang kerja yang diizinkan memuat gambar jarak jauh.'; + 'Lupakan semua izin gambar jarak jauh untuk ruang kerja.'; @override String get clearGitWorkspaceTrust => 'Hapus ruang kerja Git yang tepercaya'; @@ -1570,7 +1582,7 @@ class AppLocalizationsId extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Pilih apakah BusyMark dapat memuat gambar jarak jauh.'; + 'Gambar jarak jauh diblokir. Klik untuk opsi pemuatan.'; @override String get remoteImagesBlockedTitle => 'Gambar jarak jauh diblokir'; @@ -1580,7 +1592,36 @@ class AppLocalizationsId extends AppLocalizations { 'Dokumen ini merujuk pada gambar dari internet. Memuatnya dapat mengungkapkan informasi jaringan ke host gambar.'; @override - String get loadRemoteImagesForWorkspace => 'Muat untuk ruang kerja ini'; + String get loadThisRemoteImage => 'Muat gambar ini'; + + @override + String get remoteImageMoreOptions => 'Opsi lainnya…'; + + @override + String get remoteImageMoreOptionsTitle => 'Izin gambar jarak jauh'; + + @override + String get loadRemoteImagesInDocument => 'Muat gambar di dokumen ini'; + + @override + String get remoteImageUntilClose => 'Hingga dokumen ini ditutup.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Mengizinkan gambar jarak jauh di $workspace hingga izin ruang kerja dihapus di pengaturan Privasi.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Mengizinkan gambar jarak jauh di seluruh BusyMark hingga opsi ini dimatikan di pengaturan Privasi.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Izinkan gambar jarak jauh di seluruh BusyMark. Izin ruang kerja dikelola secara terpisah.'; + + @override + String get loadRemoteImagesForWorkspace => + 'Selalu izinkan di ruang kerja ini'; @override String get alwaysLoadRemoteImages => 'Selalu muat gambar jarak jauh'; @@ -5511,7 +5552,7 @@ class AppLocalizationsId extends AppLocalizations { String get searchCurrentWorkspace => 'Ruang kerja saat ini'; @override - String get browseNotes => 'Jelajahi catatan'; + String get browseNotes => 'Jelajahi Catatan Nextcloud'; @override String get searchActionsCommand => 'Cari tindakan'; diff --git a/lib/l10n/generated/app_localizations_it.dart b/lib/l10n/generated/app_localizations_it.dart index 7800d250..dd913682 100644 --- a/lib/l10n/generated/app_localizations_it.dart +++ b/lib/l10n/generated/app_localizations_it.dart @@ -727,6 +727,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Nuovo'; + @override String get open => 'Apri'; @@ -911,15 +914,23 @@ class AppLocalizationsIt extends AppLocalizations { String get shortcutGroupGeneral => 'Generale'; @override - String get shortcutNewDocument => 'Crea'; + String get home => 'Pagina iniziale'; + + @override + String get openMenu => 'Menu Apri'; + + @override + String get newNextcloudNote => 'Nuova nota Nextcloud'; + + @override + String get shortcutNewDocument => 'Menu Nuovo'; @override String get shortcutNewDocumentDescription => - 'Crea un file Markdown o un progetto Writerside'; + 'Mostra il menu per creare risorse'; @override - String get shortcutOpenDescription => - 'Apri un file Markdown, una cartella o un progetto Writerside'; + String get shortcutOpenDescription => 'Mostra il menu per aprire risorse'; @override String get shortcutSaveDescription => 'Salva il documento corrente'; @@ -1223,11 +1234,11 @@ class AppLocalizationsIt extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Cancella autorizzazioni per immagini remote'; + 'Cancella le autorizzazioni delle immagini degli spazi di lavoro'; @override String get clearRemoteImagePermissionsDescription => - 'Dimentica le aree di lavoro autorizzate a caricare immagini remote.'; + 'Dimentica tutte le autorizzazioni per le immagini remote degli spazi di lavoro.'; @override String get clearGitWorkspaceTrust => @@ -1582,7 +1593,7 @@ class AppLocalizationsIt extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Scegli se BusyMark può caricare immagini remote.'; + 'Immagine remota bloccata. Fai clic per le opzioni di caricamento.'; @override String get remoteImagesBlockedTitle => 'Le immagini remote sono bloccate'; @@ -1592,7 +1603,38 @@ class AppLocalizationsIt extends AppLocalizations { 'Questo documento fa riferimento a immagini su Internet. Il caricamento può rivelare informazioni di rete all’host delle immagini.'; @override - String get loadRemoteImagesForWorkspace => 'Carica per quest’area di lavoro'; + String get loadThisRemoteImage => 'Carica questa immagine'; + + @override + String get remoteImageMoreOptions => 'Altre opzioni…'; + + @override + String get remoteImageMoreOptionsTitle => + 'Autorizzazioni per le immagini remote'; + + @override + String get loadRemoteImagesInDocument => + 'Carica le immagini in questo documento'; + + @override + String get remoteImageUntilClose => 'Fino alla chiusura di questo documento.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Consente le immagini remote in $workspace finché non cancelli le autorizzazioni degli spazi di lavoro nelle impostazioni di privacy.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Consente le immagini remote in tutto BusyMark finché non disattivi questa opzione nelle impostazioni di privacy.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Consenti le immagini remote in tutto BusyMark. Le autorizzazioni degli spazi di lavoro si gestiscono separatamente.'; + + @override + String get loadRemoteImagesForWorkspace => + 'Consenti sempre in questo spazio di lavoro'; @override String get alwaysLoadRemoteImages => 'Carica sempre le immagini remote'; @@ -5557,7 +5599,7 @@ class AppLocalizationsIt extends AppLocalizations { String get searchCurrentWorkspace => 'Area di lavoro corrente'; @override - String get browseNotes => 'Sfoglia note'; + String get browseNotes => 'Sfoglia le note Nextcloud'; @override String get searchActionsCommand => 'Cerca azioni'; diff --git a/lib/l10n/generated/app_localizations_ja.dart b/lib/l10n/generated/app_localizations_ja.dart index 3f315d97..e7dfecc1 100644 --- a/lib/l10n/generated/app_localizations_ja.dart +++ b/lib/l10n/generated/app_localizations_ja.dart @@ -697,6 +697,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => '新規作成'; + @override String get open => '開く'; @@ -880,15 +883,22 @@ class AppLocalizationsJa extends AppLocalizations { String get shortcutGroupGeneral => '全般'; @override - String get shortcutNewDocument => '作成'; + String get home => 'ホーム'; + + @override + String get openMenu => '開くメニュー'; @override - String get shortcutNewDocumentDescription => - 'Markdown ファイルまたは Writerside プロジェクトを作成'; + String get newNextcloudNote => '新しい Nextcloud ノート'; @override - String get shortcutOpenDescription => - 'Markdown ファイル、フォルダー、または Writerside プロジェクトを開く'; + String get shortcutNewDocument => '新規作成メニュー'; + + @override + String get shortcutNewDocumentDescription => 'リソースを作成するメニューを表示'; + + @override + String get shortcutOpenDescription => 'リソースを開くメニューを表示'; @override String get shortcutSaveDescription => '現在のドキュメントを保存'; @@ -1161,11 +1171,11 @@ class AppLocalizationsJa extends AppLocalizations { 'Markdown のプレビューとエディターで http および https URL の画像を読み込めるようにする'; @override - String get clearRemoteImagePermissions => 'リモート画像の権限を消去'; + String get clearRemoteImagePermissions => 'ワークスペースの画像の許可を消去'; @override String get clearRemoteImagePermissionsDescription => - 'リモート画像の読み込みを許可したワークスペースの権限を忘れる'; + 'すべてのワークスペースのリモート画像の許可を消去します。'; @override String get clearGitWorkspaceTrust => '信頼済み Git ワークスペースを消去'; @@ -1509,7 +1519,8 @@ class AppLocalizationsJa extends AppLocalizations { String get remoteImageBlocked => 'リモート画像がブロックされています'; @override - String get remoteImageBlockedTooltip => 'BusyMark にリモート画像の読み込みを許可するか選択'; + String get remoteImageBlockedTooltip => + 'リモート画像をブロックしました。クリックして読み込みオプションを表示します。'; @override String get remoteImagesBlockedTitle => 'リモート画像がブロックされています'; @@ -1519,7 +1530,35 @@ class AppLocalizationsJa extends AppLocalizations { 'このドキュメントはインターネット上の画像を参照しています。読み込むと、画像ホストにネットワーク情報が公開される可能性があります。'; @override - String get loadRemoteImagesForWorkspace => 'このワークスペースで読み込む'; + String get loadThisRemoteImage => 'この画像を読み込む'; + + @override + String get remoteImageMoreOptions => 'その他のオプション…'; + + @override + String get remoteImageMoreOptionsTitle => 'リモート画像の許可'; + + @override + String get loadRemoteImagesInDocument => 'この文書の画像を読み込む'; + + @override + String get remoteImageUntilClose => 'この文書を閉じるまで有効です。'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'プライバシー設定でワークスペースの許可を消去するまで、$workspace のリモート画像を許可します。'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'プライバシー設定でこのオプションをオフにするまで、BusyMark 全体でリモート画像を許可します。'; + + @override + String get remoteImageGlobalSettingsDetail => + 'BusyMark 全体でリモート画像を許可します。ワークスペースの許可は個別に管理されます。'; + + @override + String get loadRemoteImagesForWorkspace => 'このワークスペースでは常に許可する'; @override String get alwaysLoadRemoteImages => '常にリモート画像を読み込む'; @@ -5357,7 +5396,7 @@ class AppLocalizationsJa extends AppLocalizations { String get searchCurrentWorkspace => '現在のワークスペース'; @override - String get browseNotes => 'ノートを参照'; + String get browseNotes => 'Nextcloud ノートを参照'; @override String get searchActionsCommand => 'アクションを検索'; diff --git a/lib/l10n/generated/app_localizations_ko.dart b/lib/l10n/generated/app_localizations_ko.dart index 935a39a5..b6f3bf65 100644 --- a/lib/l10n/generated/app_localizations_ko.dart +++ b/lib/l10n/generated/app_localizations_ko.dart @@ -698,6 +698,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => '새로 만들기'; + @override String get open => '열기'; @@ -881,14 +884,22 @@ class AppLocalizationsKo extends AppLocalizations { String get shortcutGroupGeneral => '일반'; @override - String get shortcutNewDocument => '만들기'; + String get home => '홈'; + + @override + String get openMenu => '열기 메뉴'; @override - String get shortcutNewDocumentDescription => - 'Markdown 파일 또는 Writerside 프로젝트 만들기'; + String get newNextcloudNote => '새 Nextcloud 노트'; @override - String get shortcutOpenDescription => 'Markdown 파일, 폴더 또는 Writerside 프로젝트 열기'; + String get shortcutNewDocument => '새로 만들기 메뉴'; + + @override + String get shortcutNewDocumentDescription => '리소스를 만드는 메뉴 표시'; + + @override + String get shortcutOpenDescription => '리소스를 여는 메뉴 표시'; @override String get shortcutSaveDescription => '현재 문서 저장'; @@ -1159,11 +1170,11 @@ class AppLocalizationsKo extends AppLocalizations { 'Markdown 미리보기 및 편집기 이미지가 http 및 https URL에서 로드되도록 허용합니다.'; @override - String get clearRemoteImagePermissions => '원격 이미지 권한 초기화'; + String get clearRemoteImagePermissions => '작업 공간의 이미지 권한 지우기'; @override String get clearRemoteImagePermissionsDescription => - '원격 이미지 로드 권한이 허용된 작업공간의 저장된 권한을 삭제합니다.'; + '모든 작업 공간의 원격 이미지 권한을 지웁니다.'; @override String get clearGitWorkspaceTrust => '신뢰할 수 있는 Git 작업공간 초기화'; @@ -1509,7 +1520,7 @@ class AppLocalizationsKo extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'BusyMark가 원격 이미지를 로드할 수 있는지 여부를 선택합니다.'; + '원격 이미지가 차단되었습니다. 클릭하여 불러오기 옵션을 확인하세요.'; @override String get remoteImagesBlockedTitle => '원격 이미지가 차단되었습니다.'; @@ -1519,7 +1530,35 @@ class AppLocalizationsKo extends AppLocalizations { '이 문서는 인터넷의 이미지를 참조합니다. 이를 로드하면 이미지 호스트에 네트워크 정보가 공개될 수 있습니다.'; @override - String get loadRemoteImagesForWorkspace => '이 작업공간에서 로드'; + String get loadThisRemoteImage => '이 이미지 불러오기'; + + @override + String get remoteImageMoreOptions => '추가 옵션…'; + + @override + String get remoteImageMoreOptionsTitle => '원격 이미지 권한'; + + @override + String get loadRemoteImagesInDocument => '이 문서의 이미지 불러오기'; + + @override + String get remoteImageUntilClose => '이 문서를 닫을 때까지 적용됩니다.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return '개인정보 보호 설정에서 작업 공간 권한을 지울 때까지 $workspace의 원격 이미지를 허용합니다.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + '개인정보 보호 설정에서 이 옵션을 끌 때까지 BusyMark 전체에서 원격 이미지를 허용합니다.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'BusyMark 전체에서 원격 이미지를 허용합니다. 작업 공간 권한은 별도로 관리됩니다.'; + + @override + String get loadRemoteImagesForWorkspace => '이 작업 공간에서 항상 허용'; @override String get alwaysLoadRemoteImages => '항상 원격 이미지 로드'; @@ -5357,7 +5396,7 @@ class AppLocalizationsKo extends AppLocalizations { String get searchCurrentWorkspace => '현재 작업 공간'; @override - String get browseNotes => '노트 찾아보기'; + String get browseNotes => 'Nextcloud 노트 찾아보기'; @override String get searchActionsCommand => '작업 검색'; diff --git a/lib/l10n/generated/app_localizations_nb.dart b/lib/l10n/generated/app_localizations_nb.dart index 254f1141..83948c8f 100644 --- a/lib/l10n/generated/app_localizations_nb.dart +++ b/lib/l10n/generated/app_localizations_nb.dart @@ -729,6 +729,9 @@ class AppLocalizationsNb extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Ny'; + @override String get open => 'Åpne'; @@ -913,15 +916,23 @@ class AppLocalizationsNb extends AppLocalizations { String get shortcutGroupGeneral => 'Generelt'; @override - String get shortcutNewDocument => 'Opprett'; + String get home => 'Hjem'; + + @override + String get openMenu => 'Åpne-meny'; + + @override + String get newNextcloudNote => 'Nytt Nextcloud-notat'; + + @override + String get shortcutNewDocument => 'Ny-meny'; @override String get shortcutNewDocumentDescription => - 'Opprett en Markdown-fil eller et Writerside-prosjekt'; + 'Vis menyen for å opprette ressurser'; @override - String get shortcutOpenDescription => - 'Åpne en Markdown-fil, en mappe eller et Writerside-prosjekt'; + String get shortcutOpenDescription => 'Vis menyen for å åpne ressurser'; @override String get shortcutSaveDescription => 'Lagre gjeldende dokument'; @@ -1216,11 +1227,11 @@ class AppLocalizationsNb extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Tøm tillatelser for eksterne bilder'; + 'Slett bildetillatelser for arbeidsområder'; @override String get clearRemoteImagePermissionsDescription => - 'Glem arbeidsområder som fikk tillatelse til å laste inn eksterne bilder.'; + 'Glem alle tillatelser for eksterne bilder i arbeidsområder.'; @override String get clearGitWorkspaceTrust => 'Tøm klarerte Git-arbeidsområder'; @@ -1573,7 +1584,7 @@ class AppLocalizationsNb extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Velg om BusyMark kan laste inn eksterne bilder.'; + 'Eksternt bilde blokkert. Klikk for innlastingsvalg.'; @override String get remoteImagesBlockedTitle => 'Eksterne bilder er blokkert'; @@ -1582,9 +1593,37 @@ class AppLocalizationsNb extends AppLocalizations { String get remoteImagesBlockedMessage => 'Dette dokumentet refererer til bilder på Internett. Når de lastes inn, kan nettverksinformasjon bli avslørt for bildeverten.'; + @override + String get loadThisRemoteImage => 'Last inn dette bildet'; + + @override + String get remoteImageMoreOptions => 'Flere valg…'; + + @override + String get remoteImageMoreOptionsTitle => 'Tillatelser for eksterne bilder'; + + @override + String get loadRemoteImagesInDocument => 'Last inn bilder i dette dokumentet'; + + @override + String get remoteImageUntilClose => 'Til dette dokumentet lukkes.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Tillater eksterne bilder i $workspace til du sletter arbeidsområdetillatelsene i personverninnstillingene.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Tillater eksterne bilder i hele BusyMark til du slår dette av i personverninnstillingene.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Tillat eksterne bilder i hele BusyMark. Tillatelser for arbeidsområder administreres separat.'; + @override String get loadRemoteImagesForWorkspace => - 'Last inn for dette arbeidsområdet'; + 'Tillat alltid i dette arbeidsområdet'; @override String get alwaysLoadRemoteImages => 'Last alltid inn eksterne bilder'; @@ -5518,7 +5557,7 @@ class AppLocalizationsNb extends AppLocalizations { String get searchCurrentWorkspace => 'Gjeldende arbeidsområde'; @override - String get browseNotes => 'Bla gjennom notater'; + String get browseNotes => 'Bla gjennom Nextcloud-notater'; @override String get searchActionsCommand => 'Søk etter handlinger'; diff --git a/lib/l10n/generated/app_localizations_nl.dart b/lib/l10n/generated/app_localizations_nl.dart index adc0af93..d20b1f96 100644 --- a/lib/l10n/generated/app_localizations_nl.dart +++ b/lib/l10n/generated/app_localizations_nl.dart @@ -730,6 +730,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Nieuw'; + @override String get open => 'Openen'; @@ -914,15 +917,23 @@ class AppLocalizationsNl extends AppLocalizations { String get shortcutGroupGeneral => 'Algemeen'; @override - String get shortcutNewDocument => 'Maken'; + String get home => 'Start'; + + @override + String get openMenu => 'Menu Openen'; + + @override + String get newNextcloudNote => 'Nieuwe Nextcloud-notitie'; + + @override + String get shortcutNewDocument => 'Menu Nieuw'; @override String get shortcutNewDocumentDescription => - 'Maak een Markdown-bestand of Writerside-project'; + 'Toon het menu om bronnen te maken'; @override - String get shortcutOpenDescription => - 'Open een Markdown-bestand, map of Writerside-project'; + String get shortcutOpenDescription => 'Toon het menu om bronnen te openen'; @override String get shortcutSaveDescription => 'Sla het huidige document op'; @@ -1217,11 +1228,11 @@ class AppLocalizationsNl extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Wis machtigingen voor externe afbeeldingen'; + 'Afbeeldingsmachtigingen voor werkruimten wissen'; @override String get clearRemoteImagePermissionsDescription => - 'Verwijder de opgeslagen rechten voor werkruimten die externe afbeeldingen mochten laden.'; + 'Vergeet alle machtigingen voor externe afbeeldingen in werkruimten.'; @override String get clearGitWorkspaceTrust => 'Wis vertrouwde Git-werkruimten'; @@ -1575,7 +1586,7 @@ class AppLocalizationsNl extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Kies of BusyMark externe afbeeldingen kan laden.'; + 'Externe afbeelding geblokkeerd. Klik voor laadopties.'; @override String get remoteImagesBlockedTitle => @@ -1586,7 +1597,37 @@ class AppLocalizationsNl extends AppLocalizations { 'Dit document verwijst naar afbeeldingen van internet. Als u ze laadt, kan netwerkinformatie aan de afbeeldingshost worden onthuld.'; @override - String get loadRemoteImagesForWorkspace => 'Voor deze werkruimte laden'; + String get loadThisRemoteImage => 'Deze afbeelding laden'; + + @override + String get remoteImageMoreOptions => 'Meer opties…'; + + @override + String get remoteImageMoreOptionsTitle => + 'Machtigingen voor externe afbeeldingen'; + + @override + String get loadRemoteImagesInDocument => 'Afbeeldingen in dit document laden'; + + @override + String get remoteImageUntilClose => 'Totdat dit document wordt gesloten.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Staat externe afbeeldingen in $workspace toe totdat je de werkruimtemachtigingen wist in de privacyinstellingen.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Staat externe afbeeldingen in heel BusyMark toe totdat je dit uitschakelt in de privacyinstellingen.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Sta externe afbeeldingen in heel BusyMark toe. Werkruimtemachtigingen worden apart beheerd.'; + + @override + String get loadRemoteImagesForWorkspace => + 'Altijd toestaan in deze werkruimte'; @override String get alwaysLoadRemoteImages => 'Externe afbeeldingen altijd laden'; @@ -5563,7 +5604,7 @@ class AppLocalizationsNl extends AppLocalizations { String get searchCurrentWorkspace => 'Huidige werkruimte'; @override - String get browseNotes => 'Notities bekijken'; + String get browseNotes => 'Door Nextcloud-notities bladeren'; @override String get searchActionsCommand => 'Acties zoeken'; diff --git a/lib/l10n/generated/app_localizations_pl.dart b/lib/l10n/generated/app_localizations_pl.dart index 0017b967..ba8c6a27 100644 --- a/lib/l10n/generated/app_localizations_pl.dart +++ b/lib/l10n/generated/app_localizations_pl.dart @@ -724,6 +724,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Nowy'; + @override String get open => 'Otwórz'; @@ -908,15 +911,22 @@ class AppLocalizationsPl extends AppLocalizations { String get shortcutGroupGeneral => 'Ogólne'; @override - String get shortcutNewDocument => 'Utwórz'; + String get home => 'Strona główna'; + + @override + String get openMenu => 'Menu Otwórz'; @override - String get shortcutNewDocumentDescription => - 'Utwórz plik Markdown lub projekt Writerside'; + String get newNextcloudNote => 'Nowa notatka Nextcloud'; @override - String get shortcutOpenDescription => - 'Otwórz plik Markdown, folder lub projekt Writerside'; + String get shortcutNewDocument => 'Menu Nowy'; + + @override + String get shortcutNewDocumentDescription => 'Pokaż menu tworzenia zasobów'; + + @override + String get shortcutOpenDescription => 'Pokaż menu otwierania zasobów'; @override String get shortcutSaveDescription => 'Zapisz bieżący dokument'; @@ -1220,11 +1230,11 @@ class AppLocalizationsPl extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Wyczyść uprawnienia do obrazów zdalnych'; + 'Wyczyść uprawnienia do obrazów w obszarach roboczych'; @override String get clearRemoteImagePermissionsDescription => - 'Zapomnij obszary robocze, którym zezwolono na wczytywanie obrazów zdalnych.'; + 'Usuń wszystkie uprawnienia obszarów roboczych do obrazów zdalnych.'; @override String get clearGitWorkspaceTrust => 'Wyczyść zaufane obszary robocze Git'; @@ -1584,7 +1594,7 @@ class AppLocalizationsPl extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Wybierz, czy BusyMark może wczytywać obrazy zdalne.'; + 'Obraz zdalny zablokowany. Kliknij, aby wyświetlić opcje wczytywania.'; @override String get remoteImagesBlockedTitle => 'Obrazy zdalne są zablokowane'; @@ -1594,7 +1604,36 @@ class AppLocalizationsPl extends AppLocalizations { 'Ten dokument odwołuje się do obrazów z internetu. Ich wczytanie może ujawnić informacje o twojej sieci serwerom udostępniającym te obrazy.'; @override - String get loadRemoteImagesForWorkspace => 'Wczytaj w tym obszarze roboczym'; + String get loadThisRemoteImage => 'Wczytaj ten obraz'; + + @override + String get remoteImageMoreOptions => 'Więcej opcji…'; + + @override + String get remoteImageMoreOptionsTitle => 'Uprawnienia do obrazów zdalnych'; + + @override + String get loadRemoteImagesInDocument => 'Wczytaj obrazy w tym dokumencie'; + + @override + String get remoteImageUntilClose => 'Do zamknięcia tego dokumentu.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Zezwala na obrazy zdalne w $workspace do czasu wyczyszczenia uprawnień obszarów roboczych w ustawieniach prywatności.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Zezwala na obrazy zdalne w całym BusyMark do czasu wyłączenia tej opcji w ustawieniach prywatności.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Zezwalaj na obrazy zdalne w całym BusyMark. Uprawnienia obszarów roboczych są zarządzane oddzielnie.'; + + @override + String get loadRemoteImagesForWorkspace => + 'Zawsze zezwalaj w tym obszarze roboczym'; @override String get alwaysLoadRemoteImages => 'Zawsze wczytuj obrazy zdalne'; @@ -5567,7 +5606,7 @@ class AppLocalizationsPl extends AppLocalizations { String get searchCurrentWorkspace => 'Bieżący obszar roboczy'; @override - String get browseNotes => 'Przeglądaj notatki'; + String get browseNotes => 'Przeglądaj notatki Nextcloud'; @override String get searchActionsCommand => 'Szukaj działań'; diff --git a/lib/l10n/generated/app_localizations_pt.dart b/lib/l10n/generated/app_localizations_pt.dart index 82a72110..2fcfbc51 100644 --- a/lib/l10n/generated/app_localizations_pt.dart +++ b/lib/l10n/generated/app_localizations_pt.dart @@ -728,6 +728,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Novo'; + @override String get open => 'Abrir'; @@ -912,15 +915,23 @@ class AppLocalizationsPt extends AppLocalizations { String get shortcutGroupGeneral => 'Geral'; @override - String get shortcutNewDocument => 'Criar'; + String get home => 'Início'; + + @override + String get openMenu => 'Menu Abrir'; + + @override + String get newNextcloudNote => 'Nova nota do Nextcloud'; + + @override + String get shortcutNewDocument => 'Menu Novo'; @override String get shortcutNewDocumentDescription => - 'Criar ficheiro Markdown ou projeto Writerside'; + 'Mostrar o menu para criar recursos'; @override - String get shortcutOpenDescription => - 'Abrir um ficheiro Markdown, uma pasta ou um projeto Writerside'; + String get shortcutOpenDescription => 'Mostrar o menu para abrir recursos'; @override String get shortcutSaveDescription => 'Guardar o documento atual'; @@ -1222,11 +1233,11 @@ class AppLocalizationsPt extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Limpar permissões de imagens remotas'; + 'Limpar permissões de imagens dos espaços de trabalho'; @override String get clearRemoteImagePermissionsDescription => - 'Esquecer os espaços de trabalho autorizados a carregar imagens remotas.'; + 'Esquecer todas as permissões dos espaços de trabalho para imagens remotas.'; @override String get clearGitWorkspaceTrust => @@ -1580,7 +1591,7 @@ class AppLocalizationsPt extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Escolha se o BusyMark pode carregar imagens remotas.'; + 'Imagem remota bloqueada. Clique para ver as opções de carregamento.'; @override String get remoteImagesBlockedTitle => 'As imagens remotas estão bloqueadas'; @@ -1589,9 +1600,37 @@ class AppLocalizationsPt extends AppLocalizations { String get remoteImagesBlockedMessage => 'Este documento faz referência a imagens da Internet. Carregá-las pode revelar informações de rede ao servidor que as hospeda.'; + @override + String get loadThisRemoteImage => 'Carregar esta imagem'; + + @override + String get remoteImageMoreOptions => 'Mais opções…'; + + @override + String get remoteImageMoreOptionsTitle => 'Permissões de imagens remotas'; + + @override + String get loadRemoteImagesInDocument => 'Carregar imagens neste documento'; + + @override + String get remoteImageUntilClose => 'Até fechar este documento.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Permite imagens remotas em $workspace até limpar as permissões de espaços de trabalho nas definições de privacidade.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Permite imagens remotas em todo o BusyMark até desativar esta opção nas definições de privacidade.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Permitir imagens remotas em todo o BusyMark. As permissões dos espaços de trabalho são geridas separadamente.'; + @override String get loadRemoteImagesForWorkspace => - 'Carregar neste espaço de trabalho'; + 'Permitir sempre neste espaço de trabalho'; @override String get alwaysLoadRemoteImages => 'Sempre carregar imagens remotas'; @@ -5576,7 +5615,7 @@ class AppLocalizationsPt extends AppLocalizations { String get searchCurrentWorkspace => 'Área de trabalho atual'; @override - String get browseNotes => 'Explorar notas'; + String get browseNotes => 'Explorar notas do Nextcloud'; @override String get searchActionsCommand => 'Pesquisar ações'; @@ -9787,6 +9826,9 @@ class AppLocalizationsPtBr extends AppLocalizationsPt { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Novo'; + @override String get open => 'Abrir'; @@ -9971,15 +10013,23 @@ class AppLocalizationsPtBr extends AppLocalizationsPt { String get shortcutGroupGeneral => 'Geral'; @override - String get shortcutNewDocument => 'Criar'; + String get home => 'Início'; + + @override + String get openMenu => 'Menu Abrir'; + + @override + String get newNextcloudNote => 'Nova nota do Nextcloud'; + + @override + String get shortcutNewDocument => 'Menu Novo'; @override String get shortcutNewDocumentDescription => - 'Criar arquivo Markdown ou projeto Writerside'; + 'Mostrar o menu para criar recursos'; @override - String get shortcutOpenDescription => - 'Abrir um arquivo Markdown, uma pasta ou um projeto Writerside'; + String get shortcutOpenDescription => 'Mostrar o menu para abrir recursos'; @override String get shortcutSaveDescription => 'Salvar o documento atual'; @@ -10282,11 +10332,11 @@ class AppLocalizationsPtBr extends AppLocalizationsPt { @override String get clearRemoteImagePermissions => - 'Limpar permissões de imagens remotas'; + 'Limpar permissões de imagens dos espaços de trabalho'; @override String get clearRemoteImagePermissionsDescription => - 'Esquecer os espaços de trabalho autorizados a carregar imagens remotas.'; + 'Esquecer todas as permissões de imagens remotas dos espaços de trabalho.'; @override String get clearGitWorkspaceTrust => @@ -10640,7 +10690,7 @@ class AppLocalizationsPtBr extends AppLocalizationsPt { @override String get remoteImageBlockedTooltip => - 'Escolha se o BusyMark pode carregar imagens remotas.'; + 'Imagem remota bloqueada. Clique para ver as opções de carregamento.'; @override String get remoteImagesBlockedTitle => 'As imagens remotas estão bloqueadas'; @@ -10649,9 +10699,37 @@ class AppLocalizationsPtBr extends AppLocalizationsPt { String get remoteImagesBlockedMessage => 'Este documento faz referência a imagens da Internet. Carregá-las pode revelar informações de rede ao servidor que as hospeda.'; + @override + String get loadThisRemoteImage => 'Carregar esta imagem'; + + @override + String get remoteImageMoreOptions => 'Mais opções…'; + + @override + String get remoteImageMoreOptionsTitle => 'Permissões de imagens remotas'; + + @override + String get loadRemoteImagesInDocument => 'Carregar imagens neste documento'; + + @override + String get remoteImageUntilClose => 'Até fechar este documento.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Permite imagens remotas em $workspace até limpar as permissões dos espaços de trabalho nas configurações de Privacidade.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Permite imagens remotas em todo o BusyMark até desativar esta opção nas configurações de Privacidade.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Permitir imagens remotas em todo o BusyMark. As permissões dos espaços de trabalho são gerenciadas separadamente.'; + @override String get loadRemoteImagesForWorkspace => - 'Carregar neste espaço de trabalho'; + 'Sempre permitir neste espaço de trabalho'; @override String get alwaysLoadRemoteImages => 'Sempre carregar imagens remotas'; @@ -14632,7 +14710,7 @@ class AppLocalizationsPtBr extends AppLocalizationsPt { String get searchCurrentWorkspace => 'Área de trabalho atual'; @override - String get browseNotes => 'Explorar notas'; + String get browseNotes => 'Explorar notas do Nextcloud'; @override String get searchActionsCommand => 'Pesquisar ações'; diff --git a/lib/l10n/generated/app_localizations_ru.dart b/lib/l10n/generated/app_localizations_ru.dart index 266971f2..a843e562 100644 --- a/lib/l10n/generated/app_localizations_ru.dart +++ b/lib/l10n/generated/app_localizations_ru.dart @@ -727,6 +727,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Создать'; + @override String get open => 'Открыть'; @@ -911,15 +914,23 @@ class AppLocalizationsRu extends AppLocalizations { String get shortcutGroupGeneral => 'Общие'; @override - String get shortcutNewDocument => 'Создать'; + String get home => 'Главная'; + + @override + String get openMenu => 'Меню «Открыть»'; + + @override + String get newNextcloudNote => 'Новая заметка Nextcloud'; + + @override + String get shortcutNewDocument => 'Меню «Создать»'; @override String get shortcutNewDocumentDescription => - 'Создать файл Markdown или проект Writerside'; + 'Показать меню создания ресурсов'; @override - String get shortcutOpenDescription => - 'Открыть файл Markdown, папку или проект Writerside'; + String get shortcutOpenDescription => 'Показать меню открытия ресурсов'; @override String get shortcutSaveDescription => 'Сохранить текущий документ'; @@ -1216,11 +1227,11 @@ class AppLocalizationsRu extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Сбросить разрешения на удалённые изображения'; + 'Очистить разрешения для изображений в рабочих пространствах'; @override String get clearRemoteImagePermissionsDescription => - 'Забыть рабочие области, которым было разрешено загружать удалённые изображения.'; + 'Забыть все разрешения рабочих пространств на загрузку удалённых изображений.'; @override String get clearGitWorkspaceTrust => @@ -1582,7 +1593,7 @@ class AppLocalizationsRu extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Выберите, может ли BusyMark загружать удалённые изображения.'; + 'Удалённое изображение заблокировано. Нажмите, чтобы выбрать способ загрузки.'; @override String get remoteImagesBlockedTitle => 'Удалённые изображения заблокированы'; @@ -1591,9 +1602,39 @@ class AppLocalizationsRu extends AppLocalizations { String get remoteImagesBlockedMessage => 'Этот документ ссылается на изображения из интернета. Их загрузка может раскрыть сведения о вашей сети серверам, на которых размещены изображения.'; + @override + String get loadThisRemoteImage => 'Загрузить это изображение'; + + @override + String get remoteImageMoreOptions => 'Другие варианты…'; + + @override + String get remoteImageMoreOptionsTitle => + 'Разрешения для удалённых изображений'; + + @override + String get loadRemoteImagesInDocument => + 'Загрузить изображения в этом документе'; + + @override + String get remoteImageUntilClose => 'До закрытия этого документа.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Разрешает удалённые изображения в $workspace, пока вы не очистите разрешения для рабочих пространств в настройках конфиденциальности.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Разрешает удалённые изображения во всём BusyMark, пока вы не отключите эту настройку в разделе конфиденциальности.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Разрешает удалённые изображения во всём BusyMark. Разрешения рабочих пространств настраиваются отдельно.'; + @override String get loadRemoteImagesForWorkspace => - 'Загрузить для этой рабочей области'; + 'Всегда разрешать в этом рабочем пространстве'; @override String get alwaysLoadRemoteImages => 'Всегда загружать удалённые изображения'; @@ -5570,7 +5611,7 @@ class AppLocalizationsRu extends AppLocalizations { String get searchCurrentWorkspace => 'Текущая рабочая область'; @override - String get browseNotes => 'Обзор заметок'; + String get browseNotes => 'Просмотр заметок Nextcloud'; @override String get searchActionsCommand => 'Поиск действий'; diff --git a/lib/l10n/generated/app_localizations_tr.dart b/lib/l10n/generated/app_localizations_tr.dart index a023fa3d..26d2c6dc 100644 --- a/lib/l10n/generated/app_localizations_tr.dart +++ b/lib/l10n/generated/app_localizations_tr.dart @@ -723,6 +723,9 @@ class AppLocalizationsTr extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Yeni'; + @override String get open => 'Aç'; @@ -907,15 +910,23 @@ class AppLocalizationsTr extends AppLocalizations { String get shortcutGroupGeneral => 'Genel'; @override - String get shortcutNewDocument => 'Oluştur'; + String get home => 'Ana Sayfa'; + + @override + String get openMenu => 'Aç Menüsü'; + + @override + String get newNextcloudNote => 'Yeni Nextcloud Notu'; + + @override + String get shortcutNewDocument => 'Yeni Menüsü'; @override String get shortcutNewDocumentDescription => - 'Markdown dosyası veya Writerside projesi oluştur'; + 'Kaynak oluşturma menüsünü göster'; @override - String get shortcutOpenDescription => - 'Markdown dosyasını, klasörünü veya Writerside projesini açın'; + String get shortcutOpenDescription => 'Kaynak açma menüsünü göster'; @override String get shortcutSaveDescription => 'Geçerli belgeyi kaydet'; @@ -1212,11 +1223,12 @@ class AppLocalizationsTr extends AppLocalizations { 'Markdown önizleme ve düzenleme görsellerinin http ve https URL\'lerinden yüklenmesine izin verin.'; @override - String get clearRemoteImagePermissions => 'Harici görsel izinlerini temizle'; + String get clearRemoteImagePermissions => + 'Çalışma alanı resim izinlerini temizle'; @override String get clearRemoteImagePermissionsDescription => - 'Harici görsellerin yüklenmesine izin verilen çalışma alanlarını unutun.'; + 'Çalışma alanlarının tüm uzak resim izinlerini unut.'; @override String get clearGitWorkspaceTrust => @@ -1570,7 +1582,7 @@ class AppLocalizationsTr extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'BusyMark\'ın harici görselleri yükleyip yükleyemeyeceğini seçin.'; + 'Uzak görsel engellendi. Yükleme seçenekleri için tıklayın.'; @override String get remoteImagesBlockedTitle => 'Harici görseller engellendi'; @@ -1580,7 +1592,36 @@ class AppLocalizationsTr extends AppLocalizations { 'Bu belge internetteki görsellere başvuruyor. Bunları yüklemek ağ bilgilerini görselin barındırıldığı sunucuya açığa çıkarabilir.'; @override - String get loadRemoteImagesForWorkspace => 'Bu çalışma alanı için yükleme'; + String get loadThisRemoteImage => 'Bu resmi yükle'; + + @override + String get remoteImageMoreOptions => 'Diğer seçenekler…'; + + @override + String get remoteImageMoreOptionsTitle => 'Uzak resim izinleri'; + + @override + String get loadRemoteImagesInDocument => 'Bu belgedeki resimleri yükle'; + + @override + String get remoteImageUntilClose => 'Bu belge kapanana kadar.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Gizlilik ayarlarında çalışma alanı izinlerini temizleyene kadar $workspace içindeki uzak resimlere izin verir.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Gizlilik ayarlarında bu seçeneği kapatana kadar BusyMark genelinde uzak resimlere izin verir.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'BusyMark genelinde uzak resimlere izin ver. Çalışma alanı izinleri ayrı yönetilir.'; + + @override + String get loadRemoteImagesForWorkspace => + 'Bu çalışma alanında her zaman izin ver'; @override String get alwaysLoadRemoteImages => 'Harici görselleri her zaman yükle'; @@ -5511,7 +5552,7 @@ class AppLocalizationsTr extends AppLocalizations { String get searchCurrentWorkspace => 'Geçerli çalışma alanı'; @override - String get browseNotes => 'Notlara göz at'; + String get browseNotes => 'Nextcloud Notlarına Göz At'; @override String get searchActionsCommand => 'Eylemleri ara'; diff --git a/lib/l10n/generated/app_localizations_uk.dart b/lib/l10n/generated/app_localizations_uk.dart index 9ade06c7..02d5b5c1 100644 --- a/lib/l10n/generated/app_localizations_uk.dart +++ b/lib/l10n/generated/app_localizations_uk.dart @@ -726,6 +726,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Створити'; + @override String get open => 'Відкрити'; @@ -910,15 +913,23 @@ class AppLocalizationsUk extends AppLocalizations { String get shortcutGroupGeneral => 'Загальні'; @override - String get shortcutNewDocument => 'Створити'; + String get home => 'Головна'; + + @override + String get openMenu => 'Меню «Відкрити»'; + + @override + String get newNextcloudNote => 'Нова нотатка Nextcloud'; + + @override + String get shortcutNewDocument => 'Меню «Створити»'; @override String get shortcutNewDocumentDescription => - 'Створити файл Markdown або проєкт Writerside'; + 'Показати меню створення ресурсів'; @override - String get shortcutOpenDescription => - 'Відкрити файл Markdown, папку або проєкт Writerside'; + String get shortcutOpenDescription => 'Показати меню відкриття ресурсів'; @override String get shortcutSaveDescription => 'Зберегти поточний документ'; @@ -1221,11 +1232,11 @@ class AppLocalizationsUk extends AppLocalizations { @override String get clearRemoteImagePermissions => - 'Очистити дозволи для віддалених зображень'; + 'Очистити дозволи на зображення в робочих просторах'; @override String get clearRemoteImagePermissionsDescription => - 'Забути робочі області, яким було дозволено завантажувати віддалені зображення.'; + 'Забути всі дозволи робочих просторів для віддалених зображень.'; @override String get clearGitWorkspaceTrust => @@ -1588,7 +1599,7 @@ class AppLocalizationsUk extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Виберіть, чи може BusyMark завантажувати віддалені зображення.'; + 'Віддалене зображення заблоковано. Натисніть, щоб переглянути параметри завантаження.'; @override String get remoteImagesBlockedTitle => 'Віддалені зображення заблоковано'; @@ -1597,9 +1608,38 @@ class AppLocalizationsUk extends AppLocalizations { String get remoteImagesBlockedMessage => 'Цей документ посилається на зображення з інтернету. Їх завантаження може розкрити відомості про вашу мережу серверам, на яких розміщено зображення.'; + @override + String get loadThisRemoteImage => 'Завантажити це зображення'; + + @override + String get remoteImageMoreOptions => 'Інші варіанти…'; + + @override + String get remoteImageMoreOptionsTitle => 'Дозволи для віддалених зображень'; + + @override + String get loadRemoteImagesInDocument => + 'Завантажити зображення в цьому документі'; + + @override + String get remoteImageUntilClose => 'До закриття цього документа.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Дозволяє віддалені зображення в $workspace, доки не очистите дозволи робочих просторів у налаштуваннях конфіденційності.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Дозволяє віддалені зображення в усьому BusyMark, доки не вимкнете цю опцію в налаштуваннях конфіденційності.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Дозволяє віддалені зображення в усьому BusyMark. Дозволи робочих просторів налаштовуються окремо.'; + @override String get loadRemoteImagesForWorkspace => - 'Завантажити для цієї робочої області'; + 'Завжди дозволяти в цьому робочому просторі'; @override String get alwaysLoadRemoteImages => @@ -5580,7 +5620,7 @@ class AppLocalizationsUk extends AppLocalizations { String get searchCurrentWorkspace => 'Поточна робоча область'; @override - String get browseNotes => 'Переглянути нотатки'; + String get browseNotes => 'Переглянути нотатки Nextcloud'; @override String get searchActionsCommand => 'Пошук дій'; diff --git a/lib/l10n/generated/app_localizations_vi.dart b/lib/l10n/generated/app_localizations_vi.dart index 7abc276f..61ed95bd 100644 --- a/lib/l10n/generated/app_localizations_vi.dart +++ b/lib/l10n/generated/app_localizations_vi.dart @@ -723,6 +723,9 @@ class AppLocalizationsVi extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => 'Tạo mới'; + @override String get open => 'Mở'; @@ -907,15 +910,22 @@ class AppLocalizationsVi extends AppLocalizations { String get shortcutGroupGeneral => 'Chung'; @override - String get shortcutNewDocument => 'Tạo'; + String get home => 'Trang chủ'; + + @override + String get openMenu => 'Menu Mở'; @override - String get shortcutNewDocumentDescription => - 'Tạo tệp Markdown hoặc dự án Writerside'; + String get newNextcloudNote => 'Ghi chú Nextcloud mới'; @override - String get shortcutOpenDescription => - 'Mở tệp Markdown, thư mục hoặc dự án Writerside'; + String get shortcutNewDocument => 'Menu Tạo mới'; + + @override + String get shortcutNewDocumentDescription => 'Hiển thị menu tạo tài nguyên'; + + @override + String get shortcutOpenDescription => 'Hiển thị menu mở tài nguyên'; @override String get shortcutSaveDescription => 'Lưu tài liệu hiện tại'; @@ -1207,11 +1217,12 @@ class AppLocalizationsVi extends AppLocalizations { 'Cho phép hình ảnh trong phần xem trước và trình biên tập Markdown được tải từ các URL http và https.'; @override - String get clearRemoteImagePermissions => 'Xóa quyền hình ảnh từ xa'; + String get clearRemoteImagePermissions => + 'Xóa quyền tải hình ảnh của không gian làm việc'; @override String get clearRemoteImagePermissionsDescription => - 'Quên các không gian làm việc đã được cho phép tải hình ảnh từ xa.'; + 'Quên mọi quyền tải hình ảnh từ xa của các không gian làm việc.'; @override String get clearGitWorkspaceTrust => @@ -1564,7 +1575,7 @@ class AppLocalizationsVi extends AppLocalizations { @override String get remoteImageBlockedTooltip => - 'Chọn xem BusyMark có thể tải hình ảnh từ xa hay không.'; + 'Hình ảnh từ xa bị chặn. Nhấp để xem tùy chọn tải.'; @override String get remoteImagesBlockedTitle => 'Hình ảnh từ xa bị chặn'; @@ -1574,7 +1585,36 @@ class AppLocalizationsVi extends AppLocalizations { 'Tài liệu này tham chiếu đến hình ảnh trên Internet. Việc tải chúng có thể tiết lộ thông tin mạng cho máy chủ lưu trữ hình ảnh.'; @override - String get loadRemoteImagesForWorkspace => 'Tải cho không gian làm việc này'; + String get loadThisRemoteImage => 'Tải hình ảnh này'; + + @override + String get remoteImageMoreOptions => 'Tùy chọn khác…'; + + @override + String get remoteImageMoreOptionsTitle => 'Quyền tải hình ảnh từ xa'; + + @override + String get loadRemoteImagesInDocument => 'Tải hình ảnh trong tài liệu này'; + + @override + String get remoteImageUntilClose => 'Cho đến khi đóng tài liệu này.'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return 'Cho phép tải hình ảnh từ xa trong $workspace cho đến khi bạn xóa quyền không gian làm việc trong phần Cài đặt quyền riêng tư.'; + } + + @override + String get remoteImageGlobalPermissionDetail => + 'Cho phép tải hình ảnh từ xa trong toàn bộ BusyMark cho đến khi bạn tắt tùy chọn này trong phần Cài đặt quyền riêng tư.'; + + @override + String get remoteImageGlobalSettingsDetail => + 'Cho phép tải hình ảnh từ xa trong toàn bộ BusyMark. Quyền của từng không gian làm việc được quản lý riêng.'; + + @override + String get loadRemoteImagesForWorkspace => + 'Luôn cho phép trong không gian làm việc này'; @override String get alwaysLoadRemoteImages => 'Luôn tải hình ảnh từ xa'; @@ -5502,7 +5542,7 @@ class AppLocalizationsVi extends AppLocalizations { String get searchCurrentWorkspace => 'Không gian làm việc hiện tại'; @override - String get browseNotes => 'Duyệt ghi chú'; + String get browseNotes => 'Duyệt ghi chú Nextcloud'; @override String get searchActionsCommand => 'Tìm thao tác'; diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 3892972d..f0373aaa 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -673,6 +673,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get markdown => 'Markdown'; + @override + String get newResource => '新建'; + @override String get open => '打开'; @@ -855,13 +858,22 @@ class AppLocalizationsZh extends AppLocalizations { String get shortcutGroupGeneral => '常规'; @override - String get shortcutNewDocument => '创建'; + String get home => '主页'; + + @override + String get openMenu => '打开菜单'; @override - String get shortcutNewDocumentDescription => '创建 Markdown 文件或 Writerside 项目'; + String get newNextcloudNote => '新建 Nextcloud 笔记'; @override - String get shortcutOpenDescription => '打开 Markdown 文件、文件夹或 Writerside 项目'; + String get shortcutNewDocument => '新建菜单'; + + @override + String get shortcutNewDocumentDescription => '显示用于新建资源的菜单'; + + @override + String get shortcutOpenDescription => '显示用于打开资源的菜单'; @override String get shortcutSaveDescription => '保存当前文档'; @@ -1129,10 +1141,10 @@ class AppLocalizationsZh extends AppLocalizations { '允许 Markdown 预览和编辑器从 http 和 https URL 加载图像。'; @override - String get clearRemoteImagePermissions => '清除远程图像权限'; + String get clearRemoteImagePermissions => '清除工作区图片权限'; @override - String get clearRemoteImagePermissionsDescription => '忘记已获准加载远程图像的工作区。'; + String get clearRemoteImagePermissionsDescription => '忘记所有工作区的远程图片权限。'; @override String get clearGitWorkspaceTrust => '清除受信任的 Git 工作区'; @@ -1474,7 +1486,7 @@ class AppLocalizationsZh extends AppLocalizations { String get remoteImageBlocked => '远程图像已阻止'; @override - String get remoteImageBlockedTooltip => '选择是否允许 BusyMark 加载远程图像。'; + String get remoteImageBlockedTooltip => '远程图像已阻止。点击查看加载选项。'; @override String get remoteImagesBlockedTitle => '远程图像已阻止'; @@ -1484,7 +1496,35 @@ class AppLocalizationsZh extends AppLocalizations { '本文档引用了来自互联网的图像。加载这些图像可能会向图像托管方泄露网络信息。'; @override - String get loadRemoteImagesForWorkspace => '为此工作区加载'; + String get loadThisRemoteImage => '加载此图片'; + + @override + String get remoteImageMoreOptions => '更多选项…'; + + @override + String get remoteImageMoreOptionsTitle => '远程图片权限'; + + @override + String get loadRemoteImagesInDocument => '加载此文档中的图片'; + + @override + String get remoteImageUntilClose => '在关闭此文档前有效。'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return '允许在 $workspace 中加载远程图片,直至在隐私设置中清除工作区权限。'; + } + + @override + String get remoteImageGlobalPermissionDetail => + '允许在整个 BusyMark 中加载远程图片,直至在隐私设置中关闭此选项。'; + + @override + String get remoteImageGlobalSettingsDetail => + '允许在整个 BusyMark 中加载远程图片。工作区权限单独管理。'; + + @override + String get loadRemoteImagesForWorkspace => '在此工作区中始终允许'; @override String get alwaysLoadRemoteImages => '始终加载远程图像'; @@ -5259,7 +5299,7 @@ class AppLocalizationsZh extends AppLocalizations { String get searchCurrentWorkspace => '当前工作区'; @override - String get browseNotes => '浏览笔记'; + String get browseNotes => '浏览 Nextcloud 笔记'; @override String get searchActionsCommand => '搜索操作'; @@ -9270,6 +9310,9 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get markdown => 'Markdown'; + @override + String get newResource => '新建'; + @override String get open => '打开'; @@ -9452,13 +9495,22 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get shortcutGroupGeneral => '常规'; @override - String get shortcutNewDocument => '创建'; + String get home => '主页'; + + @override + String get openMenu => '打开菜单'; @override - String get shortcutNewDocumentDescription => '创建 Markdown 文件或 Writerside 项目'; + String get newNextcloudNote => '新建 Nextcloud 笔记'; @override - String get shortcutOpenDescription => '打开 Markdown 文件、文件夹或 Writerside 项目'; + String get shortcutNewDocument => '新建菜单'; + + @override + String get shortcutNewDocumentDescription => '显示用于新建资源的菜单'; + + @override + String get shortcutOpenDescription => '显示用于打开资源的菜单'; @override String get shortcutSaveDescription => '保存当前文档'; @@ -9726,10 +9778,10 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { '允许 Markdown 预览和编辑器从 http 和 https URL 加载图像。'; @override - String get clearRemoteImagePermissions => '清除远程图像权限'; + String get clearRemoteImagePermissions => '清除工作区图片权限'; @override - String get clearRemoteImagePermissionsDescription => '忘记已获准加载远程图像的工作区。'; + String get clearRemoteImagePermissionsDescription => '忘记所有工作区的远程图片权限。'; @override String get clearGitWorkspaceTrust => '清除受信任的 Git 工作区'; @@ -10071,7 +10123,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get remoteImageBlocked => '远程图像已阻止'; @override - String get remoteImageBlockedTooltip => '选择是否允许 BusyMark 加载远程图像。'; + String get remoteImageBlockedTooltip => '远程图像已阻止。点击查看加载选项。'; @override String get remoteImagesBlockedTitle => '远程图像已阻止'; @@ -10081,7 +10133,35 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { '本文档引用了来自互联网的图像。加载这些图像可能会向图像托管方泄露网络信息。'; @override - String get loadRemoteImagesForWorkspace => '为此工作区加载'; + String get loadThisRemoteImage => '加载此图片'; + + @override + String get remoteImageMoreOptions => '更多选项…'; + + @override + String get remoteImageMoreOptionsTitle => '远程图片权限'; + + @override + String get loadRemoteImagesInDocument => '加载此文档中的图片'; + + @override + String get remoteImageUntilClose => '在关闭此文档前有效。'; + + @override + String remoteImageWorkspacePermissionDetail(String workspace) { + return '允许在 $workspace 中加载远程图片,直至在隐私设置中清除工作区权限。'; + } + + @override + String get remoteImageGlobalPermissionDetail => + '允许在整个 BusyMark 中加载远程图片,直至在隐私设置中关闭此选项。'; + + @override + String get remoteImageGlobalSettingsDetail => + '允许在整个 BusyMark 中加载远程图片。工作区权限单独管理。'; + + @override + String get loadRemoteImagesForWorkspace => '在此工作区中始终允许'; @override String get alwaysLoadRemoteImages => '始终加载远程图像'; @@ -13856,7 +13936,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get searchCurrentWorkspace => '当前工作区'; @override - String get browseNotes => '浏览笔记'; + String get browseNotes => '浏览 Nextcloud 笔记'; @override String get searchActionsCommand => '搜索操作'; diff --git a/lib/main.dart b/lib/main.dart index 4af70c27..3306ddec 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -12,7 +12,7 @@ import 'src/app/startup_path.dart'; import 'src/app/system_accent.dart'; import 'src/git/application/git_controller.dart'; -import 'src/git/data/git_cli_gateway.dart'; +import 'src/git/data/git_shared_gateway.dart'; import 'src/platform/gtk_animation_settings_service.dart'; import 'src/platform/gtk_window_preferences_service.dart'; import 'src/platform/gtk_header_icon_service.dart'; diff --git a/lib/src/app/app_metadata.dart b/lib/src/app/app_metadata.dart index ade34c77..b271de86 100644 --- a/lib/src/app/app_metadata.dart +++ b/lib/src/app/app_metadata.dart @@ -1 +1 @@ -const busyMarkAppVersion = '0.7.1'; +const busyMarkAppVersion = '0.7.2'; diff --git a/lib/src/app/app_settings.dart b/lib/src/app/app_settings.dart index 712ff2ab..cbcad77d 100644 --- a/lib/src/app/app_settings.dart +++ b/lib/src/app/app_settings.dart @@ -142,6 +142,7 @@ class AppSettings { required this.aiCloudProviderConsentIds, required this.allowRemoteImages, required this.remoteImageAllowedWorkspacePaths, + this.remoteImageAllowedWorkspaceIds = const [], required this.trustedGitWorkspacePaths, this.pdfExportOptions = const PdfExportOptions(), this.htmlExportOptions = const HtmlExportOptions(), @@ -296,6 +297,9 @@ class AppSettings { ), allowRemoteImages: json['allowRemoteImages'] as bool? ?? defaults.allowRemoteImages, + remoteImageAllowedWorkspaceIds: _stringListFromJson( + json['remoteImageAllowedWorkspaceIds'], + ), remoteImageAllowedWorkspacePaths: _workspacePathListFromJson( json['remoteImageAllowedWorkspacePaths'], ), @@ -362,6 +366,7 @@ class AppSettings { final List aiCloudProviderConsentIds; final bool allowRemoteImages; final List remoteImageAllowedWorkspacePaths; + final List remoteImageAllowedWorkspaceIds; final List trustedGitWorkspacePaths; final PdfExportOptions pdfExportOptions; final HtmlExportOptions htmlExportOptions; @@ -411,6 +416,7 @@ class AppSettings { 'aiCloudProviderConsentIds': aiCloudProviderConsentIds, 'allowRemoteImages': allowRemoteImages, 'remoteImageAllowedWorkspacePaths': remoteImageAllowedWorkspacePaths, + 'remoteImageAllowedWorkspaceIds': remoteImageAllowedWorkspaceIds, 'trustedGitWorkspacePaths': trustedGitWorkspacePaths, 'pdfExportOptions': pdfExportOptions.toJson(), 'htmlExportOptions': htmlExportOptions.toJson(), @@ -496,6 +502,7 @@ class AppSettings { List? aiCloudProviderConsentIds, bool? allowRemoteImages, List? remoteImageAllowedWorkspacePaths, + List? remoteImageAllowedWorkspaceIds, List? trustedGitWorkspacePaths, PdfExportOptions? pdfExportOptions, HtmlExportOptions? htmlExportOptions, @@ -553,6 +560,8 @@ class AppSettings { aiCloudProviderConsentIds: aiCloudProviderConsentIds ?? this.aiCloudProviderConsentIds, allowRemoteImages: allowRemoteImages ?? this.allowRemoteImages, + remoteImageAllowedWorkspaceIds: + remoteImageAllowedWorkspaceIds ?? this.remoteImageAllowedWorkspaceIds, remoteImageAllowedWorkspacePaths: remoteImageAllowedWorkspacePaths ?? this.remoteImageAllowedWorkspacePaths, @@ -863,8 +872,8 @@ class AppSettingsController extends Notifier { ); } - Future setSidebarVisible(bool enabled) { - if (state.sidebarVisible != enabled) { + Future setSidebarVisible(bool enabled, {bool animate = true}) { + if (animate && state.sidebarVisible != enabled) { ref.read(sidebarTransitionGenerationProvider.notifier).increment(); } return _mutate((settings) => settings.copyWith(sidebarVisible: enabled)); @@ -999,9 +1008,20 @@ class AppSettingsController extends Notifier { }); } + Future allowRemoteImagesForWorkspaceId(String id) { + return _mutate((settings) { + final allowed = {id, ...settings.remoteImageAllowedWorkspaceIds}.toList() + ..sort(); + return settings.copyWith(remoteImageAllowedWorkspaceIds: allowed); + }); + } + Future clearRemoteImageWorkspacePermissions() { return _mutate( - (settings) => settings.copyWith(remoteImageAllowedWorkspacePaths: []), + (settings) => settings.copyWith( + remoteImageAllowedWorkspacePaths: [], + remoteImageAllowedWorkspaceIds: [], + ), ); } diff --git a/lib/src/app/busymark_app.dart b/lib/src/app/busymark_app.dart index 8cb6de62..d670d660 100644 --- a/lib/src/app/busymark_app.dart +++ b/lib/src/app/busymark_app.dart @@ -1,5 +1,6 @@ +import '../workspace/workspace_resource_actions.dart'; +import 'busymark_resource_menu.dart'; import '../git/application/shared_git_tabs.dart'; -import '../workspace/recent_presentation.dart'; import '../search/welcome_notes_action.dart'; import '../nextcloud_notes/application/nextcloud_connection.dart'; import '../nextcloud_notes/application/notes_navigation.dart'; @@ -11,27 +12,24 @@ import '../core/debug_log.dart'; import '../editor/editor_text_context_menu.dart'; import 'package:busystack_git_flutter/busystack_git_flutter.dart' as shared; -import 'package:file_selector/file_selector.dart'; import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart' show mapEquals; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; -import 'package:path/path.dart' as p; import 'package:ubuntu_localizations/ubuntu_localizations.dart'; import '../../l10n/generated/app_localizations.dart'; import '../export/workspace_export_ui.dart'; import '../clipboard/clipboard_history_controller.dart'; import '../git/application/git_controller.dart'; -import '../platform/linux_header_bar_service.dart'; import '../platform/gtk_animation_settings_service.dart'; import '../platform/gtk_header_icon_service.dart'; import '../local_history/local_history_controller.dart'; import '../workspace/workspace_controller.dart'; import '../workspace/workspace_model.dart'; -import '../workspace/presentation/welcome_screen.dart'; +import '../workspace/workspace_navigation.dart'; import '../workspace/workspace_safety.dart'; import '../workspace/workspace_tabs.dart'; import '../workspace/workspace_tab_actions.dart'; @@ -39,12 +37,9 @@ import 'app_router.dart'; import 'app_locale.dart'; import 'app_settings.dart'; import '../search/search_session.dart'; -import '../search/search_activation.dart'; -import '../workspace/recent_navigation.dart'; import 'command_registry.dart'; import 'command_shortcuts.dart'; import 'keymap_controller.dart'; -import 'path_label.dart'; import 'shortcut_capture.dart'; import 'app_theme.dart'; import 'busymark_dialogs.dart'; @@ -52,7 +47,6 @@ import 'busymark_design.dart'; import 'busymark_search_field.dart'; import 'busymark_glyphs.dart'; import 'busymark_toast.dart'; -import 'localization.dart'; import 'system_accent.dart'; import 'window_control_service.dart'; import 'git_dismissal.dart'; @@ -70,12 +64,9 @@ final _busyMarkDefaultCommandRegistryProvider = BusyMarkCommandIds.browseNotes: const _NotesActionIntent( WelcomeNotesAction.browse, ), - BusyMarkCommandIds.newDocument: const _NewWorkspaceIntent(), - BusyMarkCommandIds.open: const _OpenWorkspaceIntent(), BusyMarkCommandIds.save: const _SaveActiveIntent(), BusyMarkCommandIds.export: const _ExportIntent(), BusyMarkCommandIds.fullScreen: const _ToggleFullScreenIntent(), - BusyMarkCommandIds.back: const _BackIntent(), BusyMarkCommandIds.keyboardShortcuts: const _KeyboardShortcutsIntent(), BusyMarkCommandIds.syntaxReference: const _SyntaxReferenceIntent(), BusyMarkCommandIds.settings: const _SettingsIntent(), @@ -102,6 +93,14 @@ final _busyMarkDefaultCommandRegistryProvider = }; final defaults = BusyMarkCommandCatalog.create( executions: { + for (final id in BusyMarkResourceMenuButton.commandIds) + id: () { + if (!(rootNavigatorKey.currentState?.canPop() ?? false)) { + ref + .read(resourceMenuControllerProvider(id)) + .open(allowPending: false); + } + }, for (final id in [ BusyMarkCommandIds.sidebarViewSelector, BusyMarkCommandIds.contentViewSelector, @@ -118,6 +117,17 @@ final _busyMarkDefaultCommandRegistryProvider = final search = ref.read(searchSessionProvider.notifier); search.openCategory(entry.value); }, + BusyMarkCommandIds.home: () { + unawaited(ref.read(workspaceNavigationProvider).goHome()); + }, + BusyMarkCommandIds.back: () { + final router = ref.read(appRouterProvider); + final uri = router.routeInformationProvider.value.uri; + if (uri.path == settingsRoutePath && + !(rootNavigatorKey.currentState?.canPop() ?? false)) { + router.go(SettingsReturnTarget.fromSettingsUri(uri).location); + } + }, BusyMarkCommandIds.elementProperties: () => ref .read(workspaceControllerProvider.notifier) .toggleElementProperties @@ -133,6 +143,22 @@ final _busyMarkDefaultCommandRegistryProvider = }, }, enabled: { + BusyMarkCommandIds.home: () => + ref + .read(appRouterProvider) + .routeInformationProvider + .value + .uri + .path != + '/', + BusyMarkCommandIds.back: () => + ref + .read(appRouterProvider) + .routeInformationProvider + .value + .uri + .path == + settingsRoutePath, for (final (id, mode) in [ (BusyMarkCommandIds.viewEditor, DocumentViewModePreference.editor), (BusyMarkCommandIds.viewSource, DocumentViewModePreference.source), @@ -158,12 +184,20 @@ final _busyMarkDefaultCommandRegistryProvider = ref.read(searchSessionProvider.notifier).workspaceVisible && ref.read(workspaceControllerProvider).workspace?.isRemote == true, - BusyMarkCommandIds.sidebarViewSelector: () => - ref.read(searchSessionProvider.notifier).workspaceVisible && - ref.read(workspaceControllerProvider).workspace != null, + BusyMarkCommandIds.sidebarViewSelector: () => switch (ref + .read(appRouterProvider) + .routeInformationProvider + .value + .uri + .path) { + '/' || '/workspace' => true, + _ => false, + }, BusyMarkCommandIds.contentViewSelector: () => ref.read(searchSessionProvider.notifier).workspaceVisible && ref.read(workspaceControllerProvider).activeBuffer != null && + ref.read(localHistoryControllerProvider).selectedRevision == + null && ref .read(sharedGitReviewProvider)[ref .read(workspaceControllerProvider) @@ -251,12 +285,6 @@ final busyMarkCommandRegistryProvider = Provider(( class BusyMarkApp extends ConsumerWidget { const BusyMarkApp({super.key}); - XTypeGroup _markdownTypes(BuildContext context) => XTypeGroup( - label: context.l10n.fileTypeMarkdown, - extensions: ['md', 'markdown'], - mimeTypes: ['text/markdown', 'text/x-markdown'], - ); - @override Widget build(BuildContext context, WidgetRef ref) { final router = ref.watch(appRouterProvider); @@ -266,13 +294,6 @@ class BusyMarkApp extends ConsumerWidget { ref.watch(gtkAnimationsEnabledProvider).asData?.value ?? ref.watch(initialGtkAnimationsEnabledProvider) ?? true; - ref.listen(headerBarActionsProvider, (previous, next) { - next.whenData((event) { - if (event.action == HeaderBarAction.fullScreen) { - unawaited(windowControls.toggleFullScreen()); - } - }); - }); final fallbackAccent = ref.watch(initialSystemAccentColorProvider); final accent = ref .watch(systemAccentColorProvider) @@ -315,291 +336,245 @@ class BusyMarkApp extends ConsumerWidget { supportedLocales: AppLocalizations.supportedLocales, builder: (context, child) { final commandRegistry = ref.watch(busyMarkCommandRegistryProvider); - final headerBarDefaults = _nativeHeaderBarDefaults( - context, - settings, - commandRegistry, - fullScreen: windowControls.isFullScreen, - ); - final appContent = HeaderBarConfigurationDefaults( - configuration: headerBarDefaults, - child: _BusyMarkWindowLifecycle( - child: BusyMarkCommandShortcuts( - shortcuts: commandRegistry.shortcutIntents( - excludedIds: searchCommandDestinations.keys.toSet(), - scopes: const { - BusyMarkCommandScope.application, - BusyMarkCommandScope.documentView, - }, - intentFor: BusyMarkCommandIntent.new, - ), - child: Actions( - actions: { - _NotesWorkspaceActionIntent: - CallbackAction<_NotesWorkspaceActionIntent>( - onInvoke: (intent) { - final target = rootNavigatorKey.currentContext; - final workspace = ref - .read(workspaceControllerProvider) - .workspace; - if (target == null || - !ref - .read(searchSessionProvider.notifier) - .workspaceVisible || - workspace?.isRemote != true) { - return null; - } - switch (intent.commandId) { - case BusyMarkCommandIds.syncNotes: - unawaited( - ref - .read(workspaceControllerProvider.notifier) - .refreshNextcloudNotes(), - ); - case BusyMarkCommandIds.exportNotes: - final repository = ref - .read(nextcloudNotesRepositoryProvider) - .value; - if (repository == null) return null; - unawaited( - showNotesExport(target, ref, [ - for (final note in repository.notes) - if (note.accountId == - workspace!.nextcloudAccountId && - !isNotesRecovery(note)) - note.localId, - ]), - ); - case BusyMarkCommandIds.importNotesFolder: - unawaited(showNotesImport(target, ref)); - case BusyMarkCommandIds.importNotesFile: - unawaited( - showNotesImport(target, ref, folder: false), - ); - } + final appContent = _BusyMarkWindowLifecycle( + child: BusyMarkCommandShortcuts( + shortcuts: commandRegistry.shortcutIntents( + excludedIds: searchCommandDestinations.keys.toSet(), + scopes: const { + BusyMarkCommandScope.application, + BusyMarkCommandScope.documentView, + }, + intentFor: BusyMarkCommandIntent.new, + ), + child: Actions( + actions: { + _NotesWorkspaceActionIntent: + CallbackAction<_NotesWorkspaceActionIntent>( + onInvoke: (intent) { + final target = rootNavigatorKey.currentContext; + final workspace = ref + .read(workspaceControllerProvider) + .workspace; + if (target == null || + !ref + .read(searchSessionProvider.notifier) + .workspaceVisible || + workspace?.isRemote != true) { return null; - }, - ), - BusyMarkCommandIntent: CallbackAction( - onInvoke: (intent) { - if (searchCommandDestinations.containsKey( - intent.commandId, - ) && - (rootNavigatorKey.currentState?.canPop() ?? false)) { + } + switch (intent.commandId) { + case BusyMarkCommandIds.syncNotes: + unawaited( + ref + .read(workspaceControllerProvider.notifier) + .refreshNextcloudNotes(), + ); + case BusyMarkCommandIds.exportNotes: + final repository = ref + .read(nextcloudNotesRepositoryProvider) + .value; + if (repository == null) return null; + unawaited( + showNotesExport(target, ref, [ + for (final note in repository.notes) + if (note.accountId == + workspace!.nextcloudAccountId && + !isNotesRecovery(note)) + note.localId, + ]), + ); + case BusyMarkCommandIds.importNotesFolder: + unawaited(showNotesImport(target, ref)); + case BusyMarkCommandIds.importNotesFile: + unawaited( + showNotesImport(target, ref, folder: false), + ); + } return null; - } - unawaited(commandRegistry.execute(intent.commandId)); - return null; - }, - ), - _NotesActionIntent: CallbackAction<_NotesActionIntent>( - onInvoke: (intent) { - final target = rootNavigatorKey.currentContext; - if (target != null) { - unawaited( - performWelcomeNotesAction(target, ref, intent.action), - ); - } - return null; - }, - ), - _NewWorkspaceIntent: CallbackAction<_NewWorkspaceIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - unawaited( - _showNewChooser(navigatorContext, ref, router), - ); - } - return null; - }, - ), - _OpenWorkspaceIntent: CallbackAction<_OpenWorkspaceIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - unawaited( - _showOpenChooser(navigatorContext, ref, router), - ); - } + }, + ), + BusyMarkCommandIntent: CallbackAction( + onInvoke: (intent) { + if (searchCommandDestinations.containsKey( + intent.commandId, + ) && + (rootNavigatorKey.currentState?.canPop() ?? false)) { return null; - }, - ), - _SaveActiveIntent: CallbackAction<_SaveActiveIntent>( - onInvoke: (intent) { - final state = ref.read(workspaceControllerProvider); - final navigatorContext = rootNavigatorKey.currentContext; - if (state.workspace != null && navigatorContext != null) { + } + unawaited(commandRegistry.execute(intent.commandId)); + return null; + }, + ), + _NotesActionIntent: CallbackAction<_NotesActionIntent>( + onInvoke: (intent) { + final target = rootNavigatorKey.currentContext; + if (target != null) { + unawaited( + performWorkspaceResourceAction( + ref, + WorkspaceResourceAction.forNotes(intent.action), + ), + ); + } + return null; + }, + ), + _SaveActiveIntent: CallbackAction<_SaveActiveIntent>( + onInvoke: (intent) { + final state = ref.read(workspaceControllerProvider); + final navigatorContext = rootNavigatorKey.currentContext; + if (state.workspace != null && navigatorContext != null) { + unawaited( + saveActiveWithOverwriteConfirmation( + navigatorContext, + ref, + ), + ); + } + return null; + }, + ), + _ExportIntent: CallbackAction<_ExportIntent>( + onInvoke: (intent) { + final state = ref.read(workspaceControllerProvider); + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null && canExportWorkspace(state)) { + unawaited(exportWorkspace(navigatorContext, ref)); + } + return null; + }, + ), + _ToggleFullScreenIntent: + CallbackAction<_ToggleFullScreenIntent>( + onInvoke: (intent) { + unawaited(windowControls.toggleFullScreen()); + return null; + }, + ), + _KeyboardShortcutsIntent: + CallbackAction<_KeyboardShortcutsIntent>( + onInvoke: (intent) { + final navigatorContext = + rootNavigatorKey.currentContext; + if (navigatorContext != null) { + openKeyboardShortcutsSettings(navigatorContext); + } + return null; + }, + ), + _SettingsIntent: CallbackAction<_SettingsIntent>( + onInvoke: (intent) { + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null) { + GoRouter.of(navigatorContext).go( + settingsLocationForUri( + router.routeInformationProvider.value.uri, + ), + ); + } + return null; + }, + ), + _SyntaxReferenceIntent: CallbackAction<_SyntaxReferenceIntent>( + onInvoke: (intent) { + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null) { + showBusyMarkSyntaxReferenceDialog(navigatorContext); + } + return null; + }, + ), + _OpenClipboardHistoryIntent: + CallbackAction<_OpenClipboardHistoryIntent>( + onInvoke: (intent) { + ref + .read(clipboardHistoryOpenRequestProvider.notifier) + .request(); + return null; + }, + ), + _OpenLocalHistoryIntent: + CallbackAction<_OpenLocalHistoryIntent>( + onInvoke: (intent) { + ref + .read(localHistoryOpenRequestProvider.notifier) + .request(); + return null; + }, + ), + _NextTabIntent: CallbackAction<_NextTabIntent>( + onInvoke: (intent) { + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null) { + unawaited( + _activateOpenFileTab(navigatorContext, ref, next: true), + ); + } + return null; + }, + ), + _PreviousTabIntent: CallbackAction<_PreviousTabIntent>( + onInvoke: (intent) { + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null) { + unawaited( + _activateOpenFileTab( + navigatorContext, + ref, + next: false, + ), + ); + } + return null; + }, + ), + _CloseTabIntent: CallbackAction<_CloseTabIntent>( + onInvoke: (intent) { + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null) { + unawaited(_closeActiveOpenFileTab(navigatorContext, ref)); + } + return null; + }, + ), + _CloseAllTabsIntent: CallbackAction<_CloseAllTabsIntent>( + onInvoke: (intent) { + final navigatorContext = rootNavigatorKey.currentContext; + if (navigatorContext != null) { + unawaited(_closeAllOpenFileTabs(navigatorContext, ref)); + } + return null; + }, + ), + _ToggleSidebarIntent: CallbackAction<_ToggleSidebarIntent>( + onInvoke: (intent) { + _toggleSidebar( + ref, + allowWithoutWorkspace: + router.routeInformationProvider.value.uri.path == '/', + ); + return null; + }, + ), + _DocumentViewModeIntent: + CallbackAction<_DocumentViewModeIntent>( + onInvoke: (intent) { + ref + .read(workspaceControllerProvider.notifier) + .updateActiveEditorMode(intent.mode); unawaited( - saveActiveWithOverwriteConfirmation( - navigatorContext, - ref, - ), - ); - } - return null; - }, - ), - _ExportIntent: CallbackAction<_ExportIntent>( - onInvoke: (intent) { - final state = ref.read(workspaceControllerProvider); - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null && - canExportWorkspace(state)) { - unawaited(exportWorkspace(navigatorContext, ref)); - } - return null; - }, - ), - _ToggleFullScreenIntent: - CallbackAction<_ToggleFullScreenIntent>( - onInvoke: (intent) { - unawaited(windowControls.toggleFullScreen()); - return null; - }, - ), - _BackIntent: CallbackAction<_BackIntent>( - onInvoke: (intent) { - unawaited(_navigateBack(ref, router)); - return null; - }, - ), - _KeyboardShortcutsIntent: - CallbackAction<_KeyboardShortcutsIntent>( - onInvoke: (intent) { - final navigatorContext = - rootNavigatorKey.currentContext; - if (navigatorContext != null) { - openKeyboardShortcutsSettings(navigatorContext); - } - return null; - }, - ), - _SettingsIntent: CallbackAction<_SettingsIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - GoRouter.of(navigatorContext).go( - settingsLocationForUri( - router.routeInformationProvider.value.uri, - ), - ); - } - return null; - }, - ), - _SyntaxReferenceIntent: - CallbackAction<_SyntaxReferenceIntent>( - onInvoke: (intent) { - final navigatorContext = - rootNavigatorKey.currentContext; - if (navigatorContext != null) { - showBusyMarkSyntaxReferenceDialog(navigatorContext); - } - return null; - }, - ), - _OpenClipboardHistoryIntent: - CallbackAction<_OpenClipboardHistoryIntent>( - onInvoke: (intent) { - ref - .read( - clipboardHistoryOpenRequestProvider.notifier, - ) - .request(); - return null; - }, - ), - _OpenLocalHistoryIntent: - CallbackAction<_OpenLocalHistoryIntent>( - onInvoke: (intent) { ref - .read(localHistoryOpenRequestProvider.notifier) - .request(); - return null; - }, - ), - _NextTabIntent: CallbackAction<_NextTabIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - unawaited( - _activateOpenFileTab( - navigatorContext, - ref, - next: true, - ), + .read(appSettingsControllerProvider.notifier) + .setDocumentViewMode(intent.mode), ); - } - return null; - }, - ), - _PreviousTabIntent: CallbackAction<_PreviousTabIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - unawaited( - _activateOpenFileTab( - navigatorContext, - ref, - next: false, - ), - ); - } - return null; - }, - ), - _CloseTabIntent: CallbackAction<_CloseTabIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - unawaited( - _closeActiveOpenFileTab(navigatorContext, ref), - ); - } - return null; - }, - ), - _CloseAllTabsIntent: CallbackAction<_CloseAllTabsIntent>( - onInvoke: (intent) { - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext != null) { - unawaited(_closeAllOpenFileTabs(navigatorContext, ref)); - } - return null; - }, - ), - _ToggleSidebarIntent: CallbackAction<_ToggleSidebarIntent>( - onInvoke: (intent) { - _toggleSidebar( - ref, - allowWithoutWorkspace: - router.routeInformationProvider.value.uri.path == - '/', - ); - return null; - }, - ), - _DocumentViewModeIntent: - CallbackAction<_DocumentViewModeIntent>( - onInvoke: (intent) { - ref - .read(workspaceControllerProvider.notifier) - .updateActiveEditorMode(intent.mode); - unawaited( - ref - .read(appSettingsControllerProvider.notifier) - .setDocumentViewMode(intent.mode), - ); - return null; - }, - ), - }, - child: _BusyMarkSearchShortcutHandler( - child: ColoredBox( - color: BusyMarkSurfaceColors.of(context).window, - child: child ?? const SizedBox.shrink(), - ), + return null; + }, + ), + }, + child: _BusyMarkSearchShortcutHandler( + child: ColoredBox( + color: BusyMarkSurfaceColors.of(context).window, + child: child ?? const SizedBox.shrink(), ), ), ), @@ -626,265 +601,6 @@ class BusyMarkApp extends ConsumerWidget { ); } - Future _navigateBack(WidgetRef ref, GoRouter router) async { - final uri = router.routeInformationProvider.value.uri; - if (uri.path == settingsRoutePath) { - router.go(SettingsReturnTarget.fromSettingsUri(uri).location); - return; - } - if (uri.path != '/workspace') { - return; - } - final navigatorContext = rootNavigatorKey.currentContext; - if (navigatorContext == null || - !await confirmSafeToContinue(navigatorContext, ref) || - !navigatorContext.mounted) { - return; - } - router.go('/'); - } - - Future _showOpenChooser( - BuildContext context, - WidgetRef ref, - GoRouter router, - ) async { - final headerBar = ref.read(linuxHeaderBarServiceProvider); - final recentWorkspaces = ref - .read(appSettingsControllerProvider) - .recentWorkspaces; - final container = ProviderScope.containerOf(context, listen: false); - final cachedAccounts = container.exists(nextcloudNotesRepositoryProvider) - ? ref.read(nextcloudNotesRepositoryProvider).value?.accounts - : null; - final connectedAccount = container.exists(nextcloudConnectionProvider) - ? ref.read(nextcloudConnectionProvider).account - : null; - final accountLabels = { - for (final account in cachedAccounts ?? []) - account.id: '${account.loginName} · ${account.server.host}', - if (connectedAccount != null) - connectedAccount.id: - '${connectedAccount.loginName} · ${connectedAccount.server.host}', - }; - final choice = await showBusyMarkModalDialog<_OpenChooserChoice>( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (dialogContext) => BusyMarkDialogShell( - title: context.l10n.open, - maxWidth: BusyMarkSizes.dialog, - children: [ - BusyMarkGroupedList( - filled: true, - children: [ - BusyMarkActionRow( - title: context.l10n.openMarkdownFile, - subtitle: context.l10n.markdownFileExtensions, - leading: const Icon(BusyMarkGlyphs.markdownFile), - trailing: Icon( - BusyMarkGlyphs.forwardFor(Directionality.of(dialogContext)), - ), - onTap: () => - Navigator.pop(dialogContext, const _OpenMarkdownFile()), - ), - BusyMarkActionRow( - title: context.l10n.openFolderOrWritersideProject, - subtitle: context.l10n.markdownFolderOrWritersideProject, - leading: const Icon(BusyMarkGlyphs.folder), - trailing: Icon( - BusyMarkGlyphs.forwardFor(Directionality.of(dialogContext)), - ), - onTap: () => - Navigator.pop(dialogContext, const _OpenWorkspaceFolder()), - ), - ], - ), - if (recentWorkspaces.isNotEmpty) - BusyMarkGroupedList( - title: context.l10n.recent, - filled: true, - children: [ - for (final recent in recentWorkspaces) - BusyMarkActionRow( - title: busyMarkLtrIsolateFor( - dialogContext, - recentResourceTitle(dialogContext, recent), - ), - tooltip: recent.accountId == null - ? recent.path - : accountLabels[recent.accountId], - subtitleWidget: recent.accountId == null - ? BusyMarkPathLabel( - path: recentResourceLocation( - dialogContext, - recent, - recentResources: recentWorkspaces, - ), - style: Theme.of(dialogContext).textTheme.bodySmall, - ) - : Text( - recentResourceLocation( - dialogContext, - recent, - accountLabel: accountLabels[recent.accountId], - ), - ), - leading: const Icon(BusyMarkGlyphs.history), - trailing: Icon( - BusyMarkGlyphs.forwardFor( - Directionality.of(dialogContext), - ), - ), - onTap: () => Navigator.pop( - dialogContext, - _OpenRecentResource(recent), - ), - ), - ], - ), - ], - ), - ); - if (!context.mounted || choice == null) { - return; - } - if (choice case _OpenRecentResource(:final resource)) { - await openRecentResource(context, ref, resource); - return; - } - final path = switch (choice) { - _OpenMarkdownFile() => await _chooseMarkdownFile(ref), - _OpenWorkspaceFolder() => await _chooseWorkspaceFolder(ref), - _OpenRecentResource() => null, - }; - if (path == null || path.isEmpty || !context.mounted) { - return; - } - if (!await confirmSafeToContinue(context, ref) || !context.mounted) { - return; - } - await ref.read(workspaceControllerProvider.notifier).openPath(path); - if (context.mounted && - ref.read(workspaceControllerProvider).workspace != null) { - router.go('/workspace'); - } - } - - Future _showNewChooser( - BuildContext context, - WidgetRef ref, - GoRouter router, - ) async { - final startsWorkspace = - settingsReturnTargetForUri(router.routeInformationProvider.value.uri) == - SettingsReturnTarget.welcome; - final headerBar = ref.read(linuxHeaderBarServiceProvider); - final choice = await showBusyMarkModalDialog<_NewChooserChoice>( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (dialogContext) => BusyMarkDialogShell( - title: context.l10n.create, - maxWidth: BusyMarkSizes.dialog, - children: [ - BusyMarkGroupedList( - filled: true, - children: [ - BusyMarkActionRow( - title: context.l10n.createMarkdownFile, - subtitle: context.l10n.createMarkdownFileDescription, - leading: const Icon(BusyMarkGlyphs.newDocument), - trailing: Icon( - BusyMarkGlyphs.forwardFor(Directionality.of(dialogContext)), - ), - onTap: () => - Navigator.pop(dialogContext, const _CreateMarkdownFile()), - ), - BusyMarkActionRow( - title: context.l10n.createWritersideProject, - subtitle: context.l10n.createWritersideProjectDescription, - leading: const Icon(BusyMarkGlyphs.writersideProject), - trailing: Icon( - BusyMarkGlyphs.forwardFor(Directionality.of(dialogContext)), - ), - onTap: () => Navigator.pop( - dialogContext, - const _CreateWritersideProject(), - ), - ), - ], - ), - ], - ), - ); - if (choice == null || !context.mounted) { - return; - } - switch (choice) { - case _CreateMarkdownFile(): - final controller = ref.read(workspaceControllerProvider.notifier); - if (startsWorkspace) { - if (!await confirmSafeToContinue(context, ref) || !context.mounted) { - return; - } - if (!await controller.createMarkdownWorkspace()) return; - } else { - await controller.createMarkdownFile(); - } - if (context.mounted) { - router.go('/workspace'); - } - case _CreateWritersideProject(): - if (!await confirmSafeToContinue(context, ref) || !context.mounted) { - return; - } - await _createWritersideProject(context, ref, router); - } - } - - Future _createWritersideProject( - BuildContext context, - WidgetRef ref, - GoRouter router, - ) async { - final parentPath = await getDirectoryPath( - initialDirectory: _initialDirectory(ref), - confirmButtonText: context.l10n.chooseLocation, - canCreateDirectories: true, - ); - if (parentPath == null || !context.mounted) { - return; - } - final headerBar = ref.read(linuxHeaderBarServiceProvider); - final created = await showBusyMarkModalEditorDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - maxWidth: BusyMarkSizes.dialogWide, - builder: (context) => BusyMarkCreateWritersideProjectDialog( - parentDirectoryPath: parentPath, - onCreate: (request) => ref - .read(workspaceControllerProvider.notifier) - .createWritersideProject(request), - message: () => ref.read(workspaceControllerProvider).message, - ), - ); - if (created == true && context.mounted) { - router.go('/workspace'); - } - } - - Future _chooseMarkdownFile(WidgetRef ref) async { - final context = rootNavigatorKey.currentContext; - if (context == null) { - return null; - } - final selected = await openFile( - acceptedTypeGroups: [_markdownTypes(context)], - initialDirectory: _initialDirectory(ref), - confirmButtonText: context.l10n.open, - ); - return selected?.path; - } - Future _activateOpenFileTab( BuildContext context, WidgetRef ref, { @@ -896,7 +612,6 @@ class BusyMarkApp extends ConsumerWidget { return; } final tabs = workspaceTabEntries( - workspace: workspace, gitTabs: ref.read(sharedGitReviewProvider)[workspace.id] ?? const SharedGitTabs(), @@ -931,7 +646,6 @@ class BusyMarkApp extends ConsumerWidget { return; } final tabs = workspaceTabEntries( - workspace: workspace, gitTabs: ref.read(sharedGitReviewProvider)[workspace.id] ?? const SharedGitTabs(), @@ -966,7 +680,6 @@ class BusyMarkApp extends ConsumerWidget { WidgetRef ref, WorkspaceTabEntry tab, ) async { - final gitController = ref.read(gitControllerProvider.notifier); switch (tab.kind) { case WorkspaceTabKind.file: ref @@ -976,7 +689,6 @@ class BusyMarkApp extends ConsumerWidget { await ref .read(workspaceControllerProvider.notifier) .activateDocumentBuffer(tab.bufferId!); - gitController.deactivateDiffFile(); case WorkspaceTabKind.gitDiff: ref .read(sharedGitReviewProvider.notifier) @@ -988,30 +700,9 @@ class BusyMarkApp extends ConsumerWidget { ref .read(sharedGitReviewProvider.notifier) .deactivate(ref.read(workspaceControllerProvider).workspace!.id); - gitController.deactivateDiffFile(); } } - Future _chooseWorkspaceFolder(WidgetRef ref) async { - final context = rootNavigatorKey.currentContext; - if (context == null) { - return null; - } - return getDirectoryPath( - initialDirectory: _initialDirectory(ref), - confirmButtonText: context.l10n.open, - canCreateDirectories: false, - ); - } - - String? _initialDirectory(WidgetRef ref) { - final lastPath = ref.read(appSettingsControllerProvider).lastOpenedPath; - if (lastPath == null || lastPath.isEmpty) { - return null; - } - return p.extension(lastPath).isEmpty ? lastPath : p.dirname(lastPath); - } - void _toggleSidebar(WidgetRef ref, {required bool allowWithoutWorkspace}) { final workspace = ref.read(workspaceControllerProvider).workspace; if (workspace == null && !allowWithoutWorkspace) { @@ -1038,82 +729,6 @@ class BusyMarkApp extends ConsumerWidget { WorkspaceKind.writersideModule => true, }; } - - HeaderBarConfiguration _nativeHeaderBarDefaults( - BuildContext context, - AppSettings settings, - BusyMarkCommandRegistry commandRegistry, { - required bool fullScreen, - }) { - final material = MaterialLocalizations.of(context); - final l10n = context.l10n; - final theme = HeaderBarTheme.fromContext(context); - final textDirection = Directionality.maybeOf(context) ?? TextDirection.ltr; - BusyMarkCommand command(String id) => commandRegistry[id]!; - String label(String id) => command(id).label(context); - String shortcut(String id) => command(id).shortcut?.label ?? ''; - String accelerator(String id) => command(id).shortcut?.gtkAccelerator ?? ''; - final labels = HeaderBarLabels( - editor: label(BusyMarkCommandIds.viewEditor), - source: label(BusyMarkCommandIds.viewSource), - preview: label(BusyMarkCommandIds.viewReading), - split: label(BusyMarkCommandIds.viewSplit), - viewMode: l10n.viewMode, - editorShortcut: shortcut(BusyMarkCommandIds.viewEditor), - editorGtkAccelerator: accelerator(BusyMarkCommandIds.viewEditor), - sourceShortcut: shortcut(BusyMarkCommandIds.viewSource), - sourceGtkAccelerator: accelerator(BusyMarkCommandIds.viewSource), - previewShortcut: shortcut(BusyMarkCommandIds.viewReading), - previewGtkAccelerator: accelerator(BusyMarkCommandIds.viewReading), - splitShortcut: shortcut(BusyMarkCommandIds.viewSplit), - splitGtkAccelerator: accelerator(BusyMarkCommandIds.viewSplit), - search: material.searchFieldLabel, - searchShortcut: '', - refresh: l10n.validate, - menu: l10n.mainMenu, - sidebar: settings.sidebarVisible ? l10n.hideSidebar : l10n.showSidebar, - sidebarShortcut: shortcut(BusyMarkCommandIds.toggleSidebar), - back: material.backButtonTooltip, - backShortcut: shortcut(BusyMarkCommandIds.back), - save: label(BusyMarkCommandIds.save), - export: label(BusyMarkCommandIds.export), - exportShortcut: shortcut(BusyMarkCommandIds.export), - exportGtkAccelerator: accelerator(BusyMarkCommandIds.export), - fullScreen: label(BusyMarkCommandIds.fullScreen), - fullScreenShortcut: shortcut(BusyMarkCommandIds.fullScreen), - fullScreenGtkAccelerator: accelerator(BusyMarkCommandIds.fullScreen), - settings: label(BusyMarkCommandIds.settings), - settingsShortcut: shortcut(BusyMarkCommandIds.settings), - settingsGtkAccelerator: accelerator(BusyMarkCommandIds.settings), - syntaxReference: label(BusyMarkCommandIds.syntaxReference), - syntaxReferenceShortcut: shortcut(BusyMarkCommandIds.syntaxReference), - syntaxReferenceGtkAccelerator: accelerator( - BusyMarkCommandIds.syntaxReference, - ), - reportIssue: l10n.reportIssue, - aboutBusyMark: l10n.aboutBusyMark, - ); - return HeaderBarConfiguration( - title: l10n.appTitle, - viewMode: AppViewMode.editor, - searchQuery: '', - textDirection: textDirection, - canRefresh: false, - canExportPdf: false, - canExportHtml: false, - documentControlsVisible: false, - searchActive: false, - searchVisible: false, - sidebarVisible: false, - sidebarToggleVisible: false, - backVisible: false, - fullScreen: fullScreen, - modalBarrierDepth: 0, - sidebarWidth: BusyMarkSizes.sidebarWidth, - labels: labels, - theme: theme, - ); - } } class _BusyMarkWindowLifecycle extends ConsumerStatefulWidget { @@ -1277,11 +892,9 @@ class _BusyMarkWindowLifecycleState Future _showWindowCloseDialog(BuildContext context) { final l10n = AppLocalizations.of(context); - final headerBar = ref.read(linuxHeaderBarServiceProvider); final dirtyBuffers = ref.read(workspaceControllerProvider).dirtyBuffers; return showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: l10n.closeUnsavedChangesTitle, maxWidth: BusyMarkSizes.dialog, @@ -1346,7 +959,6 @@ class _BusyMarkSearchShortcutHandler extends ConsumerStatefulWidget { class _BusyMarkSearchShortcutHandlerState extends ConsumerState<_BusyMarkSearchShortcutHandler> { - final _editorContextKeys = BusyMarkContextMenuKeys(); BusyMarkMenuSession? _editorContextMenuSession; @override void initState() { @@ -1356,7 +968,6 @@ class _BusyMarkSearchShortcutHandlerState @override void dispose() { - _editorContextKeys.clear(); unawaited(_editorContextMenuSession?.dismiss()); HardwareKeyboard.instance.removeHandler(_handleKeyEvent); super.dispose(); @@ -1367,10 +978,9 @@ class _BusyMarkSearchShortcutHandlerState ?.findAncestorStateOfType(); if (BusyMarkShortcutCapture.suppressing || editable?.textEditingValue.composing.isValid == true) { - _editorContextKeys.clear(); return KeyEventResult.ignored; } - return _editorContextKeys.handle( + return handleBusyMarkContextMenuKey( event, editable == null ? null @@ -1463,30 +1073,6 @@ class _BusyMarkSearchShortcutHandlerState @override Widget build(BuildContext context) { - ref.listen( - headerBarSearchEventsProvider, - (_, next) => next.whenData((event) { - final controller = ref.read(searchSessionProvider.notifier); - if (!ref.read(searchSessionProvider).active && - (event is HeaderBarSearchQueryChanged || - event is HeaderBarSearchSubmitted)) { - controller.open(); - } - switch (event) { - case HeaderBarSearchQueryChanged(:final query): - controller.query(query); - case HeaderBarSearchSubmitted(:final query): - controller.query(query); - unawaited(activateSelectedSearchResult(context, ref)); - case HeaderBarSearchCleared(): - controller.query(''); - case HeaderBarSearchEscapePressed(): - controller.close(); - case HeaderBarSearchFocusChanged(): - break; - } - }), - ); return Focus( canRequestFocus: false, skipTraversal: true, @@ -1497,44 +1083,6 @@ class _BusyMarkSearchShortcutHandlerState } } -class _NewWorkspaceIntent extends Intent { - const _NewWorkspaceIntent(); -} - -class _OpenWorkspaceIntent extends Intent { - const _OpenWorkspaceIntent(); -} - -sealed class _OpenChooserChoice { - const _OpenChooserChoice(); -} - -final class _OpenMarkdownFile extends _OpenChooserChoice { - const _OpenMarkdownFile(); -} - -final class _OpenWorkspaceFolder extends _OpenChooserChoice { - const _OpenWorkspaceFolder(); -} - -final class _OpenRecentResource extends _OpenChooserChoice { - const _OpenRecentResource(this.resource); - - final RecentResource resource; -} - -sealed class _NewChooserChoice { - const _NewChooserChoice(); -} - -final class _CreateMarkdownFile extends _NewChooserChoice { - const _CreateMarkdownFile(); -} - -final class _CreateWritersideProject extends _NewChooserChoice { - const _CreateWritersideProject(); -} - class _SaveActiveIntent extends Intent { const _SaveActiveIntent(); } @@ -1547,10 +1095,6 @@ class _ToggleFullScreenIntent extends Intent { const _ToggleFullScreenIntent(); } -class _BackIntent extends Intent { - const _BackIntent(); -} - class _KeyboardShortcutsIntent extends Intent { const _KeyboardShortcutsIntent(); } diff --git a/lib/src/app/busymark_deferred_editor_focus.dart b/lib/src/app/busymark_deferred_editor_focus.dart new file mode 100644 index 00000000..23f0e243 --- /dev/null +++ b/lib/src/app/busymark_deferred_editor_focus.dart @@ -0,0 +1,60 @@ +import 'package:flutter/widgets.dart'; + +/// Permission from a creation action to claim the newly mounted input field. +final class BusyMarkDeferredEditorFocus with WidgetsBindingObserver { + BusyMarkDeferredEditorFocus() { + FocusManager.instance.applyFocusChangesIfNeeded(); + _initialFocus = FocusManager.instance.primaryFocus; + _openingGeneration = _modalGeneration; + if (_resumed) { + _pending = true; + FocusManager.instance.addListener(_focusChanged); + WidgetsBinding.instance.addObserver(this); + } + } + + static int _modalGeneration = 0; + + static void modalOpened() => _modalGeneration++; + late final int _openingGeneration; + late final FocusNode? _initialFocus; + bool _pending = false; + + bool get isPending => _pending && _openingGeneration == _modalGeneration; + + bool get _resumed => + WidgetsBinding.instance.lifecycleState == null || + WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed; + + void _focusChanged() { + final current = FocusManager.instance.primaryFocus; + if (current != null && + current != _initialFocus && + current is! FocusScopeNode) { + cancel(); + } + } + + bool consume(BuildContext context) { + FocusManager.instance.applyFocusChangesIfNeeded(); + final allowed = + _pending && + _resumed && + _openingGeneration == _modalGeneration && + ModalRoute.of(context)?.isCurrent != false; + cancel(); + return allowed; + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state != AppLifecycleState.resumed) cancel(); + } + + void cancel() { + if (!_pending) return; + _pending = false; + FocusManager.instance.removeListener(_focusChanged); + WidgetsBinding.instance.removeObserver(this); + } +} diff --git a/lib/src/app/busymark_design.dart b/lib/src/app/busymark_design.dart index c7d32638..5b5efc5d 100644 --- a/lib/src/app/busymark_design.dart +++ b/lib/src/app/busymark_design.dart @@ -1091,6 +1091,7 @@ class BusyMarkHeaderIconButton extends StatelessWidget { this.disabledForegroundColor, this.backgroundColor, this.overlayColor, + this.applyHeaderStateColors = false, this.borderRadius = BusyMarkRadius.headerButton, this.focusBorderRadius = BusyMarkRadius.headerButton, }); @@ -1112,6 +1113,7 @@ class BusyMarkHeaderIconButton extends StatelessWidget { final Color? disabledForegroundColor; final WidgetStateProperty? backgroundColor; final WidgetStateProperty? overlayColor; + final bool applyHeaderStateColors; final double borderRadius; final double focusBorderRadius; @@ -1169,21 +1171,32 @@ class BusyMarkHeaderIconButton extends StatelessWidget { ); final foreground = style.foregroundColor?.resolve(states) ?? colors.foreground; - final button = YaruIconButton( - focusNode: focusNode, - isSelected: selected, - tooltip: shortcut == null ? tooltip : '$tooltip ($shortcut)', - icon: BusyMarkGtkHeaderIcon( - icon, - nativeIcon: nativeIcon, - color: foreground, - ), - iconSize: BusyMarkSizes.iconButton, - padding: EdgeInsets.zero, - style: style, - hasFocusBorder: false, - onPressed: onPressed, + final label = shortcut == null ? tooltip : '$tooltip ($shortcut)'; + final artwork = BusyMarkGtkHeaderIcon( + icon, + nativeIcon: nativeIcon, + color: foreground, ); + final button = applyHeaderStateColors + ? _BusyMarkHeaderStateButton( + focusNode: focusNode, + isSelected: selected, + tooltip: label, + icon: artwork, + style: style, + onPressed: onPressed, + ) + : YaruIconButton( + focusNode: focusNode, + isSelected: selected, + tooltip: label, + icon: artwork, + iconSize: BusyMarkSizes.iconButton, + padding: EdgeInsets.zero, + style: style, + hasFocusBorder: false, + onPressed: onPressed, + ); final painted = PhysicalShape( clipper: ShapeBorderClipper(shape: shape), color: @@ -1204,14 +1217,32 @@ class BusyMarkHeaderIconButton extends StatelessWidget { // The Linux accessibility bridge exposes the semantic label as the // control's name; IconButton's tooltip alone is not a native name. return MergeSemantics( - child: Semantics( - label: shortcut == null ? tooltip : '$tooltip ($shortcut)', - child: content, - ), + child: Semantics(label: label, child: content), ); } } +class _BusyMarkHeaderStateButton extends YaruIconButton { + const _BusyMarkHeaderStateButton({ + required super.focusNode, + required super.isSelected, + required super.tooltip, + required super.icon, + required super.style, + required super.onPressed, + }) : super( + iconSize: BusyMarkSizes.iconButton, + padding: EdgeInsets.zero, + hasFocusBorder: false, + ); + + @override + // Yaru merges its default style first. Give the native header layers + // precedence while retaining Yaru's size and input behavior. + ButtonStyle defaultStyleOf(BuildContext context) => + style!.merge(super.defaultStyleOf(context)); +} + /// A compact icon action that keeps Yaru's interaction and focus behavior. /// /// Compact controls are appropriate inside dense editor affordances, where a @@ -1273,93 +1304,34 @@ class BusyMarkCompactIconButton extends StatelessWidget { } } -/// Opens an existing header menu after Flutter has observed the trigger's key -/// releases. GTK grabs input while a native menu is open. +/// Opens a header menu as soon as its trigger has been laid out. class BusyMarkHeaderMenuController { BusyMarkHeaderMenuController({this.debugLabel}); + final String? debugLabel; VoidCallback? _show; bool _pending = false; - bool _listening = false; - final _awaitingKeys = {}; - - void open({Iterable shortcuts = const []}) { - final keyboard = HardwareKeyboard.instance; - final triggerKeys = { - for (final shortcut in shortcuts) ...?shortcut.triggers, - for (final shortcut in shortcuts.whereType()) ...{ - if (shortcut.control) ...{ - LogicalKeyboardKey.controlLeft, - LogicalKeyboardKey.controlRight, - }, - if (shortcut.shift) ...{ - LogicalKeyboardKey.shiftLeft, - LogicalKeyboardKey.shiftRight, - }, - if (shortcut.alt) ...{ - LogicalKeyboardKey.altLeft, - LogicalKeyboardKey.altRight, - }, - if (shortcut.meta) ...{ - LogicalKeyboardKey.metaLeft, - LogicalKeyboardKey.metaRight, - }, - }, - }; - // Wait for the configured trigger and its concrete modifiers, rather than - // unrelated keys. In the live Linux keyboard state Num Lock can remain in - // physicalKeysPressed while its lock is enabled, indefinitely blocking an - // all-keys-up barrier. Keep actual lock-key bindings working as well. - _awaitingKeys - ..clear() - ..addAll( - keyboard.physicalKeysPressed.where( - (key) => triggerKeys.contains(keyboard.lookUpLayout(key)), - ), - ); + + void open({bool allowPending = true}) { + if (!allowPending && _show == null) return; if (debugLabel != null) { busyMarkViewSelectorTrace('controller-open', { 'command': debugLabel, 'attached': _show != null, - 'pressedKeys': keyboard.physicalKeysPressed.length, - 'awaitingKeys': _awaitingKeys.map((key) => key.debugName).toList(), }); } _pending = true; _tryOpen(); } - bool _released(KeyEvent event) { - _tryOpen(); - return false; - } - void _tryOpen() { if (!_pending || _show == null) return; - if (_awaitingKeys.any( - HardwareKeyboard.instance.physicalKeysPressed.contains, - )) { - if (!_listening) { - HardwareKeyboard.instance.addHandler(_released); - _listening = true; - } - return; - } - _stopListening(); _pending = false; - // Let the release finish propagating before the host toolkit grabs input. - scheduleMicrotask(() => _show?.call()); - } - - void _stopListening() { - if (_listening) HardwareKeyboard.instance.removeHandler(_released); - _listening = false; + _show!(); } void dispose() { - _stopListening(); _pending = false; - _awaitingKeys.clear(); _show = null; } } @@ -1453,14 +1425,20 @@ class _BusyMarkHeaderPopupMenuButtonState void didUpdateWidget(covariant BusyMarkHeaderPopupMenuButton oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.controller != widget.controller) { - oldWidget.controller?._show = null; + _detachController(oldWidget.controller); _attachController(); } } + void _detachController(BusyMarkHeaderMenuController? controller) { + if (controller != null && controller._show == _openFromKeyboard) { + controller._show = null; + } + } + @override void dispose() { - widget.controller?._show = null; + _detachController(widget.controller); final session = _activeMenuSession; _activeMenuSession = null; if (session != null) { @@ -1501,7 +1479,7 @@ class _BusyMarkHeaderPopupMenuButtonState final onSelected = widget.onSelected; final onCanceled = widget.onCanceled; final previousFocus = FocusManager.instance.primaryFocus; - final restoreSelectorFocus = widget.controller != null; + var restoreFocus = widget.controller != null; final owningRoute = ModalRoute.of(context); try { final items = await widget.itemBuilder(context); @@ -1542,8 +1520,10 @@ class _BusyMarkHeaderPopupMenuButtonState }); } } + restoreFocus = restoreFocus && !session.dismissed; if (mounted && !session.dismissed) { if (selection != null) { + restoreFocus = false; onSelected(selection); } else { onCanceled?.call(context); @@ -1557,7 +1537,8 @@ class _BusyMarkHeaderPopupMenuButtonState ); } } finally { - if (restoreSelectorFocus && + if (restoreFocus && + mounted && (owningRoute?.isCurrent ?? true) && previousFocus?.context?.mounted == true) { previousFocus!.requestFocus(); @@ -1964,7 +1945,7 @@ Future showBusyMarkContextMenu( ); } -/// Sidebar entry menus use the existing GTK service without a Flutter route. +/// Context menus use the existing GTK service without a Flutter route. /// Metadata entries never render; the service owns positioning and dismissal. Future showBusyMarkNativeContextMenu( BuildContext context, @@ -1977,7 +1958,7 @@ Future showBusyMarkNativeContextMenu( final snapshot = List>.unmodifiable(items); final entries = _busyMarkNativeMenuEntries(snapshot); if (entries == null) { - throw StateError('Sidebar menus require supported native menu entries.'); + throw StateError('Context menus require supported native menu entries.'); } final previousFocus = FocusManager.instance.primaryFocus; final owner = session ?? NativeMenuSession(); @@ -2542,6 +2523,12 @@ bool isBusyMarkContextMenuKeyEvent(KeyEvent event) { keyboard.isShiftPressed); } +bool handleBusyMarkContextMenuKey(KeyEvent event, VoidCallback? open) { + if (open == null || !isBusyMarkContextMenuKeyEvent(event)) return false; + open(); + return true; +} + class BusyMarkPopupSelectorOption { const BusyMarkPopupSelectorOption({ required this.value, @@ -3295,7 +3282,6 @@ class _BusyMarkSidebarRecordRowState late final FocusNode _rowFocusNode; var _contextMenuOpen = false; DateTime? _lastTapAt; - final _menuKeys = BusyMarkContextMenuKeys(); NativeMenuSession? _menuSession; bool get _hasMenu => @@ -3310,7 +3296,6 @@ class _BusyMarkSidebarRecordRowState @override void dispose() { - _menuKeys.clear(); if (_menuSession case final session?) { unawaited(const NativeMenuService().dismiss(session)); } @@ -3319,7 +3304,7 @@ class _BusyMarkSidebarRecordRowState } KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) { - return _menuKeys.handle( + return handleBusyMarkContextMenuKey( event, _hasMenu ? () => unawaited(_showContextMenu()) : null, ) @@ -3421,10 +3406,7 @@ class _BusyMarkSidebarRecordRowState clickable: enabled, selected: widget.selected || _contextMenuOpen, onKeyEvent: _handleKeyEvent, - onFocusChange: (focused) { - if (!focused) _menuKeys.clear(); - widget.onFocusChange?.call(focused); - }, + onFocusChange: widget.onFocusChange, onTap: widget.onTap == null ? null : _handleTap, onSecondaryTapUp: !_hasMenu ? null @@ -5280,14 +5262,6 @@ class BusyMarkSidebarTreeRow extends StatefulWidget { } class BusyMarkSidebarTreeRowState extends State { - final _menuKeys = BusyMarkContextMenuKeys(); - - @override - void dispose() { - _menuKeys.clear(); - super.dispose(); - } - void showMenuFromKeyboard() { final onMenuRequested = widget.onMenuRequested; if (!widget.enabled || onMenuRequested == null) { @@ -5328,7 +5302,7 @@ class BusyMarkSidebarTreeRowState extends State { return KeyEventResult.handled; } } - return _menuKeys.handle( + return handleBusyMarkContextMenuKey( event, widget.enabled && widget.onMenuRequested != null ? showMenuFromKeyboard @@ -5380,10 +5354,7 @@ class BusyMarkSidebarTreeRowState extends State { ? null : (details) => widget.onMenuRequested!(context, details.globalPosition)), - onFocusChange: (focused) { - if (!focused) _menuKeys.clear(); - widget.onFocusChange?.call(focused); - }, + onFocusChange: widget.onFocusChange, child: Row( children: [ SizedBox( diff --git a/lib/src/app/busymark_dialogs.dart b/lib/src/app/busymark_dialogs.dart index 99188cd9..e3690c6f 100644 --- a/lib/src/app/busymark_dialogs.dart +++ b/lib/src/app/busymark_dialogs.dart @@ -3,14 +3,13 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:url_launcher/url_launcher.dart'; import '../../l10n/generated/app_localizations.dart'; -import '../platform/linux_header_bar_service.dart'; import 'app_metadata.dart'; import 'busymark_dialog_identity.dart'; +import 'busymark_deferred_editor_focus.dart'; import 'busymark_design.dart'; import 'busymark_glyphs.dart'; import 'localization.dart'; @@ -171,10 +170,6 @@ class _BusyMarkModalShortcutBoundaryState } } -final _busyMarkModalDepths = Map.identity(); -final _busyMarkModalBarrierUpdateTails = - Map>.identity(); - Color busyMarkModalBarrierColor(BuildContext context) { return BusyMarkSurfaceColors.of(context).shade; } @@ -182,44 +177,22 @@ Color busyMarkModalBarrierColor(BuildContext context) { Future showBusyMarkModalDialog( BuildContext context, { required WidgetBuilder builder, - LinuxHeaderBarService? headerBarService, Color? barrierColor, bool barrierDismissible = true, }) async { - final effectiveHeaderBarService = - headerBarService ?? _busyMarkHeaderBarServiceFrom(context); - return _coordinateBusyMarkModal( + final previousFocus = FocusManager.instance.primaryFocus; + if (!context.mounted) return null; + final surface = _showBusyMarkFlutterDialog( context, - headerBarService: effectiveHeaderBarService, - showSurface: () => _showBusyMarkFlutterDialog( - context, - builder: builder, - barrierColor: barrierColor, - barrierDismissible: barrierDismissible, - ), + builder: builder, + barrierColor: barrierColor, + barrierDismissible: barrierDismissible, ); -} - -Future _coordinateBusyMarkModal( - BuildContext context, { - required LinuxHeaderBarService? headerBarService, - required ({Future result, ModalRoute route}) Function() showSurface, -}) async { - final previousFocus = FocusManager.instance.primaryFocus; - await acquireBusyMarkModalBarrier(headerBarService); - if (!context.mounted) { - await releaseBusyMarkModalBarrier(headerBarService); - return null; - } - ModalRoute? closingRoute; try { - final surface = showSurface(); - closingRoute = surface.route; return await surface.result; } finally { - final restoration = _ModalFocusRestoration(previousFocus, closingRoute); + final restoration = _ModalFocusRestoration(previousFocus, surface.route); try { - await releaseBusyMarkModalBarrier(headerBarService); if (context.mounted && restoration.mayRestore) { previousFocus!.requestFocus(); } @@ -311,6 +284,7 @@ class _ModalFocusRestoration with WidgetsBindingObserver { initialBarrierColor: barrierColor ?? busyMarkModalBarrierColor(context), barrierDismissible: barrierDismissible, ); + BusyMarkDeferredEditorFocus.modalOpened(); return (result: navigator.push(route), route: route); } @@ -353,13 +327,11 @@ class _BusyMarkDialogRoute extends DialogRoute { Future showBusyMarkModalEditorDialog( BuildContext context, { required WidgetBuilder builder, - LinuxHeaderBarService? headerBarService, double maxWidth = 700, double? maxHeight = 760, }) { return showBusyMarkModalDialog( context, - headerBarService: headerBarService, barrierDismissible: false, builder: (dialogContext) => BusyMarkModalEditorSurface( maxWidth: maxWidth, @@ -370,90 +342,6 @@ Future showBusyMarkModalEditorDialog( ); } -/// Acquires a reference-counted native header-bar modal barrier. -/// -/// Every call must be paired with [releaseBusyMarkModalBarrier]. Route -/// dialogs acquire it automatically. -Future acquireBusyMarkModalBarrier(LinuxHeaderBarService? service) async { - if (service == null) { - return; - } - final depth = _busyMarkModalDepths[service] ?? 0; - final nextDepth = depth + 1; - _busyMarkModalDepths[service] = nextDepth; - final depthUpdate = _enqueueBusyMarkModalBarrierUpdate( - service, - depth: nextDepth, - ); - try { - await depthUpdate; - } on Object catch (error, stackTrace) { - final remainingDepth = (_busyMarkModalDepths[service] ?? 0) - 1; - if (remainingDepth > 0) { - _busyMarkModalDepths[service] = remainingDepth; - } else { - _busyMarkModalDepths.remove(service); - try { - await _enqueueBusyMarkModalBarrierUpdate(service, depth: 0); - } on Object { - // Preserve the acquisition failure if its best-effort rollback fails. - } - } - Error.throwWithStackTrace(error, stackTrace); - } -} - -/// Releases a barrier acquired by [acquireBusyMarkModalBarrier]. -Future releaseBusyMarkModalBarrier(LinuxHeaderBarService? service) async { - if (service == null) { - return; - } - final depth = _busyMarkModalDepths[service] ?? 0; - if (depth <= 1) { - _busyMarkModalDepths.remove(service); - await _enqueueBusyMarkModalBarrierUpdate(service, depth: 0); - return; - } - final nextDepth = depth - 1; - _busyMarkModalDepths[service] = nextDepth; - await _enqueueBusyMarkModalBarrierUpdate(service, depth: nextDepth); -} - -Future _enqueueBusyMarkModalBarrierUpdate( - LinuxHeaderBarService service, { - required int depth, -}) { - final previous = - _busyMarkModalBarrierUpdateTails[service] ?? Future.value(); - final ready = previous.then( - (_) {}, - onError: (Object _, StackTrace _) {}, - ); - late final Future update; - update = ready.then((_) => service.setModalBarrierDepth(depth)).whenComplete( - () { - if (identical(_busyMarkModalBarrierUpdateTails[service], update)) { - _busyMarkModalBarrierUpdateTails.remove(service); - } - }, - ); - _busyMarkModalBarrierUpdateTails[service] = update; - return update; -} - -LinuxHeaderBarService? _busyMarkHeaderBarServiceFrom(BuildContext context) { - try { - return ProviderScope.containerOf( - context, - listen: false, - ).read(linuxHeaderBarServiceProvider); - } on StateError { - // Standalone widget hosts may not install Riverpod. Explicit injection - // remains available for those hosts. - return null; - } -} - class BusyMarkModalEditorSurface extends StatelessWidget { const BusyMarkModalEditorSurface({ super.key, @@ -511,11 +399,9 @@ class BusyMarkModalEditorSurface extends StatelessWidget { } void showBusyMarkAboutDialog(BuildContext context) { - final headerBar = LinuxHeaderBarService.instance; unawaited( showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => const _BusyMarkAboutDialog(), ), ); @@ -534,11 +420,9 @@ Future _openApacheLicense() async { } void showBusyMarkSyntaxReferenceDialog(BuildContext context) { - final headerBar = LinuxHeaderBarService.instance; unawaited( showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => const _SyntaxReferenceDialog(), ), ); diff --git a/lib/src/app/busymark_focus.dart b/lib/src/app/busymark_focus.dart index d63cd786..ed340a86 100644 --- a/lib/src/app/busymark_focus.dart +++ b/lib/src/app/busymark_focus.dart @@ -122,53 +122,3 @@ class _BusyMarkFocusIndicatorState extends State { ); } } - -/// Let Flutter observe every trigger release before a native menu grabs keys. -final class BusyMarkContextMenuKeys { - VoidCallback? _open; - bool _triggerReleased = false, _awaitingShift = false; - - bool handle(KeyEvent event, VoidCallback? open) { - final keyboard = HardwareKeyboard.instance; - final key = event.logicalKey; - final trigger = - !keyboard.isControlPressed && - !keyboard.isAltPressed && - !keyboard.isMetaPressed && - (key == LogicalKeyboardKey.contextMenu && !keyboard.isShiftPressed || - key == LogicalKeyboardKey.f10 && keyboard.isShiftPressed); - if (event is KeyDownEvent) { - clear(); - if (!trigger || open == null) return false; - _open = open; - _awaitingShift = key == LogicalKeyboardKey.f10; - return true; - } - if (_open == null) return false; - if (event is KeyRepeatEvent) return true; - if (event is! KeyUpEvent) return false; - if (key == LogicalKeyboardKey.f10 || - key == LogicalKeyboardKey.contextMenu) { - _triggerReleased = true; - } - // The aggregate mask can clear before the concrete Shift-up reaches the - // Flutter view. Waiting only for F10-up still races a native GTK grab. - if ((key == LogicalKeyboardKey.shiftLeft || - key == LogicalKeyboardKey.shiftRight) && - !keyboard.isShiftPressed) { - _awaitingShift = false; - } - if (_triggerReleased && !_awaitingShift) { - final action = _open!; - clear(); - action(); - } - return true; - } - - void clear() { - _open = null; - _triggerReleased = false; - _awaitingShift = false; - } -} diff --git a/lib/src/app/busymark_glyphs.dart b/lib/src/app/busymark_glyphs.dart index 6eace91c..74fac667 100644 --- a/lib/src/app/busymark_glyphs.dart +++ b/lib/src/app/busymark_glyphs.dart @@ -52,6 +52,7 @@ abstract final class BusyMarkGlyphs { static const IconData home = YaruIcons.home; static const IconData htmlBlock = YaruIcons.code; static const IconData image = YaruIcons.image; + static const IconData imageBlocked = YaruIcons.hide; static const IconData imageMissing = YaruIcons.image_missing; static const IconData indent = YaruIcons.indent_more; static const IconData info = YaruIcons.information; diff --git a/lib/src/app/busymark_native_controls.dart b/lib/src/app/busymark_native_controls.dart index e3dc5dd2..8a19d80c 100644 --- a/lib/src/app/busymark_native_controls.dart +++ b/lib/src/app/busymark_native_controls.dart @@ -8,6 +8,8 @@ import 'busymark_glyphs.dart'; enum BusyMarkNativeActionRole { inline, standard, suggested, destructive } +enum BusyMarkActionPresentation { standard, alert, toast } + class BusyMarkNativeActionButton extends StatefulWidget { const BusyMarkNativeActionButton({ super.key, @@ -15,12 +17,14 @@ class BusyMarkNativeActionButton extends StatefulWidget { required this.child, required this.onPressed, this.compact = false, + this.presentation = BusyMarkActionPresentation.standard, }); final BusyMarkNativeActionRole role; final Widget child; final VoidCallback? onPressed; final bool compact; + final BusyMarkActionPresentation presentation; @override State createState() => @@ -61,7 +65,7 @@ class BusyMarkNativeActionButtonState Widget build(BuildContext context) { final colors = BusyMarkSurfaceColors.of(context); final theme = Theme.of(context); - final style = switch (widget.role) { + var style = switch (widget.role) { // Match BusyMarkPushButton.flat: native neutral foreground, never the // accent/link foreground from the application's text-button theme. BusyMarkNativeActionRole.inline => theme.textButtonTheme.style?.copyWith( @@ -84,6 +88,35 @@ class BusyMarkNativeActionButtonState BusyMarkNativeActionRole.standard => theme.filledButtonTheme.style, BusyMarkNativeActionRole.suggested => theme.elevatedButtonTheme.style, }; + switch (widget.presentation) { + case BusyMarkActionPresentation.standard: + break; + case BusyMarkActionPresentation.alert: + style = style?.copyWith( + minimumSize: const WidgetStatePropertyAll(Size(104, 38)), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(BusyMarkRadius.md), + ), + ), + textStyle: WidgetStatePropertyAll( + theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600), + ), + ); + case BusyMarkActionPresentation.toast: + style = theme.filledButtonTheme.style?.copyWith( + minimumSize: const WidgetStatePropertyAll(Size(48, 30)), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(BusyMarkRadius.md), + ), + ), + foregroundColor: WidgetStatePropertyAll(colors.foreground), + textStyle: WidgetStatePropertyAll( + theme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.w600), + ), + ); + } final states = _states; final enabled = widget.onPressed != null; final foreground = enabled @@ -115,7 +148,9 @@ class BusyMarkNativeActionButtonState final radius = resolvedShape is RoundedRectangleBorder ? resolvedShape.borderRadius : BorderRadius.circular(kYaruButtonRadius); - final padding = widget.compact + final padding = + widget.compact || + widget.presentation == BusyMarkActionPresentation.toast ? const EdgeInsets.symmetric( horizontal: BusyMarkSpacing.md, vertical: BusyMarkSpacing.xs, @@ -527,11 +562,13 @@ class BusyMarkNativeDialogShell extends StatelessWidget { super.key, required this.title, this.maxWidth = BusyMarkSizes.dialogWide, + this.showHeader = true, this.children = const [], this.actions = const [], }); final String title; final double maxWidth; + final bool showHeader; final List children, actions; @override Widget build(BuildContext context) => Semantics( @@ -561,34 +598,37 @@ class BusyMarkNativeDialogShell extends StatelessWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ - Padding( - padding: const EdgeInsets.all(BusyMarkSpacing.headerInset), - child: Row( - children: [ - const SizedBox(width: BusyMarkSizes.iconButton), - Expanded( - child: Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.titleMedium, + if (showHeader) + Padding( + padding: const EdgeInsets.all( + BusyMarkSpacing.headerInset, + ), + child: Row( + children: [ + const SizedBox(width: BusyMarkSizes.iconButton), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.titleMedium, + ), + ), + BusyMarkHeaderIconButton( + tooltip: MaterialLocalizations.of( + context, + ).closeButtonTooltip, + icon: BusyMarkGlyphs.windowClose, + onPressed: () { + if (ModalRoute.of(context)?.isCurrent == true) { + Navigator.maybePop(context); + } + }, ), - ), - BusyMarkHeaderIconButton( - tooltip: MaterialLocalizations.of( - context, - ).closeButtonTooltip, - icon: BusyMarkGlyphs.windowClose, - onPressed: () { - if (ModalRoute.of(context)?.isCurrent == true) { - Navigator.maybePop(context); - } - }, - ), - ], + ], + ), ), - ), Flexible( child: SingleChildScrollView( padding: const EdgeInsets.all(BusyMarkSpacing.lg), @@ -655,3 +695,92 @@ class BusyMarkNativeDialogButton extends StatelessWidget { ), ); } + +/// A short decision with its own heading and response area. +class BusyMarkAlert extends StatelessWidget { + const BusyMarkAlert({ + super.key, + required this.heading, + required this.children, + required this.responses, + }); + + final String heading; + final List children; + final List responses; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return BusyMarkNativeDialogShell( + title: heading, + showHeader: false, + maxWidth: 440, + children: [ + Padding( + padding: const EdgeInsets.all(BusyMarkSpacing.sm), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Semantics( + header: true, + child: Text( + heading, + textAlign: TextAlign.center, + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(height: BusyMarkSpacing.sm), + DefaultTextStyle.merge( + style: theme.textTheme.bodyMedium, + textAlign: TextAlign.center, + child: Column( + mainAxisSize: MainAxisSize.min, + children: children, + ), + ), + const SizedBox(height: BusyMarkSpacing.xl), + OverflowBar( + alignment: MainAxisAlignment.center, + overflowAlignment: OverflowBarAlignment.center, + spacing: BusyMarkSpacing.sm, + overflowSpacing: BusyMarkSpacing.sm, + children: responses, + ), + ], + ), + ), + ], + ); + } +} + +class BusyMarkAlertResponse extends StatelessWidget { + const BusyMarkAlertResponse({ + super.key, + required this.label, + required this.onPressed, + this.destructive = false, + this.suggested = false, + }) : assert(!destructive || !suggested); + + final String label; + final VoidCallback? onPressed; + final bool destructive; + final bool suggested; + + @override + Widget build(BuildContext context) => BusyMarkNativeActionButton( + role: destructive + ? BusyMarkNativeActionRole.destructive + : suggested + ? BusyMarkNativeActionRole.suggested + : BusyMarkNativeActionRole.standard, + presentation: BusyMarkActionPresentation.alert, + onPressed: onPressed, + child: Text(label, textAlign: TextAlign.center), + ); +} diff --git a/lib/src/app/busymark_resource_menu.dart b/lib/src/app/busymark_resource_menu.dart new file mode 100644 index 00000000..ee91ab18 --- /dev/null +++ b/lib/src/app/busymark_resource_menu.dart @@ -0,0 +1,103 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../workspace/workspace_resource_actions.dart'; +import 'busymark_design.dart'; +import 'busymark_glyphs.dart'; +import 'command_registry.dart'; +import 'localization.dart'; + +final resourceMenuControllerProvider = + Provider.family((ref, id) { + final controller = BusyMarkHeaderMenuController(); + ref.onDispose(controller.dispose); + return controller; + }); + +class BusyMarkResourceMenuButton extends ConsumerWidget { + const BusyMarkResourceMenuButton._(this.commandId); + + static const commandIds = [ + BusyMarkCommandIds.open, + BusyMarkCommandIds.newDocument, + ]; + static const buttons = [ + BusyMarkResourceMenuButton._(BusyMarkCommandIds.open), + BusyMarkResourceMenuButton._(BusyMarkCommandIds.newDocument), + ]; + + final String commandId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final registry = + BusyMarkCommandRegistryScope.maybeOf(context) ?? + BusyMarkCommandCatalog.metadata; + final command = registry[commandId]!; + final l10n = context.l10n; + final isNew = commandId == BusyMarkCommandIds.newDocument; + final entries = isNew + ? [ + ( + WorkspaceResourceAction.newMarkdown, + l10n.createMarkdownFile, + BusyMarkGlyphs.markdownFile, + 'M', + ), + ( + WorkspaceResourceAction.newNote, + l10n.newNextcloudNote, + BusyMarkGlyphs.newDocument, + 'N', + ), + ( + WorkspaceResourceAction.newWriterside, + l10n.createWritersideProject, + BusyMarkGlyphs.writersideProject, + 'W', + ), + ] + : [ + ( + WorkspaceResourceAction.openMarkdown, + l10n.openMarkdownFile, + BusyMarkGlyphs.markdownFile, + 'M', + ), + ( + WorkspaceResourceAction.openFolder, + l10n.openFolderOrWritersideProject, + BusyMarkGlyphs.folder, + 'F', + ), + ( + WorkspaceResourceAction.browseNotes, + l10n.browseNotes, + BusyMarkGlyphs.documentHistory, + 'N', + ), + ]; + return BusyMarkHeaderPopupMenuButton( + key: ValueKey(isNew ? 'header-new-menu' : 'header-open-menu'), + controller: ref.watch(resourceMenuControllerProvider(commandId)), + tooltip: isNew ? l10n.newResource : l10n.open, + shortcut: command.shortcut?.label, + icon: isNew ? BusyMarkGlyphs.add : BusyMarkGlyphs.folder, + itemBuilder: (_) => [ + for (final (action, label, icon, mnemonic) in entries) + BusyMarkPopupMenuItem( + value: action, + label: label, + icon: icon, + mnemonic: mnemonic, + shortcut: mnemonic, + gtkAccelerator: mnemonic.toLowerCase(), + ), + ], + onSelected: (action) => + unawaited(performWorkspaceResourceAction(ref, action)), + ); + } +} diff --git a/lib/src/app/busymark_shortcuts.dart b/lib/src/app/busymark_shortcuts.dart index 8cef356d..bfb77020 100644 --- a/lib/src/app/busymark_shortcuts.dart +++ b/lib/src/app/busymark_shortcuts.dart @@ -33,6 +33,7 @@ enum BusyMarkAppShortcutAction { save, export, fullScreen, + home, back, search, keyboardShortcuts, @@ -57,6 +58,7 @@ abstract final class BusyMarkAppShortcuts { static const saveLabel = 'Ctrl+S'; static const exportLabel = 'Ctrl+Shift+E'; static const fullScreenLabel = 'F11'; + static const homeLabel = 'Alt+Home'; static const backLabel = 'Alt+Left'; static const searchLabel = 'Ctrl+F'; static const quickOpenLabel = 'Ctrl+Shift+D'; @@ -98,12 +100,20 @@ abstract final class BusyMarkAppShortcuts { static const newDocument = BusyMarkShortcutDefinition( label: newDocumentLabel, - activator: SingleActivator(LogicalKeyboardKey.keyN, control: true), + activator: SingleActivator( + LogicalKeyboardKey.keyN, + control: true, + includeRepeats: false, + ), gtkAccelerator: newDocumentGtkAccelerator, ); static const open = BusyMarkShortcutDefinition( label: openLabel, - activator: SingleActivator(LogicalKeyboardKey.keyO, control: true), + activator: SingleActivator( + LogicalKeyboardKey.keyO, + control: true, + includeRepeats: false, + ), gtkAccelerator: openGtkAccelerator, ); static const save = BusyMarkShortcutDefinition( @@ -134,6 +144,15 @@ abstract final class BusyMarkAppShortcuts { ), gtkAccelerator: backGtkAccelerator, ); + static const home = BusyMarkShortcutDefinition( + label: homeLabel, + activator: SingleActivator( + LogicalKeyboardKey.home, + alt: true, + includeRepeats: false, + ), + gtkAccelerator: 'Home', + ); static const search = BusyMarkShortcutDefinition( label: searchLabel, activator: SingleActivator(LogicalKeyboardKey.keyF, control: true), @@ -207,6 +226,7 @@ abstract final class BusyMarkAppShortcuts { BusyMarkAppShortcutAction.save: save, BusyMarkAppShortcutAction.export: export, BusyMarkAppShortcutAction.fullScreen: fullScreen, + BusyMarkAppShortcutAction.home: home, BusyMarkAppShortcutAction.back: back, BusyMarkAppShortcutAction.search: search, BusyMarkAppShortcutAction.commandPalette: commandPalette, diff --git a/lib/src/app/busymark_toast.dart b/lib/src/app/busymark_toast.dart index 1914d7e0..fe0b20de 100644 --- a/lib/src/app/busymark_toast.dart +++ b/lib/src/app/busymark_toast.dart @@ -5,6 +5,7 @@ import 'package:flutter/material.dart'; import 'busymark_design.dart'; import 'busymark_glyphs.dart'; +import 'busymark_native_controls.dart'; /// Controls how a toast is ordered when another toast is already visible. enum BusyMarkToastPriority { normal, high } @@ -33,6 +34,7 @@ class BusyMarkToastOverlay extends StatefulWidget { message: message, actionLabel: actionLabel, onAction: onAction, + actionScope: onAction == null ? null : FocusScope.of(context), duration: duration, priority: priority, ); @@ -56,6 +58,7 @@ class BusyMarkToastOverlay extends StatefulWidget { message: message, actionLabel: actionLabel, onAction: onAction, + actionScope: onAction == null ? null : FocusScope.of(context), duration: duration, priority: priority, ); @@ -86,6 +89,7 @@ class _BusyMarkToastOverlayState extends State { required String message, required String? actionLabel, required VoidCallback? onAction, + required FocusScopeNode? actionScope, required Duration duration, required BusyMarkToastPriority priority, }) { @@ -98,6 +102,7 @@ class _BusyMarkToastOverlayState extends State { message: normalizedMessage, actionLabel: actionLabel?.trim(), onAction: onAction, + actionScope: actionScope, duration: duration, priority: priority, ); @@ -150,8 +155,9 @@ class _BusyMarkToastOverlayState extends State { } void _invokeAction(_BusyMarkToast toast) { - toast.onAction?.call(); + if (_active?.id != toast.id) return; _dismiss(toast.id); + toast.onAction?.call(); } @override @@ -229,6 +235,7 @@ class _BusyMarkToast { required this.message, required this.actionLabel, required this.onAction, + required this.actionScope, required this.duration, required this.priority, }); @@ -237,6 +244,7 @@ class _BusyMarkToast { final String message; final String? actionLabel; final VoidCallback? onAction; + final FocusScopeNode? actionScope; final Duration duration; final BusyMarkToastPriority priority; @@ -261,54 +269,68 @@ class _BusyMarkToastSurface extends StatelessWidget { final theme = Theme.of(context); final colors = BusyMarkSurfaceColors.of(context); final actionLabel = toast.actionLabel; - return Semantics( - container: true, - liveRegion: true, - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 560), - child: Material( - color: BusyMarkLinuxPalette.transparent, - child: DecoratedBox( - decoration: BoxDecoration( - color: colors.popover, - borderRadius: BorderRadius.circular(BusyMarkRadius.lg), - border: Border.all(color: colors.floatingBorder), - boxShadow: BusyMarkShadow.nativeCardShadowsFor(context), - ), - child: Padding( - padding: const EdgeInsetsDirectional.fromSTEB( - BusyMarkSpacing.lg, - BusyMarkSpacing.sm, - BusyMarkSpacing.sm, - BusyMarkSpacing.sm, + final scope = toast.actionScope; + return Focus( + parentNode: scope?.context?.mounted == true ? scope : null, + canRequestFocus: false, + skipTraversal: true, + includeSemantics: false, + child: Semantics( + container: true, + liveRegion: true, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: Material( + color: BusyMarkLinuxPalette.transparent, + child: DecoratedBox( + decoration: BoxDecoration( + color: colors.popover, + borderRadius: BorderRadius.circular(BusyMarkRadius.lg), + border: Border.all(color: colors.floatingBorder), + boxShadow: BusyMarkShadow.nativeCardShadowsFor(context), ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: Text( - toast.message, - maxLines: 3, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyMedium?.copyWith( - color: colors.foreground, - fontWeight: FontWeight.w600, + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB( + BusyMarkSpacing.lg, + BusyMarkSpacing.sm, + BusyMarkSpacing.sm, + BusyMarkSpacing.sm, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + toast.message, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium?.copyWith( + color: colors.foreground, + fontWeight: FontWeight.w600, + ), ), ), - ), - if (actionLabel != null && actionLabel.isNotEmpty) ...[ - const SizedBox(width: BusyMarkSpacing.sm), - TextButton(onPressed: onAction, child: Text(actionLabel)), + if (actionLabel != null && actionLabel.isNotEmpty) ...[ + const SizedBox(width: BusyMarkSpacing.sm), + Flexible( + child: BusyMarkNativeActionButton( + role: BusyMarkNativeActionRole.standard, + presentation: BusyMarkActionPresentation.toast, + onPressed: onAction, + child: Text(actionLabel), + ), + ), + ], + const SizedBox(width: BusyMarkSpacing.xs), + BusyMarkCompactIconButton( + tooltip: MaterialLocalizations.of( + context, + ).closeButtonTooltip, + icon: BusyMarkGlyphs.windowClose, + onPressed: onDismiss, + ), ], - const SizedBox(width: BusyMarkSpacing.xs), - BusyMarkCompactIconButton( - tooltip: MaterialLocalizations.of( - context, - ).closeButtonTooltip, - icon: BusyMarkGlyphs.windowClose, - onPressed: onDismiss, - ), - ], + ), ), ), ), diff --git a/lib/src/app/command_registry.dart b/lib/src/app/command_registry.dart index 58428404..1c67ef7b 100644 --- a/lib/src/app/command_registry.dart +++ b/lib/src/app/command_registry.dart @@ -483,6 +483,7 @@ abstract final class BusyMarkCommandIds { static const save = 'file.save'; static const export = 'file.export'; static const fullScreen = 'view.fullScreen'; + static const home = 'navigation.home'; static const back = 'navigation.back'; static const search = 'search.find'; static const searchWorkspace = 'search.workspace'; @@ -638,7 +639,7 @@ abstract final class BusyMarkCommandCatalog { ), command( id: BusyMarkCommandIds.newNote, - label: (c) => c.l10n.nextcloudNewNote, + label: (c) => c.l10n.newNextcloudNote, category: (c) => c.l10n.nextcloudNotes, scope: BusyMarkCommandScope.application, ), @@ -900,6 +901,7 @@ abstract final class BusyMarkCommandCatalog { BusyMarkAppShortcutAction.save => BusyMarkCommandIds.save, BusyMarkAppShortcutAction.export => BusyMarkCommandIds.export, BusyMarkAppShortcutAction.fullScreen => BusyMarkCommandIds.fullScreen, + BusyMarkAppShortcutAction.home => BusyMarkCommandIds.home, BusyMarkAppShortcutAction.back => BusyMarkCommandIds.back, BusyMarkAppShortcutAction.search => BusyMarkCommandIds.search, BusyMarkAppShortcutAction.quickOpen => BusyMarkCommandIds.quickOpen, @@ -926,10 +928,11 @@ abstract final class BusyMarkCommandCatalog { BusyMarkAppShortcutAction action, ) => switch (action) { BusyMarkAppShortcutAction.newDocument => context.l10n.shortcutNewDocument, - BusyMarkAppShortcutAction.open => context.l10n.open, + BusyMarkAppShortcutAction.open => context.l10n.openMenu, BusyMarkAppShortcutAction.save => context.l10n.save, BusyMarkAppShortcutAction.export => context.l10n.export, BusyMarkAppShortcutAction.fullScreen => context.l10n.fullScreen, + BusyMarkAppShortcutAction.home => context.l10n.home, BusyMarkAppShortcutAction.back => context.l10n.back, BusyMarkAppShortcutAction.search => context.l10n.searchInDocument, BusyMarkAppShortcutAction.quickOpen => context.l10n.searchDocumentsCommand, diff --git a/lib/src/app/save_destination_picker.dart b/lib/src/app/save_destination_picker.dart new file mode 100644 index 00000000..0ab9fd38 --- /dev/null +++ b/lib/src/app/save_destination_picker.dart @@ -0,0 +1,246 @@ +import 'dart:io'; + +import 'package:file_selector/file_selector.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:path/path.dart' as p; + +import '../core/save_destination.dart'; +import 'busymark_design.dart'; +import 'busymark_dialogs.dart'; +import 'busymark_native_controls.dart'; +import 'busymark_toast.dart'; +import 'localization.dart'; + +const _saveChooser = MethodChannel('busymark/save_chooser'); + +/// Use GTK's save dialog for a single file. GtkFileChooserNative and the +/// FileChooser portal return a pathname without the pre-confirmation review. +Future pickSaveDestination( + BuildContext context, { + required String suggestedName, + required String actionLabel, + required String filterLabel, + required List patterns, + String? initialDirectory, + String? suffix, + bool suffixOnlyWhenMissing = false, + SaveDestinationKind kind = SaveDestinationKind.file, + bool Function()? isCurrent, +}) async { + try { + final review = await _saveChooser + .invokeMapMethod('save', { + 'suggestedName': SaveDestination.withSuffix( + suggestedName, + suffix, + onlyWhenMissing: suffixOnlyWhenMissing, + ), + 'actionLabel': actionLabel, + 'cancelLabel': context.l10n.cancel, + 'filterLabel': filterLabel, + 'patterns': patterns, + 'initialDirectory': initialDirectory, + 'suffix': suffix, + 'suffixOnlyWhenMissing': suffixOnlyWhenMissing, + 'allowLink': kind == SaveDestinationKind.fileOrSymbolicLink, + }); + if (review == null || !context.mounted || isCurrent?.call() == false) { + return null; + } + final destination = SaveDestination.fromChooserReview(review, kind: kind); + if (SaveDestination.withSuffix( + destination.path, + suffix, + onlyWhenMissing: suffixOnlyWhenMissing, + ) != + destination.path) { + throw const FormatException('Unexpected native save filename extension'); + } + return destination; + } on Object catch (error) { + if (context.mounted) { + BusyMarkToastOverlay.show( + context, + message: + error is PlatformException || + error is FileSystemException || + error is FormatException + ? context.l10n.errorFileOperationInvalidTarget + : error.toString(), + priority: BusyMarkToastPriority.high, + ); + } + return null; + } +} + +Future pickHtmlSiteDestination( + BuildContext context, { + required String suggestedName, + String? initialDirectory, + required Future Function(String path) validateReplacement, +}) async { + String? selectedFolder; + try { + selectedFolder = await getDirectoryPath( + initialDirectory: initialDirectory, + confirmButtonText: context.l10n.chooseLocation, + ); + } on PlatformException catch (error) { + if (context.mounted) { + BusyMarkToastOverlay.show( + context, + message: error.message ?? context.l10n.errorFileOperationInvalidTarget, + priority: BusyMarkToastPriority.high, + ); + } + return null; + } + final folder = selectedFolder; + if (folder == null || !context.mounted) return null; + final name = await showBusyMarkModalDialog( + context, + builder: (context) => + _SiteDirectoryName(folder: folder, suggestedName: suggestedName), + ); + if (name == null || !context.mounted) return null; + return confirmSaveDestination( + context, + p.join(folder, name), + kind: SaveDestinationKind.directory, + replacementDetails: context.l10n.htmlOwnedDirectoryOnly, + validateReplacement: validateReplacement, + ); +} + +Future confirmSaveDestination( + BuildContext context, + String path, { + SaveDestinationKind kind = SaveDestinationKind.file, + bool Function()? isCurrent, + Future Function(String path)? validateReplacement, + String? replacementDetails, + String? operation, +}) async { + if (!context.mounted || isCurrent?.call() == false) return null; + try { + final destination = SaveDestination.inspect(path, kind: kind); + if (!destination.replacesExisting) return destination; + if (validateReplacement != null) { + await validateReplacement(destination.path); + } + if (!context.mounted || isCurrent?.call() == false) return null; + final accepted = await showBusyMarkModalDialog( + context, + builder: (context) => BusyMarkAlert( + heading: + operation ?? + context.l10n.errorPathAlreadyExists(p.basename(destination.path)), + responses: [ + BusyMarkAlertResponse( + label: context.l10n.cancel, + onPressed: () => Navigator.pop(context, false), + ), + BusyMarkAlertResponse( + label: context.l10n.overwrite, + destructive: true, + onPressed: () => Navigator.pop(context, true), + ), + ], + children: [ + if (operation != null) + Text( + context.l10n.errorPathAlreadyExists(p.basename(destination.path)), + ), + Text(destination.path, textDirection: TextDirection.ltr), + if (replacementDetails != null) Text(replacementDetails), + ], + ), + ); + if (accepted != true || !context.mounted || isCurrent?.call() == false) { + return null; + } + destination.requireCurrent(destination.path); + return destination; + } on Object catch (error) { + if (context.mounted) { + BusyMarkToastOverlay.show( + context, + message: error is FileSystemException + ? context.l10n.errorFileOperationInvalidTarget + : error.toString(), + priority: BusyMarkToastPriority.high, + ); + } + return null; + } +} + +class _SiteDirectoryName extends StatefulWidget { + const _SiteDirectoryName({required this.folder, required this.suggestedName}); + + final String folder; + final String suggestedName; + + @override + State<_SiteDirectoryName> createState() => _SiteDirectoryNameState(); +} + +class _SiteDirectoryNameState extends State<_SiteDirectoryName> { + late final _name = TextEditingController(text: widget.suggestedName) + ..selection = TextSelection( + baseOffset: 0, + extentOffset: p.basenameWithoutExtension(widget.suggestedName).length, + ); + + String? get _destinationName { + final name = _name.text; + if (name.trim().isEmpty || + name == '.' || + name == '..' || + name.contains('/') || + name.contains('\u0000')) { + return null; + } + return name; + } + + void _accept() { + if (_destinationName case final name?) Navigator.pop(context, name); + } + + @override + void dispose() { + _name.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => BusyMarkNativeDialogShell( + title: context.l10n.export, + actions: [ + BusyMarkNativeDialogButton( + label: context.l10n.cancel, + onPressed: () => Navigator.pop(context), + ), + BusyMarkNativeDialogButton( + label: context.l10n.export, + suggested: true, + onPressed: _destinationName == null ? null : _accept, + ), + ], + children: [ + Text(widget.folder), + const SizedBox(height: BusyMarkSpacing.md), + BusyMarkNativeTextEntry( + label: context.l10n.folder, + autofocus: true, + controller: _name, + textDirection: TextDirection.ltr, + onChanged: (_) => setState(() {}), + onSubmitted: (_) => _accept(), + ), + ], + ); +} diff --git a/lib/src/assets/asset_ingestion_service.dart b/lib/src/assets/asset_ingestion_service.dart index 6f42fe7d..31710574 100644 --- a/lib/src/assets/asset_ingestion_service.dart +++ b/lib/src/assets/asset_ingestion_service.dart @@ -349,15 +349,15 @@ class AssetIngestionService { final metadata = Directory(p.join(key, _transactionDirectoryName)); await metadata.create(recursive: true); final lockFile = File(p.join(metadata.path, _directoryLockFileName)); - final operatingSystemLock = lockFile.openSync(mode: FileMode.append); + final operatingSystemLock = await lockFile.open(mode: FileMode.append); try { - operatingSystemLock.lockSync(FileLock.blockingExclusive); + await operatingSystemLock.lock(FileLock.blockingExclusive); return await operation(); } finally { try { - operatingSystemLock.unlockSync(); + await operatingSystemLock.unlock(); } finally { - operatingSystemLock.closeSync(); + await operatingSystemLock.close(); } } }, diff --git a/lib/src/clipboard/clipboard_history_panel.dart b/lib/src/clipboard/clipboard_history_panel.dart index bd07ce13..3d6df637 100644 --- a/lib/src/clipboard/clipboard_history_panel.dart +++ b/lib/src/clipboard/clipboard_history_panel.dart @@ -26,7 +26,6 @@ class _ClipboardHistoryPanelState extends ConsumerState { final _listScrollController = ScrollController(); final _listFocusNode = FocusNode(debugLabel: 'Clipboard History list'); final _entryKeys = {}; - final _menuKeys = BusyMarkContextMenuKeys(); String? _selectedId; @override @@ -47,7 +46,6 @@ class _ClipboardHistoryPanelState extends ConsumerState { void dispose() { _listScrollController.dispose(); _listFocusNode.dispose(); - _menuKeys.clear(); super.dispose(); } @@ -70,9 +68,6 @@ class _ClipboardHistoryPanelState extends ConsumerState { _entryKeys.removeWhere((id, _) => !visibleIds.contains(id)); return Focus( focusNode: _listFocusNode, - onFocusChange: (focused) { - if (!focused) _menuKeys.clear(); - }, onKeyEvent: (_, event) => _handleKey(event, visible, registry), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, @@ -189,7 +184,7 @@ class _ClipboardHistoryPanelState extends ConsumerState { BusyMarkClipboardInsertionRegistry registry, ) { if (_listFocusNode.hasPrimaryFocus && - _menuKeys.handle(event, () { + handleBusyMarkContextMenuKey(event, () { final selected = visible .where((entry) => entry.id == _selectedId) .firstOrNull; diff --git a/lib/src/core/atomic_file_exceptions.dart b/lib/src/core/atomic_file_exceptions.dart new file mode 100644 index 00000000..996d8b0d --- /dev/null +++ b/lib/src/core/atomic_file_exceptions.dart @@ -0,0 +1,25 @@ +class AtomicFileAlreadyExistsException implements Exception { + const AtomicFileAlreadyExistsException(this.path); + + final String path; + + @override + String toString() => 'A filesystem entity already exists at "$path".'; +} + +class AtomicFileChangedException implements Exception { + const AtomicFileChangedException(this.path, {this.recoveryPath, this.cause}); + + final String path; + final String? recoveryPath; + final Object? cause; + + @override + String toString() { + final recovery = recoveryPath == null + ? '' + : ' The displaced version was preserved at "$recoveryPath".'; + final detail = cause == null ? '' : ' Validation failed: $cause.'; + return 'The file at "$path" changed during publication.$recovery$detail'; + } +} diff --git a/lib/src/core/atomic_file_writer.dart b/lib/src/core/atomic_file_writer.dart index 32feba68..087cb7cc 100644 --- a/lib/src/core/atomic_file_writer.dart +++ b/lib/src/core/atomic_file_writer.dart @@ -5,31 +5,11 @@ import 'package:path/path.dart' as p; import 'linux_atomic_file_api.dart'; -class AtomicFileAlreadyExistsException implements Exception { - const AtomicFileAlreadyExistsException(this.path); +import 'atomic_file_exceptions.dart'; +import 'recoverable_file_replacement.dart'; +import 'save_destination.dart'; - final String path; - - @override - String toString() => 'A filesystem entity already exists at "$path".'; -} - -class AtomicFileChangedException implements Exception { - const AtomicFileChangedException(this.path, {this.recoveryPath, this.cause}); - - final String path; - final String? recoveryPath; - final Object? cause; - - @override - String toString() { - final recovery = recoveryPath == null - ? '' - : ' The displaced version was preserved at "$recoveryPath".'; - final detail = cause == null ? '' : ' Validation failed: $cause.'; - return 'The file at "$path" changed during publication.$recovery$detail'; - } -} +export 'atomic_file_exceptions.dart'; /// Publishes generated bytes without ever exposing a partially written file. class AtomicFileWriter { @@ -39,7 +19,9 @@ class AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { if (!Platform.isLinux) { @@ -62,6 +44,11 @@ class AtomicFileWriter { try { await stagedFile.writeAsBytes(bytes, flush: true); await beforePublish?.call(); + if (authorization != null) { + authorization.requireCurrent(absoluteTarget); + overwrite = authorization.replacesExisting; + acceptReplaced = authorization.acceptsDisplaced; + } if (overwrite) { final targetType = await FileSystemEntity.type( absoluteTarget, @@ -76,6 +63,9 @@ class AtomicFileWriter { } if (acceptReplaced != null) { if (targetType == FileSystemEntityType.notFound) { + if (authorization != null) { + throw AtomicFileChangedException(absoluteTarget); + } final errorNumber = LinuxAtomicFileApi.instance.publishNoReplace( stagedFile.absolute.path, absoluteTarget, @@ -91,18 +81,29 @@ class AtomicFileWriter { ); } final atomicApi = LinuxAtomicFileApi.instance; - if (!atomicApi.isAvailable) { - throw FileSystemException( - 'Conflict-safe replacement requires Linux renameat2', - absoluteTarget, - ); - } + authorization?.requireCurrent(absoluteTarget); final exchangeError = atomicApi.exchange( stagedFile.absolute.path, absoluteTarget, ); if (exchangeError != null) { - throw AtomicFileChangedException(absoluteTarget); + if (exchangeError == LinuxAtomicFileApi.fileMissingError) { + throw AtomicFileChangedException(absoluteTarget); + } + if (authorization != null && + atomicApi.exchangeUnsupported(exchangeError, parent.path)) { + await replaceFileWithoutExchange( + staged: stagedFile, + destination: authorization, + checkBeforeCommit: checkBeforeCommit, + ); + return; + } + throw FileSystemException( + 'Could not exchange the existing file', + absoluteTarget, + OSError('atomic exchange failed', exchangeError), + ); } Object? callbackError; var accepted = false; diff --git a/lib/src/core/linux_atomic_file_api.dart b/lib/src/core/linux_atomic_file_api.dart index d44948dd..e1f04220 100644 --- a/lib/src/core/linux_atomic_file_api.dart +++ b/lib/src/core/linux_atomic_file_api.dart @@ -24,12 +24,15 @@ typedef _ErrnoLocationDart = Pointer Function(); typedef _LinkNative = Int32 Function(Pointer oldPath, Pointer newPath); typedef _LinkDart = int Function(Pointer oldPath, Pointer newPath); +typedef _OpenNative = Int32 Function(Pointer, Int32); +typedef _OpenDart = int Function(Pointer, int); +typedef _DescriptorNative = Int32 Function(Int32); +typedef _DescriptorDart = int Function(int); /// Small Linux-only wrapper around atomic `renameat2` file exchanges. /// -/// Exchanging a staged file with its destination lets callers verify the exact -/// inode that was replaced and exchange it back without overwriting a -/// concurrent writer. +/// Exchanging a staged file with its destination retains the exact displaced +/// inode so callers can verify it before cleanup. final class LinuxAtomicFileApi { LinuxAtomicFileApi._() { if (!Platform.isLinux) { @@ -49,20 +52,36 @@ final class LinuxAtomicFileApi { '__errno_location', ); _link = _library!.lookupFunction<_LinkNative, _LinkDart>('link'); + _open = library.lookupFunction<_OpenNative, _OpenDart>('open'); + _close = library.lookupFunction<_DescriptorNative, _DescriptorDart>( + 'close', + ); + _fsync = library.lookupFunction<_DescriptorNative, _DescriptorDart>( + 'fsync', + ); } static const fileExistsError = 17; + static const fileMissingError = 2; + static const operationNotSupportedError = 95; static const _invalidArgumentError = 22; static const _functionNotImplementedError = 38; - static const _operationNotSupportedError = 95; static const _atCurrentWorkingDirectory = -100; static const _renameNoReplace = 1; static const _renameExchange = 2; + // The ARM Linux UAPI keeps different values for these two open(2) flags. + static final _armOpenFlags = + Abi.current() == Abi.linuxArm || Abi.current() == Abi.linuxArm64; + static final _openDirectoryFlag = _armOpenFlags ? 0x4000 : 0x10000; + static final _noFollowFlag = _armOpenFlags ? 0x8000 : 0x20000; static final instance = LinuxAtomicFileApi._(); _RenameAt2Dart? _renameAt2; _ErrnoLocationDart? _errnoLocation; _LinkDart? _link; + late final _OpenDart _open; + late final _DescriptorDart _close; + late final _DescriptorDart _fsync; DynamicLibrary? _library; bool get isAvailable => _renameAt2 != null && _errnoLocation != null; @@ -72,7 +91,7 @@ final class LinuxAtomicFileApi { final renameAt2 = _renameAt2; final errnoLocation = _errnoLocation; if (renameAt2 == null || errnoLocation == null) { - return null; + return _functionNotImplementedError; } final nativeFirstPath = firstPath.toNativeUtf8(); final nativeSecondPath = secondPath.toNativeUtf8(); @@ -91,6 +110,63 @@ final class LinuxAtomicFileApi { } } + /// EINVAL also describes invalid operands. Retry only a known-valid pair + /// in the staging directory before treating it as a capability failure. + bool exchangeUnsupported(int error, String directory) { + if (error == _functionNotImplementedError || + error == operationNotSupportedError) { + return true; + } + if (error != _invalidArgumentError) return false; + final probe = Directory(directory).createTempSync('.exchange-probe-'); + try { + final first = File('${probe.path}/first')..createSync(); + final second = File('${probe.path}/second')..createSync(); + final result = exchange(first.path, second.path); + return result == _invalidArgumentError || + result == _functionNotImplementedError || + result == operationNotSupportedError; + } finally { + probe.deleteSync(recursive: true); + } + } + + /// Moves the entry itself. A hard link cannot displace a name safely. + int? moveNoReplace(String oldPath, String newPath) => + publishNoReplace(oldPath, newPath, renameOnly: true); + + int openDirectory(String path) => _openEntry(path, _openDirectoryFlag); + + // O_PATH | O_NOFOLLOW keeps the directory entry's inode alive across rename, + // including on filesystems that assign inode numbers in memory. + int pinEntry(String path) => _openEntry(path, 0x200000 | _noFollowFlag); + + int _openEntry(String path, int flags) { + final native = path.toNativeUtf8(); + try { + final descriptor = _open(native, flags | 0x80000); // O_CLOEXEC + if (descriptor >= 0) return descriptor; + throw FileSystemException( + 'Could not open an entry for safe publication', + path, + OSError('open failed', _errnoLocation!().value), + ); + } finally { + malloc.free(native); + } + } + + void closeDescriptor(int descriptor) => _close(descriptor); + + void flushDirectory(int descriptor, String path) { + if (_fsync(descriptor) == 0) return; + throw FileSystemException( + 'Could not flush publication directory', + path, + OSError('fsync failed', _errnoLocation!().value), + ); + } + /// Publishes [oldPath] at [newPath] without replacing an existing entity. /// /// Returns `null` on success, otherwise the Linux errno value. @@ -98,11 +174,12 @@ final class LinuxAtomicFileApi { String oldPath, String newPath, { bool directory = false, + bool renameOnly = false, }) { final errnoLocation = _errnoLocation; final link = _link; if (errnoLocation == null || link == null) { - return _operationNotSupportedError; + return operationNotSupportedError; } final nativeOldPath = oldPath.toNativeUtf8(); final nativeNewPath = newPath.toNativeUtf8(); @@ -120,13 +197,14 @@ final class LinuxAtomicFileApi { return null; } final errorNumber = errnoLocation().value; + if (renameOnly) return errorNumber; if (errorNumber != _invalidArgumentError && errorNumber != _functionNotImplementedError && - errorNumber != _operationNotSupportedError) { + errorNumber != operationNotSupportedError) { return errorNumber; } } - if (directory) return _operationNotSupportedError; + if (directory || renameOnly) return operationNotSupportedError; final result = link(nativeOldPath, nativeNewPath); return result == 0 ? null : errnoLocation().value; } finally { diff --git a/lib/src/core/linux_file_identity.dart b/lib/src/core/linux_file_identity.dart index 7083948f..b1f871f3 100644 --- a/lib/src/core/linux_file_identity.dart +++ b/lib/src/core/linux_file_identity.dart @@ -27,14 +27,17 @@ final class LinuxFileIdentity { /// Unsupported identity inspection returns null. Recovery must fail closed /// rather than infer identity from a pathname or matching document bytes. - static String? read(String path) { + static String? read(String path) => version(path)?.identity; + + static LinuxFileVersion? version(String path, {bool followLinks = false}) { final statx = _statx; if (statx == null) return null; final nativePath = path.toNativeUtf8(); final buffer = calloc(256); try { // AT_FDCWD, AT_SYMLINK_NOFOLLOW, STATX_BASIC_STATS | STATX_BTIME. - if (statx(-100, nativePath, 0x100, 0xfff, buffer) != 0) { + if (statx(-100, nativePath, followLinks ? 0 : 0x100, 0xfff, buffer) != + 0) { throw FileSystemException('Cannot inspect filesystem identity', path); } final data = ByteData.sublistView(buffer.asTypedList(256)); @@ -46,10 +49,31 @@ final class LinuxFileIdentity { final birth = mask & 0x800 == 0 ? '' : ':${data.getInt64(0x50, Endian.host)}:${data.getUint32(0x58, Endian.host)}'; - return '$major:$minor:$inode$birth'; + (int, int) timestamp(int offset) => ( + data.getInt64(offset, Endian.host), + data.getUint32(offset + 8, Endian.host), + ); + final inodeIdentity = '$major:$minor:$inode'; + return ( + identity: '$inodeIdentity$birth', + inodeIdentity: inodeIdentity, + mode: data.getUint16(0x1c, Endian.host), + size: data.getUint64(0x28, Endian.host), + modified: timestamp(0x70), + changed: timestamp(0x60), + ); } finally { calloc.free(buffer); malloc.free(nativePath); } } } + +typedef LinuxFileVersion = ({ + String identity, + String inodeIdentity, + int mode, + int size, + (int, int) modified, + (int, int) changed, +}); diff --git a/lib/src/core/recoverable_file_replacement.dart b/lib/src/core/recoverable_file_replacement.dart new file mode 100644 index 00000000..51fe2596 --- /dev/null +++ b/lib/src/core/recoverable_file_replacement.dart @@ -0,0 +1,160 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +import 'atomic_file_exceptions.dart'; +import 'linux_atomic_file_api.dart'; +import 'linux_file_identity.dart'; +import 'save_destination.dart'; + +/// Replacement for filesystems that offer no-replace rename but no exchange. +/// The original is recoverable by name during the gap between the renames. +Future replaceFileWithoutExchange({ + required File staged, + required SaveDestination destination, + FutureOr Function(String)? acceptDisplaced, + void Function()? checkBeforeCommit, +}) async { + final target = destination.path; + if (!destination.replacesRegularFile) { + throw FileSystemException( + 'This filesystem requires atomic exchange to replace this entry', + target, + ); + } + final api = LinuxAtomicFileApi.instance; + final parent = p.dirname(target); + final parentFd = api.openDirectory(parent); + final parentHandle = '/proc/self/fd/$parentFd'; + final targetHandle = p.join(parentHandle, p.basename(target)); + int? stagedFd, recoveryFd, originalFd; + Directory? recovery; + var displaced = false; + var published = false; + try { + if (!destination.acceptsParent(parentHandle)) { + throw AtomicFileChangedException(target); + } + final parentInode = LinuxFileIdentity.version( + parentHandle, + followLinks: true, + )!.inodeIdentity; + // exFAT updates the directory's reported birth time on rename into it. + // The open descriptor pins the inode so it cannot be reused. + bool parentIsCurrent() => + LinuxFileIdentity.version(parent, followLinks: true)?.inodeIdentity == + parentInode; + final stageParent = p.dirname(staged.absolute.path); + stagedFd = api.openDirectory(stageParent); + final stagedHandle = '/proc/self/fd/$stagedFd/${p.basename(staged.path)}'; + final stagedVersion = LinuxFileIdentity.version(stagedHandle); + final recoveryDir = Directory( + parentHandle, + ).createTempSync('.busymark-recovery-'); + recovery = recoveryDir; + recoveryFd = api.openDirectory(recoveryDir.path); + final recoveryHandle = '/proc/self/fd/$recoveryFd/${p.basename(target)}'; + // Check flush support before changing the destination and persist both + // directory entries before and after publishing the replacement. + api.flushDirectory(parentFd, parent); + api.flushDirectory(recoveryFd, recoveryDir.path); + destination.requireCurrent(target); + originalFd = api.pinEntry(targetHandle); + final original = LinuxFileIdentity.version( + '/proc/self/fd/$originalFd', + followLinks: true, + ); + final moveError = api.moveNoReplace(targetHandle, recoveryHandle); + if (moveError == LinuxAtomicFileApi.fileMissingError) { + throw AtomicFileChangedException(target); + } + if (moveError != null) { + throw FileSystemException( + 'Could not secure the original for recoverable replacement', + target, + OSError('no-replace rename failed', moveError), + ); + } + displaced = true; + + try { + api.flushDirectory(recoveryFd, recoveryDir.path); + api.flushDirectory(parentFd, parent); + final displacedVersion = LinuxFileIdentity.version(recoveryHandle); + if (original == null || + displacedVersion?.identity != original.identity || + !destination.acceptsDisplacedFile(recoveryHandle)) { + throw AtomicFileChangedException( + target, + cause: 'Original entry changed', + ); + } + if (await acceptDisplaced?.call(recoveryHandle) == false || + LinuxFileIdentity.version(recoveryHandle) != displacedVersion) { + throw AtomicFileChangedException( + target, + cause: 'Original content changed', + ); + } + if (stagedVersion == null || + LinuxFileIdentity.version(stagedHandle) != stagedVersion) { + throw AtomicFileChangedException(target, cause: 'Staged file changed'); + } + if (!parentIsCurrent()) { + throw AtomicFileChangedException(target); + } + checkBeforeCommit?.call(); + final error = api.moveNoReplace(stagedHandle, targetHandle); + if (error == LinuxAtomicFileApi.fileExistsError) { + throw AtomicFileChangedException(target); + } + if (error != null) { + throw FileSystemException( + 'Could not publish the replacement file', + target, + OSError('no-replace rename failed', error), + ); + } + published = true; + api.flushDirectory(stagedFd, stageParent); + api.flushDirectory(parentFd, parent); + if (!parentIsCurrent() || + LinuxFileIdentity.version(recoveryHandle) != displacedVersion) { + throw AtomicFileChangedException( + target, + cause: 'Original changed after publication', + ); + } + File(recoveryHandle).deleteSync(); + displaced = false; + } on Object catch (error) { + if (!published && + api.moveNoReplace(recoveryHandle, targetHandle) == null) { + displaced = false; + api.flushDirectory(parentFd, parent); + api.flushDirectory(recoveryFd, recoveryDir.path); + rethrow; + } + throw AtomicFileChangedException( + target, + recoveryPath: p.join( + Link('/proc/self/fd/$recoveryFd').targetSync(), + p.basename(target), + ), + cause: error, + ); + } + } finally { + if (!displaced && recovery != null) { + try { + recovery.deleteSync(); + } on FileSystemException { + // An empty recovery folder is safe to leave behind. + } + } + for (final fd in [originalFd, recoveryFd, stagedFd, parentFd]) { + if (fd != null) api.closeDescriptor(fd); + } + } +} diff --git a/lib/src/core/save_destination.dart b/lib/src/core/save_destination.dart new file mode 100644 index 00000000..e2732ccd --- /dev/null +++ b/lib/src/core/save_destination.dart @@ -0,0 +1,176 @@ +import 'dart:io'; + +import 'package:path/path.dart' as p; + +import 'atomic_file_exceptions.dart'; +import 'linux_file_identity.dart'; + +enum SaveDestinationKind { file, fileOrSymbolicLink, directory } + +/// The entry reviewed for one save operation. A missing target only permits +/// no-replace publication. Existing entries must match at publication time. +final class SaveDestination { + SaveDestination._( + this.path, + this._parent, + this._entry, + this._linkTarget, + this._referent, + ); + + final String path; + final String _parent; + final LinuxFileVersion? _entry; + final String? _linkTarget; + final LinuxFileVersion? _referent; + + bool get replacesExisting => _entry != null; + bool get replacesRegularFile => (_entry?.mode ?? 0) & 0xf000 == 0x8000; + + static String withSuffix( + String path, + String? suffix, { + bool onlyWhenMissing = false, + }) { + if (suffix == null) return path; + final extension = p.extension(path); + if (extension.toLowerCase() == suffix.toLowerCase() || + (onlyWhenMissing && extension.isNotEmpty)) { + return path; + } + return '$path$suffix'; + } + + static SaveDestination inspect( + String path, { + SaveDestinationKind kind = SaveDestinationKind.file, + }) { + path = p.normalize(p.absolute(path)); + final parent = LinuxFileIdentity.version( + p.dirname(path), + followLinks: true, + ); + if (parent == null || (parent.mode & 0xf000) != 0x4000) { + throw FileSystemException('Unsupported save destination folder', path); + } + final type = FileSystemEntity.typeSync(path, followLinks: false); + if (type == FileSystemEntityType.notFound) { + return SaveDestination._(path, parent.identity, null, null, null); + } + final entry = LinuxFileIdentity.version(path); + final fileType = (entry?.mode ?? 0) & 0xf000; + final expectedType = kind == SaveDestinationKind.directory + ? 0x4000 + : 0x8000; + if (fileType == expectedType) { + return SaveDestination._(path, parent.identity, entry, null, null); + } + if (kind == SaveDestinationKind.fileOrSymbolicLink && fileType == 0xa000) { + final linkTarget = Link(path).targetSync(); + final referent = LinuxFileIdentity.version(path, followLinks: true); + if (referent != null && referent.mode & 0xf000 == 0x8000) { + return SaveDestination._( + path, + parent.identity, + entry, + linkTarget, + referent, + ); + } + } + throw FileSystemException('Unsupported save destination', path); + } + + /// Validates the state captured by the chooser before its Replace prompt. + /// A response without an entry review can authorize only a missing target. + static SaveDestination fromChooserReview( + Map review, { + required SaveDestinationKind kind, + }) { + final path = review['path']; + if (path is! String || !p.isAbsolute(path)) { + throw const FormatException('Invalid native save pathname'); + } + final destination = inspect(path, kind: kind); + for (final field in destination.chooserReview.entries) { + if (review[field.key] != field.value) { + throw AtomicFileChangedException(path); + } + } + return destination; + } + + Map get chooserReview => { + 'path': path, + 'parent': _parent, + 'entry': _chooserVersion(_entry), + 'linkTarget': _linkTarget, + 'referent': _chooserVersion(_referent), + }; + + static String? _chooserVersion(LinuxFileVersion? version) => version == null + ? null + : '${version.identity}/${version.mode}/${version.size}/' + '${version.modified.$1}:${version.modified.$2}/' + '${version.changed.$1}:${version.changed.$2}'; + + void requireCurrent(String destination) { + if (!p.equals(path, p.normalize(p.absolute(destination))) || + !_matches(path, displaced: false)) { + throw AtomicFileChangedException(destination); + } + } + + bool acceptsDisplaced(String stagedPath) => + replacesExisting && _matches(stagedPath, displaced: true); + + /// The recoverable replacement protocol verifies the parent independently + /// using an open directory descriptor. + bool acceptsDisplacedFile(String stagedPath) => + replacesRegularFile && _matchesEntry(stagedPath, displaced: true); + + bool acceptsParent(String directory) => + LinuxFileIdentity.version(directory, followLinks: true)?.identity == + _parent; + + bool _matches(String candidate, {required bool displaced}) { + try { + if (!acceptsParent(p.dirname(path))) { + return false; + } + return _matchesEntry(candidate, displaced: displaced); + } on FileSystemException { + return false; + } + } + + bool _matchesEntry(String candidate, {required bool displaced}) { + try { + if (_entry == null) { + return FileSystemEntity.typeSync(candidate, followLinks: false) == + FileSystemEntityType.notFound; + } + final current = LinuxFileIdentity.version(candidate); + if (current == null || + current.identity != _entry.identity || + current.mode != _entry.mode || + current.size != _entry.size || + current.modified != _entry.modified || + (!displaced && current.changed != _entry.changed)) { + return false; + } + final linkTarget = _linkTarget; + if (linkTarget == null) return true; + return Link(candidate).targetSync() == linkTarget && + LinuxFileIdentity.version( + p.isAbsolute(linkTarget) + ? linkTarget + : p.join(p.dirname(path), linkTarget), + followLinks: true, + ) == + _referent; + } on FileSystemException { + return false; + } + } +} diff --git a/lib/src/core/uri_utils.dart b/lib/src/core/uri_utils.dart index f843f5d0..31c57f7e 100644 --- a/lib/src/core/uri_utils.dart +++ b/lib/src/core/uri_utils.dart @@ -19,3 +19,8 @@ bool isLaunchableExternalUri(Uri uri) { bool isRemoteResourceUriScheme(String scheme) { return _remoteResourceUriSchemes.contains(scheme.toLowerCase()); } + +bool isRemoteImageSource(String? source) { + final scheme = source == null ? null : Uri.tryParse(source.trim())?.scheme; + return scheme == 'http' || scheme == 'https'; +} diff --git a/lib/src/editor/clipboard_paste_resolver.dart b/lib/src/editor/clipboard_paste_resolver.dart index f3ff28ea..8d3ffa41 100644 --- a/lib/src/editor/clipboard_paste_resolver.dart +++ b/lib/src/editor/clipboard_paste_resolver.dart @@ -210,6 +210,7 @@ class BusyMarkClipboardPasteResolver { final decoded = const WysiwygClipboardHtml().decode( html, mode: markdownMode ?? MarkdownMode.commonMark, + external: snapshot.external, ); if (decoded != null && hasUsableClipboardHtmlContent(decoded)) { candidates.add( diff --git a/lib/src/editor/markdown_image_permission_scope.dart b/lib/src/editor/markdown_image_permission_scope.dart new file mode 100644 index 00000000..355c58e5 --- /dev/null +++ b/lib/src/editor/markdown_image_permission_scope.dart @@ -0,0 +1,73 @@ +import 'package:flutter/widgets.dart'; + +import '../core/source_span.dart'; +import '../platform/native_menu_service.dart'; + +typedef MarkdownImagePermissionResolver = + MarkdownImageActions Function( + String source, + SourceSpan? span, + String? renderedSource, + ); + +typedef MarkdownImagePermissionMenu = + Future Function( + BuildContext context, + Offset? position, + NativeMenuSession session, + ); + +class MarkdownImageActions { + const MarkdownImageActions({ + required this.allowed, + this.documentOpening, + this.openMenu, + }); + + final bool allowed; + final Object? documentOpening; + final MarkdownImagePermissionMenu? openMenu; +} + +class MarkdownImagePermissionScope extends InheritedWidget { + const MarkdownImagePermissionScope({ + super.key, + required this.resolve, + required super.child, + }); + + final MarkdownImagePermissionResolver resolve; + + static MarkdownImageActions? of( + BuildContext context, + String source, + SourceSpan? span, + ) => context + .dependOnInheritedWidgetOfExactType() + ?.resolve( + source, + span, + context + .dependOnInheritedWidgetOfExactType() + ?.source, + ); + + @override + bool updateShouldNotify(MarkdownImagePermissionScope oldWidget) => + resolve != oldWidget.resolve; +} + +/// The source snapshot from which this renderer obtained its source ranges. +class MarkdownImageProjection extends InheritedWidget { + const MarkdownImageProjection({ + super.key, + required this.source, + required super.child, + }); + + final String? source; + + @override + bool updateShouldNotify(MarkdownImageProjection oldWidget) => + source != oldWidget.source; +} diff --git a/lib/src/editor/markdown_image_view.dart b/lib/src/editor/markdown_image_view.dart index bd075d1c..5de32af7 100644 --- a/lib/src/editor/markdown_image_view.dart +++ b/lib/src/editor/markdown_image_view.dart @@ -4,7 +4,9 @@ import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; +import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:path/path.dart' as p; import 'package:xml/xml.dart' as xml; @@ -13,6 +15,10 @@ import '../app/busymark_design.dart'; import '../app/busymark_glyphs.dart'; import '../app/localization.dart'; import '../core/local_image_resolver.dart'; +import '../core/source_span.dart'; +import '../core/uri_utils.dart'; +import '../platform/native_menu_service.dart'; +import 'markdown_image_permission_scope.dart'; import '../assets/document_media_context.dart'; /// Resolves an authored image width using the shared document-view bounds. @@ -42,10 +48,12 @@ class MarkdownImageView extends StatelessWidget { required this.workspaceRoot, required this.writersideRoot, required this.imagesDir, - required this.allowRemoteImages, - this.onRemoteImageBlocked, + this.allowRemoteImages = false, + this.sourceSpan, + this.wrapAvailableImage, this.width, this.height, + this.preferredHeight, this.maxWidth = BusyMarkSizes.documentImageMaxWidth, this.maxHeight, }); @@ -57,17 +65,39 @@ class MarkdownImageView extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; + final SourceSpan? sourceSpan; + final Widget Function(Widget child)? wrapAvailableImage; final double? width; final double? height; + final double? preferredHeight; + double? get _imageHeight => height ?? preferredHeight; final double maxWidth; final double? maxHeight; @override Widget build(BuildContext context) { final trimmedSource = source.trim(); - final image = _imageForSource(context, trimmedSource); - return DefaultTextStyle.merge( + final remote = isRemoteImageSource(trimmedSource); + final actions = remote + ? MarkdownImagePermissionScope.of(context, trimmedSource, sourceSpan) + : null; + final isBlocked = remote && !(actions?.allowed ?? allowRemoteImages); + final image = isBlocked + ? _RemoteImageBlockedPlaceholder( + key: ValueKey(( + actions?.documentOpening, + sourceSpan?.startOffset, + sourceSpan?.endOffset, + trimmedSource, + )), + source: trimmedSource, + alt: alt, + width: width, + height: height, + openMenu: actions?.openMenu, + ) + : _imageForSource(context, trimmedSource); + final content = DefaultTextStyle.merge( style: const TextStyle( decoration: TextDecoration.none, fontStyle: FontStyle.normal, @@ -86,6 +116,7 @@ class MarkdownImageView extends StatelessWidget { ), ), ); + return isBlocked ? content : wrapAvailableImage?.call(content) ?? content; } Widget? _imageForSource(BuildContext context, String source) { @@ -104,7 +135,7 @@ class MarkdownImageView extends StatelessWidget { ? _MarkdownImagePlaceholder( source: source, alt: alt, - height: height ?? 120, + height: _imageHeight ?? 120, ) : _fileImage(File(path), source, _isSvgPath(path)); }, @@ -125,28 +156,21 @@ class MarkdownImageView extends StatelessWidget { return _fileImage(File(resolvedPath), source, _isSvgPath(resolvedPath)); } if (uri.scheme == 'http' || uri.scheme == 'https') { - if (!allowRemoteImages) { - return _RemoteImageBlockedPlaceholder( - source: source, - alt: alt, - height: height ?? 120, - onTap: onRemoteImageBlocked, - ); - } if (_isSvgPath(uri.path)) { return _networkSvg(source); } return Image.network( source, + semanticLabel: alt.trim().isEmpty ? null : alt, width: width, - height: height, + height: _imageHeight, fit: BoxFit.contain, alignment: Alignment.center, errorBuilder: (context, error, stackTrace) => _MarkdownImagePlaceholder( source: source, alt: alt, - height: height ?? 120, + height: _imageHeight ?? 120, ), ); } @@ -172,26 +196,26 @@ class MarkdownImageView extends StatelessWidget { source: source, alt: alt, width: width, - height: height, + height: _imageHeight, ); } if (!file.existsSync()) { return _MarkdownImagePlaceholder( source: source, alt: alt, - height: height ?? 120, + height: _imageHeight ?? 120, ); } return Image.file( file, width: width, - height: height, + height: _imageHeight, fit: BoxFit.contain, alignment: Alignment.center, errorBuilder: (context, error, stackTrace) => _MarkdownImagePlaceholder( source: source, alt: alt, - height: height ?? 120, + height: _imageHeight ?? 120, ), ); } @@ -201,7 +225,7 @@ class MarkdownImageView extends StatelessWidget { source: source, alt: alt, width: width, - height: height, + height: _imageHeight, ); } } @@ -963,10 +987,12 @@ class _MarkdownImagePlaceholder extends StatelessWidget { : alt.trim().isEmpty ? source : '$alt\n$source'; - return SizedBox( - height: height, + return ConstrainedBox( + constraints: BoxConstraints(minHeight: height), child: Center( - child: Padding( + heightFactor: 1, + child: SingleChildScrollView( + primary: false, padding: const EdgeInsets.all(BusyMarkSpacing.md), child: Column( mainAxisSize: MainAxisSize.min, @@ -994,64 +1020,191 @@ class _MarkdownImagePlaceholder extends StatelessWidget { } } -class _RemoteImageBlockedPlaceholder extends StatelessWidget { +/// Preview's selection region opens its toolbar on secondary button down. +/// Claim that button for the image before the selection recognizer's deadline, +/// while still waiting for the pointer release to present the GTK menu. +class _RemoteImageMenuTapRecognizer extends TapGestureRecognizer { + @override + void addAllowedPointer(PointerDownEvent event) { + super.addAllowedPointer(event); + if (event.buttons == kSecondaryMouseButton) { + resolve(GestureDisposition.accepted); + } + } +} + +class _RemoteImageBlockedPlaceholder extends StatefulWidget { const _RemoteImageBlockedPlaceholder({ + super.key, required this.source, required this.alt, + required this.width, required this.height, - required this.onTap, + required this.openMenu, }); final String source; final String alt; - final double height; - final VoidCallback? onTap; + final double? width; + final double? height; + final MarkdownImagePermissionMenu? openMenu; + + @override + State<_RemoteImageBlockedPlaceholder> createState() => + _RemoteImageBlockedPlaceholderState(); +} + +class _RemoteImageBlockedPlaceholderState + extends State<_RemoteImageBlockedPlaceholder> { + final _focus = FocusNode(debugLabel: 'Remote image permissions'); + NativeMenuSession? _menu; + bool _hovered = false; + + Future _open([Offset? position]) async { + final openMenu = widget.openMenu; + if (_menu != null || openMenu == null) return; + _focus.requestFocus(); + // The native service captures the primary focus when opening. Apply the + // pointer focus request before it takes that snapshot. + FocusManager.instance.applyFocusChangesIfNeeded(); + final session = NativeMenuSession(); + setState(() => _menu = session); + try { + await openMenu(context, position, session); + } finally { + if (mounted) setState(() => _menu = null); + } + } + + KeyEventResult _onKey(FocusNode node, KeyEvent event) { + if (isBusyMarkContextMenuKeyEvent(event)) { + unawaited(_open()); + return KeyEventResult.handled; + } + final keyboard = HardwareKeyboard.instance; + if (event is KeyDownEvent && + !keyboard.isControlPressed && + !keyboard.isAltPressed && + !keyboard.isMetaPressed && + !keyboard.isShiftPressed && + (event.logicalKey == LogicalKeyboardKey.enter || + event.logicalKey == LogicalKeyboardKey.numpadEnter || + event.logicalKey == LogicalKeyboardKey.space)) { + unawaited(_open()); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + @override + void dispose() { + if (_menu case final session?) { + unawaited(const NativeMenuService().dismiss(session)); + } + _focus.dispose(); + super.dispose(); + } @override Widget build(BuildContext context) { final colors = BusyMarkSurfaceColors.of(context); - final label = alt.trim().isEmpty ? source : '$alt\n$source'; - final content = SizedBox( - height: height, - child: Center( - child: Padding( - padding: const EdgeInsets.all(BusyMarkSpacing.md), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - BusyMarkGlyphs.imageMissing, - size: BusyMarkSizes.iconMd, - color: colors.mutedForeground, - ), - const SizedBox(height: BusyMarkSpacing.xs), - Text( - context.l10n.remoteImageBlocked, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodySmall?.copyWith( - color: colors.foreground, - fontWeight: FontWeight.w700, + final l10n = context.l10n; + final enabled = widget.openMenu != null; + final alt = widget.alt.trim(); + final details = alt.isEmpty ? widget.source : '$alt\n${widget.source}'; + final radius = BorderRadius.circular(BusyMarkRadius.sm); + return Align( + alignment: AlignmentDirectional.centerStart, + widthFactor: 1, + heightFactor: 1, + child: BusyMarkFocusIndicator( + borderRadius: radius, + enabled: enabled, + child: Focus( + focusNode: _focus, + canRequestFocus: enabled, + includeSemantics: false, + onFocusChange: (_) => setState(() {}), + onKeyEvent: enabled ? _onKey : null, + child: Semantics( + container: true, + button: enabled, + focusable: enabled, + focused: enabled ? _focus.hasFocus : null, + onFocus: enabled ? _focus.requestFocus : null, + // Linux exposes the label to assistive technology. The visible + // tooltip below remains short regardless of the source length. + label: '${l10n.remoteImageBlocked}\n$details', + onTap: enabled ? () => unawaited(_open()) : null, + excludeSemantics: true, + child: Tooltip( + message: enabled && _menu == null + ? l10n.remoteImageBlockedTooltip + : '', + constraints: const BoxConstraints(maxWidth: 240), + excludeFromSemantics: true, + child: MouseRegion( + cursor: enabled ? SystemMouseCursors.click : MouseCursor.defer, + onEnter: enabled + ? (_) => setState(() => _hovered = true) + : null, + onExit: enabled + ? (_) => setState(() => _hovered = false) + : null, + child: RawGestureDetector( + behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, + gestures: { + if (enabled) + _RemoteImageMenuTapRecognizer: + GestureRecognizerFactoryWithHandlers< + _RemoteImageMenuTapRecognizer + >(_RemoteImageMenuTapRecognizer.new, (recognizer) { + recognizer.onTap = () => unawaited(_open()); + recognizer.onSecondaryTapUp = (event) => + unawaited(_open(event.globalPosition)); + }), + }, + child: Container( + width: widget.width, + height: widget.height, + padding: const EdgeInsets.symmetric( + horizontal: BusyMarkSpacing.xs, + vertical: BusyMarkSpacing.xxs, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + BusyMarkGlyphs.imageBlocked, + size: BusyMarkSizes.iconSm, + color: colors.mutedForeground, + ), + const SizedBox(width: BusyMarkSpacing.xs), + Flexible( + child: Text( + l10n.remoteImageBlocked, + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall + ?.copyWith( + color: colors.mutedForeground, + decoration: enabled && _hovered + ? TextDecoration.underline + : null, + decorationColor: colors.mutedForeground, + ), + ), + ), + ], + ), + ), ), ), - const SizedBox(height: BusyMarkSpacing.xxs), - Text( - label, - textAlign: TextAlign.center, - style: Theme.of( - context, - ).textTheme.bodySmall?.copyWith(color: colors.mutedForeground), - ), - ], + ), ), ), ), ); - if (onTap == null) { - return content; - } - return Tooltip( - message: context.l10n.remoteImageBlockedTooltip, - child: InkWell(onTap: onTap, child: content), - ); } } diff --git a/lib/src/editor/source/source_controller.dart b/lib/src/editor/source/source_controller.dart index bb14e0eb..cc2ca517 100644 --- a/lib/src/editor/source/source_controller.dart +++ b/lib/src/editor/source/source_controller.dart @@ -10,7 +10,6 @@ class BusyMarkSourceController extends BusyMarkSourceEditingController { super.onFullTextChanged, }) { renderText = false; - visualMarkdown = false; } void replaceFullTextAndLanguage({ @@ -20,6 +19,5 @@ class BusyMarkSourceController extends BusyMarkSourceEditingController { this.language = language; setFullText(text); renderText = false; - visualMarkdown = false; } } diff --git a/lib/src/editor/source/source_document.dart b/lib/src/editor/source/source_document.dart index 4bb4490e..b14f7e9c 100644 --- a/lib/src/editor/source/source_document.dart +++ b/lib/src/editor/source/source_document.dart @@ -33,7 +33,9 @@ class SourceDocument { SourceHiddenRanges(ranges: const [], textLength: fullText.length), lineIndex = SourceLineIndex(fullText) { visibleText = this.hiddenRanges.visibleTextFor(fullText); - visibleLineIndex = SourceLineIndex(visibleText); + visibleLineIndex = this.hiddenRanges.isEmpty + ? lineIndex + : SourceLineIndex(visibleText); } SourceDocument._({ @@ -51,16 +53,26 @@ class SourceDocument { required SourceVisibleEdit edit, }) { final visibleText = hiddenRanges.visibleTextFor(fullText); + final lineIndex = SourceLineIndex.updated( + previous: previous.lineIndex, + source: fullText, + oldStart: edit.fullStart, + oldEnd: edit.fullEnd, + ); + if (hiddenRanges.isEmpty) { + return SourceDocument._( + fullText: fullText, + hiddenRanges: hiddenRanges, + lineIndex: lineIndex, + visibleText: visibleText, + visibleLineIndex: lineIndex, + ); + } final visibleChange = _changedRange(previous.visibleText, visibleText); return SourceDocument._( fullText: fullText, hiddenRanges: hiddenRanges, - lineIndex: SourceLineIndex.updated( - previous: previous.lineIndex, - source: fullText, - oldStart: edit.fullStart, - oldEnd: edit.fullEnd, - ), + lineIndex: lineIndex, visibleText: visibleText, visibleLineIndex: SourceLineIndex.updated( previous: previous.visibleLineIndex, diff --git a/lib/src/editor/source/source_editor.dart b/lib/src/editor/source/source_editor.dart index 1d5a4157..1ad8a7b0 100644 --- a/lib/src/editor/source/source_editor.dart +++ b/lib/src/editor/source/source_editor.dart @@ -11,6 +11,8 @@ import 'dart:math' as math; import 'package:flutter/foundation.dart' show setEquals, visibleForTesting; import 'package:flutter/material.dart'; + +import '../../app/busymark_deferred_editor_focus.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:path/path.dart' as p; @@ -81,6 +83,7 @@ class BusyMarkSourceEditor extends StatefulWidget { required this.language, required this.filePath, this.documentId, + this.creationFocus, required this.diagnostics, required this.editorFontSize, required this.wordWrap, @@ -132,6 +135,7 @@ class BusyMarkSourceEditor extends StatefulWidget { final SourceSyntaxLanguage language; final String? filePath; final String? documentId; + final BusyMarkDeferredEditorFocus? creationFocus; final Iterable diagnostics; final double editorFontSize; final bool wordWrap; @@ -373,6 +377,23 @@ class BusyMarkSourceEditorState extends State { _lastObservedEditingValue = _fullEditingValue(); _controller.addListener(_handleControllerActivity); _scrollController.addListener(_scheduleSessionPublication); + _scheduleCreationFocus(); + } + + void _scheduleCreationFocus() { + final request = widget.creationFocus; + if (request == null) return; + final node = _focusNode; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && + identical(widget.creationFocus, request) && + identical(_focusNode, node) && + node.context != null && + request.consume(context) && + node.canRequestFocus) { + node.requestFocus(); + } + }); } @override @@ -460,6 +481,10 @@ class BusyMarkSourceEditorState extends State { oldWidget.searchSnapshot?.searching) { _syncSearchOptions(); } + if (oldWidget.creationFocus != widget.creationFocus) { + oldWidget.creationFocus?.cancel(); + _scheduleCreationFocus(); + } if (widget.wordWrap && !oldWidget.wordWrap) { WidgetsBinding.instance.addPostFrameCallback((_) { if (_horizontalScrollController.hasClients) { @@ -471,6 +496,7 @@ class BusyMarkSourceEditorState extends State { @override void dispose() { + widget.creationFocus?.cancel(); widget.clipboardInsertionRegistry?.unregister(_historyInsertionTarget); _searchDebounce?.cancel(); _foldRefreshDebounce?.cancel(); diff --git a/lib/src/editor/source/source_search.dart b/lib/src/editor/source/source_search.dart index 68ec1d16..38704d97 100644 --- a/lib/src/editor/source/source_search.dart +++ b/lib/src/editor/source/source_search.dart @@ -445,42 +445,6 @@ SourceSearchResult _decodeSearchResult( ); } -class SourceWorkspaceSearchFileResult { - const SourceWorkspaceSearchFileResult({ - required this.filePath, - required this.matches, - }); - - final String filePath; - final List matches; -} - -List searchWorkspaceSources({ - required Map files, - required SourceSearchOptions options, - int maxFiles = 80, -}) { - final results = []; - final sortedPaths = files.keys.toList()..sort(); - for (final path in sortedPaths) { - if (!_isAuthoringContentPath(path)) { - continue; - } - final document = SourceDocument(fullText: files[path]!); - final result = searchSourceDocument(document, options); - if (result.matches.isEmpty) { - continue; - } - results.add( - SourceWorkspaceSearchFileResult(filePath: path, matches: result.matches), - ); - if (results.length >= maxFiles) { - break; - } - } - return List.unmodifiable(results); -} - SourceSearchResult searchSourceDocument( SourceDocument document, SourceSearchOptions options, { @@ -591,20 +555,6 @@ bool _isHighSurrogate(int unit) => unit >= 0xD800 && unit <= 0xDBFF; bool _isLowSurrogate(int unit) => unit >= 0xDC00 && unit <= 0xDFFF; -bool _isAuthoringContentPath(String path) { - final lower = path.toLowerCase(); - return lower.endsWith('.md') || - lower.endsWith('.topic') || - lower.endsWith('.tree') || - lower.endsWith('.cfg') || - lower.endsWith('.list') || - lower.endsWith('.xml') || - lower.endsWith('.properties') || - lower.endsWith('.yaml') || - lower.endsWith('.yml') || - lower.endsWith('.json'); -} - bool _matchesEqual( List left, List right, diff --git a/lib/src/editor/source_highlighter.dart b/lib/src/editor/source_highlighter.dart index bfb5ac26..ec81c50b 100644 --- a/lib/src/editor/source_highlighter.dart +++ b/lib/src/editor/source_highlighter.dart @@ -40,11 +40,6 @@ final _xmlTagPattern = RegExp(r']+/?>'); final _xmlTagNamePattern = RegExp(r'^\s?)(.*)$'); TextSpan buildBusyMarkReadOnlySourceTextSpan({ required BuildContext context, @@ -105,7 +100,6 @@ class BusyMarkSourceEditingController extends TextEditingController { SourceSearchResult _searchResult = SourceSearchResult.empty; void Function(String fullText, SourceVisibleEdit? edit)? onFullTextChanged; bool renderText = true; - bool visualMarkdown = false; SourceSyntaxLanguage get language => _language; @@ -520,9 +514,6 @@ class BusyMarkSourceEditingController extends TextEditingController { colors, _searchResult, ); - if (visualMarkdown && _language == SourceSyntaxLanguage.markdown) { - return _visualMarkdownTextSpan(source, baseStyle, palette); - } return TextSpan( style: baseStyle, children: switch (_language) { @@ -2039,245 +2030,6 @@ TextStyle? _mergeHighlightStyles( return style; } -TextSpan _visualMarkdownTextSpan( - String source, - TextStyle baseStyle, - BusyMarkSyntaxColors palette, -) { - final spans = []; - final lines = source.split('\n'); - MarkdownFence? openFence; - - for (var index = 0; index < lines.length; index++) { - final line = lines[index]; - final activeFence = openFence; - final closesFence = activeFence?.closes(line) ?? false; - final openingFence = activeFence == null ? MarkdownFence.parse(line) : null; - if (closesFence || openingFence != null) { - openFence = closesFence ? null : openingFence; - spans.add( - TextSpan( - text: line, - style: baseStyle.copyWith( - color: palette.keyword, - fontFamily: BusyMarkTypography.monoFontFamily, - ), - ), - ); - } else if (activeFence != null) { - spans.add( - TextSpan( - text: line, - style: baseStyle.copyWith( - color: palette.literal, - fontFamily: BusyMarkTypography.monoFontFamily, - backgroundColor: palette.punctuation.withValues( - alpha: BusyMarkAlpha.sourceSyntaxBackground, - ), - ), - ), - ); - } else { - spans.addAll(_visualMarkdownLineSpans(line, baseStyle, palette)); - } - if (index < lines.length - 1) { - spans.add(TextSpan(text: '\n', style: baseStyle)); - } - } - - return TextSpan(style: baseStyle, children: spans); -} - -List _visualMarkdownLineSpans( - String line, - TextStyle baseStyle, - BusyMarkSyntaxColors palette, -) { - final heading = _visualMarkdownHeadingPattern.firstMatch(line); - if (heading != null) { - final marker = heading.group(1)!; - final content = heading.group(2)!; - final level = marker.trim().length; - return [ - TextSpan(text: marker, style: baseStyle), - ..._visualInlineSpans( - content, - _markdownHeadingStyle(baseStyle, level), - palette, - ), - ]; - } - - final list = _visualMarkdownListPattern.firstMatch(line); - if (list != null) { - final marker = list.group(1)!; - final task = list.group(2); - final text = list.group(3)!; - return [ - TextSpan( - text: marker, - style: baseStyle.copyWith(color: palette.punctuation), - ), - if (task != null) - TextSpan( - text: task, - style: baseStyle.copyWith(color: palette.keyword), - ), - ..._visualInlineSpans(text, baseStyle, palette), - ]; - } - - final quote = _visualMarkdownQuotePattern.firstMatch(line); - if (quote != null) { - return [ - TextSpan( - text: quote.group(1)!, - style: baseStyle.copyWith(color: palette.punctuation), - ), - ..._visualInlineSpans( - quote.group(2)!, - baseStyle.copyWith(color: palette.comment), - palette, - ), - ]; - } - - return _visualInlineSpans(line, baseStyle, palette); -} - -List _visualInlineSpans( - String source, - TextStyle baseStyle, - BusyMarkSyntaxColors palette, -) { - final spans = []; - var index = 0; - - void addText(String text, [TextStyle? style]) { - if (text.isEmpty) { - return; - } - spans.add(TextSpan(text: text, style: style ?? baseStyle)); - } - - while (index < source.length) { - if (source.startsWith('\\', index) && index + 1 < source.length) { - addText(source[index]); - addText(source[index + 1]); - index += 2; - continue; - } - - final code = _delimitedInline(source, index, '`'); - if (code != null) { - addText(code.opening); - addText( - code.inner, - baseStyle.copyWith( - fontFamily: BusyMarkTypography.monoFontFamily, - backgroundColor: palette.punctuation.withValues( - alpha: BusyMarkAlpha.sourceSyntaxBackground, - ), - ), - ); - addText(code.closing); - index = code.end; - continue; - } - - final link = _visualLinkAt(source, index); - if (link != null) { - addText(link.opening); - addText( - link.label, - baseStyle.copyWith( - color: link.image ? palette.comment : palette.link, - decoration: link.image ? null : TextDecoration.underline, - ), - ); - addText(link.closing); - index = link.end; - continue; - } - - final strong = - _delimitedInline(source, index, '**') ?? - _delimitedInline(source, index, '__'); - if (strong != null) { - addText(strong.opening); - spans.addAll( - _visualInlineSpans( - strong.inner, - baseStyle.copyWith(fontWeight: FontWeight.w700), - palette, - ), - ); - addText(strong.closing); - index = strong.end; - continue; - } - - final strike = _delimitedInline(source, index, '~~'); - if (strike != null) { - addText(strike.opening); - spans.addAll( - _visualInlineSpans( - strike.inner, - baseStyle.copyWith(decoration: TextDecoration.lineThrough), - palette, - ), - ); - addText(strike.closing); - index = strike.end; - continue; - } - - final emphasis = - _delimitedInline(source, index, '*') ?? - _delimitedInline(source, index, '_'); - if (emphasis != null) { - addText(emphasis.opening); - spans.addAll( - _visualInlineSpans( - emphasis.inner, - baseStyle.copyWith(fontStyle: FontStyle.italic), - palette, - ), - ); - addText(emphasis.closing); - index = emphasis.end; - continue; - } - - final next = _nextVisualMarkerIndex(source, index + 1); - addText(source.substring(index, next)); - index = next; - } - - return spans; -} - -int _nextVisualMarkerIndex(String source, int start) { - var next = source.length; - for (final marker in const [ - '\\', - '`', - '![', - '[', - '**', - '__', - '~~', - '*', - '_', - ]) { - final found = source.indexOf(marker, start); - if (found >= 0 && found < next) { - next = found; - } - } - return next; -} - TextStyle _markdownHeadingStyle(TextStyle baseStyle, int level) { final scale = BusyMarkTypography.markdownHeadingScale(level); return baseStyle.copyWith( @@ -2295,82 +2047,6 @@ TextStyle _transparentLayoutStyle(TextStyle style) { ); } -_VisualDelimitedInline? _delimitedInline( - String source, - int start, - String marker, -) { - if (!source.startsWith(marker, start)) { - return null; - } - final contentStart = start + marker.length; - final end = source.indexOf(marker, contentStart); - if (end <= contentStart) { - return null; - } - return _VisualDelimitedInline( - opening: marker, - inner: source.substring(contentStart, end), - closing: marker, - end: end + marker.length, - ); -} - -_VisualLink? _visualLinkAt(String source, int start) { - final image = source.startsWith('![', start); - if (!image && !source.startsWith('[', start)) { - return null; - } - final labelStart = start + (image ? 2 : 1); - final labelEnd = source.indexOf(']', labelStart); - if (labelEnd < 0 || - labelEnd + 1 >= source.length || - source[labelEnd + 1] != '(') { - return null; - } - final destinationEnd = source.indexOf(')', labelEnd + 2); - if (destinationEnd < 0) { - return null; - } - return _VisualLink( - image: image, - opening: source.substring(start, labelStart), - label: source.substring(labelStart, labelEnd), - closing: source.substring(labelEnd, destinationEnd + 1), - end: destinationEnd + 1, - ); -} - -class _VisualDelimitedInline { - const _VisualDelimitedInline({ - required this.opening, - required this.inner, - required this.closing, - required this.end, - }); - - final String opening; - final String inner; - final String closing; - final int end; -} - -class _VisualLink { - const _VisualLink({ - required this.image, - required this.opening, - required this.label, - required this.closing, - required this.end, - }); - - final bool image; - final String opening; - final String label; - final String closing; - final int end; -} - List _normalizedFoldRegions( Iterable regions, ) { diff --git a/lib/src/editor/writerside_video_view.dart b/lib/src/editor/writerside_video_view.dart index a2a78666..719a0d05 100644 --- a/lib/src/editor/writerside_video_view.dart +++ b/lib/src/editor/writerside_video_view.dart @@ -7,6 +7,9 @@ import '../app/busymark_design.dart'; import '../assets/document_media_context.dart'; import '../app/busymark_glyphs.dart'; import '../app/localization.dart'; +import '../core/source_span.dart'; +import '../core/uri_utils.dart'; +import 'markdown_image_permission_scope.dart'; import '../writerside/writerside_video.dart'; import 'markdown_image_view.dart'; import 'writerside_video_player_host.dart'; @@ -20,8 +23,8 @@ class BusyMarkWritersideVideoView extends StatefulWidget { required this.workspaceRoot, required this.writersideRoot, required this.imagesDir, - required this.allowRemoteImages, - this.onRemoteImageBlocked, + this.allowRemoteImages = false, + this.posterSpan, this.onOpenFailed, this.playerHost = const PlatformWritersideVideoPlayerHost(), this.width, @@ -38,7 +41,7 @@ class BusyMarkWritersideVideoView extends StatefulWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; + final SourceSpan? posterSpan; final VoidCallback? onOpenFailed; final WritersideVideoPlayerHost playerHost; final double? width; @@ -218,6 +221,40 @@ class _BusyMarkWritersideVideoViewState required bool trustedHostedPoster, }) { final colors = BusyMarkSurfaceColors.of(context); + final blocked = + !trustedHostedPoster && + isRemoteImageSource(poster) && + !(MarkdownImagePermissionScope.of( + context, + poster, + widget.posterSpan, + )?.allowed ?? + widget.allowRemoteImages); + final authoredPoster = MarkdownImageView( + source: poster, + sourceSpan: widget.posterSpan, + alt: context.l10n.videoPreview, + activeFilePath: widget.activeFilePath, + workspaceRoot: widget.workspaceRoot, + writersideRoot: widget.writersideRoot, + imagesDir: widget.imagesDir, + allowRemoteImages: widget.allowRemoteImages, + ); + if (blocked) { + return Material( + color: colors.panel, + child: Column( + children: [ + Expanded(child: authoredPoster), + if (target != null) + BusyMarkPushButton.standard( + onPressed: () => _startPlayer(target), + child: Text(context.l10n.openVideo), + ), + ], + ), + ); + } return Material( color: colors.panel, child: InkWell( @@ -237,16 +274,7 @@ class _BusyMarkWritersideVideoViewState _posterFallback(colors), ) else if (poster.isNotEmpty) - MarkdownImageView( - source: poster, - alt: context.l10n.videoPreview, - activeFilePath: widget.activeFilePath, - workspaceRoot: widget.workspaceRoot, - writersideRoot: widget.writersideRoot, - imagesDir: widget.imagesDir, - allowRemoteImages: widget.allowRemoteImages, - onRemoteImageBlocked: widget.onRemoteImageBlocked, - ) + authoredPoster else _posterFallback(colors), Center( diff --git a/lib/src/editor/wysiwyg/writerside_editing_adapter.dart b/lib/src/editor/wysiwyg/writerside_editing_adapter.dart index fdc23ecf..5b3a8734 100644 --- a/lib/src/editor/wysiwyg/writerside_editing_adapter.dart +++ b/lib/src/editor/wysiwyg/writerside_editing_adapter.dart @@ -568,6 +568,7 @@ class WritersideEditingAdapter { attributes: attributes, rawSource: node.rawSource, sourceSpan: node.span, + posterSpan: tag == 'video' ? node.span : null, preserveRaw: !editable || (tag == 'p' && @@ -586,6 +587,7 @@ class WritersideEditingAdapter { kind: BusyInlineKind.image, text: node.attributes['alt'] ?? '', destination: node.attributes['src'], + imageSpan: node.span, attributes: node.attributes, ), ] @@ -698,6 +700,7 @@ class WritersideEditingAdapter { ? '\n' : node.plainText, destination: node.attributes['href'] ?? node.attributes['src'], + imageSpan: kind == BusyInlineKind.image ? node.span : null, children: kind == BusyInlineKind.html ? const [] : inlinesFromNodes(node.children, sourceBindings: sourceBindings), diff --git a/lib/src/editor/wysiwyg/wysiwyg_block_widgets.dart b/lib/src/editor/wysiwyg/wysiwyg_block_widgets.dart index c136599d..0fd09e64 100644 --- a/lib/src/editor/wysiwyg/wysiwyg_block_widgets.dart +++ b/lib/src/editor/wysiwyg/wysiwyg_block_widgets.dart @@ -150,7 +150,6 @@ class BusyMarkWysiwygBlockField extends StatelessWidget { this.writersideRoot, this.imagesDir = 'images', required this.allowRemoteImages, - this.onRemoteImageBlocked, this.onMathDiagnostic, required this.controller, required this.undoController, @@ -206,7 +205,6 @@ class BusyMarkWysiwygBlockField extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; final BusyMarkWysiwygMathDiagnosticCallback? onMathDiagnostic; final BusyMarkWysiwygTextController controller; final UndoHistoryController undoController; @@ -441,12 +439,12 @@ class BusyMarkWysiwygBlockField extends StatelessWidget { return BusyMarkWritersideVideoView( source: source, previewSource: block.attributes['preview-src'], + posterSpan: block.posterSpan, activeFilePath: documentFilePath, workspaceRoot: workspaceRoot, writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, onOpenFailed: () => BusyMarkToastOverlay.maybeShow( context, message: context.l10n.couldNotOpenTarget(source), @@ -480,7 +478,6 @@ class BusyMarkWysiwygBlockField extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, onEdit: _editHtmlBlock, ); } @@ -523,7 +520,6 @@ class BusyMarkWysiwygBlockField extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, ) : readOnly ? SelectableText( @@ -896,7 +892,6 @@ class _RenderedHtmlBlockEditor extends StatelessWidget { required this.writersideRoot, required this.imagesDir, required this.allowRemoteImages, - required this.onRemoteImageBlocked, required this.onEdit, }); @@ -906,7 +901,6 @@ class _RenderedHtmlBlockEditor extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; final VoidCallback onEdit; @override @@ -958,14 +952,28 @@ class _RenderedHtmlBlockEditor extends StatelessWidget { ], ), const SizedBox(height: BusyMarkSpacing.sm), - _RenderedHtmlBlocks( - blocks: block.children, - documentFilePath: documentFilePath, - workspaceRoot: workspaceRoot, - writersideRoot: writersideRoot, - imagesDir: imagesDir, - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, + _RenderedHtmlMedia( + buildImage: (inline) => MarkdownImageView( + source: inline.destination ?? '', + sourceSpan: inline.imageSpan, + alt: inline.text, + activeFilePath: documentFilePath, + workspaceRoot: workspaceRoot, + writersideRoot: writersideRoot, + imagesDir: imagesDir, + allowRemoteImages: allowRemoteImages, + maxWidth: BusyMarkSizes.previewMinWidth, + maxHeight: BusyMarkSizes.previewInlineImageMaxHeight, + preferredHeight: BusyMarkSizes.previewInlineImageHeight, + ), + child: _RenderedHtmlBlocks( + blocks: block.children, + documentFilePath: documentFilePath, + workspaceRoot: workspaceRoot, + writersideRoot: writersideRoot, + imagesDir: imagesDir, + allowRemoteImages: allowRemoteImages, + ), ), ], ), @@ -981,7 +989,6 @@ class _RenderedHtmlBlocks extends StatelessWidget { required this.writersideRoot, required this.imagesDir, required this.allowRemoteImages, - required this.onRemoteImageBlocked, }); final List blocks; @@ -990,7 +997,6 @@ class _RenderedHtmlBlocks extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; @override Widget build(BuildContext context) { @@ -1005,7 +1011,6 @@ class _RenderedHtmlBlocks extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, first: index == 0, ), ], @@ -1021,7 +1026,6 @@ class _RenderedHtmlBlock extends StatelessWidget { required this.writersideRoot, required this.imagesDir, required this.allowRemoteImages, - required this.onRemoteImageBlocked, required this.first, }); @@ -1031,7 +1035,6 @@ class _RenderedHtmlBlock extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; final bool first; @override @@ -1073,13 +1076,13 @@ class _RenderedHtmlBlock extends StatelessWidget { alignment: AlignmentDirectional.centerStart, child: MarkdownImageView( source: _imageSource(block), + sourceSpan: _imageSpan(block.inlines), alt: block.plainText, activeFilePath: documentFilePath, workspaceRoot: workspaceRoot, writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, ), ), ), @@ -1111,7 +1114,6 @@ class _RenderedHtmlBlock extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, ), ), BusyBlockKind.table => _RenderedHtmlTable(block: block, first: first), @@ -1124,7 +1126,6 @@ class _RenderedHtmlBlock extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, first: first, ), BusyBlockKind.thematicBreak => const BusyMarkDocumentThematicBreak(), @@ -1136,7 +1137,6 @@ class _RenderedHtmlBlock extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, first: first, ), BusyBlockKind.htmlBlock => _RenderedHtmlBlocks( @@ -1146,7 +1146,6 @@ class _RenderedHtmlBlock extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, ), _ => Padding( padding: EdgeInsets.only( @@ -1175,7 +1174,6 @@ class _RenderedHtmlFigure extends StatelessWidget { required this.writersideRoot, required this.imagesDir, required this.allowRemoteImages, - required this.onRemoteImageBlocked, required this.first, }); @@ -1185,7 +1183,6 @@ class _RenderedHtmlFigure extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; final bool first; @override @@ -1216,7 +1213,6 @@ class _RenderedHtmlFigure extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, ), if (captionBlocks.isNotEmpty) Padding( @@ -1246,7 +1242,6 @@ class _RenderedHtmlListItem extends StatelessWidget { required this.writersideRoot, required this.imagesDir, required this.allowRemoteImages, - required this.onRemoteImageBlocked, required this.first, }); @@ -1256,7 +1251,6 @@ class _RenderedHtmlListItem extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; final bool first; @override @@ -1295,7 +1289,6 @@ class _RenderedHtmlListItem extends StatelessWidget { writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, ), ), ], @@ -1392,6 +1385,16 @@ class _RenderedHtmlTableCell extends StatelessWidget { } } +class _RenderedHtmlMedia extends InheritedWidget { + const _RenderedHtmlMedia({required this.buildImage, required super.child}); + + final Widget Function(BusyInline) buildImage; + + @override + bool updateShouldNotify(_RenderedHtmlMedia oldWidget) => + buildImage != oldWidget.buildImage; +} + class _RenderedHtmlInlineText extends StatelessWidget { const _RenderedHtmlInlineText({required this.block, this.style}); @@ -1425,27 +1428,16 @@ class _RenderedHtmlInlineText extends StatelessWidget { BusyInline inline, TextStyle? baseStyle, ) { - final colors = BusyMarkSurfaceColors.of(context); final scheme = Theme.of(context).colorScheme; final childBaseStyle = _styleForInline(context, inline, baseStyle); if (inline.kind == BusyInlineKind.image) { - final alt = inline.text.trim().isEmpty ? context.l10n.image : inline.text; return WidgetSpan( alignment: PlaceholderAlignment.middle, child: Padding( padding: const EdgeInsets.symmetric(horizontal: BusyMarkSpacing.xs), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - BusyMarkGlyphs.image, - size: BusyMarkSizes.iconSm, - color: colors.mutedForeground, - ), - const SizedBox(width: BusyMarkSpacing.xs), - Text(alt, style: childBaseStyle), - ], - ), + child: context + .dependOnInheritedWidgetOfExactType<_RenderedHtmlMedia>()! + .buildImage(inline), ), ); } @@ -2830,7 +2822,6 @@ class _ImageBlockEditor extends StatelessWidget { required this.writersideRoot, required this.imagesDir, required this.allowRemoteImages, - required this.onRemoteImageBlocked, }); final BusyBlock block; @@ -2839,7 +2830,6 @@ class _ImageBlockEditor extends StatelessWidget { final String? writersideRoot; final String imagesDir; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; @override Widget build(BuildContext context) { @@ -2849,13 +2839,13 @@ class _ImageBlockEditor extends StatelessWidget { alignment: AlignmentDirectional.centerStart, child: MarkdownImageView( source: source, + sourceSpan: _imageSpan(block.inlines), alt: block.plainText, activeFilePath: documentFilePath, workspaceRoot: workspaceRoot, writersideRoot: writersideRoot, imagesDir: imagesDir, allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, width: width, maxWidth: width ?? BusyMarkSizes.documentImageMaxWidth, ), @@ -2891,3 +2881,11 @@ String? _imageSourceFromInline(BusyInline inline) { } return null; } + +SourceSpan? _imageSpan(List inlines) { + for (final inline in inlines) { + if (inline.kind == BusyInlineKind.image) return inline.imageSpan; + if (_imageSpan(inline.children) case final span?) return span; + } + return null; +} diff --git a/lib/src/editor/wysiwyg/wysiwyg_clipboard_html.dart b/lib/src/editor/wysiwyg/wysiwyg_clipboard_html.dart index 596e3850..f8a589c0 100644 --- a/lib/src/editor/wysiwyg/wysiwyg_clipboard_html.dart +++ b/lib/src/editor/wysiwyg/wysiwyg_clipboard_html.dart @@ -28,6 +28,7 @@ class WysiwygClipboardHtml { WysiwygClipboardFragment? decode( String source, { required MarkdownMode mode, + bool external = true, }) { if (source.length > maxRichClipboardBytes || utf8.encode(source).length > maxRichClipboardBytes) { @@ -42,12 +43,14 @@ class WysiwygClipboardHtml { // Fragment parsing retains leading text that document parsing consumes // before an inferred . Full clipboard documents are accepted too. final body = html.parseFragment(content); - final normalizer = _HtmlNormalizer(); + final normalizer = _HtmlNormalizer(external: external); final clean = dom.Element.tag('div') ..nodes.addAll(normalizer.nodes(body.nodes, 0, const {})); + if (external) _normalizeBrowserParagraphs(clean); var id = 0; - final parsed = const RawHtmlAdapter( + final parsed = RawHtmlAdapter( preserveInlineWhitespace: true, + importClipboardLists: external, ).parseRawHtmlBlock(clean.outerHtml, () => 'clipboard-html-${id++}'); if (parsed == null || !parsed.safe || parsed.blocks.isEmpty) return null; BusyBlock task(BusyBlock block) { @@ -334,6 +337,9 @@ class _HtmlWriter { } class _HtmlNormalizer { + _HtmlNormalizer({required this.external}); + + final bool external; var count = 0; static const _formattingTags = ['strong', 'em', 'u', 'del']; static const _discard = { @@ -354,8 +360,9 @@ class _HtmlNormalizer { List nodes( Iterable input, int depth, - Set styles, - ) { + Set styles, { + bool preformatted = false, + }) { if (depth > maxRawHtmlDepth) { throw const FormatException('Clipboard HTML nesting limit'); } @@ -367,6 +374,10 @@ class _HtmlNormalizer { throw const FormatException('Clipboard HTML node limit'); } if (node is dom.Text) { + if (preformatted) { + out.add(dom.Text(node.data)); + continue; + } bool structural(dom.Node? sibling) => sibling is dom.Element && isSafeBlockHtmlTag(sibling.localName ?? ''); @@ -453,7 +464,13 @@ class _HtmlNormalizer { } } } - final children = nodes(node.nodes, depth + 1, inherited); + final children = nodes( + node.nodes, + depth + 1, + inherited, + preformatted: + preformatted || (external && (tag == 'pre' || tag == 'code')), + ); if (_formattingTags.contains(tag)) tag = 'span'; if (!isSafeHtmlTag(tag)) { out.addAll(children); @@ -465,6 +482,26 @@ class _HtmlNormalizer { if (name == 'style' || name.startsWith('on')) continue; // IDs from another document must not collide with destination anchors. if (name == 'id') continue; + if (external && name == 'class') { + if (tag == 'pre' || tag == 'code') { + final languages = entry.value + .split(RegExp(r'\s+')) + .where( + (name) => + name.startsWith('language-') || name.startsWith('lang-'), + ); + if (languages.isNotEmpty) { + attrs[name] = languages + .map( + (name) => name.startsWith('lang-') + ? 'language-${name.substring(5)}' + : name, + ) + .join(' '); + } + } + continue; + } if (isSafeHtmlUrlAttribute(tag, name, entry.value)) { attrs[name] = entry.value; } @@ -474,7 +511,24 @@ class _HtmlNormalizer { children, sanitizeHtmlAttributes(tag, attrs) ?? const {}, ); - if (tag == 'span' && normalized.attributes.isEmpty) { + if (external && + tag == 'a' && + !_hasImportedAnchorContent(normalized) && + node.querySelector('video, audio, picture') != null) { + if (normalized.attributes['href'] case final destination?) { + final label = + node.attributes['aria-label'] ?? node.attributes['title']; + normalized.nodes.add( + dom.Text( + label == null || label.trim().isEmpty ? destination : label, + ), + ); + } + } + if (external && tag == 'a' && !_hasImportedAnchorContent(normalized)) { + // Keep its spacing and any breaks for the paragraph boundary pass. + out.addAll(normalized.nodes.toList()); + } else if (tag == 'span' && normalized.attributes.isEmpty) { out.addAll(normalized.nodes.toList()); } else if (tag == 'table' && _isLayoutTable(normalized, node)) { // Web pages often use a one-column table to wrap an entire article. @@ -578,3 +632,163 @@ class _HtmlNormalizer { return hasDocumentContent; } } + +// Only line-break runs in paragraph flow are browser spacing. A single break, +// preformatted content, and breaks between words of a link label stay intact. +void _normalizeBrowserParagraphs(dom.Element container) { + // These are real table cells. Layout tables were already unwrapped into + // document containers. Keep the entire cell subtree in its inline form. + final tag = container.localName; + if (tag == 'td' || tag == 'th') return; + const flow = { + 'p', + 'div', + 'article', + 'aside', + 'section', + 'header', + 'footer', + 'main', + 'nav', + 'details', + 'blockquote', + 'li', + }; + for (final child in container.children.toList()) { + if (child.localName != 'pre' && child.localName != 'code') { + _normalizeBrowserParagraphs(child); + } + } + if (!flow.contains(tag)) return; + + // A stream across wrapper boundaries, retaining the original DOM nodes so + // only participating breaks are removed when the wrappers are split. + final tokens = []; + void collect(dom.Node node) { + if (node is! dom.Element || + node.localName == 'br' || + isSafeBlockHtmlTag(node.localName ?? '') || + const {'img', 'video', 'audio', 'code'}.contains(node.localName)) { + tokens.add(node); + return; + } + final start = tokens.length; + for (final child in node.nodes) { + collect(child); + } + if (node.localName == 'a') { + final label = tokens.sublist(start); + final first = label.indexWhere(_hasImportedAnchorContent); + final last = label.lastIndexWhere(_hasImportedAnchorContent); + if (first >= 0) { + tokens.replaceRange(start + first, start + last + 1, [node]); + } + } + } + + for (final node in container.nodes) { + collect(node); + } + final separators = {}; + final run = []; + var breaks = 0; + void finishRun() { + if (breaks >= 2) { + for (final (index, node) in run.indexed) { + separators[node] = index == 0; + } + } + run.clear(); + breaks = 0; + } + + for (final node in tokens) { + if (node is dom.Element && node.localName == 'br') { + run.add(node); + breaks++; + } else if (node is dom.Text && node.data.trim().isEmpty) { + if (run.isNotEmpty) run.add(node); + } else { + finishRun(); + } + } + finishRun(); + if (separators.isEmpty) return; + + final output = []; + var paragraph = []; + void flush() { + if (paragraph.any(_hasImportedAnchorContent) || + paragraph.any((node) => node is dom.Element)) { + output.add( + _element( + 'p', + paragraph, + tag == 'p' ? container.attributes.cast() : const {}, + ), + ); + } + paragraph = []; + } + + final wrapperCopies = {}; + void copy(dom.Node node, List wrappers) { + if (separators[node] case final boundary?) { + if (boundary) flush(); + return; + } + if (node is dom.Element && + !isSafeBlockHtmlTag(node.localName ?? '') && + node.nodes.isNotEmpty && + !const {'code', 'kbd', 'samp'}.contains(node.localName)) { + for (final child in node.nodes) { + copy(child, [...wrappers, node]); + } + return; + } + if (node is dom.Element && + isSafeBlockHtmlTag(node.localName ?? '') && + node.localName != 'img') { + flush(); + output.add(node.clone(true)); + return; + } + var destination = paragraph; + for (final wrapper in wrappers) { + final last = destination.lastOrNull; + if (last is dom.Element && identical(last, wrapperCopies[wrapper])) { + destination = last.nodes; + } else { + final clone = wrapper.clone(false); + wrapperCopies[wrapper] = clone; + destination.add(clone); + destination = clone.nodes; + } + } + destination.add(node.clone(true)); + } + + for (final node in container.nodes) { + copy(node, const []); + } + flush(); + if (tag == 'p') { + final parent = container.parentNode; + if (parent != null) { + final index = parent.nodes.indexOf(container); + parent.nodes.removeAt(index); + parent.nodes.insertAll(index, output); + } + } else { + container.nodes + ..clear() + ..addAll(output); + } +} + +bool _hasImportedAnchorContent(dom.Node node) { + if (node is dom.Text) return node.data.trim().isNotEmpty; + if (node is! dom.Element) return false; + return const {'img', 'video', 'audio', 'source'}.contains(node.localName) || + node.nodes.any(_hasImportedAnchorContent); +} diff --git a/lib/src/editor/wysiwyg/wysiwyg_document_controller.dart b/lib/src/editor/wysiwyg/wysiwyg_document_controller.dart index c4606b42..83f74333 100644 --- a/lib/src/editor/wysiwyg/wysiwyg_document_controller.dart +++ b/lib/src/editor/wysiwyg/wysiwyg_document_controller.dart @@ -1,6 +1,7 @@ import '../../writerside/writerside_property_validation.dart'; import 'dart:convert'; import '../../core/source_span.dart'; +import '../../core/uri_utils.dart'; import 'package:flutter/foundation.dart'; import '../../core/path_utils.dart'; @@ -197,9 +198,25 @@ class BusyMarkWysiwygDocumentController extends ChangeNotifier { rebased = rebased.copyWith(blocks: rebased.blocks.map(commit).toList()); _document = busyMarkWysiwygBindMarkdownReferences(rebased); + } else if (_hasRemoteImages()) { + _document = const MarkdownParser().rebindImageSpans(_document, source); } } + bool _hasRemoteImages() { + bool hasImage(BusyInline inline) => + (inline.kind == BusyInlineKind.image && + isRemoteImageSource(inline.destination)) || + inline.children.any(hasImage); + + return _flattenBlocks(_document.blocks).any( + (block) => + (block.kind == BusyBlockKind.image && + isRemoteImageSource(block.attributes['src'])) || + block.inlines.any(hasImage), + ); + } + BusyDocument _reparseNativeListOwnership(String source) { final parsed = busyMarkWysiwygBindMarkdownReferences( const MarkdownParser() diff --git a/lib/src/editor/wysiwyg/wysiwyg_editor.dart b/lib/src/editor/wysiwyg/wysiwyg_editor.dart index d80e3cf4..51b24081 100644 --- a/lib/src/editor/wysiwyg/wysiwyg_editor.dart +++ b/lib/src/editor/wysiwyg/wysiwyg_editor.dart @@ -1,3 +1,4 @@ +import '../markdown_image_permission_scope.dart'; import '../document_edit_history.dart'; import '../../app/command_shortcuts.dart'; import 'package:flutter/foundation.dart' show listEquals; @@ -42,7 +43,6 @@ import '../../markdown/document_outline.dart'; import '../../markdown/markdown_model.dart'; import '../../markdown/markdown_parser.dart'; import '../../markdown/markdown_source_structure.dart'; -import '../../platform/linux_header_bar_service.dart'; import '../../platform/rich_clipboard_service.dart'; import '../../spellcheck/spelling_projection.dart'; import '../../spellcheck/spelling_replacement.dart'; @@ -67,11 +67,8 @@ import 'wysiwyg_inline_controller.dart'; import 'wysiwyg_session_state.dart'; import 'wysiwyg_toolbar.dart'; import 'writerside_editing_adapter.dart'; -import 'writerside_inspector_target.dart'; -import 'writerside_properties.dart'; -import 'writerside_property_session.dart'; +import 'writerside_properties.dart' show writersideElementLabel; import '../../writerside/writerside_project.dart'; -import '../../writerside/writerside_source_loader.dart'; typedef BusyMarkWysiwygSourceChanged = void Function(String filePath, String source); @@ -123,7 +120,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { this.spellingAnnotations = const [], this.onCheckSpelling, this.readSpellingMenuItems, - this.useExternalUndoHistory = false, this.onDocumentChanged, this.workspaceRoot, this.writersideRoot, @@ -137,7 +133,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { this.onAssetSaveRequired, this.onChooseLink, this.allowRemoteImages = false, - this.onRemoteImageBlocked, this.toolbarPlacement = EditorToolbarPlacement.topLeft, this.toolbarDirection = EditorToolbarDirection.horizontal, this.onToolbarPlacementChanged, @@ -155,7 +150,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { this.readEditBase, this.readSessionState, this.undoClock, - this.headerBarService, this.documentLayout, this.visualizationRevision = 0, this.onAiEdit, @@ -190,7 +184,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { final List spellingAnnotations; final VoidCallback? onCheckSpelling; final BusyMarkWysiwygSpellingMenuReader? readSpellingMenuItems; - final bool useExternalUndoHistory; final ValueChanged? onDocumentChanged; final String? workspaceRoot; final String? writersideRoot; @@ -204,7 +197,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { final VoidCallback? onAssetSaveRequired; final Future Function(String initial)? onChooseLink; final bool allowRemoteImages; - final VoidCallback? onRemoteImageBlocked; final EditorToolbarPlacement toolbarPlacement; final EditorToolbarDirection toolbarDirection; final ValueChanged? onToolbarPlacementChanged; @@ -222,7 +214,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { final DocumentEditBaseReader? readEditBase; final WysiwygEditorSessionState Function()? readSessionState; final DocumentUndoClock? undoClock; - final LinuxHeaderBarService? headerBarService; final BusyMarkDocumentLayoutSpec? documentLayout; final int visualizationRevision; final BusyMarkAiEditCallback? onAiEdit; @@ -233,8 +224,6 @@ class BusyMarkWysiwygEditor extends StatefulWidget { } class BusyMarkWysiwygEditorState extends State { - static const _historyLimit = 100; - late final BusyMarkWysiwygDocumentController _documentController; final _textControllers = {}; final _textUndoControllers = {}; @@ -247,8 +236,6 @@ class BusyMarkWysiwygEditorState extends State { final _tableCellSpellingEditableKeys = {}; StreamSubscription>? _assetDropSubscription; final _blockKeys = {}; - final _undoStack = []; - final _redoStack = []; final _itemScrollController = ItemScrollController(); final _itemPositionsListener = ItemPositionsListener.create(); ScrollPosition? get _documentScrollPosition { @@ -274,11 +261,6 @@ class BusyMarkWysiwygEditorState extends State { late final FocusNode _selectionFocusNode; String? _activeBlockId; String? _propertiesTargetId; - BusyInlineStyleRange? _propertiesInlineTarget; - String? _videoDraftTarget; - bool _propertiesVisible = false; - bool _propertiesExplicitlyOpened = false; - final _propertySession = WritersidePropertySession(); String? _lastInspectorSelection; bool _inspectorRestorePending = false; final _propertyHoverViewportKey = GlobalKey(); @@ -309,9 +291,6 @@ class BusyMarkWysiwygEditorState extends State { _propertyHoverCapture; String? _propertyHoverScope; bool _propertyMarginHovered = false; - BusyDocument? _propertiesSnapshot; - String? _propertiesSnapshotTarget; - bool _topicPropertiesSelected = false; String? _activeCellId; final _collapsibleExpansion = {}; late final DocumentUndoGrouping _undoGrouping; @@ -361,9 +340,6 @@ class BusyMarkWysiwygEditorState extends State { @visibleForTesting int get debugUndoControllerCount => _textUndoControllers.length; - @visibleForTesting - int get debugUndoSnapshotCount => _undoStack.length; - /// Generation that projection adapters must capture for rich targets. int get spellingDocumentGeneration => _documentGeneration; @@ -549,7 +525,7 @@ class BusyMarkWysiwygEditorState extends State { } final beforeSession = _captureSessionState(); _continuousTextEdit = null; - final beforeDocument = _historySnapshot(); + _reportLiveHistorySession(); final changed = switch (target) { SpellingRichBlockTarget(:final blockId) => _documentController.replaceSpellingInBlock( @@ -571,7 +547,6 @@ class BusyMarkWysiwygEditorState extends State { _ => false, }; if (!changed) return false; - _recordUndoSnapshot(beforeDocument); _clearBlockSelection(); if (target is SpellingRichTableCellTarget) { @@ -691,12 +666,9 @@ class BusyMarkWysiwygEditorState extends State { (incomingAuthority && !acknowledged && (sourceChanged || revisionChanged))) { - // Pending property text belongs to the current authored element. An - // external replacement can reuse a projection ID for a different node. - // Recreate the panel entries rather than retargeting their drafts. + // An external replacement can reuse a projection ID for a different + // authored element; discard the previous inspection target. _propertiesTargetId = null; - _videoDraftTarget = null; - _topicPropertiesSelected = false; _releaseSelectionDrag(rebuild: false); _pendingTextFocus = null; _hasReportedVisibleHeading = false; @@ -705,8 +677,6 @@ class BusyMarkWysiwygEditorState extends State { callback: oldWidget.onSessionChanged, documentId: oldDocumentId, ); - _undoStack.clear(); - _redoStack.clear(); _resetPerDocumentState(); } _continuousTextEdit = null; @@ -763,7 +733,6 @@ class BusyMarkWysiwygEditorState extends State { for (final focusNode in _tableCellFocusNodes.values) { focusNode.dispose(); } - _propertySession.dispose(); _selectionFocusNode.dispose(); super.dispose(); } @@ -772,8 +741,6 @@ class BusyMarkWysiwygEditorState extends State { _inputSelections.clear(); _lastInspectorSelection = null; _propertiesTargetId = null; - _videoDraftTarget = null; - _topicPropertiesSelected = false; for (final controller in _textControllers.values) { controller.dispose(); } @@ -909,7 +876,7 @@ class BusyMarkWysiwygEditorState extends State { } } final selectedBlockIds = _fullySelectedBlockIds(blocks); - return BusyMarkCommandShortcuts( + final editor = BusyMarkCommandShortcuts( isComposing: () => _hasActiveClipboardComposition, shortcuts: { ...commandRegistry.blockedDefaultIntents(const { @@ -1059,16 +1026,6 @@ class BusyMarkWysiwygEditorState extends State { : null; _viewportWidth = constraints.maxWidth; final documentLayout = _documentLayout; - final showProperties = - _documentController.document.isWriterside && - _propertiesVisible && - (constraints.maxWidth >= 900 || - _propertiesExplicitlyOpened) && - widget.onInspectElement == null; - final paneWidth = showProperties && constraints.maxWidth >= 900 - ? 300.0 - : 0.0; - const paneHeight = 0.0; final editor = Stack( key: _propertyHoverViewportKey, children: [ @@ -1164,11 +1121,11 @@ class BusyMarkWysiwygEditorState extends State { visible: _toolbarVisible, maxWidth: math.max( 0, - constraints.maxWidth - paneWidth - BusyMarkSpacing.lg, + constraints.maxWidth - BusyMarkSpacing.lg, ), maxHeight: math.max( 0, - constraints.maxHeight - paneHeight - BusyMarkSpacing.lg, + constraints.maxHeight - BusyMarkSpacing.lg, ), onToggle: () => setState(() => _toolbarVisible = !_toolbarVisible), @@ -1277,266 +1234,17 @@ class BusyMarkWysiwygEditorState extends State { ), ], ); - if (!showProperties) return editor; - final panel = _writersidePropertiesPanel(); - return paneWidth > 0 - ? Row( - children: [ - Expanded(child: editor), - SizedBox(width: paneWidth, child: panel), - ], - ) - : Stack( - children: [ - Positioned.fill(child: editor), - PositionedDirectional( - top: 0, - bottom: 0, - end: 0, - width: math.min(300, constraints.maxWidth), - child: Material(elevation: 8, child: panel), - ), - ], - ); + return editor; }, ), ), ), ); - } - - Widget _writersidePropertiesPanel() { - if (!_propertySession.hasPending) { - final previous = _propertiesSnapshot; - final currentDocument = _documentController.document; - if (previous != null && - previous.source != currentDocument.source && - _propertiesSnapshotTarget == _propertiesTargetId && - _propertiesTargetId != null) { - final captured = WritersideInspectorTarget.fromSelection( - bufferId: _documentId, - revision: 0, - source: previous.source ?? '', - document: previous, - blockId: _propertiesTargetId, - inline: _propertiesInlineTarget, - ); - final refreshed = captured.refreshUnchangedElement( - revision: _documentGeneration, - source: _documentController.markdown, - document: currentDocument, - ); - _propertiesTargetId = refreshed?.block?.id; - _propertiesInlineTarget = refreshed?.inline; - } - _propertiesSnapshot = _documentController.document; - _propertiesSnapshotTarget = _propertiesTargetId; - } - final document = _propertiesSnapshot ?? _documentController.document; - final snapshot = BusyMarkWysiwygDocumentController(document: document); - final inspected = _topicPropertiesSelected - ? document.blocks - .where( - (b) => - b.attributes['element'] == 'topic' || - b.kind == BusyBlockKind.heading && - b.attributes['level'] == '1' && - !b.attributes.containsKey('element'), - ) - .firstOrNull - ?.id - : _propertiesSnapshotTarget; - final path = inspected == null - ? const [] - : snapshot.elementPath(inspected); - final target = inspected == null ? null : snapshot.blockById(inspected); - snapshot.dispose(); - final guard = _captureDialogTarget(); - final id = _documentId; - bool current() => - id == _documentId && - _isDialogTargetCurrent(guard) && - (target == null || - identical(_documentController.blockById(target.id), target)); - bool commit(bool Function() mutate) { - if (!current()) { - return _propertySession.reject(WritersidePropertyRejection.stale); - } - if (DocumentReadOnlyScope.of(context)) { - return _propertySession.reject(WritersidePropertyRejection.readOnly); - } - final before = _historySnapshot(); - final previous = _documentController.markdown; - if (!mutate()) return false; - final oldInline = _propertiesInlineTarget; - if (oldInline != null && target != null) { - final updated = _documentController.blockById(target.id); - _propertiesInlineTarget = updated == null - ? null - : busyInlineReferenceRanges(updated.inlines) - .where( - (r) => - r.kind == oldInline.kind && - r.referenceIndex == oldInline.referenceIndex, - ) - .singleOrNull; - } - if (_documentController.markdown == previous) return true; - _recordUndoSnapshot(before); - _emitMarkdown(); - return true; - } - - final inlineTarget = _propertiesInlineTarget; - return BusyMarkWritersideProperties( - key: ValueKey('writerside-properties-$_documentId'), - documentIdentity: _documentId, - effectiveProperties: WritersideEffectiveProperties( - settings: widget.writersideSettings, - ), - session: _propertySession, - onUndo: () { - _traverseDocumentHistory(redo: false); - }, - onRedo: () { - _traverseDocumentHistory(redo: true); - }, - onChooseCodeSource: () async { - final guard = _captureDialogTarget(); - final module = widget - .writersideProjectIndex - ?.modulesById[widget.writersideModuleId]; - final root = - module?.rootPath ?? widget.writersideRoot ?? widget.workspaceRoot; - if (root == null) { - _propertySession.reject(WritersidePropertyRejection.unresolved); - return null; - } - final selected = await openFile( - initialDirectory: module?.config.snippetsDir == null - ? p.dirname(document.filePath) - : p.join(root, module!.config.snippetsDir!), - confirmButtonText: context.l10n.open, - ); - if (!_isDialogTargetCurrent(guard) || selected == null) return null; - final reference = await const WritersideSourceLoader().referenceForFile( - selectedPath: selected.path, - documentPath: document.filePath, - workspaceRoot: root, - snippetsDirectory: module?.config.snippetsDir, - ); - if (!_isDialogTargetCurrent(guard)) return null; - if (reference == null) { - _propertySession.reject(WritersidePropertyRejection.unresolved); - } - return reference; - }, - document: document, - path: path, - target: target, - topicSelected: _topicPropertiesSelected, - onClose: () => setState(() { - _propertiesVisible = false; - _videoDraftTarget = null; - }), - onTargetSelected: (value) => setState(() { - _topicPropertiesSelected = value == '@topic'; - _propertiesTargetId = _topicPropertiesSelected ? null : value; - _propertiesInlineTarget = null; - _videoDraftTarget = null; - }), - onProperty: (name, value) => commit(() { - if (target == null) return false; - if (name == 'admonition-type') { - final style = busyAdmonitionStyleFromName(value); - if (style == null || - !busyMarkWysiwygCanApplyAdmonitionStyle(target)) { - return false; - } - _documentController.applyAdmonitionStyle(target.id, style); - return true; - } - return _documentController.updateWritersideProperty( - target.id, - name, - value, - ); - }), - onHeadingText: (value) => commit(() { - if (target == null || - value.trim().isEmpty || - target.plainText == value) { - return false; - } - _documentController.updateBlockText(target.id, value); - return true; - }), - onNavigation: (present, forElements, depth) => commit( - () => _documentController.setTopicNavigation( - present: present, - forElements: forElements, - depth: depth, - ), - ), - onTopicProperty: (name, value) => commit( - () => name == '@navigation' - ? value == 'default' - ? _documentController.resetTopicNavigation() - : value == 'none' - ? _documentController.updateTopicNavigation('for', 'none') - : _documentController.resetTopicNavigation() && - _documentController.updateTopicNavigation('for', '') - : name == 'switcher-label' - ? _documentController.updateTopicSwitcherLabel(value) - : _documentController.updateTopicNavigation(name, value), - ), - onManageItem: (itemId, direction, remove) => commit( - () => - target != null && - _documentController.manageWritersideItem( - target.id, - itemId: itemId, - direction: direction, - remove: remove, - title: target.attributes['element'] == 'tabs' - ? context.l10n.tab - : context.l10n.wsTerm, - ), - ), - inlineTarget: inlineTarget, - onInlineProperty: (name, value) => commit( - () => - target != null && - inlineTarget != null && - _documentController.updateInlineReference( - target.id, - inlineTarget, - name, - value, - ), - ), - videoDraft: _videoDraftTarget != null, - onInsertVideo: (value) => commit(() { - final draft = _videoDraftTarget; - if (draft == null || - !value.trim().isNotEmpty || - !_documentController.canInsertWriterside( - BusyWritersideInsertCommand.video, - draft, - )) { - return false; - } - final inserted = _documentController.insertWriterside( - BusyWritersideInsertCommand.video, - draft, - title: context.l10n.video, - attributes: {'src': value.trim()}, - ); - if (inserted == null) return false; - _videoDraftTarget = null; - _propertiesTargetId = inserted; - return true; - }), + return MarkdownImageProjection( + source: + _documentController.document.imageSource ?? + _documentController.document.source, + child: editor, ); } @@ -1565,10 +1273,6 @@ class BusyMarkWysiwygEditorState extends State { var attributes = {}; if (command == BusyWritersideInsertCommand.video) { setState(() { - _videoDraftTarget = blockId; - _propertiesVisible = true; - _propertiesExplicitlyOpened = true; - _topicPropertiesSelected = false; _propertiesTargetId = blockId; }); widget.onVideoPropertiesRequested?.call( @@ -1637,20 +1341,19 @@ class BusyMarkWysiwygEditorState extends State { ], ); if (name == null || !current()) return; - final before = _historySnapshot(); + _reportLiveHistorySession(); _documentController.insertVariableReference( blockId, name, selection?.isValid == true ? selection!.start : target.plainText.length, selection?.isValid == true ? selection!.end : target.plainText.length, ); - _recordUndoSnapshot(before); _emitMarkdown(); _restoreEditingFocusAfterFrame(); return; } if (!current() || !mounted) return; - final before = _historySnapshot(); + _reportLiveHistorySession(); final inserted = _documentController.insertWriterside( command, blockId, @@ -1658,12 +1361,8 @@ class BusyMarkWysiwygEditorState extends State { attributes: attributes, ); if (inserted == null) return; - _recordUndoSnapshot(before); _emitMarkdown(); setState(() { - _propertiesVisible = true; - _propertiesExplicitlyOpened = true; - _topicPropertiesSelected = false; _propertiesTargetId = inserted; }); final block = _documentController.blockById(inserted); @@ -1977,16 +1676,8 @@ class BusyMarkWysiwygEditorState extends State { )) { return; } - if (widget.onInspectElement == null && - !_propertySession.transition()) { - return; - } setState(() { _propertiesTargetId = capture.block.id; - _propertiesInlineTarget = null; - _propertiesVisible = widget.onInspectElement == null; - _propertiesExplicitlyOpened = true; - _topicPropertiesSelected = false; }); _publishInspectorTarget( explicit: true, @@ -2255,7 +1946,6 @@ class BusyMarkWysiwygEditorState extends State { writersideRoot: widget.writersideRoot, imagesDir: widget.imagesDir, allowRemoteImages: widget.allowRemoteImages, - onRemoteImageBlocked: widget.onRemoteImageBlocked, onMathDiagnostic: widget.onMathDiagnostic, controller: _textControllerFor(block), undoController: _textUndoControllerFor(block), @@ -2862,6 +2552,11 @@ class BusyMarkWysiwygEditorState extends State { FocusNode node, KeyEvent event, ) { + // The selection node is also an ancestor of interactive block content. + // Its editing keys belong to the selection input when that input owns focus. + if (identical(node, _selectionFocusNode) && !node.hasPrimaryFocus) { + return KeyEventResult.ignored; + } final key = event.logicalKey; if (_hasDocumentInputComposition && (key == LogicalKeyboardKey.backspace || @@ -2911,113 +2606,6 @@ class BusyMarkWysiwygEditorState extends State { _selectionPointer == null; } - BusyDocument _historySnapshot() { - _reportLiveHistorySession(); - final markdown = _documentController.markdown; - return _documentController.document.copyWith( - blocks: [ - for (final block in _documentController.document.blocks) - _historyBlockSnapshot(block), - ], - source: markdown, - ); - } - - BusyBlock _historyBlockSnapshot(BusyBlock block) { - return BusyBlock( - id: block.id, - kind: block.kind, - inlines: block.inlines, - children: [ - for (final child in block.children) _historyBlockSnapshot(child), - ], - attributes: block.attributes, - rawSource: block.rawSource, - preserveRaw: block.preserveRaw, - isSourceOnly: block.isSourceOnly, - isGenerated: block.isGenerated, - isSourceProtected: block.isSourceProtected, - dirty: block.dirty, - ); - } - - void _recordUndoSnapshot([BusyDocument? previousDocument]) { - if (widget.useExternalUndoHistory) { - if (previousDocument == null) _reportLiveHistorySession(); - return; - } - final snapshot = previousDocument ?? _historySnapshot(); - if (_undoStack.isNotEmpty && _undoStack.last.source == snapshot.source) { - return; - } - _undoStack.add(snapshot); - if (_undoStack.length > _historyLimit) { - _undoStack.removeAt(0); - } - _redoStack.clear(); - } - - bool _undoEditorChange() { - final filePath = _documentController.document.filePath; - final current = _historySnapshot(); - while (_undoStack.isNotEmpty) { - final previous = _undoStack.removeLast(); - if (previous.filePath != filePath) { - continue; - } - if (current.source != previous.source) { - _redoStack.add(current); - } - _restoreEditorSnapshot(previous); - return true; - } - return false; - } - - bool _redoEditorChange() { - final filePath = _documentController.document.filePath; - final current = _historySnapshot(); - while (_redoStack.isNotEmpty) { - final next = _redoStack.removeLast(); - if (next.filePath != filePath) { - continue; - } - if (current.source != next.source) { - _undoStack.add(current); - } - _restoreEditorSnapshot(next); - return true; - } - return false; - } - - void _restoreEditorSnapshot(BusyDocument snapshot) { - final activeId = _activeBlockId; - final activePath = _documentController.elementPath(activeId ?? ''); - final selection = _textControllers[activeId]?.selection; - _clearBlockSelection(); - _documentController.replaceDocument(snapshot); - // A structural operation can move text into a new child. When Undo removes - // that child, recover the closest surviving owner from this actual model - // path rather than moving the caret to the document's first heading. - _activeBlockId = _documentController.blockById(activeId ?? '') != null - ? activeId - : activePath.reversed - .where((b) => _documentController.blockById(b.id) != null) - .firstOrNull - ?.id; - _emitMarkdown(); - WidgetsBinding.instance.addPostFrameCallback((_) { - if (mounted) { - _focusActiveOrFirstBlock( - initialSelectionOffset: selection?.isValid == true - ? selection!.extentOffset - : null, - ); - } - }); - } - void _handleBlockFocused(String blockId) { if (_selectionPointer != null && _hasBlockSelection) { _selectionFocusNode.requestFocus(); @@ -3062,9 +2650,6 @@ class BusyMarkWysiwygEditorState extends State { return; } final controller = _textControllers[blockId]; - final undoSnapshot = widget.useExternalUndoHistory - ? null - : _historySnapshot(); _reportTextHistorySession(blockId, _inputSelections[blockId]); final undoGroup = origin == _WysiwygTextEditOrigin.paste ? null @@ -3085,7 +2670,6 @@ class BusyMarkWysiwygEditorState extends State { if (currentBlock != null && busyMarkWysiwygBlockContainsMath(currentBlock)) { _documentController.updateMathSource(blockId, value); - if (undoSnapshot != null) _recordUndoSnapshot(undoSnapshot); _emitMarkdown(undoGroup: undoGroup, reportEditingSession: true); return; } @@ -3113,7 +2697,6 @@ class BusyMarkWysiwygEditorState extends State { previousSelection.end == oldText.length, ); if (splitResult != null) { - if (undoSnapshot != null) _recordUndoSnapshot(undoSnapshot); _emitMarkdown(undoGroup: undoGroup); _focusBlockAfterFrame(splitResult.blockId, offset: splitResult.offset); return; @@ -3136,7 +2719,6 @@ class BusyMarkWysiwygEditorState extends State { preserveTextWhitespace: origin == _WysiwygTextEditOrigin.paste, normalizePastedFormatting: origin == _WysiwygTextEditOrigin.paste, ); - if (undoSnapshot != null) _recordUndoSnapshot(undoSnapshot); if (controller != null) _rememberModelTextSelection(blockId, controller); if (value.isNotEmpty) { _pendingInlineKindsByBlockId.remove(blockId); @@ -3228,9 +2810,6 @@ class BusyMarkWysiwygEditorState extends State { return; } final previousSelection = _inputSelections[cellId]; - final undoSnapshot = widget.useExternalUndoHistory - ? null - : _historySnapshot(); _reportTextHistorySession(cellId, previousSelection); if (markdownSource) { _documentController.updateTableCellMarkdownSource( @@ -3241,7 +2820,6 @@ class BusyMarkWysiwygEditorState extends State { } else { _documentController.updateTableCellText(tableBlockId, cellId, accepted); } - if (undoSnapshot != null) _recordUndoSnapshot(undoSnapshot); _emitMarkdown( reportEditingSession: true, undoGroup: _undoGroupForTextEdit( @@ -3278,7 +2856,7 @@ class BusyMarkWysiwygEditorState extends State { }) { _clearBlockSelection(); _setActiveBlock(tableBlockId); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.insertTableRow(tableBlockId, rowIndex, after: after); _emitMarkdown(); } @@ -3286,7 +2864,7 @@ class BusyMarkWysiwygEditorState extends State { void _handleTableRowDeleted(String tableBlockId, int rowIndex) { _clearBlockSelection(); _setActiveBlock(tableBlockId); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.deleteTableRow(tableBlockId, rowIndex); _emitMarkdown(); } @@ -3298,7 +2876,7 @@ class BusyMarkWysiwygEditorState extends State { }) { _clearBlockSelection(); _setActiveBlock(tableBlockId); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.insertTableColumn( tableBlockId, columnIndex, @@ -3310,7 +2888,7 @@ class BusyMarkWysiwygEditorState extends State { void _handleTableColumnDeleted(String tableBlockId, int columnIndex) { _clearBlockSelection(); _setActiveBlock(tableBlockId); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.deleteTableColumn(tableBlockId, columnIndex); _emitMarkdown(); } @@ -3322,7 +2900,7 @@ class BusyMarkWysiwygEditorState extends State { ) { _clearBlockSelection(); _setActiveBlock(tableBlockId); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.setTableColumnAlignment( tableBlockId, columnIndex, @@ -3333,7 +2911,7 @@ class BusyMarkWysiwygEditorState extends State { void _handleTableDeleted(String tableBlockId) { _clearBlockSelection(); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.deleteTable(tableBlockId); _emitMarkdown(); } @@ -3364,7 +2942,7 @@ class BusyMarkWysiwygEditorState extends State { await assets.rollbackAll(); return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyImageBlock( blockId, source: result.source, @@ -3390,7 +2968,7 @@ class BusyMarkWysiwygEditorState extends State { if (!_isDialogTargetCurrent(target) || source == null) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.updateRawHtmlBlock(blockId, source); _emitMarkdown(); } @@ -3776,7 +3354,6 @@ class BusyMarkWysiwygEditorState extends State { .firstOrNull; } } - if (explicit) _propertiesInlineTarget = inline; widget.onInspectElement?.call( _documentController.document, targetId, @@ -3790,16 +3367,13 @@ class BusyMarkWysiwygEditorState extends State { void restoreEditingFocus() => _restoreEditingFocusAfterFrame(); + void focusNewDocument() => + _focusActiveOrFirstBlock(initialSelectionOffset: 0); + void inspectCurrentSelection() { if (!_documentController.document.isWriterside) return; - if (widget.onInspectElement == null && !_propertySession.transition()) { - return; - } setState(() { _propertiesTargetId = _activeBlockId; - _propertiesVisible = widget.onInspectElement == null; - _propertiesExplicitlyOpened = true; - _topicPropertiesSelected = false; }); _publishInspectorTarget(explicit: true); } @@ -3828,9 +3402,6 @@ class BusyMarkWysiwygEditorState extends State { } void _reportTextHistorySession(String targetId, TextSelection? selection) { - if (!widget.useExternalUndoHistory) { - return; - } if (selection?.isValid != true || !mounted || DocumentReadOnlyScope.of(context)) { @@ -3862,8 +3433,7 @@ class BusyMarkWysiwygEditorState extends State { } void _reportLiveHistorySession() { - if (!widget.useExternalUndoHistory || - _pendingTextFocus != null || + if (_pendingTextFocus != null || !mounted || DocumentReadOnlyScope.of(context) || SchedulerBinding.instance.schedulerPhase == @@ -4780,7 +4350,7 @@ class BusyMarkWysiwygEditorState extends State { .clamp(start, controller.text.length) .toInt(); final activeInlineKinds = _activeInlineKindsAt(blockId, start); - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.applyEnterAt( blockId, start, @@ -4789,7 +4359,6 @@ class BusyMarkWysiwygEditorState extends State { if (result == null) { return KeyEventResult.handled; } - _recordUndoSnapshot(undoSnapshot); if (_documentController.blockText(result.blockId).isEmpty) { _setPendingInlineKinds(result.blockId, activeInlineKinds); } @@ -4818,12 +4387,11 @@ class BusyMarkWysiwygEditorState extends State { : LogicalKeyboardKey.arrowRight; if (key == LogicalKeyboardKey.enter) { final activeInlineKinds = _activeInlineKindsAt(blockId, offset); - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.applyEnterAt(blockId, offset); if (result == null) { return KeyEventResult.handled; } - _recordUndoSnapshot(undoSnapshot); if (_documentController.blockText(result.blockId).isEmpty) { _setPendingInlineKinds(result.blockId, activeInlineKinds); } @@ -4832,12 +4400,11 @@ class BusyMarkWysiwygEditorState extends State { return KeyEventResult.handled; } if (key == LogicalKeyboardKey.backspace && offset == 0) { - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.applyBackspaceAtStart(blockId); if (result == null) { return KeyEventResult.ignored; } - _recordUndoSnapshot(undoSnapshot); _emitMarkdown(); _focusBlockAfterFrame(result.blockId, offset: result.offset); return KeyEventResult.handled; @@ -5003,7 +4570,7 @@ class BusyMarkWysiwygEditorState extends State { } _clearBlockSelection(); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.insertTableRow( tableBlockId, table.children.length - 1, @@ -5889,7 +5456,7 @@ class BusyMarkWysiwygEditorState extends State { return; } if (selectedBlocks.isNotEmpty) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyBlockCommandToBlocks( selectedBlocks.map((block) => block.id), command, @@ -5903,7 +5470,7 @@ class BusyMarkWysiwygEditorState extends State { return; } if (command == BusyWysiwygBlockCommand.thematicBreak) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); final nextBlockId = _documentController.insertThematicBreakAfter(blockId); _emitMarkdown(); if (nextBlockId != null) { @@ -5911,7 +5478,7 @@ class BusyMarkWysiwygEditorState extends State { } return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyBlockCommand(blockId, command); _emitMarkdown(); } @@ -5955,7 +5522,7 @@ class BusyMarkWysiwygEditorState extends State { return; } if (selectedBlocks.isNotEmpty) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyAdmonitionStyleToBlocks( selectedBlocks .map((block) => _documentController.admonitionTargetId(block.id)) @@ -5972,7 +5539,7 @@ class BusyMarkWysiwygEditorState extends State { if (blockId == null) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyAdmonitionStyle( _documentController.admonitionTargetId(blockId), style, @@ -5985,7 +5552,7 @@ class BusyMarkWysiwygEditorState extends State { void _applyInlineCommand(BusyWysiwygInlineCommand command) { final selectedRanges = _selectedTextRanges(); if (selectedRanges.isNotEmpty) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); for (final range in selectedRanges) { _documentController.applyInlineCommand( range.block.id, @@ -6013,7 +5580,7 @@ class BusyMarkWysiwygEditorState extends State { } return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyInlineCommand( blockId, command, @@ -6087,7 +5654,7 @@ class BusyMarkWysiwygEditorState extends State { } // The existing text mutation and semantic wrapping serialize and escape the // element for both document formats. One snapshot covers the whole insert. - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.updateBlockText( target.targetId, original.replaceRange(selection.start, selection.end, inserted), @@ -6438,7 +6005,7 @@ class BusyMarkWysiwygEditorState extends State { destination.href.trim().isEmpty) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); for (final range in rangesToApply) { _documentController.applyInlineCommand( range.block.id, @@ -6497,7 +6064,7 @@ class BusyMarkWysiwygEditorState extends State { destination.href.trim().isEmpty) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyInlineCommand( blockId, BusyWysiwygInlineCommand.link, @@ -6572,7 +6139,7 @@ class BusyMarkWysiwygEditorState extends State { final currentBlock = _documentController.blockById(blockId); if (currentBlock != null && !busyMarkWysiwygBlockContainsMath(currentBlock)) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); final insertion = _documentController.insertInlineMath( blockId, start, @@ -6596,7 +6163,7 @@ class BusyMarkWysiwygEditorState extends State { if (insertion == null) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); controller.value = TextEditingValue( text: insertion.source, selection: TextSelection( @@ -6615,7 +6182,7 @@ class BusyMarkWysiwygEditorState extends State { if (blockId == null) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); final mathId = _documentController.insertDisplayMathAfter(blockId); if (mathId == null) { return; @@ -6654,7 +6221,7 @@ class BusyMarkWysiwygEditorState extends State { await assets.rollbackAll(); return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.applyImageBlock( blockId, source: result.source, @@ -7009,7 +6576,7 @@ class BusyMarkWysiwygEditorState extends State { edit.end, edit.replacement, ); - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final destination = _documentController.updateMathSource( blockId, updatedSource, @@ -7018,13 +6585,12 @@ class BusyMarkWysiwygEditorState extends State { ); if (destination == null) return false; _continuousTextEdit = null; - _recordUndoSnapshot(undoSnapshot); _clearBlockSelection(collapseFields: false); _emitMarkdown(); _focusBlockAfterFrame(destination.blockId, offset: destination.offset); return true; } - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.insertStyledBlocksAtSelection( blockId: blockId, selectionStart: start, @@ -7036,7 +6602,6 @@ class BusyMarkWysiwygEditorState extends State { return false; } _continuousTextEdit = null; - _recordUndoSnapshot(undoSnapshot); _clearBlockSelection(collapseFields: false); _emitMarkdown(); _focusBlockAfterFrame(result.blockId, offset: result.offset); @@ -7121,7 +6686,7 @@ class BusyMarkWysiwygEditorState extends State { .clamp(start, controller.text.length) .toInt(); if (styledBlocks != null && !busyMarkWysiwygBlockContainsMath(cell)) { - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final offset = _documentController.insertStyledInlinesInTableCell( tableBlockId: tableId, cellId: cellId, @@ -7133,7 +6698,6 @@ class BusyMarkWysiwygEditorState extends State { if (origin == _WysiwygTextEditOrigin.paste) { _continuousTextEdit = null; } - _recordUndoSnapshot(undoSnapshot); _emitMarkdown(); _focusTextTargetAfterFrame(cellId, offset: offset); return true; @@ -7147,7 +6711,7 @@ class BusyMarkWysiwygEditorState extends State { if (origin == _WysiwygTextEditOrigin.paste) { _continuousTextEdit = null; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _updateTableCellFromControllerText(tableId, cellId, nextText); _emitMarkdown(); _focusTextTargetAfterFrame( @@ -7161,6 +6725,12 @@ class BusyMarkWysiwygEditorState extends State { if (_hasBlockSelection) { return _replaceDocumentSelectionWithText('\t'); } + final block = _documentController.blockById(blockId); + if (block == null || + block.kind == BusyBlockKind.image || + !_isFocusableTextBlock(block)) { + return false; + } final controller = _textControllers[blockId]; if (controller == null) { return false; @@ -7234,7 +6804,7 @@ class BusyMarkWysiwygEditorState extends State { return; } if (selectedRanges.isNotEmpty) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); for (final range in selectedRanges) { _documentController.insertInlineImage( range.block.id, @@ -7251,7 +6821,7 @@ class BusyMarkWysiwygEditorState extends State { return; } final selection = activeSelection!; - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.insertInlineImage( activeBlockId!, selectionStart: selection.start, @@ -7287,7 +6857,7 @@ class BusyMarkWysiwygEditorState extends State { return; } if (block?.kind == BusyBlockKind.table) { - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.replaceTable( blockId, columns: result.columns, @@ -7298,7 +6868,7 @@ class BusyMarkWysiwygEditorState extends State { _emitMarkdown(); return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); final paragraphId = _documentController.insertTableAfter( blockId, columns: result.columns, @@ -7335,7 +6905,7 @@ class BusyMarkWysiwygEditorState extends State { source.trim().isEmpty) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); final paragraphId = _documentController.insertRawHtmlBlockAfter( blockId, source, @@ -7369,11 +6939,10 @@ class BusyMarkWysiwygEditorState extends State { if (blockIds.isEmpty) { return false; } - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); if (!_documentController.indentListItems(blockIds)) { return false; } - _recordUndoSnapshot(undoSnapshot); _clearBlockSelection(); _emitMarkdown(); return true; @@ -7384,11 +6953,10 @@ class BusyMarkWysiwygEditorState extends State { if (blockIds.isEmpty) { return false; } - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); if (!_documentController.outdentListItems(blockIds)) { return false; } - _recordUndoSnapshot(undoSnapshot); _clearBlockSelection(); _emitMarkdown(); return true; @@ -7399,7 +6967,7 @@ class BusyMarkWysiwygEditorState extends State { if (blockIds.isEmpty) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.toggleTaskChecked(blockIds); _clearBlockSelection(); _emitMarkdown(); @@ -7413,7 +6981,7 @@ class BusyMarkWysiwygEditorState extends State { return; } _handleBlockFocused(blockId); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.toggleTaskChecked([blockId]); _emitMarkdown(); } @@ -7431,7 +6999,7 @@ class BusyMarkWysiwygEditorState extends State { final offset = selection.isValid ? selection.extentOffset.clamp(0, controller.text.length).toInt() : block.plainText.length; - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.insertHardBreak(blockId, offset); _emitMarkdown(); _focusBlockAfterFrame(blockId, offset: offset + 1); @@ -7450,7 +7018,7 @@ class BusyMarkWysiwygEditorState extends State { final offset = selection.isValid ? selection.extentOffset.clamp(0, controller.text.length).toInt() : block.plainText.length; - _recordUndoSnapshot(); + _reportLiveHistorySession(); _documentController.insertBlankLine(blockId, offset); _emitMarkdown(); _focusBlockAfterFrame(blockId, offset: offset + 2); @@ -7466,10 +7034,7 @@ class BusyMarkWysiwygEditorState extends State { blockIds.length == 1 && firstBlock?.kind == BusyBlockKind.codeBlock) { setState(() { - _propertiesVisible = widget.onInspectElement == null; - _propertiesExplicitlyOpened = true; _propertiesTargetId = firstBlock!.id; - _topicPropertiesSelected = false; }); _publishInspectorTarget(explicit: true, multiple: false); return; @@ -7482,7 +7047,7 @@ class BusyMarkWysiwygEditorState extends State { if (!_isDialogTargetCurrent(target) || language == null) { return; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); for (final blockId in blockIds) { _documentController.applyCodeBlockLanguage(blockId, language); } @@ -7508,12 +7073,8 @@ class BusyMarkWysiwygEditorState extends State { required WidgetBuilder builder, double maxWidth = BusyMarkSizes.dialogCompact, }) { - final headerBar = widget.headerBarService; return showBusyMarkModalEditorDialog( context, - headerBarService: headerBar != null && headerBar.isAvailable - ? headerBar - : null, maxWidth: maxWidth, builder: builder, ); @@ -8023,9 +7584,7 @@ class BusyMarkWysiwygEditorState extends State { final committed = widget.readEditBase?.call(); if (widget.readEditBase != null && committed != null) { // The shared buffer retains its final-newline policy for rich edits. - final expected = !widget.useExternalUndoHistory - ? markdown - : _editBase.source.endsWith('\n') + final expected = _editBase.source.endsWith('\n') ? (markdown.endsWith('\n') ? markdown : '$markdown\n') : markdown.replaceFirst(RegExp(r'\n+$'), ''); if (committed.source != expected) { @@ -8076,8 +7635,6 @@ class BusyMarkWysiwygEditorState extends State { _pendingTextFocus = null; _documentSelection = null; _propertiesTargetId = null; - _videoDraftTarget = null; - _topicPropertiesSelected = false; _documentController.replaceDocument(document); _initialFocusScheduled = false; _scheduleSessionRestore( @@ -8093,11 +7650,8 @@ class BusyMarkWysiwygEditorState extends State { return; } _reportLiveHistorySession(); - if (widget.useExternalUndoHistory || - !(redo ? _redoEditorChange() : _undoEditorChange())) { - (redo ? widget.onRedo : widget.onUndo)?.call(); - synchronizeAuthoritativeState(); - } + (redo ? widget.onRedo : widget.onUndo)?.call(); + synchronizeAuthoritativeState(); } Future _runAiEdit({String? blockId}) async { @@ -8155,7 +7709,7 @@ class BusyMarkWysiwygEditorState extends State { mode: _documentController.document.mode, validateLocalReferences: false, ); - _recordUndoSnapshot(); + _reportLiveHistorySession(); _clearBlockSelection(); _documentController.replaceDocument(parsed.busyDocument); _emitMarkdown(); @@ -9275,7 +8829,7 @@ class BusyMarkWysiwygEditorState extends State { if (ranges.length == 1 && first.isEmpty) { return false; } - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.deleteTextSelection( firstBlockId: first.block.id, firstStartOffset: first.start, @@ -9286,7 +8840,6 @@ class BusyMarkWysiwygEditorState extends State { if (result == null) { return false; } - _recordUndoSnapshot(undoSnapshot); _clearBlockSelection(collapseFields: false); _emitMarkdown(); _focusBlockAfterFrame(result.blockId, offset: result.offset); @@ -9310,7 +8863,7 @@ class BusyMarkWysiwygEditorState extends State { .replaceAll('\r\n', '\n') .replaceAll('\r', '\n'); final activeInlineKinds = _activeInlineKindsAt(first.block.id, first.start); - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.replaceTextSelectionWithText( firstBlockId: first.block.id, firstStartOffset: first.start, @@ -9325,7 +8878,6 @@ class BusyMarkWysiwygEditorState extends State { if (result == null) { return false; } - _recordUndoSnapshot(undoSnapshot); if (origin == _WysiwygTextEditOrigin.paste) { _continuousTextEdit = null; } @@ -9353,7 +8905,7 @@ class BusyMarkWysiwygEditorState extends State { if (ranges.length == 1 && first.isEmpty) { return false; } - final undoSnapshot = _historySnapshot(); + _reportLiveHistorySession(); final result = _documentController.replaceTextSelectionWithStyledBlocks( firstBlockId: first.block.id, firstStartOffset: first.start, @@ -9367,7 +8919,6 @@ class BusyMarkWysiwygEditorState extends State { return false; } _continuousTextEdit = null; - _recordUndoSnapshot(undoSnapshot); _clearBlockSelection(collapseFields: false); _emitMarkdown(); _focusBlockAfterFrame(result.blockId, offset: result.offset); @@ -9899,7 +9450,7 @@ class BusyMarkWysiwygEditorState extends State { if (end <= start) { return false; } - _recordUndoSnapshot(); + _reportLiveHistorySession(); final nextText = text.replaceRange(start, end, ''); final cellEntry = _tableCellEntry(blockId); if (cellEntry == null) { @@ -10441,7 +9992,6 @@ class _FloatingWysiwygToolbar extends StatelessWidget { icon: visible ? BusyMarkGlyphs.hide : BusyMarkGlyphs.edit, onPressed: onToggle, accented: true, - elevated: true, foregroundColor: BusyMarkLinuxPalette.white, ), ); diff --git a/lib/src/editor/wysiwyg/wysiwyg_toolbar.dart b/lib/src/editor/wysiwyg/wysiwyg_toolbar.dart index 97a153b7..96e6d9e7 100644 --- a/lib/src/editor/wysiwyg/wysiwyg_toolbar.dart +++ b/lib/src/editor/wysiwyg/wysiwyg_toolbar.dart @@ -410,7 +410,6 @@ class BusyMarkWysiwygToolbar extends StatelessWidget { tooltip: context.l10n.writerside, icon: BusyMarkGlyphs.insertObject, transparent: false, - elevated: true, foregroundColor: BusyMarkLinuxPalette.white, backgroundColor: _editorToolbarButtonBackground(context), itemBuilder: (context) => [ @@ -521,7 +520,6 @@ class BusyMarkWysiwygToolbar extends StatelessWidget { icon: BusyMarkGlyphs.font, shortcut: null, transparent: false, - elevated: true, foregroundColor: BusyMarkLinuxPalette.white, backgroundColor: _editorToolbarButtonBackground(context), itemBuilder: (context) => [ @@ -622,7 +620,6 @@ class BusyMarkWysiwygToolbar extends StatelessWidget { onPressed: onPressed, shortcut: shortcut, transparent: false, - elevated: true, foregroundColor: BusyMarkLinuxPalette.white, backgroundColor: _editorToolbarButtonBackground(context), ); diff --git a/lib/src/export/export_options_editor.dart b/lib/src/export/export_options_editor.dart index 14b4bc21..89c37717 100644 --- a/lib/src/export/export_options_editor.dart +++ b/lib/src/export/export_options_editor.dart @@ -5,7 +5,6 @@ import '../app/app_settings.dart'; import '../app/busymark_design.dart'; import '../app/busymark_dialogs.dart'; import '../app/localization.dart'; -import '../platform/linux_header_bar_service.dart'; import '../writerside/writerside_model.dart'; import 'export_options.dart'; import 'html_export_styles.dart'; @@ -41,10 +40,8 @@ Future showExportOptions( await controller.waitUntilLoaded(); if (!context.mounted) return null; final settings = ref.read(appSettingsControllerProvider); - final bar = ref.read(linuxHeaderBarServiceProvider); final selection = await showBusyMarkModalEditorDialog( context, - headerBarService: bar.isAvailable ? bar : null, maxWidth: 720, builder: (context) => ExportOptionsDialog( pdf: settings.pdfExportOptions, diff --git a/lib/src/export/html_export_models.dart b/lib/src/export/html_export_models.dart index eaff908d..b57fc61e 100644 --- a/lib/src/export/html_export_models.dart +++ b/lib/src/export/html_export_models.dart @@ -1,3 +1,4 @@ +import '../core/save_destination.dart'; import '../assets/document_media_context.dart'; import '../markdown/markdown_model.dart'; import 'export_options.dart'; @@ -83,6 +84,7 @@ class MarkdownHtmlExportRequest { required this.workspaceRoot, required this.destinationPath, this.overwrite = false, + this.authorization, this.mode = MarkdownMode.commonMark, this.document, this.options = const HtmlExportOptions(), @@ -91,6 +93,7 @@ class MarkdownHtmlExportRequest { final DocumentMediaContext? media; final String source, filePath, workspaceRoot, destinationPath; final bool overwrite; + final SaveDestination? authorization; final MarkdownMode mode; final BusyDocument? document; final HtmlExportOptions options; diff --git a/lib/src/export/html_export_publisher.dart b/lib/src/export/html_export_publisher.dart index 1add12ca..65df774a 100644 --- a/lib/src/export/html_export_publisher.dart +++ b/lib/src/export/html_export_publisher.dart @@ -1,3 +1,4 @@ +import '../core/save_destination.dart'; import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; @@ -9,7 +10,15 @@ import 'html_export_models.dart'; const htmlExportManifest = '.busymark-html-export.json'; class HtmlExportPublisher { - const HtmlExportPublisher({this.fileWriter = const AtomicFileWriter()}); + const HtmlExportPublisher({ + this.fileWriter = const AtomicFileWriter(), + this.beforeSiteExchange, + this.afterSiteExchange, + }); + final Future Function(String destination, String stage)? + beforeSiteExchange; + final Future Function(String destination, String stage)? + afterSiteExchange; final AtomicFileWriter fileWriter; Future staging(String destination) async { @@ -28,9 +37,11 @@ class HtmlExportPublisher { required String html, required String assetsName, required bool overwrite, + SaveDestination? authorization, required HtmlExportCancellationToken token, }) async { token.check(); + authorization?.requireCurrent(destination); final type = await FileSystemEntity.type(destination, followLinks: false); if (type != FileSystemEntityType.notFound && !overwrite) { throw const HtmlExportException( @@ -79,17 +90,26 @@ class HtmlExportPublisher { destination, utf8.encode(html), overwrite: overwrite, + authorization: authorization, + beforePublish: token.check, + checkBeforeCommit: token.check, ); } + Future siteOwnership(String path) => + _verifyOwned(Directory(path), 'site'); + Future publishSite({ required Directory stage, required String destination, required bool overwrite, + SaveDestination? authorization, + String? expectedOwnership, required HtmlExportCancellationToken token, }) async { await _manifest(stage, 'site'); token.check(); + authorization?.requireCurrent(destination); final type = await FileSystemEntity.type(destination, followLinks: false); if (type == FileSystemEntityType.notFound) { _publishDirectory(stage.path, destination); @@ -102,6 +122,9 @@ class HtmlExportPublisher { } final previous = Directory(destination); final identity = await _verifyOwned(previous, 'site'); + if (authorization != null && identity != expectedOwnership) { + throw const HtmlExportException('The destination changed during export.'); + } token.check(); final api = LinuxAtomicFileApi.instance; if (!api.isAvailable) { @@ -109,25 +132,33 @@ class HtmlExportPublisher { 'Atomic directory replacement is unavailable on this system. Choose a new destination.', ); } + await beforeSiteExchange?.call(destination, stage.path); + authorization?.requireCurrent(destination); + token.check(); final error = api.exchange(stage.path, destination); if (error != null) { + if (api.exchangeUnsupported(error, p.dirname(destination))) { + throw const HtmlExportException( + 'This filesystem cannot atomically replace an HTML site. Choose a new destination.', + ); + } throw HtmlExportException( 'Could not atomically replace the HTML export (system error $error).', ); } // Verify the exchanged directory too, protecting a concurrently changed target. try { - if (await _verifyOwned(stage, 'site') != identity) { + await afterSiteExchange?.call(destination, stage.path); + if (authorization?.acceptsDisplaced(stage.path) == false || + await _verifyOwned(stage, 'site') != identity) { throw const HtmlExportException( 'The destination changed during export.', ); } } on Object { - final rollback = api.exchange(stage.path, destination); - if (rollback != null) { - throw HtmlExportRecoveryException(stage.path); - } - rethrow; + // The destination may have changed again during verification. A second + // exchange could move that newer work into recursive stage cleanup. + throw HtmlExportRecoveryException(stage.path); } } @@ -245,10 +276,10 @@ class HtmlExportPublisher { } } -/// Cleanup must retain the displaced directory if even rollback is unavailable. +/// Displaced output must survive cleanup when publication is uncertain. class HtmlExportRecoveryException extends HtmlExportException { HtmlExportRecoveryException(String stagePath) : super( - 'Directory replacement could not be rolled back. The previous output is retained at $stagePath.', + 'The destination may contain published or newer output. The displaced output is retained at $stagePath; review both locations before recovery.', ); } diff --git a/lib/src/export/html_export_service.dart b/lib/src/export/html_export_service.dart index c1452d90..37b70f20 100644 --- a/lib/src/export/html_export_service.dart +++ b/lib/src/export/html_export_service.dart @@ -1,3 +1,4 @@ +import '../core/save_destination.dart'; import '../assets/document_media_context.dart'; import 'dart:convert'; import 'dart:io'; @@ -93,6 +94,7 @@ class HtmlExportService { options: request.options, customCss: customCss, overwrite: request.overwrite, + authorization: request.authorization, roots: [ if (request.filePath.isNotEmpty) p.dirname(request.filePath), if (request.workspaceRoot.isNotEmpty) request.workspaceRoot, @@ -112,6 +114,8 @@ class HtmlExportService { required String instanceId, required String destinationPath, bool overwrite = false, + SaveDestination? authorization, + String? expectedSiteOwnership, HtmlExportOptions options = const HtmlExportOptions(), WritersideProject? capturedProject, HtmlExportCancellationToken? cancellationToken, @@ -158,6 +162,8 @@ class HtmlExportService { options: options, customCss: customCss, overwrite: overwrite, + authorization: authorization, + expectedSiteOwnership: expectedSiteOwnership, roots: project.modules.map((m) => m.rootPath).toList(), modules: project.modules, warnings: warnings, @@ -173,6 +179,8 @@ class HtmlExportService { required HtmlExportOptions options, required String customCss, required bool overwrite, + SaveDestination? authorization, + String? expectedSiteOwnership, required List roots, List modules = const [], DocumentMediaContext? media, @@ -292,6 +300,8 @@ class HtmlExportService { stage: stage, destination: destination, overwrite: overwrite, + authorization: authorization, + expectedOwnership: expectedSiteOwnership, token: token, ); } else { @@ -301,6 +311,7 @@ class HtmlExportService { html: outputs.values.single, assetsName: assetName, overwrite: overwrite, + authorization: authorization, token: token, ); } diff --git a/lib/src/export/html_export_ui.dart b/lib/src/export/html_export_ui.dart index a3ff6f2b..2d42298a 100644 --- a/lib/src/export/html_export_ui.dart +++ b/lib/src/export/html_export_ui.dart @@ -1,8 +1,7 @@ import '../nextcloud_notes/application/nextcloud_connection.dart'; import '../nextcloud_notes/application/notes_media.dart'; import 'dart:async'; -import 'dart:io'; -import 'package:file_selector/file_selector.dart'; +import '../app/save_destination_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:path/path.dart' as p; @@ -13,7 +12,6 @@ import '../app/busymark_dialogs.dart'; import '../app/localization.dart'; import '../math/math_providers.dart'; import '../markdown/markdown_model.dart'; -import '../platform/linux_header_bar_service.dart'; import '../visualization/visualization_providers.dart'; import '../workspace/workspace_controller.dart'; import '../workspace/workspace_model.dart'; @@ -56,7 +54,6 @@ Future exportWorkspaceToHtml( ).context; if (!context.mounted) return; - final headerBar = ref.read(linuxHeaderBarServiceProvider); final configuration = configuredSelection ?? await showExportOptions( @@ -82,63 +79,29 @@ Future exportWorkspaceToHtml( : path.isEmpty ? context.l10n.untitledMarkdownFileName : p.basename(path); - final location = await getSaveLocation( - suggestedName: site - ? '${instance!.id}-html' - : '${p.basenameWithoutExtension(name)}.html', - initialDirectory: (workspace.filesystemRootPath ?? '').isEmpty - ? null - : (workspace.filesystemRootPath ?? ''), - acceptedTypeGroups: site - ? const [] - : [ - XTypeGroup( - label: context.l10n.fileTypeHtml, - extensions: const ['html'], - mimeTypes: const ['text/html'], - ), - ], - confirmButtonText: context.l10n.export, - ); - if (location == null || !context.mounted) return; - final destination = - !site && p.extension(location.path).toLowerCase() != '.html' - ? '${location.path}.html' - : location.path; - var overwrite = false; - if (await FileSystemEntity.type(destination, followLinks: false) != - FileSystemEntityType.notFound) { - if (!context.mounted) return; - overwrite = - await showBusyMarkModalDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkDialogShell( - title: context.l10n.warning, - actions: [ - BusyMarkDialogButton( - label: context.l10n.cancel, - onPressed: () => Navigator.pop(context, false), - ), - BusyMarkDialogButton( - label: context.l10n.overwrite, - destructive: true, - onPressed: () => Navigator.pop(context, true), - ), - ], - children: [ - Text(context.l10n.errorPathAlreadyExists(destination)), - if (site) Text(context.l10n.htmlOwnedDirectoryOnly), - ], - ), - ) ?? - false; - if (!overwrite || !context.mounted) return; - } - if (!context.mounted) return; - // Capture text and service before starting the modal operation. Subsequent - // workspace notifications cannot replace these inputs. final service = ref.read(htmlExportServiceProvider); + String? siteOwnership; + final authorization = site + ? await pickHtmlSiteDestination( + context, + suggestedName: '${instance!.id}-html', + initialDirectory: workspace.filesystemRootPath, + validateReplacement: (path) async { + siteOwnership = await service.publisher.siteOwnership(path); + }, + ) + : await pickSaveDestination( + context, + suggestedName: '${p.basenameWithoutExtension(name)}.html', + initialDirectory: workspace.filesystemRootPath, + actionLabel: context.l10n.export, + suffix: '.html', + filterLabel: context.l10n.fileTypeHtml, + patterns: const ['*.[hH][tT][mM][lL]'], + ); + if (authorization == null || !context.mounted) return; + final destination = authorization.path; + final overwrite = authorization.replacesExisting; final request = MarkdownHtmlExportRequest( source: snapshot.activeText, media: media, @@ -146,6 +109,7 @@ Future exportWorkspaceToHtml( workspaceRoot: (workspace.filesystemRootPath ?? ''), destinationPath: destination, overwrite: overwrite, + authorization: authorization, options: options, mode: workspace.markdown?.mode ?? MarkdownMode.commonMark, ); @@ -154,7 +118,6 @@ Future exportWorkspaceToHtml( final outcome = await showBusyMarkModalDialog<_Outcome>( context, barrierDismissible: false, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => _Progress( token: token, operation: (progress) => site @@ -164,6 +127,8 @@ Future exportWorkspaceToHtml( instanceId: selected!.id, destinationPath: destination, overwrite: overwrite, + authorization: authorization, + expectedSiteOwnership: siteOwnership, options: options, cancellationToken: token, onProgress: progress, @@ -179,7 +144,6 @@ Future exportWorkspaceToHtml( final result = outcome.result; await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: result == null ? context.l10n.htmlExportFailed diff --git a/lib/src/export/markdown_copy_export_service.dart b/lib/src/export/markdown_copy_export_service.dart index 30206568..75c89cbf 100644 --- a/lib/src/export/markdown_copy_export_service.dart +++ b/lib/src/export/markdown_copy_export_service.dart @@ -7,6 +7,7 @@ import 'package:uuid/uuid.dart'; import '../assets/document_media_resolver.dart'; import '../core/atomic_file_writer.dart'; +import '../core/save_destination.dart'; import '../nextcloud_notes/data/notes_attachment_references.dart'; /// Exports one remote Markdown buffer and provider-owned media as a local copy. @@ -20,6 +21,7 @@ class MarkdownCopyExportService { required String destinationPath, required DocumentMediaContext media, bool overwrite = false, + SaveDestination? authorization, void Function(String reference)? onMissing, bool Function()? isCancelled, }) async { @@ -95,8 +97,19 @@ class MarkdownCopyExportService { destination, utf8.encode(exported), overwrite: overwrite, + authorization: authorization, + beforePublish: () { + if (isCancelled?.call() == true) { + throw const FileSystemException('Export cancelled.'); + } + }, ); ownsPublished = false; + } on AtomicFileChangedException catch (error) { + // An uncertain exchange may have published the copy. Its attachments + // must survive alongside the displaced destination. + if (error.recoveryPath != null) ownsPublished = false; + rethrow; } finally { if (ownsPublished && await published.exists()) { await published.delete(recursive: true); diff --git a/lib/src/export/markdown_pdf_export_service.dart b/lib/src/export/markdown_pdf_export_service.dart index bfe2c7c3..8ec83bf5 100644 --- a/lib/src/export/markdown_pdf_export_service.dart +++ b/lib/src/export/markdown_pdf_export_service.dart @@ -188,6 +188,9 @@ class MarkdownPdfExportService { request.destinationPath, pdfBytes, overwrite: request.overwrite, + authorization: request.authorization, + beforePublish: token.throwIfCancelled, + checkBeforeCommit: token.throwIfCancelled, ); } on AtomicFileAlreadyExistsException catch (error) { throw MarkdownPdfExportException( @@ -195,6 +198,12 @@ class MarkdownPdfExportService { detail: error.path, cause: error, ); + } on AtomicFileChangedException catch (error) { + throw MarkdownPdfExportException( + MarkdownPdfFailureCode.fileSystem, + detail: error.toString(), + cause: error, + ); } on FileSystemException catch (error) { throw MarkdownPdfExportException( MarkdownPdfFailureCode.fileSystem, diff --git a/lib/src/export/markdown_pdf_export_ui.dart b/lib/src/export/markdown_pdf_export_ui.dart index 035ee2b3..18e8a160 100644 --- a/lib/src/export/markdown_pdf_export_ui.dart +++ b/lib/src/export/markdown_pdf_export_ui.dart @@ -1,9 +1,8 @@ import '../nextcloud_notes/application/nextcloud_connection.dart'; import '../nextcloud_notes/application/notes_media.dart'; import 'dart:async'; -import 'dart:io'; -import 'package:file_selector/file_selector.dart'; +import '../app/save_destination_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:path/path.dart' as p; @@ -13,7 +12,6 @@ import '../app/busymark_dialogs.dart'; import '../app/busymark_design.dart'; import '../app/busymark_toast.dart'; import '../app/localization.dart'; -import '../platform/linux_header_bar_service.dart'; import '../math/math_providers.dart'; import '../workspace/workspace_model.dart'; import '../workspace/workspace_controller.dart'; @@ -113,7 +111,6 @@ Future exportActiveMarkdownToPdf( ).context; if (!context.mounted) return; - final headerBar = ref.read(linuxHeaderBarServiceProvider); final document = documentSnapshot ?? await prepareMarkdownPdfSnapshot(snapshot); if (!context.mounted) return; @@ -134,45 +131,16 @@ Future exportActiveMarkdownToPdf( : activePath == null || activePath.isEmpty ? context.l10n.untitledMarkdownFileName : p.basename(activePath); - final location = await getSaveLocation( - acceptedTypeGroups: [ - XTypeGroup( - label: context.l10n.fileTypePdf, - extensions: const ['pdf'], - mimeTypes: const ['application/pdf'], - ), - ], + final destination = await pickSaveDestination( + context, suggestedName: '${p.basenameWithoutExtension(baseName)}.pdf', initialDirectory: _initialDirectory(workspace, activePath), - confirmButtonText: context.l10n.export, + actionLabel: context.l10n.export, + suffix: '.pdf', + filterLabel: context.l10n.fileTypePdf, + patterns: const ['*.[pP][dD][fF]'], ); - if (location == null || !context.mounted) { - return; - } - - final destinationPath = _withPdfExtension(location.path); - final targetType = await FileSystemEntity.type( - destinationPath, - followLinks: false, - ); - if (!context.mounted) { - return; - } - var overwrite = false; - if (targetType != FileSystemEntityType.notFound) { - final confirmed = await _confirmPdfOverwrite( - context, - headerBar, - destinationPath, - ); - if (!confirmed || !context.mounted) { - return; - } - overwrite = true; - } - if (!context.mounted) { - return; - } + if (destination == null || !context.mounted) return; final cancellationToken = MarkdownPdfCancellationToken(); final request = MarkdownPdfExportRequest( @@ -180,15 +148,15 @@ Future exportActiveMarkdownToPdf( media: media, filePath: activePath ?? '', workspaceRoot: (workspace.filesystemRootPath ?? ''), - destinationPath: destinationPath, + destinationPath: destination.path, options: options, - overwrite: overwrite, + overwrite: destination.replacesExisting, + authorization: destination, document: document, titlePage: selected.titlePage, ); final outcome = await showBusyMarkModalDialog<_PdfExportOutcome>( context, - headerBarService: headerBar.isAvailable ? headerBar : null, barrierDismissible: false, builder: (context) => _MarkdownPdfProgressDialog( cancellationToken: cancellationToken, @@ -203,7 +171,7 @@ Future exportActiveMarkdownToPdf( final failure = outcome.failure; if (failure != null) { if (failure.code != MarkdownPdfFailureCode.cancelled) { - await showMarkdownPdfExportError(context, headerBar, failure); + await showMarkdownPdfExportError(context, failure); } return; } @@ -248,44 +216,9 @@ String? _initialDirectory(Workspace workspace, String? activePath) { : (workspace.filesystemRootPath ?? ''); } -String _withPdfExtension(String path) { - final normalized = p.normalize(path); - return p.extension(normalized).toLowerCase() == '.pdf' - ? normalized - : '$normalized.pdf'; -} - -Future _confirmPdfOverwrite( - BuildContext context, - LinuxHeaderBarService headerBar, - String path, -) async { - return await showBusyMarkModalDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkDialogShell( - title: context.l10n.warning, - actions: [ - BusyMarkDialogButton( - label: context.l10n.cancel, - onPressed: () => Navigator.pop(context, false), - ), - BusyMarkDialogButton( - label: context.l10n.overwrite, - destructive: true, - onPressed: () => Navigator.pop(context, true), - ), - ], - children: [Text(context.l10n.errorPathAlreadyExists(path))], - ), - ) ?? - false; -} - @visibleForTesting Future showMarkdownPdfExportError( BuildContext context, - LinuxHeaderBarService headerBar, MarkdownPdfExportException failure, ) { final message = switch (failure.code) { @@ -301,7 +234,6 @@ Future showMarkdownPdfExportError( }; return showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: context.l10n.exportAsPdf, actions: [ diff --git a/lib/src/export/markdown_pdf_models.dart b/lib/src/export/markdown_pdf_models.dart index 3deb8318..4bd12eba 100644 --- a/lib/src/export/markdown_pdf_models.dart +++ b/lib/src/export/markdown_pdf_models.dart @@ -1,3 +1,4 @@ +import '../core/save_destination.dart'; import '../assets/document_media_context.dart'; import 'package:flutter/foundation.dart'; @@ -40,6 +41,7 @@ class MarkdownPdfExportRequest { required this.destinationPath, required this.options, required this.overwrite, + this.authorization, this.mode = MarkdownMode.commonMark, this.document, this.titlePage, @@ -53,6 +55,7 @@ class MarkdownPdfExportRequest { final String destinationPath; final PdfExportOptions options; final bool overwrite; + final SaveDestination? authorization; final MarkdownMode mode; /// A pre-parsed semantic document. When present, PDF export consumes this diff --git a/lib/src/export/markdown_visualization_export.dart b/lib/src/export/markdown_visualization_export.dart index 3cc1d8b3..7c0bef66 100644 --- a/lib/src/export/markdown_visualization_export.dart +++ b/lib/src/export/markdown_visualization_export.dart @@ -86,6 +86,10 @@ class MarkdownVisualizationExportRenderer { ]); } finally { cancellationToken.detach(); + for (final key in keys) { + coordinator.cancel(key); + coordinator.clearLastSuccessful(key); + } } cancellationToken.throwIfCancelled(); diff --git a/lib/src/export/writerside_pdf_export_service.dart b/lib/src/export/writerside_pdf_export_service.dart index 932140f1..db33e1bc 100644 --- a/lib/src/export/writerside_pdf_export_service.dart +++ b/lib/src/export/writerside_pdf_export_service.dart @@ -1,5 +1,6 @@ import 'dart:io'; import 'dart:convert'; + import 'package:crypto/crypto.dart'; import 'package:path/path.dart' as p; @@ -140,6 +141,7 @@ class WritersidePdfExportService { ? request.titlePage ?? PdfTitlePageData.forInstance(instance) : null, overwrite: request.overwrite, + authorization: request.authorization, mode: MarkdownMode.writersideMarkdown, document: document, ), @@ -306,17 +308,7 @@ class WritersidePdfExportService { token.throwIfCancelled(); final selection = selected[index]; final topic = selection.topic; - String source; - try { - source = - topic.markdown?.source ?? await File(topic.filePath).readAsString(); - } on FileSystemException catch (error) { - throw WritersidePdfExportException( - WritersidePdfFailureCode.fileSystem, - detail: error.message, - cause: error, - ); - } + final source = topic.document.source; combinedSourceBytes += source.length; if (combinedSourceBytes > maximumCombinedSourceBytes) { throw const WritersidePdfExportException( @@ -324,22 +316,11 @@ class WritersidePdfExportService { detail: 'The selected instance is too large to export safely.', ); } - final parsedTopic = topic.format == WritersideTopicFormat.xml - ? moduleService.topicParser.parseXml( - filePath: topic.filePath, - source: source, - topicsRoot: topic.topicRoot, - ) - : moduleService.topicParser.parseMarkdown( - filePath: topic.filePath, - source: source, - topicsRoot: topic.topicRoot, - ); final resolved = documentResolver.resolve( - parsedTopic.document, + topic.document, WritersideResolveContext( module: selection.module, - topic: parsedTopic, + topic: topic, instance: instance, modulesByOrigin: modulesByOrigin, ), @@ -356,7 +337,7 @@ class WritersidePdfExportService { } var rendered = documentRenderer.toBusyDocument( resolved.document, - title: resolved.title ?? _topicTitle(parsedTopic, instance.id), + title: resolved.title ?? _topicTitle(topic, instance.id), includeTitleHeading: true, ); if (selection.hidden) { @@ -366,7 +347,7 @@ class WritersidePdfExportService { } final assets = await _resolveBusyAssets( selection.module, - parsedTopic, + topic, preparePdfFootnotes(rendered), modulesByOrigin, ); diff --git a/lib/src/export/writerside_pdf_export_ui.dart b/lib/src/export/writerside_pdf_export_ui.dart index 42a6343a..ffb9f706 100644 --- a/lib/src/export/writerside_pdf_export_ui.dart +++ b/lib/src/export/writerside_pdf_export_ui.dart @@ -1,7 +1,6 @@ import 'dart:async'; -import 'dart:io'; -import 'package:file_selector/file_selector.dart'; +import '../app/save_destination_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:path/path.dart' as p; @@ -13,7 +12,6 @@ import '../app/busymark_dialogs.dart'; import '../app/busymark_toast.dart'; import '../app/localization.dart'; import '../math/math_providers.dart'; -import '../platform/linux_header_bar_service.dart'; import '../visualization/visualization_providers.dart'; import '../workspace/workspace_controller.dart'; import '../workspace/workspace_model.dart'; @@ -73,7 +71,6 @@ Future exportWritersideModuleToPdf( final instances = module.instances .where((instance) => !instance.isLibrary) .toList(growable: false); - final headerBar = ref.read(linuxHeaderBarServiceProvider); final selected = configuredSelection ?? await showExportOptions( @@ -89,47 +86,30 @@ Future exportWritersideModuleToPdf( !context.mounted) { return; } - final location = await getSaveLocation( - acceptedTypeGroups: [ - XTypeGroup( - label: context.l10n.fileTypePdf, - extensions: const ['pdf'], - mimeTypes: const ['application/pdf'], - ), - ], + final destination = await pickSaveDestination( + context, suggestedName: '${selected.instance!.id}.pdf', initialDirectory: module.rootPath, - confirmButtonText: context.l10n.export, + actionLabel: context.l10n.export, + suffix: '.pdf', + filterLabel: context.l10n.fileTypePdf, + patterns: const ['*.[pP][dD][fF]'], ); - if (location == null || !context.mounted) { - return; - } - final destination = _withPdfExtension(location.path); - var overwrite = false; - if (await FileSystemEntity.type(destination, followLinks: false) != - FileSystemEntityType.notFound) { - if (!context.mounted || - !await _confirmOverwrite(context, headerBar, destination)) { - return; - } - overwrite = true; - } - if (!context.mounted) { - return; - } + if (destination == null || !context.mounted) return; + final token = WritersidePdfCancellationToken(); final request = WritersidePdfExportRequest( moduleRoot: module.rootPath, projectRoot: workspace.rootPath, instanceId: selected.instance!.id, - destinationPath: destination, - overwrite: overwrite, + destinationPath: destination.path, + overwrite: destination.replacesExisting, + authorization: destination, options: selected.pdf!, titlePage: selected.titlePage, ); final outcome = await showBusyMarkModalDialog<_WritersidePdfOutcome>( context, - headerBarService: headerBar.isAvailable ? headerBar : null, barrierDismissible: false, builder: (context) => _WritersidePdfProgressDialog( cancellationToken: token, @@ -143,7 +123,7 @@ Future exportWritersideModuleToPdf( } if (outcome.failure case final failure?) { if (failure.code != WritersidePdfFailureCode.cancelled) { - await _showWritersidePdfError(context, headerBar, failure); + await _showWritersidePdfError(context, failure); } return; } @@ -256,36 +236,8 @@ class _WritersidePdfOutcome { final WritersidePdfExportException? failure; } -Future _confirmOverwrite( - BuildContext context, - LinuxHeaderBarService headerBar, - String path, -) async { - return await showBusyMarkModalDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkDialogShell( - title: context.l10n.warning, - actions: [ - BusyMarkDialogButton( - label: context.l10n.cancel, - onPressed: () => Navigator.pop(context, false), - ), - BusyMarkDialogButton( - label: context.l10n.overwrite, - destructive: true, - onPressed: () => Navigator.pop(context, true), - ), - ], - children: [Text(context.l10n.errorPathAlreadyExists(path))], - ), - ) ?? - false; -} - Future _showWritersidePdfError( BuildContext context, - LinuxHeaderBarService headerBar, WritersidePdfExportException failure, ) { final message = switch (failure.code) { @@ -302,7 +254,6 @@ Future _showWritersidePdfError( }; return showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: context.l10n.exportWritersideAsPdf, maxWidth: BusyMarkSizes.dialog, @@ -328,10 +279,3 @@ Future _showWritersidePdfError( ), ); } - -String _withPdfExtension(String path) { - final normalized = p.normalize(path); - return p.extension(normalized).toLowerCase() == '.pdf' - ? normalized - : '$normalized.pdf'; -} diff --git a/lib/src/export/writerside_pdf_models.dart b/lib/src/export/writerside_pdf_models.dart index ec27b92f..1ef9544e 100644 --- a/lib/src/export/writerside_pdf_models.dart +++ b/lib/src/export/writerside_pdf_models.dart @@ -1,3 +1,4 @@ +import '../core/save_destination.dart'; import 'package:flutter/foundation.dart'; import 'markdown_pdf_models.dart'; @@ -9,6 +10,7 @@ class WritersidePdfExportRequest { required this.instanceId, required this.destinationPath, required this.overwrite, + this.authorization, this.projectRoot, this.options = const PdfExportOptions(), this.titlePage, @@ -19,6 +21,7 @@ class WritersidePdfExportRequest { final String instanceId; final String destinationPath; final bool overwrite; + final SaveDestination? authorization; final PdfExportOptions options; final PdfTitlePageData? titlePage; } diff --git a/lib/src/feedback/presentation/feedback_dialog.dart b/lib/src/feedback/presentation/feedback_dialog.dart index 854b5592..c6ff44f5 100644 --- a/lib/src/feedback/presentation/feedback_dialog.dart +++ b/lib/src/feedback/presentation/feedback_dialog.dart @@ -9,7 +9,6 @@ import 'package:uuid/uuid.dart'; import '../../app/busymark_design.dart'; import '../../app/busymark_dialogs.dart'; import '../../app/localization.dart'; -import '../../platform/linux_header_bar_service.dart'; import '../feedback_metadata.dart'; import '../feedback_service.dart'; import '../feedback_submission.dart'; @@ -33,14 +32,10 @@ abstract final class BusyMarkFeedbackKeys { static const status = ValueKey('feedback.status'); } -void showBusyMarkFeedbackDialog( - BuildContext context, { - LinuxHeaderBarService? headerBarService, -}) { +void showBusyMarkFeedbackDialog(BuildContext context) { unawaited( showBusyMarkModalEditorDialog( context, - headerBarService: headerBarService, maxWidth: 680, maxHeight: 760, builder: (dialogContext) => BusyMarkFeedbackDialog( diff --git a/lib/src/git/application/git_controller.dart b/lib/src/git/application/git_controller.dart index 48425251..d6c6fce4 100644 --- a/lib/src/git/application/git_controller.dart +++ b/lib/src/git/application/git_controller.dart @@ -8,7 +8,6 @@ import 'package:path/path.dart' as p; import 'package:busystack_git/busystack_git.dart' as shared; import '../../app/app_settings.dart'; -import '../../core/path_utils.dart'; import '../../workspace/workspace_controller.dart'; import '../../workspace/workspace_model.dart'; import '../domain/git_models.dart'; @@ -31,299 +30,65 @@ class GitStagedDiffSnapshot { final String fingerprint; } -class GitFileHistoryState { - const GitFileHistoryState({ - this.entries = const [], - this.currentPath, - this.hasMore = false, - this.isLoadingMore = false, - this.selectedCommitHash, - this.comparisonType = GitComparisonType.commitChange, - this.comparison, - }); - - final List entries; - final String? currentPath; - final bool hasMore; - final bool isLoadingMore; - final String? selectedCommitHash; - final GitComparisonType comparisonType; - final GitHistoricalFileComparison? comparison; - - GitFileHistoryEntry? get selectedEntry { - final hash = selectedCommitHash; - if (hash == null) { - return null; - } - return entries.where((entry) => entry.commit.fullHash == hash).firstOrNull; - } - - GitFileHistoryState copyWith({ - List? entries, - Object? currentPath = _unset, - bool? hasMore, - bool? isLoadingMore, - Object? selectedCommitHash = _unset, - GitComparisonType? comparisonType, - Object? comparison = _unset, - }) { - return GitFileHistoryState( - entries: entries ?? this.entries, - currentPath: identical(currentPath, _unset) - ? this.currentPath - : currentPath as String?, - hasMore: hasMore ?? this.hasMore, - isLoadingMore: isLoadingMore ?? this.isLoadingMore, - selectedCommitHash: identical(selectedCommitHash, _unset) - ? this.selectedCommitHash - : selectedCommitHash as String?, - comparisonType: comparisonType ?? this.comparisonType, - comparison: identical(comparison, _unset) - ? this.comparison - : comparison as GitHistoricalFileComparison?, - ); - } -} - -class GitProjectHistoryState { - const GitProjectHistoryState({ - this.commits = const [], - this.hasMore = false, - this.isLoadingMore = false, - this.selectedCommitHash, - this.selectedFilePath, - this.details, - this.comparisonType = GitComparisonType.commitChange, - this.comparison, - }); - - final List commits; - final bool hasMore; - final bool isLoadingMore; - final String? selectedCommitHash; - final String? selectedFilePath; - final GitCommitDetails? details; - final GitComparisonType comparisonType; - final GitHistoricalFileComparison? comparison; - - GitProjectHistoryState copyWith({ - List? commits, - bool? hasMore, - bool? isLoadingMore, - Object? selectedCommitHash = _unset, - Object? selectedFilePath = _unset, - Object? details = _unset, - GitComparisonType? comparisonType, - Object? comparison = _unset, - }) { - return GitProjectHistoryState( - commits: commits ?? this.commits, - hasMore: hasMore ?? this.hasMore, - isLoadingMore: isLoadingMore ?? this.isLoadingMore, - selectedCommitHash: identical(selectedCommitHash, _unset) - ? this.selectedCommitHash - : selectedCommitHash as String?, - selectedFilePath: identical(selectedFilePath, _unset) - ? this.selectedFilePath - : selectedFilePath as String?, - details: identical(details, _unset) - ? this.details - : details as GitCommitDetails?, - comparisonType: comparisonType ?? this.comparisonType, - comparison: identical(comparison, _unset) - ? this.comparison - : comparison as GitHistoricalFileComparison?, - ); - } -} - class GitState { const GitState({ this.availability = const GitAvailability.unavailable(), this.repositoryInfo, this.statusSnapshot, - this.selectedView = GitView.changes, - this.selectedChange, - this.changeDiff, - this.fileHistory = const GitFileHistoryState(), - this.projectHistory = const GitProjectHistoryState(), - this.selectedCommitFilePath, - this.openDiffFilePaths = const [], - this.branches = const [], this.requiresWorkspaceTrust = false, this.isRefreshing = false, - this.isRunningOperation = false, this.lastError, - this.lastOperationMessage, this.attachedWorkspace, - this.scopedFilePath, }); final GitAvailability availability; final GitRepositoryInfo? repositoryInfo; final GitStatusSnapshot? statusSnapshot; - final GitView selectedView; - final GitChangeSelection? selectedChange; - final GitDiff? changeDiff; - final GitFileHistoryState fileHistory; - final GitProjectHistoryState projectHistory; - final String? selectedCommitFilePath; - final List openDiffFilePaths; - final List branches; final bool requiresWorkspaceTrust; final bool isRefreshing; - final bool isRunningOperation; final GitFailure? lastError; - final String? lastOperationMessage; final Workspace? attachedWorkspace; - final String? scopedFilePath; bool get isRepository => repositoryInfo != null; - String? get selectedFilePath => selectedChange?.path; - String? get selectedCommitHash => switch (selectedView) { - GitView.fileHistory => fileHistory.selectedCommitHash, - GitView.projectHistory => projectHistory.selectedCommitHash, - GitView.changes => null, - }; - GitDiff? get selectedDiff => switch (selectedView) { - GitView.changes => changeDiff, - GitView.fileHistory => fileHistory.comparison?.diff, - GitView.projectHistory => projectHistory.comparison?.diff, - }; - String? get selectedDiffOpenFilePath { - return switch (selectedView) { - GitView.changes => () { - final selection = selectedChange; - if (selection == null) { - return null; - } - final path = selectedCommitFilePath ?? selection.path; - final status = statusSnapshot?.files - .where((file) => file.repoRelativePath == path) - .firstOrNull; - return (status?.hasWorkingTreeFile ?? false) ? path : null; - }(), - GitView.fileHistory => fileHistory.currentPath, - GitView.projectHistory => null, - }; - } - - List get history => switch (selectedView) { - GitView.fileHistory => [ - for (final entry in fileHistory.entries) entry.commit, - ], - GitView.projectHistory => projectHistory.commits, - GitView.changes => const [], - }; - String? get historyFilePath => - selectedView == GitView.fileHistory ? fileHistory.currentPath : null; - - GitDiff? get selectedDiffForDisplay { - final diff = selectedDiff; - final path = selectedCommitFilePath; - if (diff == null) { - return null; - } - if (path == null) { - return null; - } - if (!openDiffFilePaths.contains(path) && openDiffFilePaths.isNotEmpty) { - return null; - } - final selectedFiles = [ - for (final file in diff.files) - if (file.matchesPath(path)) file, - ]; - if (selectedFiles.isEmpty) { - return diff.files.isEmpty ? diff : null; - } - return GitDiff( - title: path, - files: selectedFiles, - rawPatch: diff.rawPatch, - hasBinaryFiles: selectedFiles.any((file) => file.binary), - fileSnapshots: diff.fileSnapshots, - ); - } GitState copyWith({ GitAvailability? availability, Object? repositoryInfo = _unset, Object? statusSnapshot = _unset, - GitView? selectedView, - Object? selectedChange = _unset, - Object? changeDiff = _unset, - GitFileHistoryState? fileHistory, - GitProjectHistoryState? projectHistory, - Object? selectedCommitFilePath = _unset, - List? openDiffFilePaths, - List? branches, bool? requiresWorkspaceTrust, bool? isRefreshing, - bool? isRunningOperation, Object? lastError = _unset, - Object? lastOperationMessage = _unset, Object? attachedWorkspace = _unset, - Object? scopedFilePath = _unset, - }) { - return GitState( - availability: availability ?? this.availability, - repositoryInfo: identical(repositoryInfo, _unset) - ? this.repositoryInfo - : repositoryInfo as GitRepositoryInfo?, - statusSnapshot: identical(statusSnapshot, _unset) - ? this.statusSnapshot - : statusSnapshot as GitStatusSnapshot?, - selectedView: selectedView ?? this.selectedView, - selectedChange: identical(selectedChange, _unset) - ? this.selectedChange - : selectedChange as GitChangeSelection?, - changeDiff: identical(changeDiff, _unset) - ? this.changeDiff - : changeDiff as GitDiff?, - fileHistory: fileHistory ?? this.fileHistory, - projectHistory: projectHistory ?? this.projectHistory, - selectedCommitFilePath: identical(selectedCommitFilePath, _unset) - ? this.selectedCommitFilePath - : selectedCommitFilePath as String?, - openDiffFilePaths: openDiffFilePaths ?? this.openDiffFilePaths, - branches: branches ?? this.branches, - requiresWorkspaceTrust: - requiresWorkspaceTrust ?? this.requiresWorkspaceTrust, - isRefreshing: isRefreshing ?? this.isRefreshing, - isRunningOperation: isRunningOperation ?? this.isRunningOperation, - lastError: identical(lastError, _unset) - ? this.lastError - : lastError as GitFailure?, - lastOperationMessage: identical(lastOperationMessage, _unset) - ? this.lastOperationMessage - : lastOperationMessage as String?, - attachedWorkspace: identical(attachedWorkspace, _unset) - ? this.attachedWorkspace - : attachedWorkspace as Workspace?, - scopedFilePath: identical(scopedFilePath, _unset) - ? this.scopedFilePath - : scopedFilePath as String?, - ); - } + }) => GitState( + availability: availability ?? this.availability, + repositoryInfo: identical(repositoryInfo, _unset) + ? this.repositoryInfo + : repositoryInfo as GitRepositoryInfo?, + statusSnapshot: identical(statusSnapshot, _unset) + ? this.statusSnapshot + : statusSnapshot as GitStatusSnapshot?, + requiresWorkspaceTrust: + requiresWorkspaceTrust ?? this.requiresWorkspaceTrust, + isRefreshing: isRefreshing ?? this.isRefreshing, + lastError: identical(lastError, _unset) + ? this.lastError + : lastError as GitFailure?, + attachedWorkspace: identical(attachedWorkspace, _unset) + ? this.attachedWorkspace + : attachedWorkspace as Workspace?, + ); } class GitController extends Notifier { static const _refreshDebounce = Duration(milliseconds: 350); - static const _historyPageSize = 50; late GitRepositoryGateway _gateway; final _validation = const GitValidation(); Timer? _debounce; - var _knownHashes = {}; + StreamSubscription? _repositoryWatch; var _refreshEpoch = 0; var _workspaceEpoch = 0; var _attachmentEpoch = 0; - var _commitDetailsEpoch = 0; - var _branchesEpoch = 0; - var _fileHistoryEpoch = 0; - var _projectHistoryEpoch = 0; - var _diffEpoch = 0; var _isUpdatingWorkspaceTrust = false; ({ String workspaceId, @@ -334,6 +99,7 @@ class GitController extends Notifier { _sharedAssociation; ({ + Object owner, String workspaceId, shared.RepositoryId repository, String workspacePath, @@ -348,6 +114,7 @@ class GitController extends Notifier { bool bindSharedStatusSource( Workspace workspace, shared.RepositoryId repository, { + Object? owner, required Future Function() refresh, required Future Function() current, required Future Function(List, bool) stage, @@ -359,7 +126,9 @@ class GitController extends Notifier { } _refreshEpoch++; _debounce?.cancel(); + _stopRepositoryWatch(); _sharedStatusSource = ( + owner: owner ?? refresh, workspaceId: workspace.id, repository: repository, workspacePath: workspace.rootPath, @@ -370,18 +139,11 @@ class GitController extends Notifier { return true; } - void projectSharedOperation( - Workspace workspace, - shared.RepositoryId repository, - bool running, - ) { - if (_sharedStatusSource?.repository != repository || - state.attachedWorkspace?.id != workspace.id) { - return; - } - if (state.isRunningOperation != running) { - state = state.copyWith(isRunningOperation: running); - } + void releaseSharedStatusSource(Object owner) { + if (!ref.mounted || !identical(_sharedStatusSource?.owner, owner)) return; + _sharedStatusSource = null; + _refreshEpoch++; + _scheduleRefresh(immediate: true); } Future refreshFromSharedSnapshot({bool refresh = false}) async { @@ -519,7 +281,20 @@ class GitController extends Notifier { } } }); - ref.onDispose(() => _debounce?.cancel()); + final files = ref.read(workspaceFileMonitorProvider).events.listen((event) { + final root = state.attachedWorkspace?.filesystemRootPath; + if (_sharedStatusSource == null && + _repositoryWatch == null && + root != null && + (p.equals(root, event.path) || p.isWithin(root, event.path))) { + _scheduleRefresh(); + } + }); + ref.onDispose(() { + _debounce?.cancel(); + _stopRepositoryWatch(); + unawaited(files.cancel()); + }); return const GitState(); } @@ -527,22 +302,20 @@ class GitController extends Notifier { final changedOwner = state.attachedWorkspace?.id != workspace.id || state.attachedWorkspace?.rootPath != workspace.rootPath || - state.attachedWorkspace?.isRemote != workspace.isRemote; - if (changedOwner) { - _attachmentEpoch++; - _workspaceEpoch++; - _sharedAssociation = null; - _sharedStatusSource = null; - } + state.attachedWorkspace?.kind != workspace.kind; + if (!changedOwner) return; + _stopRepositoryWatch(); + _attachmentEpoch++; + _workspaceEpoch++; + _sharedAssociation = null; + _sharedStatusSource = null; if (workspace.isRemote) { _debounce?.cancel(); - _knownHashes = {}; state = const GitState(); return; } if (_gateway is UnavailableGitRepositoryGateway) { _debounce?.cancel(); - _knownHashes = {}; state = _workspaceResetState( workspace, availability: const GitAvailability.unavailable( @@ -555,19 +328,12 @@ class GitController extends Notifier { workspace.kind == WorkspaceKind.untitledMarkdown || workspace.kind == WorkspaceKind.singleMarkdown) { _debounce?.cancel(); - _knownHashes = {}; state = const GitState(); return; } - if (changedOwner) { - _debounce?.cancel(); - _knownHashes = {}; - state = _workspaceResetState(workspace); - _scheduleRefresh(immediate: true); - } else { - state = state.copyWith(attachedWorkspace: workspace); - _scheduleRefresh(); - } + _debounce?.cancel(); + state = _workspaceResetState(workspace); + _scheduleRefresh(immediate: true); } Future refresh() async { @@ -597,20 +363,12 @@ class GitController extends Notifier { } state = state.copyWith(availability: availability); if (!availability.available) { + _stopRepositoryWatch(); state = state.copyWith( isRefreshing: false, requiresWorkspaceTrust: false, repositoryInfo: null, statusSnapshot: null, - selectedChange: null, - changeDiff: null, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - fileHistory: const GitFileHistoryState(), - projectHistory: const GitProjectHistoryState(), - branches: const [], - lastOperationMessage: null, - scopedFilePath: null, ); return; } @@ -641,20 +399,12 @@ class GitController extends Notifier { return; } if (repository == null) { + _stopRepositoryWatch(); state = state.copyWith( isRefreshing: false, requiresWorkspaceTrust: false, repositoryInfo: null, statusSnapshot: null, - selectedChange: null, - changeDiff: null, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - fileHistory: const GitFileHistoryState(), - projectHistory: const GitProjectHistoryState(), - branches: const [], - lastOperationMessage: null, - scopedFilePath: null, ); return; } @@ -674,17 +424,42 @@ class GitController extends Notifier { _setWorkspaceTrustRequiredState(); return; } + final previous = state.repositoryInfo; + if (previous?.identityKey != repository.identityKey || + previous?.rootPath != repository.rootPath || + previous?.gitDirPath != repository.gitDirPath) { + _stopRepositoryWatch(); + } state = state.copyWith(repositoryInfo: repository); final status = await _gateway.status(repository); if (!_isCurrentRefresh(workspaceId, refreshEpoch)) { return; } _applyStatus(status, workspace); + // The shared watcher covers linked-worktree metadata outside the opened + // directory too. The session takes ownership when a Git view opens. + _repositoryWatch ??= _gateway + .watch(repository) + .listen( + (_) { + if (_isCurrentWorkspace(workspaceId) && + _sharedStatusSource == null) { + _scheduleRefresh(); + } + }, + onError: (Object error) { + if (_isCurrentWorkspace(workspaceId) && + _sharedStatusSource == null) { + _setFailure(error, commandName: 'watch'); + } + }, + ); } on Object catch (error) { if (!_isCurrentRefresh(workspaceId, refreshEpoch)) { return; } if (error is GitWorkspaceRootRequired) { + _stopRepositoryWatch(); _sharedAssociation = null; _sharedStatusSource = null; state = _workspaceResetState(workspace); @@ -699,27 +474,11 @@ class GitController extends Notifier { Workspace workspace, { bool requiresTrust = false, }) { - final scoped = _workspaceScopedRepoPath(workspace, status.repositoryInfo); - final selectedChange = _reconcileChangeSelection( - state.selectedChange, - status, - ); - final clearChangeTab = - state.selectedView == GitView.changes && selectedChange == null; state = state.copyWith( isRefreshing: false, requiresWorkspaceTrust: requiresTrust, repositoryInfo: status.repositoryInfo, statusSnapshot: status, - scopedFilePath: scoped, - selectedChange: selectedChange, - changeDiff: selectedChange == state.selectedChange - ? state.changeDiff - : null, - selectedCommitFilePath: clearChangeTab - ? null - : state.selectedCommitFilePath, - openDiffFilePaths: clearChangeTab ? const [] : state.openDiffFilePaths, lastError: null, ); } @@ -749,1227 +508,122 @@ class GitController extends Notifier { } } - Future selectView(GitView view) async { - final activePath = switch (view) { - GitView.changes => - state.changeDiff == null ? null : state.selectedChange?.path, - GitView.fileHistory => - state.fileHistory.comparison?.diff.files.firstOrNull?.displayPath, - GitView.projectHistory => state.projectHistory.selectedFilePath, - }; - state = state.copyWith( - selectedView: view, - selectedCommitFilePath: activePath, - openDiffFilePaths: activePath == null ? const [] : [activePath], - ); - switch (view) { - case GitView.changes: - return; - case GitView.fileHistory: - final path = state.scopedFilePath; - if (path != null && - (state.fileHistory.currentPath != path || - state.fileHistory.entries.isEmpty)) { - await _loadFileHistory(path); - } - case GitView.projectHistory: - if (state.projectHistory.commits.isEmpty) { - await loadProjectHistory(); - } - } - } - - void clearSelection() { - state = state.copyWith( - selectedChange: null, - changeDiff: null, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - ); - } - - void deactivateDiffFile() { - if (state.selectedCommitFilePath == null) { - return; - } - state = state.copyWith(selectedCommitFilePath: null); - } - - Future activateDiffFile(String repoRelativePath) async { - if (!state.openDiffFilePaths.contains(repoRelativePath)) { - return; - } - switch (state.selectedView) { - case GitView.changes: - if (state.changeDiff != null) { - state = state.copyWith(selectedCommitFilePath: repoRelativePath); - } - case GitView.fileHistory: - if (state.fileHistory.comparison != null) { - state = state.copyWith(selectedCommitFilePath: repoRelativePath); - } - case GitView.projectHistory: - await selectCommitFile(repoRelativePath); - } - } + Future stageFiles(List paths) => + _stageThroughSession(paths, false); + Future unstageFiles(List paths) => + _stageThroughSession(paths, true); - Future selectChange(GitChangeSelection selection) async { - final failure = _validation.validateRepoRelativePaths( - selection.repoRelativePaths, - ); + Future _stageThroughSession(List paths, bool unstage) async { + final operation = _captureRepositoryOperation(), + source = _sharedStatusSource; + if (operation == null) return; + final failure = _validation.validateRepoRelativePaths(paths); if (failure != null) { state = state.copyWith(lastError: failure); return; } - state = state.copyWith( - selectedView: GitView.changes, - selectedChange: selection, - changeDiff: null, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - ); - await _loadChangedFileDiff(selection); - } - - Future selectChangedFile(String repoRelativePath) async { - final selection = _preferredChangeSelection(repoRelativePath); - if (selection != null) { - await selectChange(selection); - } - } - - Future showCurrentFileDiff() async { - final path = state.scopedFilePath; - if (path != null) { - final selection = _preferredChangeSelection(path); - if (selection != null) { - await selectChange(selection); - } - } - } - - Future loadFileHistory(String absolutePath) async { - final repository = _trustedRepositoryInfo; - if (repository == null) { - return; - } - final relative = _repoRelativePath(repository.rootPath, absolutePath); - if (relative == null) { - return; - } - await _loadFileHistory(relative); - } - - Future loadActiveFileHistory() async { - final path = state.scopedFilePath; - if (path != null) { - await _loadFileHistory(path); - } - } - - Future loadProjectHistory() => _loadProjectHistory(); - - Future loadCommitDetails(String hash) async { - if (state.selectedView == GitView.fileHistory) { - await selectFileHistoryCommit(hash); - } else { - await selectProjectCommit(hash); - } - } - - Future selectFileHistoryCommit(String hash) async { - final operation = _captureRepositoryOperation(); - final entry = state.fileHistory.entries - .where((candidate) => candidate.commit.fullHash == hash) - .firstOrNull; - if (operation == null || entry == null || !_knownHashes.contains(hash)) { - _setInvalidCommit(hash); + if (source == null || + source.repository.key != _sharedAssociation?.repository.key) { + _setFailure( + const shared.GitException(shared.GitErrorCode.disconnected), + commandName: 'git', + ); return; } - final requestEpoch = ++_commitDetailsEpoch; - state = state.copyWith(isRunningOperation: true, lastError: null); try { - final comparison = await _gateway.compareFileWithParent( - operation.repository, - hash, - oldPath: entry.oldPath, - newPath: entry.newPath, - ); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; - } - final displayPath = comparison.newPath ?? comparison.oldPath; - state = state.copyWith( - isRunningOperation: false, - selectedView: GitView.fileHistory, - fileHistory: state.fileHistory.copyWith( - selectedCommitHash: hash, - comparisonType: GitComparisonType.commitChange, - comparison: comparison, - ), - selectedCommitFilePath: displayPath, - openDiffFilePaths: displayPath == null ? const [] : [displayPath], - ); + await source.stage(List.unmodifiable(paths), unstage); } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; + if (_isCurrentRepositoryOperation(operation)) { + _setFailure(error, commandName: 'git'); } - _setFailure(error, commandName: 'show'); - state = state.copyWith(isRunningOperation: false); } } - Future selectProjectCommit(String hash) async { + Future stagedDiffForAi() async { final operation = _captureRepositoryOperation(); - if (operation == null) { - return; - } - if (!_knownHashes.contains(hash)) { - _setInvalidCommit(hash); - return; + if (operation == null || + (state.statusSnapshot?.stagedFiles.isEmpty ?? true)) { + return null; } - final requestEpoch = ++_commitDetailsEpoch; - state = state.copyWith(isRunningOperation: true, lastError: null); try { - final details = await _gateway.commitDetails(operation.repository, hash); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; + final patch = await _gateway.stagedPatch(operation.repository); + if (!_isCurrentRepositoryOperation(operation)) { + return null; } - final firstFilePath = _firstDiffFilePath(details.changedFiles); - state = state.copyWith( - selectedView: GitView.projectHistory, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - projectHistory: state.projectHistory.copyWith( - selectedCommitHash: hash, - selectedFilePath: firstFilePath, - details: details, - comparisonType: GitComparisonType.commitChange, - comparison: null, - ), - ); - if (firstFilePath == null) { - state = state.copyWith( - isRunningOperation: false, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - ); - return; + if (patch.trim().isEmpty) { + return null; } - await _loadProjectFileComparison( - operation, - hash, - firstFilePath, - requestEpoch: requestEpoch, + return GitStagedDiffSnapshot( + patch: patch, + fingerprint: _stagedDiffFingerprint(patch), ); } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; + if (_isCurrentRepositoryOperation(operation)) { + _setFailure(error, commandName: 'diff'); } - _setFailure(error, commandName: 'show'); - state = state.copyWith(isRunningOperation: false); + return null; } } - Future selectCommitFile(String repoRelativePath) async { - final project = state.projectHistory; - final hash = project.selectedCommitHash; - final details = project.details; - if (hash == null || details == null) { - return; - } - final failure = _validation.validateRepoRelativePaths([repoRelativePath]); - if (failure != null) { - state = state.copyWith(lastError: failure); - return; - } - if (!details.changedFiles.any( - (file) => file.matchesPath(repoRelativePath), - )) { - return; - } + Future stagedDiffMatches(String fingerprint) async { final operation = _captureRepositoryOperation(); if (operation == null) { - return; - } - final requestEpoch = ++_commitDetailsEpoch; - state = state.copyWith( - isRunningOperation: true, - projectHistory: project.copyWith(selectedFilePath: repoRelativePath), - ); - await _loadProjectFileComparison( - operation, - hash, - repoRelativePath, - requestEpoch: requestEpoch, - ); - } - - Future compareFileHistoryWithCurrent() async { - final operation = _captureRepositoryOperation(); - final history = state.fileHistory; - final entry = history.selectedEntry; - final historicalPath = entry?.newPath; - final currentPath = history.currentPath; - if (operation == null || entry == null || currentPath == null) { - return; + return false; } - final requestEpoch = ++_commitDetailsEpoch; - state = state.copyWith(isRunningOperation: true, lastError: null); try { - final comparison = historicalPath == null - ? await _comparisonFromEmptyWorkingTree( - operation.repository, - currentPath, - ) - : await _gateway.compareFileWithWorkingTree( - operation.repository, - entry.commit.fullHash, - historicalPath: historicalPath, - currentPath: currentPath, - ); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; - } - state = state.copyWith( - isRunningOperation: false, - fileHistory: state.fileHistory.copyWith( - comparisonType: GitComparisonType.commitVersusCurrent, - comparison: comparison, - ), - selectedCommitFilePath: currentPath, - openDiffFilePaths: [currentPath], - ); + final patch = await _gateway.stagedPatch(operation.repository); + return _isCurrentRepositoryOperation(operation) && + patch.trim().isNotEmpty && + _stagedDiffFingerprint(patch) == fingerprint; } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; + if (_isCurrentRepositoryOperation(operation)) { + _setFailure(error, commandName: 'diff'); } - _setFailure(error, commandName: 'diff'); - state = state.copyWith(isRunningOperation: false); + return false; } } - Future restoreSelectedFileVersion() async { - if (_rejectDirtyWorkspaceRestore()) return false; - if (selectedFileHasStagedChanges) { - state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.stagedChanges, - userMessageKey: 'gitErrorRestoreStagedFile', - rawMessage: '', - commandName: 'restore', - ), - ); - return false; - } - final operation = _captureRepositoryOperation(); - final history = state.fileHistory; - final entry = history.selectedEntry; - final historicalPath = entry?.newPath ?? entry?.pathAtCommit; - final currentPath = history.currentPath; - if (operation == null || - entry == null || - historicalPath == null || - currentPath == null) { - return false; - } - final absoluteCurrentPath = p.isAbsolute(currentPath) - ? p.normalize(currentPath) - : p.normalize(p.join(operation.repository.rootPath, currentPath)); - final protected = await ref - .read(workspaceControllerProvider.notifier) - .protectPathsBeforeExternalReplacement([absoluteCurrentPath]); - if (!protected) { - _rejectDirtyWorkspaceRestore(); - return false; - } - if (_rejectDirtyWorkspaceRestore()) return false; - if (!_isCurrentRepositoryOperation(operation)) return false; - state = state.copyWith( - isRunningOperation: true, - lastError: null, - lastOperationMessage: null, - ); - try { - final result = await _gateway.restoreFileFromCommit( - operation.repository, - entry.commit.fullHash, - historicalPath: historicalPath, - currentPath: currentPath, - ); - if (!_isCurrentRepositoryOperation(operation)) { - return false; - } - final reloaded = await ref - .read(workspaceControllerProvider.notifier) - .refreshWorkspaceFromDiskPreservingOpenTabs(); - if (!reloaded || !_isCurrentRepositoryOperation(operation)) { - return false; - } - state = state.copyWith( - isRunningOperation: false, - lastOperationMessage: result.message, - ); - await refresh(); - return _isCurrentRepositoryOperation(operation); - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation)) { - return false; - } - _setFailure(error, commandName: 'restore'); - state = state.copyWith(isRunningOperation: false); - return false; + String _stagedDiffFingerprint(String patch) => + sha256.convert(utf8.encode(patch)).toString(); + + void _scheduleRefresh({bool immediate = false}) { + _debounce?.cancel(); + if (immediate) { + unawaited(refresh()); + return; } + _debounce = Timer(_refreshDebounce, () => unawaited(refresh())); } - bool _rejectDirtyWorkspaceRestore() { - if (!ref.read(workspaceControllerProvider).hasUnsavedChanges) return false; + void _setWorkspaceTrustRequiredState() { + _debounce?.cancel(); + _stopRepositoryWatch(); + _workspaceEpoch++; state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.dirtyWorkspace, - userMessageKey: 'gitErrorDirtyWorkspace', - rawMessage: '', - commandName: 'restore', - ), + isRefreshing: false, + requiresWorkspaceTrust: true, + repositoryInfo: null, + statusSnapshot: null, + lastError: null, ); - return true; } - Future resetCurrentBranchToSelectedCommit(GitResetMode mode) async { - final project = state.projectHistory; - final hash = project.selectedCommitHash; - final operation = _captureRepositoryOperation(); - if (hash == null || - operation == null || - !_knownHashes.contains(hash) || - !project.commits.any((commit) => commit.fullHash == hash)) { - _setInvalidCommit(hash ?? ''); - return false; - } - if (operation.repository.currentBranch == null) { - state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.detachedHead, - userMessageKey: 'gitErrorResetDetachedHead', - rawMessage: '', - commandName: 'reset', - ), - ); - return false; - } - if (ref.read(workspaceControllerProvider).hasUnsavedChanges) { - state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.dirtyWorkspace, - userMessageKey: 'gitErrorResetDirtyWorkspace', - rawMessage: '', - commandName: 'reset', - ), - ); - return false; - } - final completed = await _runOperation( - (repository) => _gateway.resetCurrentBranch(repository, hash, mode), - context: operation, - ); - if (!completed || !_isCurrentRepositoryOperation(operation)) { - return false; - } - await loadBranches(); - if (!_isCurrentRepositoryOperation(operation)) { - return false; - } - await loadProjectHistory(); - return _isCurrentRepositoryOperation(operation) && state.lastError == null; + void _stopRepositoryWatch() { + final watch = _repositoryWatch; + _repositoryWatch = null; + if (watch != null) unawaited(watch.cancel()); } - bool get selectedFileHasStagedChanges { - final currentPath = state.fileHistory.currentPath; - if (currentPath == null) { - return false; - } - return state.statusSnapshot?.stagedFiles.any( - (file) => - file.repoRelativePath == currentPath || - (file.hasStagedRename && - file.originalRepoRelativePath == currentPath), - ) ?? - false; - } - - bool isOutsideWorkspace(String repoRelativePath) { - final repository = state.repositoryInfo; - final workspace = state.attachedWorkspace; - if (repository == null || workspace == null) { - return false; - } - final absolute = p.normalize(p.join(repository.rootPath, repoRelativePath)); - if (workspace.kind == WorkspaceKind.singleMarkdown) { - final active = workspace.activeFilePath ?? workspace.rootPath; - return p.normalize(active) != absolute; - } - final relative = p.relative( - absolute, - from: p.normalize(workspace.rootPath), - ); - return relative == '..' || - relative.startsWith('..${p.separator}') || - p.isAbsolute(relative); - } - - void closeDiffFile(String repoRelativePath) { - final openPaths = [...state.openDiffFilePaths]; - final index = openPaths.indexOf(repoRelativePath); - if (index < 0) { - return; - } - openPaths.removeAt(index); - if (openPaths.isEmpty) { - state = state.copyWith( - selectedCommitFilePath: null, - openDiffFilePaths: const [], - ); - return; - } - final nextIndex = index >= openPaths.length ? openPaths.length - 1 : index; - final activePath = state.selectedCommitFilePath == repoRelativePath - ? openPaths[nextIndex] - : state.selectedCommitFilePath; - state = state.copyWith( - selectedCommitFilePath: activePath, - openDiffFilePaths: openPaths, - ); - if (state.selectedView == GitView.projectHistory && activePath != null) { - unawaited(selectCommitFile(activePath)); - } - } - - Future stageFiles(List paths) => - _stageThroughSession(paths, false); - Future unstageFiles(List paths) => - _stageThroughSession(paths, true); - - Future _stageThroughSession(List paths, bool unstage) async { - final operation = _captureRepositoryOperation(), - source = _sharedStatusSource; - if (operation == null) return; - final failure = _validation.validateRepoRelativePaths(paths); - if (failure != null) { - state = state.copyWith(lastError: failure); - return; - } - if (source == null || - source.repository.key != _sharedAssociation?.repository.key) { - _setFailure( - const shared.GitException(shared.GitErrorCode.disconnected), - commandName: 'git', - ); - return; - } - try { - await source.stage(List.unmodifiable(paths), unstage); - } on Object catch (error) { - if (_isCurrentRepositoryOperation(operation)) { - _setFailure(error, commandName: 'git'); - } - } - } - - Future rollbackFiles(List repoRelativePaths) { - return _runPathOperation( - repoRelativePaths, - (repository, paths) => _gateway.rollbackTracked(repository, paths), - ); - } - - Future deleteUntrackedFiles(List repoRelativePaths) async { - final snapshot = state.statusSnapshot; - if (snapshot == null) { - return; - } - final failure = _validation.validateRepoRelativePaths(repoRelativePaths); - if (failure != null) { - state = state.copyWith(lastError: failure); - return; - } - for (final path in repoRelativePaths) { - final status = snapshot.files - .where((file) => file.repoRelativePath == path) - .firstOrNull; - if (status?.untracked != true) { - state = state.copyWith( - lastError: GitFailure( - code: GitFailureCode.invalidPath, - userMessageKey: 'gitErrorUnsafePath', - rawMessage: path, - commandName: 'delete', - ), - ); - return; - } - } - await _runPathOperation( - repoRelativePaths, - (repository, paths) => - _gateway.discardUntracked(repository, paths, snapshot), - ); - } - - Future commit(String message) async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return false; - } - final messageFailure = _validation.validateCommitMessage(message); - final stagedFailure = _validation.validateHasStagedFiles( - state.statusSnapshot, - ); - final failure = messageFailure ?? stagedFailure; - if (failure != null) { - state = state.copyWith(lastError: failure); - return false; - } - final completed = await _runOperation( - (repository) => _gateway.commit(repository, message), - context: operation, - ); - if (completed) { - await loadProjectHistory(); - } - return completed; - } - - Future configureAuthorIdentity({ - required String name, - required String email, - required bool globally, - }) { - return _runOperation( - (repository) => _gateway.configureAuthorIdentity( - repository, - name: name, - email: email, - globally: globally, - ), - ); - } - - Future stagedDiffForAi() async { - final operation = _captureRepositoryOperation(); - if (operation == null || - (state.statusSnapshot?.stagedFiles.isEmpty ?? true)) { - return null; - } - try { - final diff = await _gateway.diffAll(operation.repository, staged: true); - if (!_isCurrentRepositoryOperation(operation)) { - return null; - } - if (diff.rawPatch.trim().isEmpty) { - return null; - } - return GitStagedDiffSnapshot( - patch: diff.rawPatch, - fingerprint: _stagedDiffFingerprint(diff.rawPatch), - ); - } on Object catch (error) { - if (_isCurrentRepositoryOperation(operation)) { - _setFailure(error, commandName: 'diff'); - } - return null; - } - } - - Future stagedDiffMatches(String fingerprint) async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return false; - } - try { - final diff = await _gateway.diffAll(operation.repository, staged: true); - return _isCurrentRepositoryOperation(operation) && - diff.rawPatch.trim().isNotEmpty && - _stagedDiffFingerprint(diff.rawPatch) == fingerprint; - } on Object catch (error) { - if (_isCurrentRepositoryOperation(operation)) { - _setFailure(error, commandName: 'diff'); - } - return false; - } - } - - String _stagedDiffFingerprint(String patch) => - sha256.convert(utf8.encode(patch)).toString(); - - Future pullFastForwardOnly() async { - await _runOperation( - (repository) => _gateway.pullFastForwardOnly(repository), - ); - } - - Future fetch() async { - await _runOperation((repository) => _gateway.fetch(repository)); - } - - Future push({bool allowSetUpstream = false}) async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return; - } - final repository = operation.repository; - if (repository.upstreamBranch != null) { - await _runOperation( - (repository) => _gateway.push(repository), - context: operation, - ); - return; - } - final branch = repository.currentBranch; - if (branch == null) { - state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.noUpstream, - userMessageKey: 'gitErrorNoUpstream', - rawMessage: '', - commandName: 'push', - ), - ); - return; - } - final remotes = await _gateway.remotes(repository); - final currentRepository = _trustedRepositoryInfo; - if (!_isCurrentRepositoryOperation(operation) || - currentRepository?.currentBranch != branch || - currentRepository?.upstreamBranch != null) { - return; - } - if (remotes.isEmpty) { - state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.noRemote, - userMessageKey: 'gitErrorNoRemote', - rawMessage: '', - commandName: 'push', - ), - ); - return; - } - if (remotes.length > 1 || !allowSetUpstream) { - state = state.copyWith( - lastError: GitFailure( - code: remotes.length > 1 - ? GitFailureCode.multipleRemotes - : GitFailureCode.noUpstream, - userMessageKey: remotes.length > 1 - ? 'gitErrorMultipleRemotes' - : 'gitErrorNoUpstream', - rawMessage: remotes.join(', '), - commandName: 'push', - ), - ); - return; - } - await _runOperation( - (repository) => - _gateway.pushSetUpstream(repository, remotes.single, branch), - context: operation, - ); - } - - Future createBranch(String branchName) async { - final failure = _validation.validateBranchNameShape(branchName); - if (failure != null) { - state = state.copyWith(lastError: failure); - return; - } - final completed = await _runOperation( - (repository) => _gateway.createBranch(repository, branchName.trim()), - ); - if (completed) { - await loadBranches(); - } - } - - Future switchBranch(String branchName) async { - if (ref.read(workspaceControllerProvider).hasUnsavedChanges) { - state = state.copyWith( - lastError: const GitFailure( - code: GitFailureCode.dirtyWorkspace, - userMessageKey: 'gitErrorDirtyWorkspace', - rawMessage: '', - commandName: 'switch', - ), - ); - return; - } - final completed = await _runOperation( - (repository) => _gateway.switchBranch(repository, branchName), - ); - if (completed) { - await loadBranches(); - } - } - - Future initializeRepository() async { - final workspace = state.attachedWorkspace; - final context = _captureWorkspaceOperation(); - final trustedWorkspacePath = workspace == null - ? null - : _trustedWorkspaceGitPath(workspace); - if (workspace == null || - context == null || - trustedWorkspacePath == null || - workspace.kind == WorkspaceKind.nextcloudNotes || - workspace.kind == WorkspaceKind.untitledMarkdown || - workspace.kind == WorkspaceKind.singleMarkdown) { - return; - } - if (state.lastError is GitWorkspaceRootRequired) return; - if (_gateway case final GitWorkspaceRootInspector inspector) { - await inspector.requireWorkspaceRoot(workspace.rootPath); - if (!_isCurrentWorkspaceOperation(context)) return; - } - await _runRootOperation( - trustedWorkspacePath, - _gateway.initializeRepository, - context: context, - ); - } - - Future> loadBranches() async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return state.branches; - } - final requestEpoch = ++_branchesEpoch; - state = state.copyWith(isRunningOperation: true, lastError: null); - try { - final branches = await _gateway.branches(operation.repository); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _branchesEpoch) { - return state.branches; - } - state = state.copyWith(isRunningOperation: false, branches: branches); - return branches; - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _branchesEpoch) { - return state.branches; - } - _setFailure(error, commandName: 'branch'); - state = state.copyWith(isRunningOperation: false); - return state.branches; - } - } - - Future _loadFileHistory( - String repoRelativePath, { - bool append = false, - }) async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return; - } - final requestEpoch = ++_fileHistoryEpoch; - final existing = append - ? state.fileHistory.entries - : const []; - state = state.copyWith( - isRunningOperation: true, - lastError: null, - selectedView: GitView.fileHistory, - fileHistory: state.fileHistory.copyWith( - currentPath: repoRelativePath, - isLoadingMore: append, - selectedCommitHash: append - ? state.fileHistory.selectedCommitHash - : null, - comparison: append ? state.fileHistory.comparison : null, - ), - ); - try { - final page = await _gateway.fileHistory( - operation.repository, - repoRelativePath, - limit: _historyPageSize + 1, - skip: existing.length, - ); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _fileHistoryEpoch) { - return; - } - final hasMore = page.length > _historyPageSize; - final entries = [...existing, ...page.take(_historyPageSize)]; - _knownHashes.addAll(entries.map((entry) => entry.commit.fullHash)); - state = state.copyWith( - isRunningOperation: false, - fileHistory: state.fileHistory.copyWith( - entries: entries, - currentPath: repoRelativePath, - hasMore: hasMore, - isLoadingMore: false, - ), - selectedCommitFilePath: append ? state.selectedCommitFilePath : null, - openDiffFilePaths: append ? state.openDiffFilePaths : const [], - ); - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _fileHistoryEpoch) { - return; - } - _setFailure(error, commandName: 'log'); - state = state.copyWith( - isRunningOperation: false, - fileHistory: state.fileHistory.copyWith(isLoadingMore: false), - ); - } - } - - Future loadMoreFileHistory() async { - final history = state.fileHistory; - if (!history.hasMore || - history.isLoadingMore || - history.currentPath == null) { - return; - } - await _loadFileHistory(history.currentPath!, append: true); - } - - Future _loadProjectHistory({bool append = false}) async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return; - } - final requestEpoch = ++_projectHistoryEpoch; - final existing = append - ? state.projectHistory.commits - : const []; - state = state.copyWith( - isRunningOperation: true, - lastError: null, - selectedView: GitView.projectHistory, - projectHistory: state.projectHistory.copyWith( - isLoadingMore: append, - selectedCommitHash: append - ? state.projectHistory.selectedCommitHash - : null, - selectedFilePath: append ? state.projectHistory.selectedFilePath : null, - details: append ? state.projectHistory.details : null, - comparison: append ? state.projectHistory.comparison : null, - ), - ); - try { - final page = await _gateway.history( - operation.repository, - limit: _historyPageSize + 1, - skip: existing.length, - ); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _projectHistoryEpoch) { - return; - } - final hasMore = page.length > _historyPageSize; - final commits = [...existing, ...page.take(_historyPageSize)]; - _knownHashes.addAll(commits.map((commit) => commit.fullHash)); - state = state.copyWith( - isRunningOperation: false, - projectHistory: state.projectHistory.copyWith( - commits: commits, - hasMore: hasMore, - isLoadingMore: false, - ), - selectedCommitFilePath: append ? state.selectedCommitFilePath : null, - openDiffFilePaths: append ? state.openDiffFilePaths : const [], - ); - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _projectHistoryEpoch) { - return; - } - _setFailure(error, commandName: 'log'); - state = state.copyWith( - isRunningOperation: false, - projectHistory: state.projectHistory.copyWith(isLoadingMore: false), - ); - } - } - - Future loadMoreProjectHistory() async { - final history = state.projectHistory; - if (!history.hasMore || history.isLoadingMore) { - return; - } - await _loadProjectHistory(append: true); - } - - Future _loadChangedFileDiff(GitChangeSelection selection) async { - final operation = _captureRepositoryOperation(); - if (operation == null) { - return; - } - final requestEpoch = ++_diffEpoch; - state = state.copyWith(isRunningOperation: true, lastError: null); - try { - final diff = switch (selection.comparison) { - GitComparisonType.staged => _gateway.diffFile( - operation.repository, - selection.path, - staged: true, - originalRepoRelativePath: selection.originalRepoRelativePath, - ), - GitComparisonType.unstaged => _gateway.diffFile( - operation.repository, - selection.path, - staged: false, - originalRepoRelativePath: selection.originalRepoRelativePath, - ), - GitComparisonType.untracked => _gateway.diffUntrackedFile( - operation.repository, - selection.path, - ), - GitComparisonType.commitChange || - GitComparisonType.commitVersusCurrent => throw StateError( - 'Historical comparison cannot be loaded as a working-tree change.', - ), - }; - final loaded = await diff; - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _diffEpoch || - state.selectedChange != selection) { - return; - } - state = state.copyWith( - isRunningOperation: false, - changeDiff: loaded, - selectedCommitFilePath: selection.path, - openDiffFilePaths: [selection.path], - ); - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _diffEpoch) { - return; - } - _setFailure(error, commandName: 'diff'); - state = state.copyWith(isRunningOperation: false); - } - } - - Future _loadProjectFileComparison( - _GitRepositoryOperation operation, - String hash, - String repoRelativePath, { - required int requestEpoch, - }) async { - try { - final file = state.projectHistory.details?.changedFiles - .where((candidate) => candidate.matchesPath(repoRelativePath)) - .firstOrNull; - if (file == null) { - state = state.copyWith(isRunningOperation: false); - return; - } - final comparison = await _gateway.compareFileWithParent( - operation.repository, - hash, - oldPath: file.oldPath, - newPath: file.newPath, - ); - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch || - state.projectHistory.selectedCommitHash != hash || - state.projectHistory.selectedFilePath != repoRelativePath) { - return; - } - final displayPath = comparison.newPath ?? comparison.oldPath; - final openPaths = displayPath == null - ? state.openDiffFilePaths - : state.openDiffFilePaths.contains(displayPath) - ? state.openDiffFilePaths - : [...state.openDiffFilePaths, displayPath]; - state = state.copyWith( - isRunningOperation: false, - projectHistory: state.projectHistory.copyWith( - comparisonType: GitComparisonType.commitChange, - comparison: comparison, - ), - selectedCommitFilePath: displayPath, - openDiffFilePaths: openPaths, - ); - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(operation) || - requestEpoch != _commitDetailsEpoch) { - return; - } - _setFailure(error, commandName: 'show'); - state = state.copyWith(isRunningOperation: false); - } - } - - Future _comparisonFromEmptyWorkingTree( - GitRepositoryInfo repository, - String currentPath, - ) async { - final diff = await _gateway.diffUntrackedFile(repository, currentPath); - return GitHistoricalFileComparison( - oldPath: null, - newPath: diff.files.isEmpty ? null : currentPath, - oldContent: '', - newContent: diff.files.isEmpty ? '' : diff.fileSnapshots[currentPath], - diff: diff, - ); - } - - Future _runPathOperation( - List repoRelativePaths, - Future Function( - GitRepositoryInfo repository, - List paths, - ) - operation, - ) async { - final context = _captureRepositoryOperation(); - if (context == null) { - return; - } - final failure = _validation.validateRepoRelativePaths(repoRelativePaths); - if (failure != null) { - state = state.copyWith(lastError: failure); - return; - } - await _runOperation( - (repository) => operation(repository, repoRelativePaths), - context: context, - ); - } - - Future _runOperation( - Future Function(GitRepositoryInfo repository) - operation, { - _GitRepositoryOperation? context, - }) async { - final currentContext = context ?? _captureRepositoryOperation(); - if (currentContext == null || - !_isCurrentRepositoryOperation(currentContext)) { - return false; - } - state = state.copyWith( - isRunningOperation: true, - lastError: null, - lastOperationMessage: null, - ); - try { - final result = await operation(currentContext.repository); - if (!_isCurrentRepositoryOperation(currentContext)) { - return false; - } - state = state.copyWith( - isRunningOperation: false, - lastOperationMessage: result.message, - ); - await refresh(); - if (!_isCurrentRepositoryOperation(currentContext)) { - return false; - } - final selected = state.selectedChange; - if (selected != null) { - await _loadChangedFileDiff(selected); - if (!_isCurrentRepositoryOperation(currentContext)) { - return false; - } - } - return true; - } on Object catch (error) { - if (!_isCurrentRepositoryOperation(currentContext)) { - return false; - } - _setFailure(error, commandName: 'git'); - state = state.copyWith(isRunningOperation: false); - return false; - } - } - - Future _runRootOperation( - String rootPath, - Future Function(String rootPath) operation, { - required _GitWorkspaceOperation context, - }) async { - if (!_isCurrentWorkspaceOperation(context)) { - return false; - } - state = state.copyWith( - isRunningOperation: true, - lastError: null, - lastOperationMessage: null, - ); - try { - final result = await operation(rootPath); - if (!_isCurrentWorkspaceOperation(context)) { - return false; - } - state = state.copyWith( - isRunningOperation: false, - lastOperationMessage: result.message, - ); - await refresh(); - return _isCurrentWorkspaceOperation(context); - } on Object catch (error) { - if (!_isCurrentWorkspaceOperation(context)) { - return false; - } - _setFailure(error, commandName: 'git'); - state = state.copyWith(isRunningOperation: false); - return false; - } - } - - void _scheduleRefresh({bool immediate = false}) { - _debounce?.cancel(); - if (immediate) { - unawaited(refresh()); - return; - } - _debounce = Timer(_refreshDebounce, () => unawaited(refresh())); - } - - void _setWorkspaceTrustRequiredState() { - _debounce?.cancel(); - _workspaceEpoch++; - _knownHashes = {}; - state = state.copyWith( - isRefreshing: false, - isRunningOperation: false, - requiresWorkspaceTrust: true, - repositoryInfo: null, - statusSnapshot: null, - selectedChange: null, - changeDiff: null, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - fileHistory: const GitFileHistoryState(), - projectHistory: const GitProjectHistoryState(), - branches: const [], - lastError: null, - lastOperationMessage: null, - scopedFilePath: null, - ); - } - - void _setFailure(Object error, {required String commandName}) { - final failure = error is GitFailure - ? error - : GitFailure( - code: GitFailureCode.commandFailed, - userMessageKey: 'gitErrorCommandFailed', - rawMessage: '$error', - commandName: commandName, - ); - state = state.copyWith(lastError: failure); + void _setFailure(Object error, {required String commandName}) { + final failure = error is GitFailure + ? error + : GitFailure( + code: GitFailureCode.commandFailed, + userMessageKey: 'gitErrorCommandFailed', + rawMessage: '$error', + commandName: commandName, + ); + state = state.copyWith(lastError: failure); } GitState _workspaceResetState( @@ -1978,7 +632,6 @@ class GitController extends Notifier { }) { return GitState( availability: availability ?? state.availability, - selectedView: GitView.changes, attachedWorkspace: workspace, requiresWorkspaceTrust: !_workspaceHasGitTrust(workspace), ); @@ -2066,158 +719,6 @@ class GitController extends Notifier { } return state.repositoryInfo; } - - String? _workspaceScopedRepoPath( - Workspace workspace, - GitRepositoryInfo repository, - ) { - final active = workspace.activeFilePath ?? workspace.markdown?.filePath; - if (active == null || !isMarkdownPath(active)) { - return null; - } - return _repoRelativePath(repository.rootPath, active); - } - - String? _repoRelativePath(String rootPath, String absolutePath) { - final relative = p.normalize(p.relative(absolutePath, from: rootPath)); - if (relative == '.' || - relative.startsWith('..') || - p.isAbsolute(relative)) { - return null; - } - return relative.replaceAll(r'\', '/'); - } - - GitChangeSelection? _preferredChangeSelection(String repoRelativePath) { - final snapshot = state.statusSnapshot; - if (snapshot == null) { - return null; - } - final file = snapshot.files - .where((candidate) => candidate.repoRelativePath == repoRelativePath) - .firstOrNull; - if (file == null || file.conflicted) { - return null; - } - if (file.unstaged) { - return GitChangeSelection( - path: repoRelativePath, - comparison: GitComparisonType.unstaged, - originalRepoRelativePath: file.hasUnstagedRename - ? file.originalRepoRelativePath - : null, - ); - } - if (file.untracked) { - return GitChangeSelection( - path: repoRelativePath, - comparison: GitComparisonType.untracked, - ); - } - if (file.staged) { - return GitChangeSelection( - path: repoRelativePath, - comparison: GitComparisonType.staged, - originalRepoRelativePath: file.hasStagedRename - ? file.originalRepoRelativePath - : null, - ); - } - return null; - } - - GitChangeSelection? _reconcileChangeSelection( - GitChangeSelection? selection, - GitStatusSnapshot snapshot, - ) { - if (selection == null) { - return null; - } - final file = snapshot.files - .where((candidate) => candidate.repoRelativePath == selection.path) - .firstOrNull; - if (file == null || file.conflicted) { - return null; - } - final stillExists = switch (selection.comparison) { - GitComparisonType.staged => file.staged, - GitComparisonType.unstaged => file.unstaged, - GitComparisonType.untracked => file.untracked, - GitComparisonType.commitChange || - GitComparisonType.commitVersusCurrent => false, - }; - if (stillExists) { - return GitChangeSelection( - path: selection.path, - comparison: selection.comparison, - originalRepoRelativePath: _originalPathForComparison( - file, - selection.comparison, - ), - ); - } - if (file.unstaged) { - return GitChangeSelection( - path: selection.path, - comparison: GitComparisonType.unstaged, - originalRepoRelativePath: file.hasUnstagedRename - ? file.originalRepoRelativePath - : null, - ); - } - if (file.untracked) { - return GitChangeSelection( - path: selection.path, - comparison: GitComparisonType.untracked, - ); - } - if (file.staged) { - return GitChangeSelection( - path: selection.path, - comparison: GitComparisonType.staged, - originalRepoRelativePath: file.hasStagedRename - ? file.originalRepoRelativePath - : null, - ); - } - return null; - } - - String? _originalPathForComparison( - GitFileStatus file, - GitComparisonType comparison, - ) { - return switch (comparison) { - GitComparisonType.staged => - file.hasStagedRename ? file.originalRepoRelativePath : null, - GitComparisonType.unstaged => - file.hasUnstagedRename ? file.originalRepoRelativePath : null, - GitComparisonType.untracked || - GitComparisonType.commitChange || - GitComparisonType.commitVersusCurrent => null, - }; - } - - void _setInvalidCommit(String hash) { - state = state.copyWith( - lastError: GitFailure( - code: GitFailureCode.invalidPath, - userMessageKey: 'gitErrorInvalidCommit', - rawMessage: hash, - commandName: 'show', - ), - ); - } - - String? _firstDiffFilePath(List files) { - for (final file in files) { - final path = file.displayPath; - if (path.isNotEmpty) { - return path; - } - } - return null; - } } class _GitWorkspaceOperation { @@ -2260,169 +761,12 @@ class UnavailableGitRepositoryGateway implements GitRepositoryGateway { _unavailable(); @override - Future diffFile( - GitRepositoryInfo repository, - String repoRelativePath, { - required bool staged, - String? originalRepoRelativePath, - }) => _unavailable(); - - @override - Future diffUntrackedFile( - GitRepositoryInfo repository, - String repoRelativePath, - ) => _unavailable(); - - @override - Future diffAll( - GitRepositoryInfo repository, { - required bool staged, - }) => _unavailable(); - - @override - Future> history( - GitRepositoryInfo repository, { - String? repoRelativePath, - int limit = 200, - int skip = 0, - }) => _unavailable(); - - @override - Future> fileHistory( - GitRepositoryInfo repository, - String repoRelativePath, { - int limit = 200, - int skip = 0, - }) => _unavailable(); - - @override - Future commitDetails( - GitRepositoryInfo repository, - String hash, { - String? repoRelativePath, - }) => _unavailable(); - - @override - Future readFileAtCommit( - GitRepositoryInfo repository, - String hash, - String repoRelativePath, - ) => _unavailable(); + Stream watch(GitRepositoryInfo repository) => _unavailable(); @override - Future compareFileWithParent( - GitRepositoryInfo repository, - String hash, { - String? oldPath, - String? newPath, - }) => _unavailable(); + Future stagedPatch(GitRepositoryInfo repository) => _unavailable(); - @override - Future compareFileWithWorkingTree( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }) => _unavailable(); - - @override - Future restoreFileFromCommit( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }) => _unavailable(); - - @override - Future resetCurrentBranch( - GitRepositoryInfo repository, - String hash, - GitResetMode mode, - ) => _unavailable(); - - @override - Future> branches(GitRepositoryInfo repository) => - _unavailable(); - - @override - Future> remotes(GitRepositoryInfo repository) => _unavailable(); - - @override - Future stage( - GitRepositoryInfo repository, - List repoRelativePaths, - ) => _unavailable(); - - @override - Future unstage( - GitRepositoryInfo repository, - List repoRelativePaths, - ) => _unavailable(); - - @override - Future rollbackTracked( - GitRepositoryInfo repository, - List repoRelativePaths, - ) => _unavailable(); - - @override - Future discardUntracked( - GitRepositoryInfo repository, - List repoRelativePaths, - GitStatusSnapshot snapshot, - ) => _unavailable(); - - @override - Future commit( - GitRepositoryInfo repository, - String message, - ) => _unavailable(); - - @override - Future configureAuthorIdentity( - GitRepositoryInfo repository, { - required String name, - required String email, - required bool globally, - }) => _unavailable(); - - @override - Future fetch(GitRepositoryInfo repository) => - _unavailable(); - - @override - Future pullFastForwardOnly( - GitRepositoryInfo repository, - ) => _unavailable(); - - @override - Future push(GitRepositoryInfo repository) => - _unavailable(); - - @override - Future pushSetUpstream( - GitRepositoryInfo repository, - String remote, - String branch, - ) => _unavailable(); - - @override - Future createBranch( - GitRepositoryInfo repository, - String branchName, - ) => _unavailable(); - - @override - Future switchBranch( - GitRepositoryInfo repository, - String branchName, - ) => _unavailable(); - - @override - Future initializeRepository(String rootPath) => - _unavailable(); - - Future _unavailable() { + Never _unavailable() { throw const GitFailure( code: GitFailureCode.unavailable, userMessageKey: 'gitErrorUnavailable', @@ -2432,8 +776,4 @@ class UnavailableGitRepositoryGateway implements GitRepositoryGateway { } } -extension _FirstOrNull on Iterable { - T? get firstOrNull => isEmpty ? null : first; -} - const Object _unset = Object(); diff --git a/lib/src/git/application/git_gateway.dart b/lib/src/git/application/git_gateway.dart index e322cef8..1fffb25a 100644 --- a/lib/src/git/application/git_gateway.dart +++ b/lib/src/git/application/git_gateway.dart @@ -1,16 +1,14 @@ import '../domain/git_models.dart'; -abstract class GitRepositoryDetector { - Future availability(); - Future detectRepository(String workspacePath); -} - /// Optional controlled, non-executing discovery for the application policy. abstract interface class GitWorkspaceRootInspector { Future requireWorkspaceRoot(String workspacePath); } -abstract class GitRepositoryGateway implements GitRepositoryDetector { +abstract class GitRepositoryGateway { + Future availability(); + Future detectRepository(String workspacePath); + /// Whether this gateway can execute repository-controlled configuration. /// /// The controller will not call [detectRepository] or any repository method @@ -18,106 +16,6 @@ abstract class GitRepositoryGateway implements GitRepositoryDetector { bool get requiresWorkspaceTrust; Future status(GitRepositoryInfo repository); - Future diffFile( - GitRepositoryInfo repository, - String repoRelativePath, { - required bool staged, - String? originalRepoRelativePath, - }); - Future diffUntrackedFile( - GitRepositoryInfo repository, - String repoRelativePath, - ); - Future diffAll(GitRepositoryInfo repository, {required bool staged}); - Future> history( - GitRepositoryInfo repository, { - String? repoRelativePath, - int limit = 200, - int skip = 0, - }); - Future> fileHistory( - GitRepositoryInfo repository, - String repoRelativePath, { - int limit = 200, - int skip = 0, - }); - Future commitDetails( - GitRepositoryInfo repository, - String hash, { - String? repoRelativePath, - }); - Future readFileAtCommit( - GitRepositoryInfo repository, - String hash, - String repoRelativePath, - ); - Future compareFileWithParent( - GitRepositoryInfo repository, - String hash, { - String? oldPath, - String? newPath, - }); - Future compareFileWithWorkingTree( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }); - Future restoreFileFromCommit( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }); - Future resetCurrentBranch( - GitRepositoryInfo repository, - String hash, - GitResetMode mode, - ); - Future> branches(GitRepositoryInfo repository); - Future> remotes(GitRepositoryInfo repository); - Future stage( - GitRepositoryInfo repository, - List repoRelativePaths, - ); - Future unstage( - GitRepositoryInfo repository, - List repoRelativePaths, - ); - Future rollbackTracked( - GitRepositoryInfo repository, - List repoRelativePaths, - ); - Future discardUntracked( - GitRepositoryInfo repository, - List repoRelativePaths, - GitStatusSnapshot snapshot, - ); - Future commit( - GitRepositoryInfo repository, - String message, - ); - Future configureAuthorIdentity( - GitRepositoryInfo repository, { - required String name, - required String email, - required bool globally, - }); - Future fetch(GitRepositoryInfo repository); - Future pullFastForwardOnly(GitRepositoryInfo repository); - Future push(GitRepositoryInfo repository); - Future pushSetUpstream( - GitRepositoryInfo repository, - String remote, - String branch, - ); - Future createBranch( - GitRepositoryInfo repository, - String branchName, - ); - Future switchBranch( - GitRepositoryInfo repository, - String branchName, - ); - Future initializeRepository(String rootPath); + Stream watch(GitRepositoryInfo repository); + Future stagedPatch(GitRepositoryInfo repository); } diff --git a/lib/src/git/application/git_use_cases.dart b/lib/src/git/application/git_use_cases.dart index 63279ba2..0c1d167b 100644 --- a/lib/src/git/application/git_use_cases.dart +++ b/lib/src/git/application/git_use_cases.dart @@ -5,49 +5,6 @@ import '../domain/git_models.dart'; class GitValidation { const GitValidation(); - GitFailure? validateCommitMessage(String message) { - if (message.trim().isEmpty) { - return const GitFailure( - code: GitFailureCode.invalidCommitMessage, - userMessageKey: 'gitErrorEmptyCommitMessage', - rawMessage: '', - commandName: 'commit', - ); - } - return null; - } - - GitFailure? validateHasStagedFiles(GitStatusSnapshot? snapshot) { - if (snapshot == null || snapshot.stagedFiles.isEmpty) { - return const GitFailure( - code: GitFailureCode.noStagedFiles, - userMessageKey: 'gitErrorNoStagedFiles', - rawMessage: '', - commandName: 'commit', - ); - } - return null; - } - - GitFailure? validateBranchNameShape(String branchName) { - final value = branchName.trim(); - if (value.isEmpty || - value.startsWith('-') || - value.contains('..') || - value.contains(' ') || - value.endsWith('.') || - value.endsWith('/') || - value.contains(RegExp(r'[\x00-\x20~^:?*\\[]'))) { - return GitFailure( - code: GitFailureCode.invalidBranchName, - userMessageKey: 'gitErrorInvalidBranchName', - rawMessage: branchName, - commandName: 'check-ref-format', - ); - } - return null; - } - GitFailure? validateRepoRelativePaths(List paths) { for (final path in paths) { if (!_safeRepoRelativePath(path)) { @@ -62,10 +19,6 @@ class GitValidation { return null; } - bool isHashAllowed(String hash, Iterable knownCommits) { - return knownCommits.any((commit) => commit.fullHash == hash); - } - bool _safeRepoRelativePath(String path) { if (path.isEmpty || p.isAbsolute(path) || path.contains('\x00')) { return false; diff --git a/lib/src/git/application/shared_git_integration.dart b/lib/src/git/application/shared_git_integration.dart index ab7cb788..23925df3 100644 --- a/lib/src/git/application/shared_git_integration.dart +++ b/lib/src/git/application/shared_git_integration.dart @@ -72,7 +72,7 @@ class _BusyMarkGitWorkspaceScopeState final _sessions = >{}; final _owned = []; final _eligibleRepositories = {}; - final _legacyListeners = {}; + final _statusListeners = {}; var _discoveryCancellation = shared.GitCancellation(); var _generation = 0; Future? _discovery; @@ -177,7 +177,7 @@ class _BusyMarkGitWorkspaceScopeState ref.read(sharedGitReviewProvider)[workspace.id] ?? const shared.GitReviewTabs(), ); - _bindLegacyStatus(workspace, target, session); + _bindStatus(workspace, target, session); await session.start(); if (!mounted || generation != _generation) { throw const shared.GitException(shared.GitErrorCode.cancelled); @@ -210,43 +210,29 @@ class _BusyMarkGitWorkspaceScopeState } } - void _bindLegacyStatus( + void _bindStatus( Workspace workspace, shared.RepositoryId repository, shared.GitSession session, ) { - final engine = client; - if (engine is! shared.GitWorkflowClient) return; final generation = _generation; shared.GitSnapshot? projected; - Future? projection; - Future current() { + GitStatusSnapshot? projection; + Future current() async { final snapshot = session.snapshot; - if (snapshot == null) return Future.value(null); - if (identical(projected, snapshot) && projection != null) { - return projection!; + if (snapshot == null) return null; + if (!identical(projected, snapshot)) { + projected = snapshot; + projection = GitCliGateway.projectSharedStatus(snapshot); } - projected = snapshot; - return projection = () async { - final metadata = await (engine as shared.GitWorkflowClient).inspect( - repository, - const shared.GitInspection(shared.GitInspectionKind.remotes), - ); - if (!mounted || generation != _generation) { - throw const shared.GitException(shared.GitErrorCode.cancelled); - } - final remotes = metadata['remotes'] as List; - return GitCliGateway.projectSharedStatus( - snapshot, - hasRemote: remotes.isNotEmpty, - ); - }(); + return projection; } final controller = ref.read(gitControllerProvider.notifier); if (!controller.bindSharedStatusSource( workspace, repository, + owner: session, current: current, stage: (paths, unstage) async { if (!mounted || generation != _generation || session.isDisposed) return; @@ -274,10 +260,10 @@ class _BusyMarkGitWorkspaceScopeState )) { return; } + _statusReleases.add(() => controller.releaseSharedStatusSource(session)); shared.GitSnapshot? observed; void changed() { if (!mounted || generation != _generation) return; - controller.projectSharedOperation(workspace, repository, session.running); if (session.snapshot == null || identical(observed, session.snapshot)) { return; } @@ -285,17 +271,23 @@ class _BusyMarkGitWorkspaceScopeState unawaited(controller.refreshFromSharedSnapshot()); } - _legacyListeners[session] = changed; + _statusListeners[session] = changed; session.addListener(changed); } + final _statusReleases = []; + void _releaseAttachments() { _generation++; _discoveryCancellation.cancel(); - for (final entry in _legacyListeners.entries) { + for (final entry in _statusListeners.entries) { entry.key.removeListener(entry.value); } - _legacyListeners.clear(); + _statusListeners.clear(); + for (final release in _statusReleases) { + release(); + } + _statusReleases.clear(); for (final session in _owned) { session.dispose(); } diff --git a/lib/src/git/data/git_cli_gateway.dart b/lib/src/git/data/git_cli_gateway.dart deleted file mode 100644 index e852734f..00000000 --- a/lib/src/git/data/git_cli_gateway.dart +++ /dev/null @@ -1,2 +0,0 @@ -// Kept as the application import path; Git behavior lives in busystack_git. -export 'git_shared_gateway.dart'; diff --git a/lib/src/git/data/git_executable_locator.dart b/lib/src/git/data/git_executable_locator.dart deleted file mode 100644 index 851e1aa9..00000000 --- a/lib/src/git/data/git_executable_locator.dart +++ /dev/null @@ -1,148 +0,0 @@ -import 'dart:io'; - -import '../domain/git_models.dart'; -import 'git_process_runner.dart'; - -class GitExecutableLocator { - const GitExecutableLocator({ - this.runner = const DartGitCommandRunner(), - this.candidatePaths, - }); - - final GitCommandRunner runner; - final List? candidatePaths; - - Future locate() async { - String? probeFailure; - for (final candidate in candidatePaths ?? _candidates()) { - try { - final result = await runner.run( - candidate, - const ['--version'], - timeout: gitExecutableProbeTimeout, - commandName: 'git', - ); - if (!result.success) { - probeFailure ??= _probeResultFailure(candidate, result); - continue; - } - final version = _parseVersion(result.stdoutText); - if (version == null) { - final detail = result.stdoutText.trim().isNotEmpty - ? result.stdoutText.trim() - : result.stderrText.trim(); - return GitAvailability( - available: false, - executablePath: candidate, - unavailableReason: - 'Git at "$candidate" returned an unrecognized version' - '${detail.isEmpty ? '.' : ': $detail'}', - ); - } - if (!_supportsSwitchAndRestore(version)) { - return GitAvailability( - available: false, - executablePath: candidate, - version: version.raw, - unavailableReason: 'Git 2.56 or newer is required.', - ); - } - return GitAvailability( - available: true, - executablePath: candidate, - version: version.raw, - ); - } on Object catch (error) { - probeFailure ??= _probeExceptionFailure(candidate, error); - continue; - } - } - return GitAvailability.unavailable( - probeFailure ?? 'Git executable was not found.', - ); - } - - String _probeResultFailure(String candidate, GitProcessResult result) { - final detail = result.stderrText.trim().isNotEmpty - ? result.stderrText.trim() - : result.stdoutText.trim(); - return 'Git at "$candidate" exited with code ${result.exitCode} while ' - 'checking its version${detail.isEmpty ? '.' : ': $detail'}'; - } - - String? _probeExceptionFailure(String candidate, Object error) { - if (error is ProcessException) { - if (error.errorCode == 2 && !File(candidate).existsSync()) { - return null; - } - final launcher = error.executable.isEmpty ? candidate : error.executable; - final errorCode = error.errorCode == 0 ? '' : ' (${error.errorCode})'; - return 'Git was found at "$candidate", but "$launcher" could not be ' - 'started: ${error.message}$errorCode.'; - } - if (error is GitFailure) { - return 'Git probe for "$candidate" failed: ${error.rawMessage}'; - } - return 'Git probe for "$candidate" failed: $error'; - } - - Iterable _candidates() sync* { - final snap = Platform.environment['SNAP']; - if (snap != null && snap.isNotEmpty) { - final bundled = '$snap/usr/bin/git'; - if (File(bundled).existsSync()) { - yield bundled; - } - } - final seen = {}; - for (final directory in (Platform.environment['PATH'] ?? '').split(':')) { - if (directory.isEmpty) { - continue; - } - final candidate = '$directory/git'; - if (seen.add(candidate) && File(candidate).existsSync()) { - yield candidate; - } - } - if (seen.add('git')) { - yield 'git'; - } - } - - _GitVersion? _parseVersion(String output) { - final match = RegExp(r'git version (\d+)\.(\d+)\.(\d+)').firstMatch(output); - if (match == null) { - return null; - } - return _GitVersion( - raw: match.group(0)!.replaceFirst('git version ', ''), - major: int.parse(match.group(1)!), - minor: int.parse(match.group(2)!), - patch: int.parse(match.group(3)!), - ); - } - - bool _supportsSwitchAndRestore(_GitVersion version) { - if (version.major > 2) { - return true; - } - if (version.major < 2) { - return false; - } - return version.minor >= 56; - } -} - -class _GitVersion { - const _GitVersion({ - required this.raw, - required this.major, - required this.minor, - required this.patch, - }); - - final String raw; - final int major; - final int minor; - final int patch; -} diff --git a/lib/src/git/data/git_process_runner.dart b/lib/src/git/data/git_process_runner.dart deleted file mode 100644 index cf6ea05b..00000000 --- a/lib/src/git/data/git_process_runner.dart +++ /dev/null @@ -1,162 +0,0 @@ -import 'package:busystack_git/busystack_git.dart' as shared; -import 'dart:convert'; -import 'dart:io'; - -import '../domain/git_models.dart'; - -const gitCommandTimeout = Duration(minutes: 2); -const gitExecutableProbeTimeout = Duration(seconds: 5); -const gitCommandOutputLimitBytes = 32 * 1024 * 1024; - -abstract class GitCommandRunner { - Future run( - String executable, - List arguments, { - String? workingDirectory, - required Duration timeout, - required String commandName, - Map environment = const {}, - }); -} - -class GitProcessResult { - const GitProcessResult({ - required this.executable, - required this.arguments, - required this.exitCode, - required this.stdoutBytes, - required this.stderrBytes, - }); - - final String executable; - final List arguments; - final int exitCode; - final List stdoutBytes; - final List stderrBytes; - - String get stdoutText => utf8.decode(stdoutBytes, allowMalformed: true); - String get stderrText => utf8.decode(stderrBytes, allowMalformed: true); - - bool get success => exitCode == 0; -} - -/// Compatibility boundary for application probes and existing runner regressions. -/// Process creation, binary capture and process-group cleanup are shared. -class DartGitCommandRunner implements GitCommandRunner { - const DartGitCommandRunner({ - this.processGroupLauncher = const GitProcessGroupLauncher(), - this.maxOutputBytes = gitCommandOutputLimitBytes, - }); - final GitProcessGroupLauncher processGroupLauncher; - final int maxOutputBytes; - @override - Future run( - String executable, - List arguments, { - String? workingDirectory, - required Duration timeout, - required String commandName, - Map environment = const {}, - }) async { - if (timeout <= Duration.zero) throw ArgumentError.value(timeout, 'timeout'); - try { - final result = - await shared.ProcessGitRunner( - executable: executable, - maximumOutputBytes: maxOutputBytes, - ).run( - arguments, - cwd: workingDirectory ?? Directory.current.path, - deadline: timeout, - environment: { - ...gitEnvironmentForSnap(processGroupLauncher.snapRootOverride), - ...environment, - }, - ); - return GitProcessResult( - executable: executable, - arguments: List.unmodifiable(arguments), - exitCode: result.exitCode, - stdoutBytes: result.stdout, - stderrBytes: result.stderr, - ); - } on shared.GitException catch (error) { - throw GitFailure( - code: GitFailureCode.commandFailed, - userMessageKey: 'gitErrorCommandFailed', - commandName: commandName, - rawMessage: error.code == shared.GitErrorCode.outputLimit - ? 'Git command output exceeded the $maxOutputBytes-byte capture limit.' - : error.code == shared.GitErrorCode.deadline - ? 'Git command timed out.' - : error.diagnostic, - ); - } - } -} - -Map gitEnvironmentForSnap([String? snapRootOverride]) { - final snapRoot = snapRootOverride ?? Platform.environment['SNAP']; - if (snapRoot == null || snapRoot.isEmpty) { - return const {}; - } - return { - 'GIT_EXEC_PATH': '$snapRoot/usr/lib/git-core', - 'GIT_TEMPLATE_DIR': '$snapRoot/usr/share/git-core/templates', - 'GIT_SSH': '$snapRoot/usr/bin/ssh', - }; -} - -class GitProcessGroupLauncher { - const GitProcessGroupLauncher({this.snapRootOverride}); - - final String? snapRootOverride; - - GitProcessLaunch resolve(String executable, List arguments) { - if (!Platform.isLinux) { - return GitProcessLaunch( - executable: executable, - arguments: arguments, - processGroup: false, - ); - } - - final snapRoot = snapRootOverride ?? Platform.environment['SNAP']; - if (snapRoot != null && snapRoot.isNotEmpty) { - final bundledSetsid = '$snapRoot/usr/bin/setsid'; - if (File(bundledSetsid).existsSync()) { - return GitProcessLaunch( - executable: bundledSetsid, - arguments: ['--wait', '--', executable, ...arguments], - processGroup: true, - ); - } - // Prefer the packaged launcher whenever this binary runs from a Snap. A - // malformed package should retain Git support while sacrificing - // process-group cleanup until its packaging is corrected. - return GitProcessLaunch( - executable: executable, - arguments: arguments, - processGroup: false, - ); - } - - return GitProcessLaunch( - executable: 'setsid', - arguments: ['--wait', '--', executable, ...arguments], - processGroup: true, - ); - } -} - -class GitProcessLaunch { - const GitProcessLaunch({ - required this.executable, - required this.arguments, - required this.processGroup, - }); - - final String executable; - final List arguments; - final bool processGroup; -} diff --git a/lib/src/git/data/git_shared_gateway.dart b/lib/src/git/data/git_shared_gateway.dart index eef8a4c3..f366e0d6 100644 --- a/lib/src/git/data/git_shared_gateway.dart +++ b/lib/src/git/data/git_shared_gateway.dart @@ -1,19 +1,16 @@ import 'dart:convert'; import 'package:busystack_git/busystack_git.dart' as shared; import 'package:path/path.dart' as p; -import '../../core/anchored_path_guard.dart'; import '../application/git_gateway.dart'; import '../application/git_workspace_eligibility.dart'; -import '../domain/git_diff_parser.dart'; import '../domain/git_models.dart'; -/// Application compatibility adapter for authoring commands and the optional -/// message drafter. All Git execution and mutations belong to busystack_git. +/// Host adapter for file status and AI patch access. +/// All Git execution and mutations belong to busystack_git. /// Workspace trust, dirty buffers, localization and navigation remain here. class GitCliGateway implements GitRepositoryGateway, GitWorkspaceRootInspector { - const GitCliGateway({this.engine, this.diffParser = const GitDiffParser()}); + const GitCliGateway({this.engine}); final shared.GitEngine? engine; - final GitDiffParser diffParser; static final _engines = Expando(); shared.GitEngine get core => engine ?? (_engines[this] ??= shared.GitEngine(authorize: (_) => true)); @@ -80,845 +77,103 @@ class GitCliGateway implements GitRepositoryGateway, GitWorkspaceRootInspector { final id = await core.discover(workspacePath); if (id == null) return null; await requireGitWorkspaceRoot(workspacePath, id.root, bare: id.bare); - final state = await core.status(id); - final remotes = - (await core.inspect( - id, - const shared.GitInspection(shared.GitInspectionKind.remotes), - ))['remotes'] - as List; - return _info(state, hasRemote: remotes.isNotEmpty); + return _info(id); }); @override Future status(GitRepositoryInfo repository) => _map(() async { final id = await _repo(repository), state = await core.status(id); - final remotes = - (await core.inspect( - id, - const shared.GitInspection(shared.GitInspectionKind.remotes), - ))['remotes'] - as List; - return projectSharedStatus(state, hasRemote: remotes.isNotEmpty); + return projectSharedStatus(state); }, 'status'); - static GitRepositoryInfo _info( - shared.GitSnapshot state, { - bool hasRemote = false, - }) => GitRepositoryInfo( - rootPath: state.repository.root, - gitDirPath: state.repository.gitDir, - identityKey: state.repository.key, - currentBranch: state.branch, - detachedHeadCommit: state.branch == null ? state.head?.abbreviated : null, - upstreamBranch: state.upstream, - aheadCount: state.ahead, - behindCount: state.behind, - hasRemote: hasRemote, - isBare: state.repository.bare, - isRebasing: state.operation.kind == shared.GitOperationKind.rebase, - isMerging: state.operation.kind == shared.GitOperationKind.merge, - isCherryPicking: state.operation.kind == shared.GitOperationKind.cherryPick, - hasConflicts: state.operation.unmerged, - ); - static GitStatusSnapshot projectSharedStatus( - shared.GitSnapshot state, { - bool hasRemote = false, - }) => GitStatusSnapshot( - source: state, - repositoryInfo: _info(state, hasRemote: hasRemote), - unrepresentedPathCount: state.changes - .where((change) => change.path.utf8Path == null) - .length, - files: [ - for (final change in state.changes) - if (change.path.utf8Path != null) - GitFileStatus( - repoRelativePath: change.path.utf8Path!, - absolutePath: p.join(state.repository.root, change.path.utf8Path!), - originalRepoRelativePath: change.originalPath?.utf8Path, - indexStatus: _letter(change.index), - workTreeStatus: _letter(change.worktree), - category: change.conflicted - ? GitFileStatusCategory.conflicted - : change.untracked - ? GitFileStatusCategory.untracked - : GitFileStatusCategory.values.byName(switch (change.index == - '.' - ? change.worktree - : change.index) { - 'M' => 'modified', - 'A' => 'added', - 'D' => 'deleted', - 'R' => 'renamed', - 'C' => 'copied', - 'T' => 'typeChanged', - '!' => 'ignored', - _ => 'unknown', - }), - staged: change.staged, - unstaged: change.unstaged, - untracked: change.untracked, - deleted: change.index == 'D' || change.worktree == 'D', - renamed: change.index == 'R' || change.worktree == 'R', - copied: change.index == 'C' || change.worktree == 'C', - conflicted: change.conflicted, - ignored: change.ignored, - ), - ], - ); - static GitFileChangeStatus _letter(String value) => switch (value) { - 'M' => GitFileChangeStatus.modified, - 'A' => GitFileChangeStatus.added, - 'D' => GitFileChangeStatus.deleted, - 'R' => GitFileChangeStatus.renamed, - 'C' => GitFileChangeStatus.copied, - 'T' => GitFileChangeStatus.typeChanged, - 'U' => GitFileChangeStatus.unmerged, - '?' => GitFileChangeStatus.untracked, - '!' => GitFileChangeStatus.ignored, - '.' => GitFileChangeStatus.unmodified, - _ => GitFileChangeStatus.unknown, - }; - Future _guard(GitRepositoryInfo repository, String path) async { - try { - shared.RepoPath.text(path); - final anchor = await captureCanonicalDirectoryAnchor(repository.rootPath); - await resolveAnchoredPath( - anchor, - p.join(repository.rootPath, path), - allowRoot: false, - ); - } on Object catch (error) { - throw GitFailure( - code: GitFailureCode.invalidPath, - userMessageKey: 'gitErrorUnsafePath', - rawMessage: '$error', - commandName: 'path', - ); - } - } - - Future _diff( - shared.RepositoryId repo, - shared.GitDiffSpec comparison, - String title, - ) async { - final patch = await core.patch(repo, comparison); - final parsed = diffParser.parse( - utf8.decode(patch.bytes, allowMalformed: true), - title: title, - ); - final snapshots = {}; - for (final file in parsed.files) { - final path = file.newPath ?? file.oldPath; - if (path == null) continue; - final version = file.status == GitDiffFileStatus.deleted - ? comparison.left - : comparison.right; - final value = await core.content( - repo, - shared.RepoPath.text(path), - version, - ); - if (value.text != null) snapshots[path] = value.text!; - } - return GitDiff( - title: title, - files: parsed.files, - rawPatch: parsed.rawPatch, - hasBinaryFiles: parsed.hasBinaryFiles, - fileSnapshots: snapshots, - ); + @override + Stream watch(GitRepositoryInfo repository) async* { + yield* core.watch(await _repo(repository)); } - @override - Future diffFile( - GitRepositoryInfo repository, - String repoRelativePath, { - required bool staged, - String? originalRepoRelativePath, - }) => _map(() async { - await _guard(repository, repoRelativePath); - final id = await _repo(repository), - state = await core.status(await _repo(repository)); - return _diff( - id, - shared.GitDiffSpec( - staged - ? state.head == null - ? const shared.ContentVersion.absent() - : shared.ContentVersion( - shared.ContentKind.commit, - revision: state.head, - ) - : const shared.ContentVersion.index(), - staged - ? const shared.ContentVersion.index() - : const shared.ContentVersion.working(), - paths: [ - if (originalRepoRelativePath != null) - shared.RepoPath.text(originalRepoRelativePath), - shared.RepoPath.text(repoRelativePath), - ], - ), - repoRelativePath, - ); - }, 'diff'); - @override - Future diffAll( - GitRepositoryInfo repository, { - required bool staged, - }) => _map(() async { - final id = await _repo(repository), - state = await core.status(await _repo(repository)); - return _diff( - id, - shared.GitDiffSpec( - staged - ? state.head == null - ? const shared.ContentVersion.absent() - : shared.ContentVersion( - shared.ContentKind.commit, - revision: state.head, - ) - : const shared.ContentVersion.index(), - staged - ? const shared.ContentVersion.index() - : const shared.ContentVersion.working(), - ), - staged ? 'Staged' : 'Unstaged', - ); - }, 'diff'); - @override - Future diffUntrackedFile( - GitRepositoryInfo repository, - String repoRelativePath, - ) => _map(() async { - await _guard(repository, repoRelativePath); - final id = await _repo(repository), - path = shared.RepoPath.text(repoRelativePath); - final value = await core.content( - id, - path, - const shared.ContentVersion.working(), - ); - if (value.availability == shared.ContentAvailability.absent) { - return GitDiff( - title: repoRelativePath, - files: const [], - rawPatch: '', - hasBinaryFiles: false, - ); - } - if (value.text == null) { - return GitDiff( - title: repoRelativePath, + static GitRepositoryInfo _info(shared.RepositoryId id) => GitRepositoryInfo( + rootPath: id.root, + gitDirPath: id.gitDir, + identityKey: id.key, + ); + static GitStatusSnapshot projectSharedStatus(shared.GitSnapshot state) => + GitStatusSnapshot( + source: state, + repositoryInfo: _info(state.repository), + unrepresentedPathCount: state.changes + .where((change) => change.path.utf8Path == null) + .length, files: [ - GitDiffFile( - newPath: repoRelativePath, - status: GitDiffFileStatus.binary, - hunks: const [], - binary: true, - additions: 0, - deletions: 0, - binarySize: value.size, - ), + for (final change in state.changes) + if (change.path.utf8Path != null) + GitFileStatus( + repoRelativePath: change.path.utf8Path!, + absolutePath: p.join( + state.repository.root, + change.path.utf8Path!, + ), + originalRepoRelativePath: change.originalPath?.utf8Path, + indexStatus: _letter(change.index), + workTreeStatus: _letter(change.worktree), + category: change.conflicted + ? GitFileStatusCategory.conflicted + : change.untracked + ? GitFileStatusCategory.untracked + : GitFileStatusCategory.values.byName( + switch (change.index == '.' + ? change.worktree + : change.index) { + 'M' => 'modified', + 'A' => 'added', + 'D' => 'deleted', + 'R' => 'renamed', + 'C' => 'copied', + 'T' => 'typeChanged', + '!' => 'ignored', + _ => 'unknown', + }, + ), + staged: change.staged, + unstaged: change.unstaged, + untracked: change.untracked, + deleted: change.index == 'D' || change.worktree == 'D', + renamed: change.index == 'R' || change.worktree == 'R', + copied: change.index == 'C' || change.worktree == 'C', + conflicted: change.conflicted, + ignored: change.ignored, + ), ], - rawPatch: '', - hasBinaryFiles: true, ); - } - final diff = shared.computeTextDiff('', value.text!); - final lines = [ - for (final edit in diff.edits) - GitDiffLine( - kind: GitDiffLineKind.added, - content: edit.text.replaceFirst(RegExp(r'\r?\n$'), ''), - newLineNumber: edit.newLine, - ), - ]; - return GitDiff( - title: repoRelativePath, - rawPatch: - '--- /dev/null\n+++ b/$repoRelativePath\n@@ -0,0 +1,${lines.length} @@\n${shared.exactLines(value.text!).map((line) => '+$line').join()}', - hasBinaryFiles: false, - fileSnapshots: {repoRelativePath: value.text!}, - files: [ - GitDiffFile( - newPath: repoRelativePath, - status: GitDiffFileStatus.added, - hunks: [ - GitDiffHunk( - oldStart: 0, - oldCount: 0, - newStart: 1, - newCount: lines.length, - heading: '', - lines: lines, - ), - ], - binary: false, - additions: lines.length, - deletions: 0, - ), - ], - ); - }, 'diff'); - GitCommitSummary _summary(shared.GitCommit value) => GitCommitSummary( - fullHash: value.oid.value, - shortHash: value.oid.abbreviated, - authorName: value.author, - authorEmail: value.email, - authorDate: value.date, - subject: value.subject, - parentHashes: value.parents.map((e) => e.value).toList(), - ); - @override - Future> history( - GitRepositoryInfo repository, { - String? repoRelativePath, - int limit = 200, - int skip = 0, - }) => _map(() async { - final page = await core.history( - await _repo(repository), - filter: shared.HistoryFilter( - reference: 'HEAD', - path: repoRelativePath == null - ? null - : shared.RepoPath.text(repoRelativePath), - ), - offset: skip, - limit: limit, - ); - return page.commits.map(_summary).toList(); - }, 'log'); @override - Future> fileHistory( - GitRepositoryInfo repository, - String repoRelativePath, { - int limit = 200, - int skip = 0, - }) => _map(() async { + Future stagedPatch(GitRepositoryInfo repository) => _map(() async { final id = await _repo(repository); - final page = await core.inspect( - id, - shared.GitInspection( - shared.GitInspectionKind.fileHistory, - path: shared.RepoPath.text(repoRelativePath), - offset: skip, - limit: limit, - ), - ); - final entries = []; - for (final row in (page['entries'] as List).cast()) { - final commit = shared.GitCommit.fromJson(row['commit'] as shared.Json); - final path = shared.RepoPath.fromJson(row['pathAtCommit']); - var previous = shared.RepoPath.fromJson(row['pathInParent']); - var status = _fileStatus(row['status'] as String); - if (commit.parents.length > 1) { - // Follow history can supply a sparse/combined merge boundary. Its - // status columns do not describe this adapter's first-parent review. - final changes = await core.changedFiles( - id, - commit.oid, - parent: commit.parents.first, - ); - final change = changes - .where((change) => change.path == path) - .firstOrNull; - previous = change?.originalPath ?? path; - status = change == null - ? row['deleted'] == true - ? GitDiffFileStatus.deleted - : GitDiffFileStatus.unknown - : _fileStatus(change.index); - } - if (path.utf8Path == null || previous.utf8Path == null) { - throw const shared.GitException(shared.GitErrorCode.unsupportedContent); - } - entries.add( - GitFileHistoryEntry( - commit: _summary(commit), - pathAtCommit: path.utf8Path!, - pathInParent: previous.utf8Path, - status: status, - ), - ); - } - return entries; - }, 'log'); - GitDiffFileStatus _fileStatus(String value) => - switch (value.isEmpty ? null : value[0]) { - 'A' => GitDiffFileStatus.added, - 'D' => GitDiffFileStatus.deleted, - 'R' => GitDiffFileStatus.renamed, - 'C' => GitDiffFileStatus.copied, - 'M' || 'T' => GitDiffFileStatus.modified, - _ => GitDiffFileStatus.unknown, - }; - Future _commit(shared.RepositoryId id, String hash) async => - (await core.history( - id, - filter: shared.HistoryFilter(reference: hash), - limit: 1, - )).commits.single; - @override - Future commitDetails( - GitRepositoryInfo repository, - String hash, { - String? repoRelativePath, - }) => _map(() async { - final id = await _repo(repository), - commit = await _commit(await _repo(repository), hash); - final diff = await _diff( + final snapshot = await core.status(id); + final patch = await core.patch( id, shared.GitDiffSpec( - commit.parents.isEmpty + snapshot.head == null ? const shared.ContentVersion.absent() : shared.ContentVersion( shared.ContentKind.commit, - revision: commit.parents.first, + revision: snapshot.head, ), - shared.ContentVersion(shared.ContentKind.commit, revision: commit.oid), - paths: repoRelativePath == null - ? const [] - : [shared.RepoPath.text(repoRelativePath)], - ), - commit.subject, - ); - return GitCommitDetails( - summary: _summary(commit), - body: commit.message, - changedFiles: diff.files, - patch: diff.rawPatch, - fileSnapshots: diff.fileSnapshots, - ); - }, 'show'); - @override - Future readFileAtCommit( - GitRepositoryInfo repository, - String hash, - String repoRelativePath, - ) => _map( - () async => (await core.content( - await _repo(repository), - shared.RepoPath.text(repoRelativePath), - shared.ContentVersion( - shared.ContentKind.commit, - revision: shared.GitOid(hash), + const shared.ContentVersion.index(), ), - )).text, - 'show', - ); - Future _compare( - GitRepositoryInfo repository, - shared.ContentVersion left, - shared.ContentVersion right, - String? oldPath, - String? newPath, - ) async { - final id = await _repo(repository), - paths = [ - if (oldPath != null) oldPath, - if (newPath != null && newPath != oldPath) newPath, - ]; - final diff = await _diff( - id, - shared.GitDiffSpec( - left, - right, - paths: paths.map(shared.RepoPath.text).toList(), - ), - 'Compare revisions', - ); - Future text(String? path, shared.ContentVersion version) async => - path == null - ? '' - : (await core.content( - id, - shared.RepoPath.text(path), - version, - )).availability == - shared.ContentAvailability.absent - ? '' - : (await core.content(id, shared.RepoPath.text(path), version)).text; - return GitHistoricalFileComparison( - oldPath: oldPath, - newPath: newPath, - oldContent: await text(oldPath, left), - newContent: await text(newPath, right), - diff: diff, - ); - } - - @override - Future compareFileWithParent( - GitRepositoryInfo repository, - String hash, { - String? oldPath, - String? newPath, - }) => _map(() async { - final commit = await _commit(await _repo(repository), hash); - return _compare( - repository, - commit.parents.isEmpty - ? const shared.ContentVersion.absent() - : shared.ContentVersion( - shared.ContentKind.commit, - revision: commit.parents.first, - ), - shared.ContentVersion(shared.ContentKind.commit, revision: commit.oid), - oldPath, - newPath, ); + return utf8.decode(patch.bytes, allowMalformed: true); }, 'diff'); - @override - Future compareFileWithWorkingTree( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }) => _map( - () => _compare( - repository, - shared.ContentVersion( - shared.ContentKind.commit, - revision: shared.GitOid(hash), - ), - const shared.ContentVersion.working(), - historicalPath, - currentPath, - ), - 'diff', - ); - Future _mutate( - GitRepositoryInfo repository, - shared.GitMutation Function(shared.GitSnapshot) build, - ) => _map(() async { - final id = await _repo(repository), - before = await core.status(await _repo(repository)); - final result = await core.mutate(id, build(before)); - if (result.error != null) throw _failure(result.error!, 'git'); - return GitOperationResult( - success: result.completed, - message: result.diagnostic, - stdout: result.diagnostic, - stderr: '', - updatedStatus: result.snapshot == null - ? null - : projectSharedStatus(result.snapshot!), - ); - }); - @override - Future stage( - GitRepositoryInfo r, - List paths, - ) async { - for (final path in paths) { - await _guard(r, path); - } - return _mutate( - r, - (s) => shared.StagePaths( - paths.map(shared.RepoPath.text).toList(), - expectedHead: s.head, - expectedIndex: s.indexToken, - expectedSnapshot: s.token, - ), - ); - } - - @override - Future unstage(GitRepositoryInfo r, List paths) => - _mutate( - r, - (s) => shared.StagePaths( - paths.map(shared.RepoPath.text).toList(), - unstage: true, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - Future> _workingTokens( - GitRepositoryInfo repository, - List paths, - ) async { - final id = await _repo(repository), tokens = {}; - for (final value in paths) { - final path = shared.RepoPath.text(value); - tokens[path.key] = (await core.content( - id, - path, - const shared.ContentVersion.working(), - )).token; - } - return tokens; - } - - @override - Future rollbackTracked( - GitRepositoryInfo r, - List paths, - ) => _map(() async { - final tokens = await _workingTokens(r, paths); - return _mutate( - r, - (s) => shared.RestorePaths( - paths.map(shared.RepoPath.text).toList(), - target: shared.RestoreTarget.both, - revision: s.head, - expectedHead: s.head, - expectedIndex: s.indexToken, - contentTokens: tokens, - ), - ); - }); - @override - Future discardUntracked( - GitRepositoryInfo r, - List paths, - GitStatusSnapshot snapshot, - ) async { - for (final path in paths) { - await _guard(r, path); - } - final tokens = await _workingTokens(r, paths); - return _mutate( - r, - (s) => shared.RestorePaths( - paths.map(shared.RepoPath.text).toList(), - discardUntracked: true, - expectedHead: s.head, - expectedIndex: s.indexToken, - contentTokens: tokens, - ), - ); - } - - @override - Future commit(GitRepositoryInfo r, String message) => - _mutate( - r, - (s) => shared.CommitIndex( - message, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - @override - Future configureAuthorIdentity( - GitRepositoryInfo r, { - required String name, - required String email, - required bool globally, - }) { - if (globally) { - throw const GitFailure( - code: GitFailureCode.commandFailed, - userMessageKey: 'gitErrorCommandFailed', - rawMessage: - 'The Git integration changes repository-local identity only.', - commandName: 'config', - ); - } - return _mutate( - r, - (s) => shared.ConfigureIdentity( - name, - email, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - } - - @override - Future> branches(GitRepositoryInfo r) => _map( - () async => [ - for (final ref in await core.references(await _repo(r))) - if (ref.name.startsWith('refs/heads/')) - GitBranch( - name: ref.shortName, - current: ref.current, - upstream: ref.upstream, - objectName: ref.oid.value, - subject: ref.subject, - ), - ], - ); - @override - Future> remotes(GitRepositoryInfo r) => _map( - () async => [ - for (final remote - in (await core.inspect( - await _repo(r), - const shared.GitInspection(shared.GitInspectionKind.remotes), - ))['remotes'] - as List) - (remote as Map)['name'] as String, - ], - ); - Future _remote(GitRepositoryInfo r) async { - final names = await remotes(r); - if (r.upstreamBranch != null) return r.upstreamBranch!.split('/').first; - if (names.length == 1) return names.single; - throw GitFailure( - code: names.isEmpty - ? GitFailureCode.noRemote - : GitFailureCode.multipleRemotes, - userMessageKey: names.isEmpty - ? 'gitErrorNoRemote' - : 'gitErrorMultipleRemotes', - rawMessage: '', - commandName: 'remote', - ); - } - - @override - Future fetch(GitRepositoryInfo r) async { - final name = await _remote(r); - return _mutate( - r, - (s) => shared.FetchRemote( - name, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - } - - @override - Future pullFastForwardOnly(GitRepositoryInfo r) async { - final name = await _remote(r); - return _mutate( - r, - (s) => shared.PullRemote( - name, - r.upstreamBranch?.split('/').skip(1).join('/') ?? r.currentBranch!, - shared.PullStrategy.fastForwardOnly, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - } - - @override - Future push(GitRepositoryInfo r) async => - pushSetUpstream(r, await _remote(r), r.currentBranch!); - @override - Future pushSetUpstream( - GitRepositoryInfo r, - String remote, - String branch, - ) => _map(() async { - final id = await _repo(r), state = await core.status(await _repo(r)); - final review = await core.inspect( - id, - shared.GitInspection( - shared.GitInspectionKind.pushReview, - remote: remote, - destination: 'refs/heads/$branch', - ), - ); - return _mutate( - r, - (s) => shared.PushReviewed( - review['token'] as String, - setUpstream: r.upstreamBranch == null, - expectedHead: state.head, - expectedIndex: state.indexToken, - ), - ); - }); - @override - Future createBranch(GitRepositoryInfo r, String name) => - _mutate( - r, - (s) => shared.BranchMutation( - shared.BranchAction.create, - name, - start: s.head, - switchAfterCreate: true, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - @override - Future switchBranch(GitRepositoryInfo r, String name) => - _mutate( - r, - (s) => shared.BranchMutation( - shared.BranchAction.switchBranch, - name, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - @override - Future initializeRepository(String rootPath) => - _map(() async { - final result = await core.create(shared.InitializeRepository(rootPath)); - if (result.error != null) throw _failure(result.error!, 'init'); - return GitOperationResult( - success: result.phase == shared.GitOperationPhase.completed, - message: '', - stdout: '', - stderr: '', - ); - }); - @override - Future resetCurrentBranch( - GitRepositoryInfo r, - String hash, - GitResetMode mode, - ) async { - if (r.currentBranch == null) { - throw const GitFailure( - code: GitFailureCode.detachedHead, - userMessageKey: 'gitErrorDetachedHead', - rawMessage: '', - commandName: 'reset', - ); - } - return _mutate( - r, - (s) => shared.ResetBranch( - shared.GitOid(hash), - shared.ResetMode.values.byName(mode.name), - expectedHead: s.head, - expectedIndex: s.indexToken, - expectedWorkingToken: s.token, - ), - ); - } - - @override - Future restoreFileFromCommit( - GitRepositoryInfo r, - String hash, { - required String historicalPath, - required String currentPath, - }) => _map(() async { - await _guard(r, currentPath); - final target = shared.RepoPath.text(currentPath), - before = await core.content( - await _repo(r), - shared.RepoPath.text(currentPath), - const shared.ContentVersion.working(), - ); - return _mutate( - r, - (s) => shared.RestoreFileRevision( - shared.RepoPath.text(historicalPath), - target, - shared.GitOid(hash), - expectedWorking: before.token, - expectedHead: s.head, - expectedIndex: s.indexToken, - ), - ); - }); + static GitFileChangeStatus _letter(String value) => switch (value) { + 'M' => GitFileChangeStatus.modified, + 'A' => GitFileChangeStatus.added, + 'D' => GitFileChangeStatus.deleted, + 'R' => GitFileChangeStatus.renamed, + 'C' => GitFileChangeStatus.copied, + 'T' => GitFileChangeStatus.typeChanged, + 'U' => GitFileChangeStatus.unmerged, + '?' => GitFileChangeStatus.untracked, + '!' => GitFileChangeStatus.ignored, + '.' => GitFileChangeStatus.unmodified, + _ => GitFileChangeStatus.unknown, + }; } GitFailure _failure(shared.GitException error, String command) { diff --git a/lib/src/git/domain/git_diff_parser.dart b/lib/src/git/domain/git_diff_parser.dart deleted file mode 100644 index 01c2f96b..00000000 --- a/lib/src/git/domain/git_diff_parser.dart +++ /dev/null @@ -1,368 +0,0 @@ -import 'dart:convert'; -import 'dart:typed_data'; - -import 'git_models.dart'; - -class GitDiffParser { - const GitDiffParser(); - - GitDiff parse(String patch, {String title = ''}) { - final files = []; - _MutableDiffFile? currentFile; - _MutableDiffHunk? currentHunk; - var oldLine = 0; - var newLine = 0; - - void finishHunk() { - final hunk = currentHunk; - final file = currentFile; - if (hunk == null || file == null) { - return; - } - file.hunks.add(hunk.toImmutable()); - currentHunk = null; - } - - void finishFile() { - finishHunk(); - final file = currentFile; - if (file == null) { - return; - } - files.add(file.toImmutable()); - currentFile = null; - } - - final lines = patch.split('\n'); - if (lines.isNotEmpty && lines.last.isEmpty) { - lines.removeLast(); - } - for (final line in lines) { - if (line.startsWith('diff --git ')) { - finishFile(); - final paths = _parseDiffGitPaths(line); - currentFile = _MutableDiffFile(oldPath: paths.$1, newPath: paths.$2); - continue; - } - currentFile ??= _MutableDiffFile(); - final file = currentFile; - if (file == null) { - continue; - } - if (line.startsWith('new file mode ')) { - file.status = GitDiffFileStatus.added; - continue; - } - if (line.startsWith('deleted file mode ')) { - file.status = GitDiffFileStatus.deleted; - continue; - } - if (line.startsWith('rename from ')) { - file.oldPath = _decodeGitPath(line.substring('rename from '.length)); - file.status = GitDiffFileStatus.renamed; - continue; - } - if (line.startsWith('rename to ')) { - file.newPath = _decodeGitPath(line.substring('rename to '.length)); - file.status = GitDiffFileStatus.renamed; - continue; - } - if (line.startsWith('copy from ')) { - file.oldPath = _decodeGitPath(line.substring('copy from '.length)); - file.status = GitDiffFileStatus.copied; - continue; - } - if (line.startsWith('copy to ')) { - file.newPath = _decodeGitPath(line.substring('copy to '.length)); - file.status = GitDiffFileStatus.copied; - continue; - } - if (line.startsWith('Binary files ') || - line.startsWith('GIT binary patch')) { - file - ..binary = true - ..status = GitDiffFileStatus.binary; - continue; - } - if (line.startsWith('--- ')) { - final path = _parsePatchHeaderPath(line.substring(4)); - if (path != '/dev/null') { - file.oldPath = path; - } - continue; - } - if (line.startsWith('+++ ')) { - final path = _parsePatchHeaderPath(line.substring(4)); - if (path != '/dev/null') { - file.newPath = path; - } - continue; - } - final hunkMatch = RegExp( - r'^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@ ?(.*)$', - ).firstMatch(line); - if (hunkMatch != null) { - finishHunk(); - oldLine = int.parse(hunkMatch.group(1)!); - newLine = int.parse(hunkMatch.group(3)!); - currentHunk = _MutableDiffHunk( - oldStart: oldLine, - oldCount: int.tryParse(hunkMatch.group(2) ?? '') ?? 1, - newStart: newLine, - newCount: int.tryParse(hunkMatch.group(4) ?? '') ?? 1, - heading: hunkMatch.group(5) ?? '', - ); - continue; - } - if (currentHunk == null) { - continue; - } - final hunk = currentHunk!; - if (line == r'\ No newline at end of file') { - hunk.lines.add( - GitDiffLine(kind: GitDiffLineKind.header, content: line), - ); - continue; - } - if (line.startsWith('+') && !line.startsWith('+++')) { - hunk.lines.add( - GitDiffLine( - kind: GitDiffLineKind.added, - content: line.substring(1), - newLineNumber: newLine, - ), - ); - file.additions += 1; - newLine += 1; - continue; - } - if (line.startsWith('-') && !line.startsWith('---')) { - hunk.lines.add( - GitDiffLine( - kind: GitDiffLineKind.removed, - content: line.substring(1), - oldLineNumber: oldLine, - ), - ); - file.deletions += 1; - oldLine += 1; - continue; - } - final context = line.startsWith(' ') ? line.substring(1) : line; - hunk.lines.add( - GitDiffLine( - kind: line.startsWith(' ') - ? GitDiffLineKind.context - : GitDiffLineKind.header, - content: context, - oldLineNumber: line.startsWith(' ') ? oldLine : null, - newLineNumber: line.startsWith(' ') ? newLine : null, - ), - ); - if (line.startsWith(' ')) { - oldLine += 1; - newLine += 1; - } - } - finishFile(); - return GitDiff( - title: title, - files: files, - rawPatch: patch, - hasBinaryFiles: files.any((file) => file.binary), - ); - } - - (String?, String?) _parseDiffGitPaths(String line) { - final rest = line.substring('diff --git '.length); - if (rest.startsWith('"')) { - final first = _readQuotedPath(rest, 0); - if (first == null) { - return (null, null); - } - var secondStart = first.$2; - while (secondStart < rest.length && - rest.codeUnitAt(secondStart) == 0x20) { - secondStart += 1; - } - if (secondStart >= rest.length) { - return (null, null); - } - final second = rest.startsWith('"', secondStart) - ? _readQuotedPath(rest, secondStart)?.$1 - : rest.substring(secondStart); - if (second == null) { - return (null, null); - } - return ( - _stripDiffPathPrefix(_decodeGitPath(first.$1)), - _stripDiffPathPrefix(_decodeGitPath(second)), - ); - } - final marker = rest.indexOf(' b/'); - if (rest.startsWith('a/') && marker > 0) { - return ( - _stripDiffPathPrefix(rest.substring(0, marker)), - _stripDiffPathPrefix(rest.substring(marker + 1)), - ); - } - final parts = rest.split(' '); - if (parts.length >= 2) { - return (_stripDiffPathPrefix(parts[0]), _stripDiffPathPrefix(parts[1])); - } - return (null, null); - } - - String _parsePatchHeaderPath(String value) { - final token = value.split('\t').first; - return _stripDiffPathPrefix(_decodeGitPath(token)); - } - - (String, int)? _readQuotedPath(String value, int start) { - if (start >= value.length || value.codeUnitAt(start) != 0x22) { - return null; - } - var index = start + 1; - while (index < value.length) { - final codeUnit = value.codeUnitAt(index); - if (codeUnit == 0x5c) { - index += 2; - continue; - } - if (codeUnit == 0x22) { - return (value.substring(start, index + 1), index + 1); - } - index += 1; - } - return null; - } - - String _decodeGitPath(String value) { - if (value.length < 2 || - value.codeUnitAt(0) != 0x22 || - value.codeUnitAt(value.length - 1) != 0x22) { - return value; - } - final output = BytesBuilder(copy: false); - var index = 1; - final end = value.length - 1; - while (index < end) { - if (value.codeUnitAt(index) != 0x5c) { - index = _appendUtf8Rune(output, value, index); - continue; - } - index += 1; - if (index >= end) { - output.addByte(0x5c); - break; - } - final escaped = value.codeUnitAt(index); - if (_isOctalDigit(escaped)) { - var byte = 0; - var digits = 0; - while (index < end && - digits < 3 && - _isOctalDigit(value.codeUnitAt(index))) { - byte = (byte * 8) + value.codeUnitAt(index) - 0x30; - index += 1; - digits += 1; - } - output.addByte(byte); - continue; - } - final simpleEscape = const { - 0x61: 0x07, - 0x62: 0x08, - 0x74: 0x09, - 0x6e: 0x0a, - 0x76: 0x0b, - 0x66: 0x0c, - 0x72: 0x0d, - 0x22: 0x22, - 0x5c: 0x5c, - }[escaped]; - if (simpleEscape != null) { - output.addByte(simpleEscape); - index += 1; - continue; - } - output.addByte(0x5c); - index = _appendUtf8Rune(output, value, index); - } - return utf8.decode(output.takeBytes(), allowMalformed: true); - } - - int _appendUtf8Rune(BytesBuilder output, String value, int index) { - final firstCodeUnit = value.codeUnitAt(index); - final hasSurrogatePair = - firstCodeUnit >= 0xd800 && - firstCodeUnit <= 0xdbff && - index + 1 < value.length && - value.codeUnitAt(index + 1) >= 0xdc00 && - value.codeUnitAt(index + 1) <= 0xdfff; - final nextIndex = index + (hasSurrogatePair ? 2 : 1); - output.add(utf8.encode(value.substring(index, nextIndex))); - return nextIndex; - } - - bool _isOctalDigit(int codeUnit) => codeUnit >= 0x30 && codeUnit <= 0x37; - - String _stripDiffPathPrefix(String value) { - if (value.startsWith('a/') || value.startsWith('b/')) { - return value.substring(2); - } - return value; - } -} - -class _MutableDiffFile { - _MutableDiffFile({this.oldPath, this.newPath}); - - String? oldPath; - String? newPath; - GitDiffFileStatus status = GitDiffFileStatus.modified; - final hunks = []; - var binary = false; - var additions = 0; - var deletions = 0; - - GitDiffFile toImmutable() { - return GitDiffFile( - oldPath: oldPath, - newPath: newPath, - status: status, - hunks: List.unmodifiable(hunks), - binary: binary, - additions: additions, - deletions: deletions, - ); - } -} - -class _MutableDiffHunk { - _MutableDiffHunk({ - required this.oldStart, - required this.oldCount, - required this.newStart, - required this.newCount, - required this.heading, - }); - - final int oldStart; - final int oldCount; - final int newStart; - final int newCount; - final String heading; - final lines = []; - - GitDiffHunk toImmutable() { - return GitDiffHunk( - oldStart: oldStart, - oldCount: oldCount, - newStart: newStart, - newCount: newCount, - heading: heading, - lines: List.unmodifiable(lines), - ); - } -} diff --git a/lib/src/git/domain/git_log_parser.dart b/lib/src/git/domain/git_log_parser.dart deleted file mode 100644 index a059d480..00000000 --- a/lib/src/git/domain/git_log_parser.dart +++ /dev/null @@ -1,50 +0,0 @@ -import 'git_models.dart'; - -const gitLogRecordSeparator = '\x1e'; -const gitLogUnitSeparator = '\x1f'; - -class GitLogParser { - const GitLogParser(); - - List parse(String output) { - if (output.isEmpty) { - return const []; - } - final commits = []; - for (final record in output.split(gitLogRecordSeparator)) { - if (record.trim().isEmpty) { - continue; - } - final fields = record.split(gitLogUnitSeparator); - if (fields.length < 7) { - continue; - } - final fullHash = fields[0].trim(); - if (fullHash.isEmpty) { - continue; - } - commits.add( - GitCommitSummary( - fullHash: fullHash, - shortHash: fields[1], - authorName: fields[2], - authorEmail: fields[3], - authorDate: - DateTime.tryParse(fields[4]) ?? - DateTime.fromMillisecondsSinceEpoch(0), - subject: fields[5], - parentHashes: fields[6] - .split(' ') - .where((hash) => hash.trim().isNotEmpty) - .toList(), - ), - ); - } - return commits; - } - - GitCommitSummary? parseFirst(String output) { - final commits = parse(output); - return commits.isEmpty ? null : commits.first; - } -} diff --git a/lib/src/git/domain/git_models.dart b/lib/src/git/domain/git_models.dart index c3df32fa..76210dad 100644 --- a/lib/src/git/domain/git_models.dart +++ b/lib/src/git/domain/git_models.dart @@ -42,18 +42,8 @@ enum GitDiffFileStatus { enum GitFailureCode { unavailable, unsupportedVersion, - notRepository, invalidPath, - invalidBranchName, - invalidCommitMessage, - noStagedFiles, - noRemote, - noUpstream, - multipleRemotes, dirtyWorkspace, - stagedChanges, - detachedHead, - diverged, authorIdentity, authentication, network, @@ -61,49 +51,6 @@ enum GitFailureCode { commandFailed, } -enum GitResetMode { soft, mixed, hard, keep } - -enum GitView { changes, fileHistory, projectHistory } - -enum GitComparisonType { - staged, - unstaged, - untracked, - commitChange, - commitVersusCurrent, -} - -class GitChangeSelection { - const GitChangeSelection({ - required this.path, - required this.comparison, - this.originalRepoRelativePath, - }); - - final String path; - final GitComparisonType comparison; - final String? originalRepoRelativePath; - - List get repoRelativePaths { - final originalPath = originalRepoRelativePath; - return [ - if (originalPath != null && originalPath != path) originalPath, - path, - ]; - } - - @override - bool operator ==(Object other) { - return other is GitChangeSelection && - other.path == path && - other.comparison == comparison && - other.originalRepoRelativePath == originalRepoRelativePath; - } - - @override - int get hashCode => Object.hash(path, comparison, originalRepoRelativePath); -} - class GitAvailability { const GitAvailability({ required this.available, @@ -129,75 +76,11 @@ class GitRepositoryInfo { required this.rootPath, required this.gitDirPath, this.identityKey, - this.currentBranch, - this.detachedHeadCommit, - this.upstreamBranch, - this.aheadCount = 0, - this.behindCount = 0, - this.hasRemote = false, - this.isBare = false, - this.isRebasing = false, - this.isMerging = false, - this.isCherryPicking = false, - this.hasConflicts = false, }); final String rootPath; final String gitDirPath; final String? identityKey; - final String? currentBranch; - final String? detachedHeadCommit; - final String? upstreamBranch; - final int aheadCount; - final int behindCount; - final bool hasRemote; - final bool isBare; - final bool isRebasing; - final bool isMerging; - final bool isCherryPicking; - final bool hasConflicts; - - GitRepositoryInfo copyWith({ - String? rootPath, - String? gitDirPath, - Object? identityKey = _unset, - Object? currentBranch = _unset, - Object? detachedHeadCommit = _unset, - Object? upstreamBranch = _unset, - int? aheadCount, - int? behindCount, - bool? hasRemote, - bool? isBare, - bool? isRebasing, - bool? isMerging, - bool? isCherryPicking, - bool? hasConflicts, - }) { - return GitRepositoryInfo( - rootPath: rootPath ?? this.rootPath, - gitDirPath: gitDirPath ?? this.gitDirPath, - identityKey: identical(identityKey, _unset) - ? (rootPath == null && gitDirPath == null ? this.identityKey : null) - : identityKey as String?, - currentBranch: identical(currentBranch, _unset) - ? this.currentBranch - : currentBranch as String?, - detachedHeadCommit: identical(detachedHeadCommit, _unset) - ? this.detachedHeadCommit - : detachedHeadCommit as String?, - upstreamBranch: identical(upstreamBranch, _unset) - ? this.upstreamBranch - : upstreamBranch as String?, - aheadCount: aheadCount ?? this.aheadCount, - behindCount: behindCount ?? this.behindCount, - hasRemote: hasRemote ?? this.hasRemote, - isBare: isBare ?? this.isBare, - isRebasing: isRebasing ?? this.isRebasing, - isMerging: isMerging ?? this.isMerging, - isCherryPicking: isCherryPicking ?? this.isCherryPicking, - hasConflicts: hasConflicts ?? this.hasConflicts, - ); - } } class GitFileStatus { @@ -283,62 +166,6 @@ class GitStatusSnapshot { bool get clean => files.isEmpty && unrepresentedPathCount == 0; } -class GitCommitSummary { - const GitCommitSummary({ - required this.fullHash, - required this.shortHash, - required this.authorName, - required this.authorEmail, - required this.authorDate, - required this.subject, - required this.parentHashes, - }); - - final String fullHash; - final String shortHash; - final String authorName; - final String authorEmail; - final DateTime authorDate; - final String subject; - final List parentHashes; -} - -class GitFileHistoryEntry { - const GitFileHistoryEntry({ - required this.commit, - required this.pathAtCommit, - this.pathInParent, - required this.status, - }); - - final GitCommitSummary commit; - final String pathAtCommit; - final String? pathInParent; - final GitDiffFileStatus status; - - String? get oldPath => - status == GitDiffFileStatus.added ? null : (pathInParent ?? pathAtCommit); - - String? get newPath => - status == GitDiffFileStatus.deleted ? null : pathAtCommit; -} - -class GitCommitDetails { - const GitCommitDetails({ - required this.summary, - this.body, - required this.changedFiles, - required this.patch, - this.fileSnapshots = const {}, - }); - - final GitCommitSummary summary; - final String? body; - final List changedFiles; - final String patch; - final Map fileSnapshots; -} - class GitDiff { const GitDiff({ required this.title, @@ -355,24 +182,6 @@ class GitDiff { final Map fileSnapshots; } -class GitHistoricalFileComparison { - const GitHistoricalFileComparison({ - required this.oldPath, - required this.newPath, - required this.oldContent, - required this.newContent, - required this.diff, - }); - - final String? oldPath; - final String? newPath; - final String? oldContent; - final String? newContent; - final GitDiff diff; - - bool get binary => oldContent == null || newContent == null; -} - class GitDiffFile { const GitDiffFile({ this.oldPath, @@ -456,22 +265,6 @@ class GitDiffLine { final int? newLineNumber; } -class GitOperationResult { - const GitOperationResult({ - required this.success, - required this.message, - required this.stdout, - required this.stderr, - this.updatedStatus, - }); - - final bool success; - final String message; - final String stdout; - final String stderr; - final GitStatusSnapshot? updatedStatus; -} - class GitFailure { const GitFailure({ required this.code, @@ -488,20 +281,4 @@ class GitFailure { final int? exitCode; } -class GitBranch { - const GitBranch({ - required this.name, - required this.current, - this.upstream, - this.objectName, - this.subject, - }); - - final String name; - final bool current; - final String? upstream; - final String? objectName; - final String? subject; -} - const Object _unset = Object(); diff --git a/lib/src/git/domain/git_status_parser.dart b/lib/src/git/domain/git_status_parser.dart deleted file mode 100644 index 99015c80..00000000 --- a/lib/src/git/domain/git_status_parser.dart +++ /dev/null @@ -1,218 +0,0 @@ -import 'package:path/path.dart' as p; - -import 'git_models.dart'; - -class GitStatusParser { - const GitStatusParser(); - - GitStatusSnapshot parsePorcelainV1Z({ - required String output, - required GitRepositoryInfo repositoryInfo, - }) { - final records = output.split('\x00'); - if (records.isNotEmpty && records.last.isEmpty) { - records.removeLast(); - } - - var info = repositoryInfo; - final files = []; - for (var index = 0; index < records.length; index += 1) { - final record = records[index]; - if (record.isEmpty) { - continue; - } - if (record.startsWith('## ')) { - info = _infoWithBranchHeader(info, record.substring(3)); - continue; - } - if (record.length < 4) { - continue; - } - final x = record[0]; - final y = record[1]; - if (record[2] != ' ') { - continue; - } - final path = record.substring(3); - String? originalPath; - if ((x == 'R' || x == 'C' || y == 'R' || y == 'C') && - index + 1 < records.length) { - originalPath = records[++index]; - } - final parsed = _fileStatus( - repositoryInfo: info, - path: path, - originalPath: originalPath, - x: x, - y: y, - ); - files.add(parsed); - } - - final withConflicts = info.copyWith( - hasConflicts: files.any((file) => file.conflicted), - ); - return GitStatusSnapshot(repositoryInfo: withConflicts, files: files); - } - - GitRepositoryInfo _infoWithBranchHeader( - GitRepositoryInfo info, - String header, - ) { - final counts = _aheadBehindFromHeader(header); - final headerWithoutCounts = header.replaceFirst(RegExp(r'\s+\[.*\]$'), ''); - if (headerWithoutCounts == 'HEAD (no branch)') { - return info.copyWith( - currentBranch: null, - aheadCount: counts.$1 ?? info.aheadCount, - behindCount: counts.$2 ?? info.behindCount, - ); - } - if (headerWithoutCounts.startsWith('No commits yet on ')) { - return info.copyWith( - currentBranch: headerWithoutCounts.substring( - 'No commits yet on '.length, - ), - aheadCount: counts.$1 ?? info.aheadCount, - behindCount: counts.$2 ?? info.behindCount, - ); - } - final upstreamSeparator = headerWithoutCounts.indexOf('...'); - if (upstreamSeparator >= 0) { - return info.copyWith( - currentBranch: headerWithoutCounts.substring(0, upstreamSeparator), - upstreamBranch: headerWithoutCounts.substring(upstreamSeparator + 3), - aheadCount: counts.$1 ?? info.aheadCount, - behindCount: counts.$2 ?? info.behindCount, - ); - } - return info.copyWith( - currentBranch: headerWithoutCounts, - aheadCount: counts.$1 ?? info.aheadCount, - behindCount: counts.$2 ?? info.behindCount, - ); - } - - (int?, int?) _aheadBehindFromHeader(String header) { - final bracket = RegExp(r'\[(.*)\]$').firstMatch(header); - if (bracket == null) { - return (null, null); - } - final text = bracket.group(1)!; - final ahead = RegExp(r'ahead (\d+)').firstMatch(text); - final behind = RegExp(r'behind (\d+)').firstMatch(text); - return ( - ahead == null ? null : int.tryParse(ahead.group(1)!), - behind == null ? null : int.tryParse(behind.group(1)!), - ); - } - - GitFileStatus _fileStatus({ - required GitRepositoryInfo repositoryInfo, - required String path, - required String? originalPath, - required String x, - required String y, - }) { - final indexStatus = _statusFromCode(x); - final workTreeStatus = _statusFromCode(y); - final conflicted = _isConflict(x, y); - final untracked = x == '?' && y == '?'; - final ignored = x == '!' && y == '!'; - final renamed = x == 'R' || y == 'R'; - final copied = x == 'C' || y == 'C'; - final deleted = x == 'D' || y == 'D'; - final staged = - !conflicted && !untracked && !ignored && x != ' ' && x != '.'; - final unstaged = - !conflicted && !untracked && !ignored && y != ' ' && y != '.'; - return GitFileStatus( - repoRelativePath: path, - absolutePath: p.normalize(p.join(repositoryInfo.rootPath, path)), - originalRepoRelativePath: originalPath, - indexStatus: indexStatus, - workTreeStatus: workTreeStatus, - category: _category( - indexStatus: indexStatus, - workTreeStatus: workTreeStatus, - conflicted: conflicted, - untracked: untracked, - ignored: ignored, - renamed: renamed, - copied: copied, - deleted: deleted, - ), - staged: staged, - unstaged: unstaged, - untracked: untracked, - deleted: deleted, - renamed: renamed, - copied: copied, - conflicted: conflicted, - ignored: ignored, - ); - } - - GitFileChangeStatus _statusFromCode(String code) { - return switch (code) { - ' ' || '.' => GitFileChangeStatus.unmodified, - 'M' => GitFileChangeStatus.modified, - 'A' => GitFileChangeStatus.added, - 'D' => GitFileChangeStatus.deleted, - 'R' => GitFileChangeStatus.renamed, - 'C' => GitFileChangeStatus.copied, - 'T' => GitFileChangeStatus.typeChanged, - 'U' => GitFileChangeStatus.unmerged, - '?' => GitFileChangeStatus.untracked, - '!' => GitFileChangeStatus.ignored, - _ => GitFileChangeStatus.unknown, - }; - } - - bool _isConflict(String x, String y) { - return const {'DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU'}.contains('$x$y'); - } - - GitFileStatusCategory _category({ - required GitFileChangeStatus indexStatus, - required GitFileChangeStatus workTreeStatus, - required bool conflicted, - required bool untracked, - required bool ignored, - required bool renamed, - required bool copied, - required bool deleted, - }) { - if (conflicted) { - return GitFileStatusCategory.conflicted; - } - if (untracked) { - return GitFileStatusCategory.untracked; - } - if (ignored) { - return GitFileStatusCategory.ignored; - } - if (renamed) { - return GitFileStatusCategory.renamed; - } - if (copied) { - return GitFileStatusCategory.copied; - } - if (deleted) { - return GitFileStatusCategory.deleted; - } - if (indexStatus == GitFileChangeStatus.added || - workTreeStatus == GitFileChangeStatus.added) { - return GitFileStatusCategory.added; - } - if (indexStatus == GitFileChangeStatus.typeChanged || - workTreeStatus == GitFileChangeStatus.typeChanged) { - return GitFileStatusCategory.typeChanged; - } - if (indexStatus == GitFileChangeStatus.modified || - workTreeStatus == GitFileChangeStatus.modified) { - return GitFileStatusCategory.modified; - } - return GitFileStatusCategory.unknown; - } -} diff --git a/lib/src/local_history/local_history_comparison_view.dart b/lib/src/local_history/local_history_comparison_view.dart index ae5d8027..a0e642f9 100644 --- a/lib/src/local_history/local_history_comparison_view.dart +++ b/lib/src/local_history/local_history_comparison_view.dart @@ -1,15 +1,15 @@ import 'dart:async'; -import 'package:file_selector/file_selector.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:path/path.dart' as p; -import '../app/busymark_dialogs.dart'; import '../app/busymark_design.dart'; import '../app/busymark_glyphs.dart'; import '../app/localization.dart'; +import '../app/save_destination_picker.dart'; import '../comparison/source_comparison.dart'; +import '../core/save_destination.dart'; import '../workspace/document_buffer.dart'; import '../workspace/workspace_controller.dart'; import '../workspace/workspace_safety.dart'; @@ -174,7 +174,7 @@ class _LocalHistoryComparisonViewState document.remoteNote == null && actionsAreCurrent && data.missing - ? () => _chooseRestoreLocation(document, revision) + ? () => _restoreMissing(document, revision) : null, ); }, @@ -280,32 +280,6 @@ class _LocalHistoryComparisonViewState } } - Future _chooseRestoreLocation( - LocalHistoryDocument document, - LocalHistoryRevision revision, - ) async { - final historicalPath = - document.currentPath ?? revision.summary.historicalPath; - final extension = p.extension(historicalPath ?? ''); - final location = await getSaveLocation( - acceptedTypeGroups: [ - XTypeGroup( - label: context.l10n.source, - extensions: extension.isEmpty ? null : [extension.substring(1)], - mimeTypes: extension.isEmpty ? const ['text/plain'] : null, - ), - ], - suggestedName: p.basename(historicalPath ?? document.displayName), - initialDirectory: historicalPath == null - ? null - : p.dirname(historicalPath), - confirmButtonText: context.l10n.localHistoryRestoreRevision, - ); - if (location != null && mounted) { - await _restoreMissing(document, revision, location.path); - } - } - Future _recoverRemote( LocalHistoryDocument document, LocalHistoryRevision revision, @@ -348,43 +322,77 @@ class _LocalHistoryComparisonViewState Future _restoreMissing( LocalHistoryDocument document, - LocalHistoryRevision revision, - String path, - ) => _runRestore(() async { - if (!await confirmSafeToContinue(context, ref) || !mounted) return null; + LocalHistoryRevision revision, [ + String? originalDestination, + ]) => _runRestore(() async { final controller = ref.read(workspaceControllerProvider.notifier); - final exists = await controller.localHistoryRestorePathExists(path); - if (!mounted) return null; - var overwrite = false; - if (exists) { - overwrite = - await showBusyMarkModalDialog( - context, - barrierDismissible: false, - builder: (dialogContext) => BusyMarkDialogShell( - title: dialogContext.l10n.overwrite, - actions: [ - BusyMarkDialogButton( - label: dialogContext.l10n.cancel, - onPressed: () => Navigator.pop(dialogContext, false), - ), - BusyMarkDialogButton( - label: dialogContext.l10n.overwrite, - destructive: true, - onPressed: () => Navigator.pop(dialogContext, true), - ), - ], - children: [Text(dialogContext.l10n.errorPathAlreadyExists(path))], - ), - ) ?? - false; - if (!overwrite || !mounted) return null; + final selected = ref + .read(localHistoryControllerProvider) + .selectedRevisionId; + bool ownsComparison() => + mounted && + ref.read(localHistoryControllerProvider).selectedRevisionId == selected; + + SaveDestination? destination; + if (originalDestination == null) { + final previous = ref.read(workspaceControllerProvider); + final previousDocument = controller.captureActiveDocumentSaveTarget(); + final historicalPath = + document.currentPath ?? revision.summary.historicalPath; + final extension = p.extension(historicalPath ?? ''); + destination = await pickSaveDestination( + context, + suggestedName: p.basename(historicalPath ?? document.displayName), + initialDirectory: historicalPath == null + ? null + : p.dirname(historicalPath), + actionLabel: context.l10n.localHistoryRestoreRevision, + suffix: extension.isEmpty ? null : extension, + suffixOnlyWhenMissing: true, + filterLabel: context.l10n.source, + patterns: extension.isEmpty + ? const [] + : ['*${extension.toLowerCase()}', '*${extension.toUpperCase()}'], + kind: SaveDestinationKind.fileOrSymbolicLink, + isCurrent: () => + ownsComparison() && + (previousDocument != null + ? controller.isActiveDocumentSaveTargetCurrent(previousDocument) + : ref.read(workspaceControllerProvider).activeBuffer == null && + ref.read(workspaceControllerProvider).workspace?.id == + previous.workspace?.id), + ); + if (destination == null || !mounted || !ownsComparison()) return null; + } + if (!await confirmSafeToContinue(context, ref) || + !mounted || + !ownsComparison()) { + return null; } + final previous = ref.read(workspaceControllerProvider); + final previousDocument = controller.captureActiveDocumentSaveTarget(); + bool isCurrent() => + ownsComparison() && + (previousDocument != null + ? controller.isActiveDocumentSaveTargetCurrent(previousDocument) + : ref.read(workspaceControllerProvider).activeBuffer == null && + ref.read(workspaceControllerProvider).workspace?.id == + previous.workspace?.id); + + destination ??= await confirmSaveDestination( + context, + originalDestination!, + operation: context.l10n.localHistoryRestoreRevision, + kind: SaveDestinationKind.fileOrSymbolicLink, + isCurrent: isCurrent, + ); + if (destination == null || !isCurrent()) return null; return controller.restoreMissingLocalHistoryRevision( document: document, revision: revision, - destinationPath: path, - overwriteExisting: overwrite, + destinationPath: destination.path, + overwriteExisting: destination.replacesExisting, + authorization: destination, ); }); } diff --git a/lib/src/local_history/local_history_controller.dart b/lib/src/local_history/local_history_controller.dart index 5b4b9842..a97efa0b 100644 --- a/lib/src/local_history/local_history_controller.dart +++ b/lib/src/local_history/local_history_controller.dart @@ -69,7 +69,6 @@ class LocalHistoryState { this.selectedDocumentId, this.selectedRevisionId, this.selectedRevision, - this.browsingDocuments = false, this.inspectingRetainedDocument = false, this.warning, }); @@ -81,7 +80,7 @@ class LocalHistoryState { final String? selectedDocumentId; final String? selectedRevisionId; final LocalHistoryRevision? selectedRevision; - final bool browsingDocuments; + final bool inspectingRetainedDocument; final LocalHistoryWarning? warning; @@ -102,7 +101,6 @@ class LocalHistoryState { Object? selectedDocumentId = _unset, Object? selectedRevisionId = _unset, Object? selectedRevision = _unset, - bool? browsingDocuments, bool? inspectingRetainedDocument, Object? warning = _unset, }) => LocalHistoryState( @@ -119,7 +117,6 @@ class LocalHistoryState { selectedRevision: identical(selectedRevision, _unset) ? this.selectedRevision : selectedRevision as LocalHistoryRevision?, - browsingDocuments: browsingDocuments ?? this.browsingDocuments, inspectingRetainedDocument: inspectingRetainedDocument ?? this.inspectingRetainedDocument, warning: identical(warning, _unset) @@ -3975,7 +3972,6 @@ class LocalHistoryController extends Notifier { selectedDocumentId: null, selectedRevisionId: null, selectedRevision: null, - browsingDocuments: false, inspectingRetainedDocument: false, ); _showCaptureFailure(); @@ -3999,7 +3995,6 @@ class LocalHistoryController extends Notifier { } else { state = state.copyWith( loading: false, - browsingDocuments: false, inspectingRetainedDocument: false, ); } @@ -4027,7 +4022,6 @@ class LocalHistoryController extends Notifier { selectedDocumentId: null, selectedRevisionId: null, selectedRevision: null, - browsingDocuments: false, inspectingRetainedDocument: false, ); _showCaptureFailure(); @@ -4053,53 +4047,11 @@ class LocalHistoryController extends Notifier { selectedDocumentId: documentId, selectedRevisionId: null, selectedRevision: null, - browsingDocuments: false, inspectingRetainedDocument: inspectingRetainedDocument, ); _showCaptureFailure(); } - /// Browses retained documents without filtering the revision timeline. - /// No current editor is implied: closed, renamed, untitled, and deleted - /// documents remain first-class results. - void browseDocuments() { - _scopeGeneration++; - _loadGeneration++; - state = state.copyWith( - loading: false, - selectedDocumentId: null, - selectedRevisionId: null, - selectedRevision: null, - browsingDocuments: true, - inspectingRetainedDocument: false, - ); - _showCaptureFailure(); - } - - Future selectDocumentForPath(String path) async { - await refresh(); - if (!ref.mounted) return; - final normalized = p.normalize(path); - final activeDocument = state.snapshot.documents - .where( - (candidate) => - !candidate.deleted && - candidate.currentPath != null && - p.equals(candidate.currentPath!, normalized), - ) - .firstOrNull; - final document = - activeDocument ?? - state.snapshot.documents.where((candidate) { - final current = candidate.currentPath; - return (current != null && p.equals(current, normalized)) || - candidate.historicalPaths.any( - (historical) => p.equals(historical, normalized), - ); - }).firstOrNull; - if (document != null) selectDocument(document.id); - } - Future readRecoveryHistory() => _store.load(); /// Reads recovery content without changing History or editor navigation. @@ -6141,7 +6093,7 @@ class LocalHistoryController extends Notifier { } var selectedDocumentId = state.selectedDocumentId; - if (!state.browsingDocuments && !state.inspectingRetainedDocument) { + if (!state.inspectingRetainedDocument) { final scope = _normalBrowsingScope; if (scope != null) { selectedDocumentId = _documentIdsByBuffer[scope.bufferId]; diff --git a/lib/src/local_history/local_history_panel.dart b/lib/src/local_history/local_history_panel.dart index 6a6ee252..f1ecdf0b 100644 --- a/lib/src/local_history/local_history_panel.dart +++ b/lib/src/local_history/local_history_panel.dart @@ -29,8 +29,7 @@ class _LocalHistoryPanelState extends ConsumerState { Future _selectActive({bool preserveLookup = true}) async { final history = ref.read(localHistoryControllerProvider); - if (preserveLookup && - (history.browsingDocuments || history.inspectingRetainedDocument)) { + if (preserveLookup && history.inspectingRetainedDocument) { return; } final buffer = ref.read(workspaceControllerProvider).activeBuffer; @@ -63,8 +62,7 @@ class _LocalHistoryPanelState extends ConsumerState { if (previous == next) return; if (next.bufferId == null) { final history = ref.read(localHistoryControllerProvider); - if (!history.browsingDocuments && - !history.inspectingRetainedDocument) { + if (!history.inspectingRetainedDocument) { controller.clearDocumentScope(); } return; @@ -75,8 +73,6 @@ class _LocalHistoryPanelState extends ConsumerState { } }, ); - final visibleDocuments = [...state.snapshot.documents] - ..sort((a, b) => b.updatedAt.compareTo(a.updatedAt)); final selected = state.selectedDocument; final activeHistoryDocumentId = activeBuffer == null ? null @@ -100,7 +96,6 @@ class _LocalHistoryPanelState extends ConsumerState { children: [ _LocalHistoryHeader( selectedDocument: selected, - browsingDocuments: state.browsingDocuments, inspectingRetainedDocument: state.inspectingRetainedDocument, onBack: () => unawaited(_selectActive(preserveLookup: false)), actions: BusyMarkHeaderPopupMenuButton<_HistoryAction>.native( @@ -168,37 +163,10 @@ class _LocalHistoryPanelState extends ConsumerState { ), ), Expanded( - child: state.browsingDocuments - ? visibleDocuments.isEmpty - ? _HistoryEmpty(text: context.l10n.localHistoryNoDocuments) - : ListView.builder( - key: const ValueKey('local-history-documents'), - padding: BusyMarkInsets.sidebarList, - itemCount: visibleDocuments.length, - itemBuilder: (context, index) { - final document = visibleDocuments[index]; - final path = - document.currentPath ?? - document.historicalPaths.lastOrNull; - final subtitle = document.deleted - ? path == null - ? context.l10n.localHistoryDeleted - : '${context.l10n.localHistoryDeleted} · $path' - : path; - return BusyMarkSidebarRecordRow( - icon: document.deleted - ? BusyMarkGlyphs.delete - : BusyMarkGlyphs.documentHistory, - title: document.displayName, - subtitle: subtitle, - onTap: () => - controller.inspectRetainedDocument(document.id), - ); - }, - ) - : state.loading && - state.selectedDocumentId == null && - !state.inspectingRetainedDocument + child: + state.loading && + state.selectedDocumentId == null && + !state.inspectingRetainedDocument ? const Center(child: CircularProgressIndicator()) : activeBuffer == null && !state.inspectingRetainedDocument ? _HistoryEmpty(text: context.l10n.localHistoryNoDocuments) @@ -322,14 +290,12 @@ enum _HistoryAction { refresh, clearDocument, clearAll } class _LocalHistoryHeader extends StatelessWidget { const _LocalHistoryHeader({ required this.selectedDocument, - required this.browsingDocuments, required this.inspectingRetainedDocument, required this.onBack, required this.actions, }); final LocalHistoryDocument? selectedDocument; - final bool browsingDocuments; final bool inspectingRetainedDocument; final VoidCallback onBack; final Widget actions; @@ -339,10 +305,8 @@ class _LocalHistoryHeader extends StatelessWidget { final selectedPath = selectedDocument?.currentPath ?? selectedDocument?.historicalPaths.lastOrNull; - final contextTitle = browsingDocuments - ? context.l10n.searchDocumentsCategory - : selectedDocument?.displayName; - final retained = browsingDocuments || inspectingRetainedDocument; + final contextTitle = selectedDocument?.displayName; + final retained = inspectingRetainedDocument; return BusyMarkSidebarHeader( key: const ValueKey('local-history-panel-header'), title: context.l10n.localHistory, diff --git a/lib/src/markdown/busymark_document.dart b/lib/src/markdown/busymark_document.dart index 2cfc54ac..67c624f9 100644 --- a/lib/src/markdown/busymark_document.dart +++ b/lib/src/markdown/busymark_document.dart @@ -109,6 +109,7 @@ class BusyDocument { this.frontMatter = const {}, this.rawFrontMatter, this.source, + this.imageSource, this.authoredXml, }); @@ -120,6 +121,7 @@ class BusyDocument { final Map frontMatter; final String? rawFrontMatter; final String? source; + final String? imageSource; /// The unresolved authored XML tree. Presentation resolution never owns saves. final WritersideDocument? authoredXml; @@ -134,6 +136,7 @@ class BusyDocument { Map? frontMatter, String? rawFrontMatter, String? source, + String? imageSource, WritersideDocument? authoredXml, }) { return BusyDocument( @@ -145,6 +148,7 @@ class BusyDocument { frontMatter: frontMatter ?? this.frontMatter, rawFrontMatter: rawFrontMatter ?? this.rawFrontMatter, source: source ?? this.source, + imageSource: imageSource ?? this.imageSource, authoredXml: authoredXml ?? this.authoredXml, ); } @@ -181,6 +185,7 @@ class BusyBlock { this.attributes = const {}, this.rawSource, this.sourceSpan, + this.posterSpan, this.preserveRaw = false, this.isSourceOnly = false, this.isGenerated = false, @@ -195,6 +200,7 @@ class BusyBlock { final Map attributes; final String? rawSource; final SourceSpan? sourceSpan; + final SourceSpan? posterSpan; final bool preserveRaw; final bool isSourceOnly; final bool isGenerated; @@ -211,6 +217,8 @@ class BusyBlock { Map? attributes, String? rawSource, SourceSpan? sourceSpan, + SourceSpan? posterSpan, + bool clearPosterSpan = false, bool? preserveRaw, bool? isSourceOnly, bool? isGenerated, @@ -225,6 +233,7 @@ class BusyBlock { attributes: attributes ?? this.attributes, rawSource: rawSource ?? this.rawSource, sourceSpan: sourceSpan ?? this.sourceSpan, + posterSpan: clearPosterSpan ? null : posterSpan ?? this.posterSpan, preserveRaw: preserveRaw ?? this.preserveRaw, isSourceOnly: isSourceOnly ?? this.isSourceOnly, isGenerated: isGenerated ?? this.isGenerated, @@ -260,6 +269,7 @@ class BusyInline { required this.kind, required this.text, this.destination, + this.imageSpan, this.children = const [], this.attributes = const {}, }); @@ -267,6 +277,7 @@ class BusyInline { final BusyInlineKind kind; final String text; final String? destination; + final SourceSpan? imageSpan; final List children; final Map attributes; @@ -283,11 +294,14 @@ class BusyInline { String? destination, List? children, Map? attributes, + SourceSpan? imageSpan, + bool clearImageSpan = false, }) { return BusyInline( kind: kind ?? this.kind, text: text ?? this.text, destination: destination ?? this.destination, + imageSpan: clearImageSpan ? null : imageSpan ?? this.imageSpan, children: children ?? this.children, attributes: attributes ?? this.attributes, ); diff --git a/lib/src/markdown/markdown_ast_adapter.dart b/lib/src/markdown/markdown_ast_adapter.dart index 6f6b75d1..8421df54 100644 --- a/lib/src/markdown/markdown_ast_adapter.dart +++ b/lib/src/markdown/markdown_ast_adapter.dart @@ -5,11 +5,13 @@ import 'package:markdown/markdown.dart' as md; import 'package:xml/xml.dart'; import '../core/path_utils.dart'; +import '../core/source_span.dart'; +import '../core/uri_utils.dart'; import 'busymark_document.dart'; import 'markdown_fence.dart'; import 'markdown_front_matter.dart'; import 'markdown_model.dart'; -import 'markdown_source_annotation.dart'; +import 'markdown_source_map.dart'; import 'math_syntax.dart'; import 'raw_html_adapter.dart'; import 'raw_html_policy.dart'; @@ -100,6 +102,171 @@ class MarkdownAstAdapter { ); } + /// Binds rendered images to authored markup. The inline mapper provides + /// exact Markdown ranges and the HTML parser provides tag ranges, including + /// images inside HTML containers. If the two projections disagree about the + /// images in a chunk, the chunk contributes no guessed identities. + BusyDocument bindImageSpans(BusyDocument document) { + final source = document.source; + if (source == null) return document; + BusyMarkInlineParserContext? context; + + Iterable images(Iterable inlines) sync* { + for (final inline in inlines) { + if (inline.kind == BusyInlineKind.image) yield inline; + yield* images(inline.children); + } + } + + Iterable blockImages(BusyBlock block) sync* { + yield* images(block.inlines); + for (final child in block.children) { + yield* blockImages(child); + } + } + + Iterable posters(BusyBlock block) sync* { + if (block.kind == BusyBlockKind.video && + isRemoteImageSource(block.attributes['preview-src'])) { + yield block; + } + for (final child in block.children) { + yield* posters(child); + } + } + + BusyBlock bind(BusyBlock block) { + final rendered = blockImages(block).toList(); + final renderedPosters = posters(block).toList(); + if (rendered.isEmpty && renderedPosters.isEmpty) return block; + final blockSpan = block.sourceSpan; + final bindings = Map.identity(); + final posterBindings = Map.identity(); + if (blockSpan != null && + blockSpan.filePath == document.filePath && + blockSpan.startOffset >= 0 && + blockSpan.endOffset <= source.length && + (renderedPosters.isNotEmpty || + rendered.any( + (image) => isRemoteImageSource(image.destination), + ))) { + final start = blockSpan.startOffset; + final raw = source.substring(start, blockSpan.endOffset); + final candidates = <(BusyInline, int, int)>[]; + SourceSpan bindRange(int from, int to) => SourceSpan.fromOffsets( + filePath: document.filePath, + source: source, + startOffset: start + from, + endOffset: start + to, + ); + + var id = 0; + String nextId() => 'media-${id++}'; + final semantic = + document.mode == MarkdownMode.writersideMarkdown && + block.attributes.containsKey('element') && + raw.trimLeft().startsWith('<') + ? const WritersideEditingAdapter().parseMarkdownElement(raw, nextId) + : null; + if (semantic != null || + (block.attributes['sourceFormat'] == 'html' && + raw.trimLeft().startsWith('<'))) { + final children = semantic != null + ? [semantic] + : _rawHtmlAdapter + .parseRawHtmlBlock(raw, nextId, trackImageSpans: true) + ?.blocks ?? + const []; + for (final child in children) { + for (final image in blockImages(child)) { + if (image.imageSpan case final span?) { + candidates.add((image, span.startOffset, span.endOffset)); + } + } + } + if (semantic != null && renderedPosters.isNotEmpty) { + final authored = posters(semantic).toList(); + if (authored.length == renderedPosters.length) { + for (final (index, poster) in renderedPosters.indexed) { + final candidate = authored[index]; + final span = candidate.posterSpan; + if (span != null && + candidate.attributes['preview-src'] == + poster.attributes['preview-src']) { + posterBindings[poster] = bindRange( + span.startOffset, + span.endOffset, + ); + } + } + } + } + } else { + context ??= const MarkdownSourceMapper().createInlineParserContext( + documentSource: source, + mode: document.mode, + ); + final replacements = <(int, int)>[]; + final normalized = _protectImageDestinationsWithSpaces( + raw, + onReplacement: (end, shift) => replacements.add((end, shift)), + ); + int authoredOffset(int offset) { + for (final (end, shift) in replacements.reversed) { + if (end <= offset) return offset - shift; + } + return offset; + } + + for (final mapped in context!.parsePositionedBlocks( + normalized, + includeCodeBlocks: false, + requireUnambiguousPositions: true, + )) { + for (final image in images(mapped.inlines)) { + if (mapped.ranges[image] case final range?) { + candidates.add(( + image, + authoredOffset(range.start), + authoredOffset(range.end), + )); + } + } + } + } + + if (candidates.length == rendered.length && + rendered.indexed.every( + (entry) => + entry.$2.destination == candidates[entry.$1].$1.destination, + )) { + for (final (index, image) in rendered.indexed) { + final (_, from, to) = candidates[index]; + bindings[image] = bindRange(from, to); + } + } + } + + BusyInline applyInline(BusyInline inline) => inline.copyWith( + children: inline.children.map(applyInline).toList(), + imageSpan: bindings[inline], + clearImageSpan: !bindings.containsKey(inline), + ); + BusyBlock applyBlock(BusyBlock current) => current.copyWith( + posterSpan: posterBindings[current], + clearPosterSpan: !posterBindings.containsKey(current), + inlines: current.inlines.map(applyInline).toList(), + children: current.children.map(applyBlock).toList(), + ); + return applyBlock(block); + } + + return document.copyWith( + imageSource: source, + blocks: document.blocks.map(bind).toList(), + ); + } + /// Use the existing grammar in two phases so definitions on either side of /// a raw HTML block share one reference context. No source text is changed. List _blocksForHtml( @@ -1793,7 +1960,10 @@ class MarkdownAstAdapter { return attributes; } - String _protectImageDestinationsWithSpaces(String source) { + String _protectImageDestinationsWithSpaces( + String source, { + void Function(int end, int shift)? onReplacement, + }) { final buffer = StringBuffer(); var index = 0; while (index < source.length) { @@ -1833,6 +2003,9 @@ class MarkdownAstAdapter { ..write(_protectImageDestination(rawDestination)) ..write(')'); index = destinationEnd + 1; + if (onReplacement != null) { + onReplacement(buffer.length, buffer.length - index); + } } return buffer.toString(); } diff --git a/lib/src/markdown/markdown_parser.dart b/lib/src/markdown/markdown_parser.dart index 97b89135..1602dc2f 100644 --- a/lib/src/markdown/markdown_parser.dart +++ b/lib/src/markdown/markdown_parser.dart @@ -57,10 +57,56 @@ class MarkdownParser { /// Rebind an already edited projection to its emitted source. This reuses /// the ordinary positioned scanner; it does not infer lists from adjacency. BusyDocument rebindSourceMetadata(BusyDocument document, String source) => - _withScannedSourceMetadata( - document.copyWith(source: source), - document.diagnostics, + const MarkdownAstAdapter().bindImageSpans( + _withScannedSourceMetadata( + document.copyWith(source: source), + document.diagnostics, + ), + ); + + /// Refresh presentation ranges while retaining the editor’s live blocks, + /// serializer metadata and rich editing state. + BusyDocument rebindImageSpans(BusyDocument document, String source) { + final projected = rebindSourceMetadata(document, source); + final positions = { + for (final block in _walkBlocks(projected.blocks)) block.id: block, + }; + + List copySpans( + List live, + List positioned, + ) => [ + for (final (index, inline) in live.indexed) + (() { + final mapped = + index < positioned.length && + inline.kind == positioned[index].kind && + inline.destination == positioned[index].destination + ? positioned[index] + : null; + return inline.copyWith( + imageSpan: mapped?.imageSpan, + clearImageSpan: mapped?.imageSpan == null, + children: copySpans(inline.children, mapped?.children ?? const []), + ); + })(), + ]; + + BusyBlock bind(BusyBlock block) { + final positioned = positions[block.id]; + return block.copyWith( + inlines: copySpans(block.inlines, positioned?.inlines ?? const []), + posterSpan: positioned?.posterSpan, + clearPosterSpan: positioned?.posterSpan == null, + children: block.children.map(bind).toList(), ); + } + + return document.copyWith( + imageSource: source, + blocks: document.blocks.map(bind).toList(), + ); + } /// Keeps cross-block reference context for the HTML export projection. The /// editor and source serializer retain their existing projection by default. @@ -341,9 +387,11 @@ class MarkdownParser { title: title, preserveHtmlSemantics: preserveHtmlSemantics, ); - var busyDocument = _withScannedSourceMetadata( - renderedDocument, - sortDiagnostics(diagnostics), + var busyDocument = astAdapter.bindImageSpans( + _withScannedSourceMetadata( + renderedDocument, + sortDiagnostics(diagnostics), + ), ); final canonicalHeadings = _canonicalizeHeadings( document: busyDocument, diff --git a/lib/src/markdown/markdown_source_map.dart b/lib/src/markdown/markdown_source_map.dart index d15a09ed..e676dfab 100644 --- a/lib/src/markdown/markdown_source_map.dart +++ b/lib/src/markdown/markdown_source_map.dart @@ -1006,6 +1006,7 @@ class BusyMarkInlineParserContext { int sourceStart = 0, int? sourceEnd, bool includeCodeBlocks = true, + bool requireUnambiguousPositions = false, }) { if (source.isEmpty) return const []; final boundedStart = sourceStart.clamp(0, source.length).toInt(); @@ -1017,20 +1018,22 @@ class BusyMarkInlineParserContext { final nodes = md.BlockParser([ for (final line in sourceLines) md.Line(line.content), ], _mappingDocument).parseLines(); - final candidates = []; + final candidates = <({String text, bool code})>[]; void collect(Iterable values) { for (final node in values) { if (!includeCodeBlocks && node is md.Element && node.tag == 'pre') { - continue; - } - if (node is md.UnparsedContent) { - if (node.textContent.isNotEmpty) candidates.add(node.textContent); - } else if (node is md.Text) { - // Block HTML is deliberately retained as raw text by package: - // markdown. It still contains authored prose and must be routed - // through BusyMark's mapped inline/HTML scanner. - if (node.textContent.isNotEmpty) candidates.add(node.textContent); + // Consume the code's position without parsing any inline syntax. + // Otherwise identical prose following it could map onto the code. + final text = node.textContent.trimRight(); + if (requireUnambiguousPositions && text.isNotEmpty) { + candidates.add((text: text, code: true)); + } + } else if (node is md.UnparsedContent || node is md.Text) { + // Block HTML is retained as raw text by package:markdown. + if (node.textContent.isNotEmpty) { + candidates.add((text: node.textContent, code: false)); + } } else if (node is md.Element && node.children != null) { collect(node.children!); } @@ -1038,21 +1041,59 @@ class BusyMarkInlineParserContext { } collect(nodes); - final result = []; - var cursor = boundedStart; - for (final candidate in candidates) { - final projection = _MappedBlockInlineProjection.tryCreatePositioned( - source, - sourceLines, - candidate, - minimumSourceOffset: cursor, - maximumSourceOffset: boundedEnd, + + // Compare both monotonic placements when ranges will grant permission. + // Text skipped by the grammar (for example, a reference title) can contain + // an exact copy of a rendered image. Bind only the physical placement + // that remains the same from either end. + List<_MappedBlockInlineProjection?> project({required bool fromEnd}) { + final projections = List<_MappedBlockInlineProjection?>.filled( + candidates.length, + null, ); - if (projection == null) continue; - result.add(_translateBlockProjection(parseMapped(candidate), projection)); - cursor = projection.rawEnd; + var cursor = fromEnd ? boundedEnd : boundedStart; + for (var index = 0; index < candidates.length; index++) { + final slot = fromEnd ? candidates.length - 1 - index : index; + final projection = _MappedBlockInlineProjection.tryCreatePositioned( + source, + sourceLines, + candidates[slot].text, + minimumSourceOffset: fromEnd ? boundedStart : cursor, + maximumSourceOffset: fromEnd ? cursor : boundedEnd, + fromEnd: fromEnd, + ); + if (projection == null) continue; + projections[slot] = projection; + cursor = fromEnd ? projection.rawStart : projection.rawEnd; + } + return projections; } - return List.unmodifiable(result); + + final starts = project(fromEnd: false); + final ends = requireUnambiguousPositions ? project(fromEnd: true) : null; + return List.unmodifiable([ + for (final (index, projection) in starts.indexed) + if (projection != null && + !candidates[index].code && + (ends == null || _samePhysicalLines(projection, ends[index]))) + _translateBlockProjection( + parseMapped(candidates[index].text), + projection, + ), + ]); + } + + bool _samePhysicalLines( + _MappedBlockInlineProjection before, + _MappedBlockInlineProjection? after, + ) { + if (after == null || + before.rawLineStarts.length != after.rawLineStarts.length) { + return false; + } + return before.rawLineStarts.indexed.every( + (entry) => entry.$2 == after.rawLineStarts[entry.$1], + ); } BusyMarkMappedInlineParse _translateBlockProjection( @@ -1342,50 +1383,62 @@ class _MappedBlockInlineProjection { String logicalSource, { required int minimumSourceOffset, required int maximumSourceOffset, + required bool fromEnd, }) { if (logicalSource.isEmpty || sourceLines.isEmpty) return null; final logicalLines = logicalSource.split('\n'); - for ( - var firstSourceLine = 0; - firstSourceLine + logicalLines.length <= sourceLines.length; - firstSourceLine++ - ) { + final first = _sourceLineAt(sourceLines, minimumSourceOffset); + final last = + _sourceLineAt(sourceLines, maximumSourceOffset) - + logicalLines.length + + 1; + for (var slot = first; slot <= last; slot++) { + final lineIndex = fromEnd ? last - (slot - first) : slot; final positions = []; - var valid = true; for (var index = 0; index < logicalLines.length; index++) { - final sourceLine = sourceLines[firstSourceLine + index]; - final searchFrom = index == 0 - ? math.max(0, minimumSourceOffset - sourceLine.contentStart) - : 0; - if (searchFrom > sourceLine.content.length) { - valid = false; - break; - } - final position = sourceLine.content.indexOf( - logicalLines[index], - searchFrom, + final sourceLine = sourceLines[lineIndex + index]; + final logicalLine = logicalLines[index]; + final searchFrom = math.max( + 0, + minimumSourceOffset - sourceLine.contentStart, ); - final rawPosition = sourceLine.contentStart + position; - if (position < 0 || - rawPosition < minimumSourceOffset || - rawPosition + logicalLines[index].length > maximumSourceOffset) { - valid = false; - break; - } - positions.add(rawPosition); + final searchTo = + math.min(sourceLine.contentEnd, maximumSourceOffset) - + sourceLine.contentStart - + logicalLine.length; + if (searchTo < searchFrom) break; + final position = fromEnd + ? sourceLine.content.lastIndexOf(logicalLine, searchTo) + : sourceLine.content.indexOf(logicalLine, searchFrom); + if (position < searchFrom || position > searchTo) break; + positions.add(sourceLine.contentStart + position); } - if (!valid) continue; + if (positions.length != logicalLines.length) continue; return _fromLinePositions( source, sourceLines, logicalLines, positions, - firstSourceLine, + lineIndex, ); } return null; } + static int _sourceLineAt(List<_MappedSourceLine> lines, int offset) { + var first = 0; + var end = lines.length - 1; + while (first < end) { + final middle = (first + end) ~/ 2; + if (offset >= lines[middle].end) { + first = middle + 1; + } else { + end = middle; + } + } + return first; + } + static _MappedBlockInlineProjection? _fromLinePositions( String source, List<_MappedSourceLine> sourceLines, diff --git a/lib/src/markdown/preview_model.dart b/lib/src/markdown/preview_model.dart index 857d2768..187e88b2 100644 --- a/lib/src/markdown/preview_model.dart +++ b/lib/src/markdown/preview_model.dart @@ -41,6 +41,7 @@ class PreviewBlock { this.inlines = const [], this.children = const [], this.attributes = const {}, + this.posterSpan, this.sourceStartLine, this.sourceEndLine, this.sourceStartOffset, @@ -55,6 +56,7 @@ class PreviewBlock { final List inlines; final List children; final Map attributes; + final SourceSpan? posterSpan; final int? sourceStartLine; final int? sourceEndLine; final int? sourceStartOffset; @@ -78,6 +80,7 @@ class PreviewInline { required this.kind, required this.text, this.destination, + this.imageSpan, this.children = const [], this.attributes = const {}, }); @@ -85,6 +88,7 @@ class PreviewInline { final PreviewInlineKind kind; final String text; final String? destination; + final SourceSpan? imageSpan; final List children; final Map attributes; } @@ -95,12 +99,14 @@ class PreviewDocument { required this.modeLabel, required this.compatibility, required this.blocks, + this.source, }); final String title; final String modeLabel; final String compatibility; final List blocks; + final String? source; } extension PreviewDocumentOutline on PreviewDocument { @@ -160,6 +166,7 @@ class MarkdownPreviewBuilder { title: document.title ?? '', modeLabel: '', compatibility: '', + source: document.source, blocks: const BusyMarkPreviewBuilder().buildBlocks(document.busyDocument), ); } @@ -173,6 +180,7 @@ class BusyMarkPreviewBuilder { title: document.title ?? '', modeLabel: '', compatibility: '', + source: document.source, blocks: buildBlocks(document), ); } @@ -262,14 +270,13 @@ class BusyMarkPreviewBuilder { ), BusyBlockKind.image => PreviewBlock( kind: PreviewBlockKind.image, - text: block.inlines.isEmpty - ? block.plainText - : block.inlines.first.text, + text: block.plainText, inlines: _inlines(block.inlines, 'block-${block.id}.i'), attributes: block.attributes, ), BusyBlockKind.video => PreviewBlock( kind: PreviewBlockKind.video, + posterSpan: block.posterSpan, text: block.attributes['src'] ?? block.plainText, attributes: {...block.attributes, 'editorBlockId': block.id}, ), @@ -373,6 +380,7 @@ class BusyMarkPreviewBuilder { inlines: block.inlines, children: children, attributes: block.attributes, + posterSpan: block.posterSpan, sourceStartLine: block.sourceStartLine, sourceEndLine: children.isEmpty ? block.sourceEndLine @@ -475,6 +483,7 @@ class BusyMarkPreviewBuilder { inlines: block.inlines, children: block.children, attributes: attributes, + posterSpan: block.posterSpan, sourceStartLine: block.sourceStartLine, sourceEndLine: block.sourceEndLine, sourceStartOffset: block.sourceStartOffset, @@ -545,6 +554,7 @@ class BusyMarkPreviewBuilder { inlines: block.inlines, children: block.children, attributes: block.attributes, + posterSpan: block.posterSpan, sourceStartLine: span.startLine, sourceEndLine: span.endLine, sourceStartOffset: span.startOffset, @@ -583,6 +593,7 @@ class BusyMarkPreviewBuilder { }, text: inline.kind == BusyInlineKind.softBreak ? ' ' : inline.text, destination: inline.destination, + imageSpan: inline.imageSpan, children: _inlines(inline.children, '$path.i'), attributes: { ...inline.attributes, diff --git a/lib/src/markdown/raw_html_adapter.dart b/lib/src/markdown/raw_html_adapter.dart index c2f67e17..f92cdb28 100644 --- a/lib/src/markdown/raw_html_adapter.dart +++ b/lib/src/markdown/raw_html_adapter.dart @@ -8,6 +8,7 @@ import 'package:html/src/token.dart' as html_token; import 'package:html/src/tokenizer.dart' as html_tokenizer; import '../core/path_utils.dart'; +import '../core/source_span.dart'; import 'busymark_document.dart'; import 'raw_html_policy.dart'; @@ -51,7 +52,14 @@ class RawHtmlInlineParseResult { } class RawHtmlAdapter { - const RawHtmlAdapter({this.preserveInlineWhitespace = false}); + const RawHtmlAdapter({ + this.preserveInlineWhitespace = false, + this.importClipboardLists = false, + }); + + /// Browser lists have explicit DOM owners. Clipboard import can serialize + /// their items as a group without inferring ownership in authored Markdown. + final bool importClipboardLists; /// Clipboard selections can explicitly include spaces at inline edges. /// Callers enabling this must first remove structural HTML layout whitespace. @@ -59,12 +67,13 @@ class RawHtmlAdapter { RawHtmlBlockParseResult? parseRawHtmlBlock( String rawSource, - String Function() nextId, - ) { + String Function() nextId, { + bool trackImageSpans = false, + }) { if (!_mayContainHtml(rawSource)) { return null; } - final fragment = _parseFragment(rawSource); + final fragment = _parseFragment(rawSource, generateSpans: trackImageSpans); if (fragment == null) { return null; } @@ -78,7 +87,10 @@ class RawHtmlAdapter { return const RawHtmlBlockParseResult(safe: false); } final blocks = _blocksFromNodes(fragment.nodes, nextId); - return RawHtmlBlockParseResult(safe: true, blocks: blocks); + return RawHtmlBlockParseResult( + safe: true, + blocks: importClipboardLists ? _separateClipboardLists(blocks) : blocks, + ); } List? parseRawHtmlInlineFragment(String text) { @@ -419,7 +431,7 @@ class RawHtmlAdapter { if (_headingLevel(tag) case final level?) { final anchorId = attributes['id'] ?? slugForHeading(text); - return _applyHtmlDirection([ + final heading = _applyHtmlDirection([ BusyBlock( id: nextId(), kind: BusyBlockKind.heading, @@ -432,6 +444,7 @@ class RawHtmlAdapter { }, ), ], attributes['dir']); + return _preserveClipboardDirection(element, heading, nextId); } final List blocks = switch (tag) { @@ -507,9 +520,43 @@ class RawHtmlAdapter { ] : const [], }; - return _applyHtmlDirection(blocks, attributes['dir']); + return _preserveClipboardDirection( + element, + _applyHtmlDirection(blocks, attributes['dir']), + nextId, + ); + } + + List _preserveClipboardDirection( + html.Element element, + List blocks, + String Function() nextId, + ) { + if (!importClipboardLists || + blocks.isEmpty || + _normalizedHtmlDirection(element.attributes['dir']) == null || + blocks.singleOrNull?.rawSource != null) { + return blocks; + } + return [_importedHtmlBlock(element, blocks, nextId)]; } + BusyBlock _importedHtmlBlock( + html.Element element, + List blocks, + String Function() nextId, + ) => BusyBlock( + id: nextId(), + kind: BusyBlockKind.htmlBlock, + rawSource: element.outerHtml, + children: blocks, + attributes: { + 'sourceFormat': 'html', + 'htmlTag': element.localName!, + if (element.attributes['dir'] case final direction?) 'dir': direction, + }, + ); + List _applyHtmlDirection( List blocks, String? inheritedDirection, @@ -597,21 +644,103 @@ class RawHtmlAdapter { final attributes = sanitizeHtmlAttributes(element.localName ?? '', element.attributes) ?? {}; - final start = int.tryParse(attributes['start'] ?? '') ?? 1; + final items = element.children.where((child) => child.localName == 'li'); + final reversed = attributes.containsKey('reversed'); + final start = + int.tryParse(attributes['start'] ?? '') ?? + (importClipboardLists && reversed ? items.length : 1); var number = start; + final blocks = []; + for (final child in items) { + if (importClipboardLists && ordered) { + number = int.tryParse(child.attributes['value'] ?? '') ?? number; + } + blocks.add( + _listItemFromElement( + child, + ordered: ordered, + marker: ordered ? '$number.' : '-', + nextId: nextId, + parentAttributes: attributes, + ), + ); + if (ordered) number += importClipboardLists && reversed ? -1 : 1; + } + if (!importClipboardLists || blocks.isEmpty) return blocks; + final loose = items.any( + (item) => item.children.any((c) => c.localName == 'p'), + ); + // Alphabetic, reversed, and per-item numbering have no Markdown marker + // equivalent. Keep the sanitized list itself as the source in that case. + if (attributes.keys.any((name) => name != 'start' && name != 'type') || + (ordered && + (reversed || + (attributes['type'] ?? '1') != '1' || + start < 0 || + start + blocks.length - 1 > 999999999 || + items.any((item) => item.attributes.containsKey('value')))) || + (loose && blocks.length == 1 && blocks.single.children.isEmpty)) { + return [_importedHtmlBlock(element, blocks, nextId)]; + } + final last = blocks.length - 1; return [ - for (final child in element.children) - if (child.localName?.toLowerCase() == 'li') - _listItemFromElement( - child, - ordered: ordered, - marker: ordered ? '${number++}.' : '-', - nextId: nextId, - parentAttributes: attributes, - ), + BusyBlock( + id: nextId(), + kind: BusyBlockKind.writersideRawXml, + children: [ + for (final (index, block) in blocks.indexed) + if (loose && index < last) + block.copyWith( + attributes: { + ...block.attributes, + 'busymark-native-trailing-gap': '\n\n', + }, + ) + else + block, + ], + attributes: { + 'element': 'list', + busyMarkWritersideContainerAttribute: 'true', + 'busymark-list-form': 'markdown', + 'busymark-native-list-type': ordered ? 'decimal' : 'bullet', + 'busymark-native-list-start': '$start', + }, + ), ]; } + List _separateClipboardLists(List blocks) { + String? previousMarker; + final result = []; + for (final block in blocks) { + var children = _separateClipboardLists(block.children); + String? marker; + if (block.attributes['busymark-list-form'] == 'markdown') { + final ordered = + block.attributes['busymark-native-list-type'] == 'decimal'; + final standard = ordered ? '.' : '-'; + marker = previousMarker == standard ? (ordered ? ')' : '+') : standard; + children = [ + for (final child in children) + child.copyWith( + attributes: { + ...child.attributes, + 'marker': ordered + ? '${child.attributes['marker']!.split('.').first}$marker' + : marker, + if (!ordered && marker != '-') + 'busymark-clipboard-list-marker': marker, + }, + ), + ]; + } + result.add(block.copyWith(children: children)); + previousMarker = marker; + } + return result; + } + BusyBlock _listItemFromElement( html.Element element, { required bool ordered, @@ -620,6 +749,24 @@ class RawHtmlAdapter { Map parentAttributes = const {}, }) { final attributes = sanitizeHtmlAttributes('li', element.attributes) ?? {}; + if (importClipboardLists) { + final children = _blocksFromNodes(element.nodes, nextId); + final first = children.firstOrNull; + final inlines = + first?.kind == BusyBlockKind.paragraph && + first!.attributes.keys.every((key) => key == 'htmlTag') + ? children.removeAt(0).inlines + : const []; + return BusyBlock( + id: nextId(), + kind: ordered + ? BusyBlockKind.orderedListItem + : BusyBlockKind.unorderedListItem, + inlines: inlines, + children: children, + attributes: {...attributes, 'ordered': '$ordered', 'marker': marker}, + ); + } final inlines = []; final nestedBlocks = []; for (final child in element.nodes) { @@ -778,6 +925,20 @@ class RawHtmlAdapter { }; } + SourceSpan? _imageSpan(html.Element element) { + final span = element.sourceSpan; + if (span == null) return null; + return SourceSpan( + filePath: '', + startOffset: span.start.offset, + endOffset: span.end.offset, + startLine: span.start.line + 1, + endLine: span.end.line + 1, + startColumn: span.start.column + 1, + endColumn: span.end.column + 1, + ); + } + BusyBlock _imageBlockFromElement( html.Element element, Map attributes, @@ -791,6 +952,7 @@ class RawHtmlAdapter { kind: BusyInlineKind.image, text: attributes['alt'] ?? '', destination: attributes['src'], + imageSpan: _imageSpan(element), attributes: attributes, ), ], @@ -902,6 +1064,7 @@ class RawHtmlAdapter { kind: BusyInlineKind.image, text: attributes['alt'] ?? '', destination: attributes['src'], + imageSpan: _imageSpan(element), attributes: attributes, ), ], diff --git a/lib/src/nextcloud_notes/application/nextcloud_connection.dart b/lib/src/nextcloud_notes/application/nextcloud_connection.dart index ee653502..c5cab520 100644 --- a/lib/src/nextcloud_notes/application/nextcloud_connection.dart +++ b/lib/src/nextcloud_notes/application/nextcloud_connection.dart @@ -1,4 +1,5 @@ import '../../app/app_settings.dart'; +import '../../core/debug_log.dart'; import 'dart:async'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -106,7 +107,11 @@ final nextcloudNotesRepositoryProvider = FutureProvider(( rethrow; } ref.onDispose(() { - unawaited(repository.dispose()); + unawaited( + repository.dispose().catchError((Object error, StackTrace stack) { + busyMarkDebugLogError('Nextcloud shutdown failed', error, stack); + }), + ); }); return repository; }); @@ -119,6 +124,7 @@ enum NextcloudConnectionPhase { verifying, connected, removing, + disconnectPending, } class NextcloudConnectionState { @@ -181,9 +187,11 @@ class NextcloudConnectionController extends Notifier { final account = repository.accounts.firstOrNull; state = NextcloudConnectionState( account: account, - phase: account == null - ? NextcloudConnectionPhase.idle - : NextcloudConnectionPhase.connected, + phase: _accountPhase(account), + removalFailed: account?.disconnectPending == true, + error: account?.disconnectPending == true + ? 'Finish disconnecting this Nextcloud account.' + : null, ); } on Object { if (_disposed || generation != _generation) return; @@ -197,10 +205,18 @@ class NextcloudConnectionController extends Notifier { Future reconnect() async { final account = state.account; - if (account == null) return false; + if (account == null || account.disconnectPending) return false; return _connect(account.server.toString(), previous: account); } + NextcloudConnectionPhase _accountPhase(NextcloudAccount? account) => + switch (account) { + null => NextcloudConnectionPhase.idle, + NextcloudAccount(disconnectPending: true) => + NextcloudConnectionPhase.disconnectPending, + _ => NextcloudConnectionPhase.connected, + }; + Future _connect(String serverUrl, {NextcloudAccount? previous}) async { if (state.busy || (state.retryNotBefore?.isAfter(DateTime.now()) ?? false)) { @@ -215,9 +231,7 @@ class NextcloudConnectionController extends Notifier { phase: NextcloudConnectionPhase.starting, ); NextcloudLoginCredentials? credentials; - String? accountId; String? previousPassword; - var secretWritten = false; var committed = false; final secrets = ref.read(nextcloudSecretStoreProvider); final client = ref.read(nextcloudHttpClientProvider); @@ -234,9 +248,6 @@ class NextcloudConnectionController extends Notifier { code: NextcloudCredentialFailure.alreadyConnected, ); } - if (previous != null) { - previousPassword = await secrets.read(previous.id); - } cancellation.throwIfCancelled(); credentials = await loginFlow.authenticate( server, @@ -265,78 +276,70 @@ class NextcloudConnectionController extends Notifier { account: previous, phase: NextcloudConnectionPhase.verifying, ); - accountId = previous?.id ?? const Uuid().v4(); - await secrets.write(accountId, credentials.appPassword); - secretWritten = true; - final capabilities = await fetchNotesCapabilities( - client: client, - server: credentials.server, - loginName: credentials.loginName, - appPassword: credentials.appPassword, - ); - cancellation.throwIfCancelled(); - final account = NextcloudAccount( - id: accountId, - server: credentials.server, - loginName: credentials.loginName, - appVersion: capabilities.appVersion, - apiVersion: capabilities.apiVersion, - listEtag: previous?.listEtag, - lastModified: previous?.lastModified, - ); - await repository.upsertAccount(account, reconnect: previous != null); - committed = true; + final accountId = previous?.id ?? const Uuid().v4(); + final appPassword = credentials.appPassword; + final login = credentials; + Future publishCredential() async { + if (previous != null) previousPassword = await secrets.read(accountId); + cancellation.throwIfCancelled(); + await secrets.write(accountId, appPassword); + try { + final capabilities = await fetchNotesCapabilities( + client: client, + server: login.server, + loginName: login.loginName, + appPassword: appPassword, + ); + cancellation.throwIfCancelled(); + final account = NextcloudAccount( + id: accountId, + server: login.server, + loginName: login.loginName, + appVersion: capabilities.appVersion, + apiVersion: capabilities.apiVersion, + listEtag: previous?.listEtag, + lastModified: previous?.lastModified, + ); + await repository.upsertAccount(account, reconnect: previous != null); + committed = true; + return account; + } on Object { + try { + if (previousPassword case final password?) { + await secrets.write(accountId, password); + } else { + await secrets.delete(accountId); + } + } on Object { + throw const NextcloudCredentialException( + 'Nextcloud setup failed and BusyMark could not clean up the desktop keyring. Unlock the keyring and reconnect.', + ); + } + rethrow; + } + } + + final account = previous == null + ? await publishCredential() + : await repository.withCredentialUpdate(accountId, publishCredential); if (_disposed) return true; state = NextcloudConnectionState( account: account, phase: NextcloudConnectionPhase.connected, ); - if (previousPassword != null && - previousPassword != credentials.appPassword) { + final oldPassword = previousPassword; + if (oldPassword != null && oldPassword != appPassword) { unawaited( revokeNextcloudAppPassword( client: client, server: account.server, loginName: account.loginName, - appPassword: previousPassword, + appPassword: oldPassword, ), ); } return true; } on Object catch (error) { - if (!committed && secretWritten && accountId != null) { - try { - if (previousPassword != null) { - await secrets.write(accountId, previousPassword); - } else { - await secrets.delete(accountId); - } - } on Object { - if (credentials != null) { - await revokeNextcloudAppPassword( - client: client, - server: credentials.server, - loginName: credentials.loginName, - appPassword: credentials.appPassword, - ); - } - // Report keyring cleanup failure without falling back to plaintext. - if (!_disposed && generation == _generation) { - state = NextcloudConnectionState( - account: retainedAccount, - phase: retainedAccount == null - ? NextcloudConnectionPhase.idle - : NextcloudConnectionPhase.connected, - failure: const NextcloudCredentialException( - 'Desktop keyring cleanup failed.', - ), - error: - 'Nextcloud setup failed and BusyMark could not clean up the desktop keyring. Unlock the keyring and reconnect.', - ); - } - return false; - } - } if (!committed && credentials != null) { await revokeNextcloudAppPassword( client: client, @@ -348,9 +351,7 @@ class NextcloudConnectionController extends Notifier { if (_disposed || generation != _generation) return false; state = NextcloudConnectionState( account: retainedAccount, - phase: retainedAccount == null - ? NextcloudConnectionPhase.idle - : NextcloudConnectionPhase.connected, + phase: _accountPhase(retainedAccount), failure: error, error: switch (error) { NextcloudLoginException(code: NextcloudLoginFailure.cancelled) => @@ -391,25 +392,31 @@ class NextcloudConnectionController extends Notifier { account: account, phase: NextcloudConnectionPhase.removing, ); + NotesRepository? repository; + var revoked = false; try { - final repository = await ref.read( + final activeRepository = await ref.read( nextcloudNotesRepositoryProvider.future, ); + repository = activeRepository; final secrets = ref.read(nextcloudSecretStoreProvider); - final password = await secrets.read(account.id); - var revoked = false; - if (password != null) { - revoked = await revokeNextcloudAppPassword( - client: ref.read(nextcloudHttpClientProvider), - server: account.server, - loginName: account.loginName, - appPassword: password, - ); - } - await repository.removeAccount( + final client = ref.read(nextcloudHttpClientProvider); + await activeRepository.removeAccount( account.id, - beforeRemove: () => secrets.delete(account.id), + beforeRemove: () async { + final password = await secrets.read(account.id); + if (password != null) { + revoked = await revokeNextcloudAppPassword( + client: client, + server: account.server, + loginName: account.loginName, + appPassword: password, + ); + } + await secrets.delete(account.id); + }, ); + if (_disposed) return true; ref.invalidate(notesNavigationProvider(account.id)); await ref .read(appSettingsControllerProvider.notifier) @@ -424,18 +431,38 @@ class NextcloudConnectionController extends Notifier { } return true; } on Object catch (error) { + var remaining = repository == null + ? account + : repository.accountById(account.id); + final removedLocally = remaining == null; + if (error is NotesException && + error.code == NotesFailureCode.conflict && + repository != null) { + try { + remaining = (await repository.store.accounts()) + .where((current) => current.id == account.id) + .firstOrNull; + } on Object catch (readError, stack) { + busyMarkDebugLogError( + 'Could not inspect the Notes account', + readError, + stack, + ); + } + } if (!_disposed) { state = NextcloudConnectionState( - account: account, - phase: NextcloudConnectionPhase.connected, + account: remaining, + phase: _accountPhase(remaining), failure: error, removalFailed: true, + removedWithWarning: removedLocally && !revoked, error: error is NextcloudCredentialException ? error.message : 'BusyMark could not remove the local Nextcloud account data. Try again.', ); } - return false; + return removedLocally; } } } diff --git a/lib/src/nextcloud_notes/application/notes_repository.dart b/lib/src/nextcloud_notes/application/notes_repository.dart index 4d68217d..0638daa9 100644 --- a/lib/src/nextcloud_notes/application/notes_repository.dart +++ b/lib/src/nextcloud_notes/application/notes_repository.dart @@ -54,7 +54,7 @@ class NotesRepository { final _publishedReferences = >{}; final _accountErrors = {}; final _syncs = >{}; - final _removing = {}; + final _removing = >{}; final _creationResolutions = {}; final _bindingCandidates = {}; final _creationBindingGuards = )>{}; @@ -100,6 +100,20 @@ class NotesRepository { NextcloudAccount? accountById(String id) => _accounts[id]; NextcloudNote? noteById(String id) => _notes[id]; + NextcloudNote? availableRecentNote(String accountId, String localId) { + final note = noteById(localId); + if (note == null || + accountById(accountId)?.disconnectPending != false || + note.accountId != accountId || + isNotesRecovery(note) || + note.syncState == NoteSyncState.unavailable || + note.syncState == NoteSyncState.forbidden || + isCreationCandidateBinding(localId)) { + return null; + } + return note; + } + Future confirmNoteWebRoute(String accountId) async { _assertMutableAccount(accountId); final account = _accounts[accountId]!; @@ -137,11 +151,13 @@ class NotesRepository { bool isSynchronizing(String accountId) => _syncs.containsKey(accountId); bool _currentAccount(String id, int generation) => !_disposed && - !_removing.contains(id) && - _accounts.containsKey(id) && + !_removing.containsKey(id) && + _accounts[id]?.disconnectPending == false && (_accountGenerations[id] ?? 0) == generation; void _assertMutableAccount(String id) { - if (_disposed || _removing.contains(id) || !_accounts.containsKey(id)) { + if (_disposed || + _removing.containsKey(id) || + _accounts[id]?.disconnectPending != false) { throw const NotesException( NotesFailureCode.missing, 'The Nextcloud account is no longer available.', @@ -678,7 +694,7 @@ class NotesRepository { if (fetchCapabilities == null || account == null || _disposed || - _removing.contains(id)) { + _removing.containsKey(id)) { return Future.value(); } if (!force && @@ -759,7 +775,7 @@ class NotesRepository { Future getSettings(String id) async { final generation = accountGeneration(id); final account = _accounts[id]; - if (account == null) { + if (account == null || account.disconnectPending) { throw const NotesException( NotesFailureCode.missing, 'The account was removed.', @@ -797,114 +813,116 @@ class NotesRepository { NotesSettings original, Map patch, ) async { - if (patch.isEmpty) return original; - _assertMutableAccount(id); - _settingsTransitions.add(id); - final generation = accountGeneration(id); - try { - await _syncs[id]; - final fresh = await getSettings(id); - for (final field in patch.keys) { - if (fresh.toJson()[field] != original.toJson()[field] && - fresh.toJson()[field] != patch[field]) { - throw const NotesSettingsConflict( - NotesSettingsConflictReason.stale, - 'Server settings changed while this form was open. Reload and review them.', - ); - } - } - final pathChange = - patch.containsKey('notesPath') && - patch['notesPath'] != fresh.notesPath; - final suffixChange = - patch.containsKey('fileSuffix') && - patch['fileSuffix'] != fresh.fileSuffix; - final attempt = NotesSettingsAttempt( - id: _uuid.v4(), - original: fresh, - patch: patch, - ); - await _mutate(() async { - if (!_currentAccount(id, generation)) { - throw const NotesException( - NotesFailureCode.missing, - 'The account was removed.', - scope: NotesRequestScope.account, - ); - } - final attachments = await store.attachments(); - if ((pathChange || suffixChange) && - (hasSettingsBlockers(id) || - attachments.any( - (a) => - _notes[a.noteId]?.accountId == id && - !{'cached', 'uploaded', 'deleted'}.contains(a.state), - ))) { - throw NotesSettingsConflict( - hasSettingsBlockers(id) - ? NotesSettingsConflictReason.pendingNotes - : NotesSettingsConflictReason.pendingAttachments, - 'Synchronize or resolve pending notes, conflicts and attachment operations before changing the server collection.', - ); - } - final current = _accounts[id]!.copyWith(settingsAttempt: attempt); - await store.saveAccount(current); - _accounts[id] = current; - }); - NotesSettings result; + return store.withRequestOwnership(id, () async { + if (patch.isEmpty) return original; + _assertMutableAccount(id); + _settingsTransitions.add(id); + final generation = accountGeneration(id); try { - result = await (await _clientForAccount( - _accounts[id]!, - )).updateSettings(patch); - } on NotesException catch (error) { - await _rememberThrottle(id, error); - if (!error.possiblyExecuted) { - await _finishSettings( - id, - generation, - attempt, - fresh, - resetCheckpoint: false, - ); - rethrow; + await _syncs[id]; + final fresh = await getSettings(id); + for (final field in patch.keys) { + if (fresh.toJson()[field] != original.toJson()[field] && + fresh.toJson()[field] != patch[field]) { + throw const NotesSettingsConflict( + NotesSettingsConflictReason.stale, + 'Server settings changed while this form was open. Reload and review them.', + ); + } } - // A lost response may follow normalization/partial execution. Read first; - // if that read fails, the durable attempt fences writes across restart. - result = await getSettings(id); - if (patch.keys.every( - (key) => result.toJson()[key] == fresh.toJson()[key], - )) { - await _finishSettings( - id, - generation, - attempt, - result, - resetCheckpoint: - result.notesPath != fresh.notesPath || - result.fileSuffix != fresh.fileSuffix, - ); - throw const NotesException( - NotesFailureCode.rejected, - 'The settings response was lost and the server still reports the previous values. Review them before saving again.', - scope: NotesRequestScope.settings, - ); + final pathChange = + patch.containsKey('notesPath') && + patch['notesPath'] != fresh.notesPath; + final suffixChange = + patch.containsKey('fileSuffix') && + patch['fileSuffix'] != fresh.fileSuffix; + final attempt = NotesSettingsAttempt( + id: _uuid.v4(), + original: fresh, + patch: patch, + ); + await _mutate(() async { + if (!_currentAccount(id, generation)) { + throw const NotesException( + NotesFailureCode.missing, + 'The account was removed.', + scope: NotesRequestScope.account, + ); + } + final attachments = await store.attachments(); + if ((pathChange || suffixChange) && + (hasSettingsBlockers(id) || + attachments.any( + (a) => + _notes[a.noteId]?.accountId == id && + !{'cached', 'uploaded', 'deleted'}.contains(a.state), + ))) { + throw NotesSettingsConflict( + hasSettingsBlockers(id) + ? NotesSettingsConflictReason.pendingNotes + : NotesSettingsConflictReason.pendingAttachments, + 'Synchronize or resolve pending notes, conflicts and attachment operations before changing the server collection.', + ); + } + final current = _accounts[id]!.copyWith(settingsAttempt: attempt); + await store.saveAccount(current); + _accounts[id] = current; + }); + NotesSettings result; + try { + result = await (await _clientForAccount( + _accounts[id]!, + )).updateSettings(patch); + } on NotesException catch (error) { + await _rememberThrottle(id, error); + if (!error.possiblyExecuted) { + await _finishSettings( + id, + generation, + attempt, + fresh, + resetCheckpoint: false, + ); + rethrow; + } + // A lost response may follow normalization/partial execution. Read first; + // if that read fails, the durable attempt fences writes across restart. + result = await getSettings(id); + if (patch.keys.every( + (key) => result.toJson()[key] == fresh.toJson()[key], + )) { + await _finishSettings( + id, + generation, + attempt, + result, + resetCheckpoint: + result.notesPath != fresh.notesPath || + result.fileSuffix != fresh.fileSuffix, + ); + throw const NotesException( + NotesFailureCode.rejected, + 'The settings response was lost and the server still reports the previous values. Review them before saving again.', + scope: NotesRequestScope.settings, + ); + } } + await _finishSettings( + id, + generation, + attempt, + result, + resetCheckpoint: + pathChange || + suffixChange || + result.notesPath != fresh.notesPath || + result.fileSuffix != fresh.fileSuffix, + ); + return result; + } finally { + _settingsTransitions.remove(id); } - await _finishSettings( - id, - generation, - attempt, - result, - resetCheckpoint: - pathChange || - suffixChange || - result.notesPath != fresh.notesPath || - result.fileSuffix != fresh.fileSuffix, - ); - return result; - } finally { - _settingsTransitions.remove(id); - } + }); } Future _finishSettings( @@ -949,7 +967,7 @@ class NotesRepository { final account = _accounts[id]; if (account == null || _disposed || - _removing.contains(id) || + _removing.containsKey(id) || error.retryNotBefore == null) { return; } @@ -963,19 +981,21 @@ class NotesRepository { _accounts[id] = updated; }); Future reconcileSettings(String id) async { - final attempt = _accounts[id]?.settingsAttempt; - final generation = accountGeneration(id); - final result = await getSettings(id); - if (attempt != null) { - await _finishSettings( - id, - generation, - attempt, - result, - resetCheckpoint: true, - ); - } - return result; + return store.withRequestOwnership(id, () async { + final attempt = _accounts[id]?.settingsAttempt; + final generation = accountGeneration(id); + final result = await getSettings(id); + if (attempt != null) { + await _finishSettings( + id, + generation, + attempt, + result, + resetCheckpoint: true, + ); + } + return result; + }); } void setDisplayedMediaNotes(Iterable ids) { @@ -997,7 +1017,7 @@ class NotesRepository { Future refreshDisplayedMedia({bool force = false}) async { for (final id in _activeMediaNotes.toList()) { final note = _notes[id]; - if (note == null || _disposed || _removing.contains(note.accountId)) { + if (note == null || _disposed || _removing.containsKey(note.accountId)) { continue; } final used = (await scanNotesAttachmentReferences(note.content)) @@ -1106,6 +1126,24 @@ class NotesRepository { if (!_disposed) _changes.add(null); } + Future withCredentialUpdate( + String accountId, + Future Function() update, + ) async { + await _syncs[accountId]; + final generation = accountGeneration(accountId); + return store.withRequestOwnership(accountId, () async { + if (!_currentAccount(accountId, generation)) { + throw const NotesException( + NotesFailureCode.conflict, + 'The account changed before reconnecting.', + scope: NotesRequestScope.account, + ); + } + return update(); + }); + } + NextcloudNote _require(String localId) => _notes[localId] ?? (throw const NotesException( @@ -1189,7 +1227,7 @@ class NotesRepository { String content = '', }) async { await initialize(); - if (!_accounts.containsKey(accountId) || _removing.contains(accountId)) { + if (!_accounts.containsKey(accountId) || _removing.containsKey(accountId)) { throw const NotesException( NotesFailureCode.authentication, 'Connect a Nextcloud account first.', @@ -1224,6 +1262,7 @@ class NotesRepository { bool? favorite, }) => _mutate(() async { var current = _require(localId); + await store.validateNote(localId); _assertMutableAccount(current.accountId); final digest = sha256.convert(utf8.encode(content)).toString(); if (editorRevision != null && @@ -1323,15 +1362,28 @@ class NotesRepository { bool refreshCapabilities = false, bool onlyFreshWrites = false, }) { - if (_disposed || _removing.contains(accountId)) return Future.value(); + if (_disposed || _removing.containsKey(accountId)) return Future.value(); final existing = _syncs[accountId]; if (existing != null) return existing; - final future = _synchronize( - accountId, - allowWrites: allowWrites, - refreshCapabilities: refreshCapabilities, - onlyFreshWrites: onlyFreshWrites, - ); + final future = () async { + try { + await initialize(); + if (_disposed || _accounts[accountId]?.disconnectPending != false) { + return; + } + await store.withRequestOwnership( + accountId, + () => _synchronize( + accountId, + allowWrites: allowWrites, + refreshCapabilities: refreshCapabilities, + onlyFreshWrites: onlyFreshWrites, + ), + ); + } on NotesException catch (error) { + await reportSynchronizationFailure(accountId, error); + } + }(); _syncs[accountId] = future; _notify(); future.then( @@ -1353,10 +1405,12 @@ class NotesRepository { required bool refreshCapabilities, required bool onlyFreshWrites, }) async { - await initialize(); var account = _accounts[accountId]; - if (account == null || _settingsTransitions.contains(accountId)) return; final generation = _accountGenerations[accountId] ?? 0; + if (!_currentAccount(accountId, generation) || + _settingsTransitions.contains(accountId)) { + return; + } final deadline = _accounts[accountId]?.throttleNotBefore ?? _accountErrors[accountId]?.retryNotBefore; @@ -1410,7 +1464,7 @@ class NotesRepository { _notify(); }); } on NotesException catch (error) { - await _markAccountError(accountId, error); + await reportSynchronizationFailure(accountId, error); return; } if (!allowWrites || @@ -1485,7 +1539,7 @@ class NotesRepository { } on NotesException catch (error) { await _recordError(id, error, client: client); if (error.code == NotesFailureCode.authentication) { - await _markAccountError(accountId, error); + await reportSynchronizationFailure(accountId, error); return; } } @@ -1523,7 +1577,8 @@ class NotesRepository { NextcloudAccount account, NotesListResult list, ) => _mutate(() async { - if (_removing.contains(account.id) || !_accounts.containsKey(account.id)) { + if (_removing.containsKey(account.id) || + !_accounts.containsKey(account.id)) { return; } final updated = []; @@ -1952,7 +2007,7 @@ class NotesRepository { NoteState remote, ) => _mutate(() async { final current = _require(sent.localId); - if (_removing.contains(current.accountId) || + if (_removing.containsKey(current.accountId) || !_accounts.containsKey(current.accountId) || (sent.serverId == null && (current.serverId != null || @@ -2096,7 +2151,7 @@ class NotesRepository { final current = _notes[id]; if (current == null || _disposed || - _removing.contains(current.accountId)) { + _removing.containsKey(current.accountId)) { return; } final updated = current.copyWith( @@ -2127,9 +2182,12 @@ class NotesRepository { }); } - Future _markAccountError(String accountId, NotesException error) async { + Future reportSynchronizationFailure( + String accountId, + NotesException error, + ) async { if (_disposed || - _removing.contains(accountId) || + _removing.containsKey(accountId) || !_accounts.containsKey(accountId)) { return; } @@ -2256,7 +2314,7 @@ class NotesRepository { ); return _mutate(() async { final current = _require(originalLocalId); - if (_removing.contains(original.accountId) || + if (_removing.containsKey(original.accountId) || !_accounts.containsKey(original.accountId) || current.revision != original.revision || current.creationAttempt?.id != original.creationAttempt?.id || @@ -2451,158 +2509,160 @@ class NotesRepository { NotesCreationReview? creationReview, NoteState? reviewedRemote, }) async { - final original = _require(localId); - if (expectedRevision != null && original.revision != expectedRevision) { - throw const NotesException( - NotesFailureCode.conflict, - 'New local edits appeared. Review the conflict again.', - ); - } - if (resolution == NoteConflictResolution.saveAsNew) { - if (!_creationResolutions.add(localId)) { + return store.withRequestOwnership(_require(localId).accountId, () async { + final original = _require(localId); + if (expectedRevision != null && original.revision != expectedRevision) { throw const NotesException( NotesFailureCode.conflict, - 'A creation decision is already in progress.', + 'New local edits appeared. Review the conflict again.', ); } - try { - await recoverAsNew( - localId, - creationDecision: - original.serverId == null && - original.syncState == NoteSyncState.creationUncertain, - ); - } finally { - _creationResolutions.remove(localId); + if (resolution == NoteConflictResolution.saveAsNew) { + if (!_creationResolutions.add(localId)) { + throw const NotesException( + NotesFailureCode.conflict, + 'A creation decision is already in progress.', + ); + } + try { + await recoverAsNew( + localId, + creationDecision: + original.serverId == null && + original.syncState == NoteSyncState.creationUncertain, + ); + } finally { + _creationResolutions.remove(localId); + } + return; } - return; - } - if (resolution == NoteConflictResolution.useServerNote) { - if (creationReview == null || - creationCandidateServerId != creationReview.candidate.id) { - throw const NotesException( - NotesFailureCode.conflict, - 'Select and review a server note before confirming adoption.', - ); + if (resolution == NoteConflictResolution.useServerNote) { + if (creationReview == null || + creationCandidateServerId != creationReview.candidate.id) { + throw const NotesException( + NotesFailureCode.conflict, + 'Select and review a server note before confirming adoption.', + ); + } + await _resolveCreation(original, creationReview); + return; } - await _resolveCreation(original, creationReview); - return; - } - if (original.metadataConflict != null) { - await _resolveMetadataConflict( - original, - resolution, - mergedContent: mergedContent, - metadataChoices: metadataChoices, - ); - return; - } - if (original.serverId == null) { - throw const NotesException( - NotesFailureCode.conflict, - 'An uncertain creation needs explicit server-note confirmation or a separate note.', - ); - } - final client = await _clientForAccount(_accounts[original.accountId]!); - late NoteState fresh; - try { - fresh = await client.get(original.serverId!); - } on NotesException catch (error) { - if (error.code == NotesFailureCode.missing && - original.syncState == NoteSyncState.deletedRemotely && - resolution == NoteConflictResolution.takeRemote) { - await _setDeleted(localId, expectedRevision: original.revision); + if (original.metadataConflict != null) { + await _resolveMetadataConflict( + original, + resolution, + mergedContent: mergedContent, + metadataChoices: metadataChoices, + ); return; } - rethrow; - } - if (fresh.error) { - throw const NotesException( - NotesFailureCode.forbidden, - 'The server note is unavailable.', - ); - } - await _mutate(() async { - final current = _require(localId); - if (current.revision != original.revision) { + if (original.serverId == null) { throw const NotesException( NotesFailureCode.conflict, - 'New local edits appeared while resolving this note. Review them before applying the resolution.', + 'An uncertain creation needs explicit server-note confirmation or a separate note.', ); } - final reviewed = reviewedRemote ?? original.remote; - if (reviewed != null && - jsonEncode(fresh.toJson()) != jsonEncode(reviewed.toJson())) { - final changedAgain = current.copyWith( - remote: fresh, - readonly: fresh.readonly, - syncState: NoteSyncState.conflict, - errorMessage: - 'The server note changed again. Review its current state before resolving the conflict.', - ); - await store.saveNote(changedAgain); - _notes[localId] = changedAgain; - _notify(); - throw NotesConflictReviewChanged(fresh); + final client = await _clientForAccount(_accounts[original.accountId]!); + late NoteState fresh; + try { + fresh = await client.get(original.serverId!); + } on NotesException catch (error) { + if (error.code == NotesFailureCode.missing && + original.syncState == NoteSyncState.deletedRemotely && + resolution == NoteConflictResolution.takeRemote) { + await _setDeleted(localId, expectedRevision: original.revision); + return; + } + rethrow; } - final merge = NotesConflictMerge(current, fresh); - final merging = resolution == NoteConflictResolution.merge; - final resolved = resolution == NoteConflictResolution.takeRemote - ? _fromRemote( - localId, - current.accountId, - fresh, - revision: current.revision + 1, - previous: current, - ).copyWith( - editorRevision: current.revision + 1, - editorContentDigest: sha256 - .convert(utf8.encode(fresh.content)) - .toString(), - ) - : current.copyWith( - content: merging - ? mergedContent ?? merge.content.resolve() - : current.content, - title: merging - ? merge.title.resolve( - metadataChoices[NotesMergeAttribute.title], - ) - : current.title, - category: merging - ? merge.category.resolve( - metadataChoices[NotesMergeAttribute.category], - ) - : current.category, - favorite: merging - ? merge.favorite.resolve( - metadataChoices[NotesMergeAttribute.favorite], - ) - : current.favorite, - etag: fresh.etag, - base: fresh, - remote: null, - readonly: fresh.readonly, - error: false, - revision: current.revision + 1, - localActivityMicros: clock().microsecondsSinceEpoch, - failureCode: null, - failureScope: null, - retryCount: 0, - syncState: NoteSyncState.pending, - errorMessage: null, - ); - if (fresh.readonly && - resolution != NoteConflictResolution.takeRemote && - _readonlyBlocks(resolved, fresh)) { + if (fresh.error) { throw const NotesException( NotesFailureCode.forbidden, - 'The server note is read-only. Only its favorite can be changed; recover protected local changes as a new note.', + 'The server note is unavailable.', ); } - await store.saveNote(resolved); - _notes[localId] = resolved; - _notify(); + await _mutate(() async { + final current = _require(localId); + if (current.revision != original.revision) { + throw const NotesException( + NotesFailureCode.conflict, + 'New local edits appeared while resolving this note. Review them before applying the resolution.', + ); + } + final reviewed = reviewedRemote ?? original.remote; + if (reviewed != null && + jsonEncode(fresh.toJson()) != jsonEncode(reviewed.toJson())) { + final changedAgain = current.copyWith( + remote: fresh, + readonly: fresh.readonly, + syncState: NoteSyncState.conflict, + errorMessage: + 'The server note changed again. Review its current state before resolving the conflict.', + ); + await store.saveNote(changedAgain); + _notes[localId] = changedAgain; + _notify(); + throw NotesConflictReviewChanged(fresh); + } + final merge = NotesConflictMerge(current, fresh); + final merging = resolution == NoteConflictResolution.merge; + final resolved = resolution == NoteConflictResolution.takeRemote + ? _fromRemote( + localId, + current.accountId, + fresh, + revision: current.revision + 1, + previous: current, + ).copyWith( + editorRevision: current.revision + 1, + editorContentDigest: sha256 + .convert(utf8.encode(fresh.content)) + .toString(), + ) + : current.copyWith( + content: merging + ? mergedContent ?? merge.content.resolve() + : current.content, + title: merging + ? merge.title.resolve( + metadataChoices[NotesMergeAttribute.title], + ) + : current.title, + category: merging + ? merge.category.resolve( + metadataChoices[NotesMergeAttribute.category], + ) + : current.category, + favorite: merging + ? merge.favorite.resolve( + metadataChoices[NotesMergeAttribute.favorite], + ) + : current.favorite, + etag: fresh.etag, + base: fresh, + remote: null, + readonly: fresh.readonly, + error: false, + revision: current.revision + 1, + localActivityMicros: clock().microsecondsSinceEpoch, + failureCode: null, + failureScope: null, + retryCount: 0, + syncState: NoteSyncState.pending, + errorMessage: null, + ); + if (fresh.readonly && + resolution != NoteConflictResolution.takeRemote && + _readonlyBlocks(resolved, fresh)) { + throw const NotesException( + NotesFailureCode.forbidden, + 'The server note is read-only. Only its favorite can be changed; recover protected local changes as a new note.', + ); + } + await store.saveNote(resolved); + _notes[localId] = resolved; + _notify(); + }); }); } @@ -2731,7 +2791,7 @@ class NotesRepository { void validate() { final current = _require(original.localId); if (account == null || - _removing.contains(original.accountId) || + _removing.containsKey(original.accountId) || _accounts[original.accountId]?.server != account.server || _accounts[original.accountId]?.loginName != account.loginName || current.serverId != null || @@ -2860,38 +2920,40 @@ class NotesRepository { /// Online refresh plus explicit action only. The API has no atomic conditional DELETE. Future delete(String localId) async { - final original = _require(localId); - if (original.serverId == null) { - if (original.syncState == NoteSyncState.creationUncertain || - original.syncState == NoteSyncState.syncing) { - throw const NotesException( + return store.withRequestOwnership(_require(localId).accountId, () async { + final original = _require(localId); + if (original.serverId == null) { + if (original.syncState == NoteSyncState.creationUncertain || + original.syncState == NoteSyncState.syncing) { + throw const NotesException( + NotesFailureCode.conflict, + 'Resolve the uncertain creation before deleting this note.', + ); + } + await _setDeleted(localId, expectedRevision: original.revision); + return; + } + final running = _syncs[original.accountId]; + if (running != null) await running; + final client = await _clientForAccount(_accounts[original.accountId]!); + final current = _require(localId); + final fresh = await client.get(current.serverId!); + if (fresh.etag != current.etag) { + await _setState( + localId, + NoteSyncState.conflict, + 'The note changed on Nextcloud. Review the fresh version before deleting.', + remote: fresh, + ); + throw NotesException( NotesFailureCode.conflict, - 'Resolve the uncertain creation before deleting this note.', + 'The note changed on Nextcloud; deletion was cancelled.', + remote: fresh, ); } - await _setDeleted(localId, expectedRevision: original.revision); - return; - } - final running = _syncs[original.accountId]; - if (running != null) await running; - final client = await _clientForAccount(_accounts[original.accountId]!); - final current = _require(localId); - final fresh = await client.get(current.serverId!); - if (fresh.etag != current.etag) { - await _setState( - localId, - NoteSyncState.conflict, - 'The note changed on Nextcloud. Review the fresh version before deleting.', - remote: fresh, - ); - throw NotesException( - NotesFailureCode.conflict, - 'The note changed on Nextcloud; deletion was cancelled.', - remote: fresh, - ); - } - await client.delete(current.serverId!); - await _setDeleted(localId, expectedRevision: current.revision); + await client.delete(current.serverId!); + await _setDeleted(localId, expectedRevision: current.revision); + }); } Future _setDeleted( @@ -3110,7 +3172,7 @@ class NotesRepository { if (note == null || note.accountId != accountId || _disposed || - _removing.contains(accountId)) { + _removing.containsKey(accountId)) { return null; } final accountGeneration = this.accountGeneration(accountId); @@ -3353,69 +3415,71 @@ class NotesRepository { String reference, { bool retainForHistory = false, }) async { - final note = _require(localId); - if (note.readonly || note.error) { - throw const NotesException( - NotesFailureCode.forbidden, - 'This Nextcloud note is read-only.', - ); - } - final items = await store.attachments(localId); - final matching = items - .where( - (a) => - a.reference == reference || - (canonicalAttachmentReference(reference) != null && - a.remotePath == canonicalAttachmentReference(reference)), - ) - .toList(); - if (matching.isEmpty) return; - final attachment = matching.first; - if (attachment.state == 'uploading' || attachment.state == 'uncertain') { - throw const NotesException( - NotesFailureCode.conflict, - 'Resolve the uncertain attachment upload before deleting.', - ); - } - if (attachment.remotePath != null) { - if (!(_accounts[note.accountId]?.supportsAttachmentDeletion ?? false)) { + return store.withRequestOwnership(_require(localId).accountId, () async { + final note = _require(localId); + if (note.readonly || note.error) { throw const NotesException( - NotesFailureCode.unsupported, - 'Remote attachment cleanup is unavailable: it requires a verified Notes version of 6.1.0 or newer. Notes and attachment upload/download remain available.', + NotesFailureCode.forbidden, + 'This Nextcloud note is read-only.', ); } - if (note.serverId == null) return; - await _mutate(() async { - final current = _require(localId); - final pending = current.copyWith( - revision: current.revision + 1, - syncState: NoteSyncState.pending, - ); - await store.updateAttachment( - NotesAttachment( - id: attachment.id, - noteId: localId, - filename: attachment.filename, - reference: attachment.reference, - remotePath: attachment.remotePath, - state: 'deletePending', - ), - note: pending, + final items = await store.attachments(localId); + final matching = items + .where( + (a) => + a.reference == reference || + (canonicalAttachmentReference(reference) != null && + a.remotePath == canonicalAttachmentReference(reference)), + ) + .toList(); + if (matching.isEmpty) return; + final attachment = matching.first; + if (attachment.state == 'uploading' || attachment.state == 'uncertain') { + throw const NotesException( + NotesFailureCode.conflict, + 'Resolve the uncertain attachment upload before deleting.', ); - _notes[localId] = pending; + } + if (attachment.remotePath != null) { + if (!(_accounts[note.accountId]?.supportsAttachmentDeletion ?? false)) { + throw const NotesException( + NotesFailureCode.unsupported, + 'Remote attachment cleanup is unavailable: it requires a verified Notes version of 6.1.0 or newer. Notes and attachment upload/download remain available.', + ); + } + if (note.serverId == null) return; + await _mutate(() async { + final current = _require(localId); + final pending = current.copyWith( + revision: current.revision + 1, + syncState: NoteSyncState.pending, + ); + await store.updateAttachment( + NotesAttachment( + id: attachment.id, + noteId: localId, + filename: attachment.filename, + reference: attachment.reference, + remotePath: attachment.remotePath, + state: 'deletePending', + ), + note: pending, + ); + _notes[localId] = pending; + _notify(); + }); + await synchronize(note.accountId); + return; + } + await _mutate(() async { + if (retainForHistory) { + await _retainDeletedAttachment(attachment); + } else { + await store.removeAttachment(attachment.id); + await _invalidateAttachmentMedia(attachment); + } _notify(); }); - await synchronize(note.accountId); - return; - } - await _mutate(() async { - if (retainForHistory) { - await _retainDeletedAttachment(attachment); - } else { - await store.removeAttachment(attachment.id); - await _invalidateAttachmentMedia(attachment); - } - _notify(); }); } @@ -3553,24 +3617,51 @@ class NotesRepository { Future removeAccount( String accountId, { Future Function()? beforeRemove, - }) async { + }) { + if (_disposed || _removing.containsKey(accountId)) { + return Future.error( + const NotesException( + NotesFailureCode.conflict, + 'Nextcloud account removal is already in progress or unavailable.', + scope: NotesRequestScope.account, + ), + ); + } + final removal = _removeAccount(accountId, beforeRemove).whenComplete(() { + _removing.remove(accountId); + }); + _removing[accountId] = removal; + return removal; + } + + Future _removeAccount( + String accountId, + Future Function()? beforeRemove, + ) async { _validateId(accountId); - _removing.add(accountId); _accountGenerations[accountId] = (_accountGenerations[accountId] ?? 0) + 1; for (final entry in _downloads.entries.where( (e) => e.key.startsWith('$accountId:'), )) { entry.value.cancel(); } - try { - await _syncs[accountId]; - await _mutate(() async { + await _syncs[accountId]; + await initialize(); + await _mutate( + () => store.withRequestOwnership(accountId, () async { + final account = _accounts[accountId]!; + if (beforeRemove != null && !account.disconnectPending) { + await store.markDisconnectPending(account); + _accounts[accountId] = account.copyWith(disconnectPending: true); + _notify(); + } await beforeRemove?.call(); await store.removeAccount(accountId); _accounts.remove(accountId); _accountErrors.remove(accountId); _notes.removeWhere((_, n) => n.accountId == accountId); _publishedReferences.removeWhere((id, _) => !_notes.containsKey(id)); + _notify(); final directory = Directory( p.join(p.dirname(store.path), 'media', accountId), ); @@ -3578,11 +3669,8 @@ class NotesRepository { !await FileSystemEntity.isLink(directory.path)) { await directory.delete(recursive: true); } - _notify(); - }); - } finally { - _removing.remove(accountId); - } + }, removing: beforeRemove != null), + ); } Future dispose() => _disposing ??= _dispose(); @@ -3592,15 +3680,17 @@ class NotesRepository { for (final cancellation in _downloads.values) { cancellation.cancel(); } - await Future.wait([ - ..._syncs.values, - ..._capabilityRequests.values, - ..._mediaResolutions.values.map( - (f) => f.then((_) {}, onError: (Object _, StackTrace _) {}), - ), - ]); - await _mutations; - await _changes.close(); - await store.close(); + try { + await Future.wait([ + if (_initialization case final initialization?) initialization, + ..._syncs.values, + ..._removing.values, + ..._capabilityRequests.values, + ..._mediaResolutions.values, + ]); + } finally { + await _mutations; + await Future.wait([_changes.close(), store.close()]); + } } } diff --git a/lib/src/nextcloud_notes/application/notes_sync_coordinator.dart b/lib/src/nextcloud_notes/application/notes_sync_coordinator.dart index a1156f6e..1c770523 100644 --- a/lib/src/nextcloud_notes/application/notes_sync_coordinator.dart +++ b/lib/src/nextcloud_notes/application/notes_sync_coordinator.dart @@ -149,6 +149,16 @@ class NotesSyncCoordinator { } Future _run(String id, int generation) async { + try { + await _runPasses(id, generation); + } on NotesException catch (error) { + if (!_disposed && generation == _generation) { + await repository.reportSynchronizationFailure(id, error); + } + } + } + + Future _runPasses(String id, int generation) async { do { _followup = false; final manual = _manual; diff --git a/lib/src/nextcloud_notes/data/notes_store.dart b/lib/src/nextcloud_notes/data/notes_store.dart index 6503dcb3..a0748fd9 100644 --- a/lib/src/nextcloud_notes/data/notes_store.dart +++ b/lib/src/nextcloud_notes/data/notes_store.dart @@ -6,6 +6,7 @@ import 'dart:typed_data'; import 'package:path/path.dart' as p; import 'package:sqlite3/sqlite3.dart'; +import 'package:uuid/uuid.dart'; import '../../assets/asset_limits.dart'; import '../domain/notes_models.dart'; @@ -20,7 +21,15 @@ class NotesStore { if (result[1] == true) { pending?.complete(result[2]); } else { - pending?.completeError(StateError(result[2] as String)); + pending?.completeError( + result[3] == true + ? const NotesException( + NotesFailureCode.conflict, + 'Another BusyMark window changed this Notes state or owns a request. Your editor changes are retained. Use Save As to preserve them before reopening this window.', + scope: NotesRequestScope.account, + ) + : StateError(result[2] as String), + ); } }); } @@ -66,7 +75,9 @@ class NotesStore { } Future _call(String action, [Object? argument]) { - if (_closed) return Future.error(StateError('The Notes store is closed.')); + if (_closed && action != 'close') { + return Future.error(StateError('The Notes store is closed.')); + } final id = ++_serial; final completer = Completer(); _pending[id] = completer; @@ -94,9 +105,11 @@ class NotesStore { Future saveAccount(NextcloudAccount account) => commit(accounts: [account]); + Future validateNote(String id) => _call('validateNote', id); + Future saveNote(NextcloudNote note) => commit(notes: [note]); - /// Content, exact revision, reference state, outbox and checkpoint commit together. + /// Content, exact revision, reference state and checkpoint commit together. Future commit({ List accounts = const [], List notes = const [], @@ -104,19 +117,7 @@ class NotesStore { }) async { await _call('commit', { 'accounts': accounts.map((a) => [a.id, jsonEncode(a.toJson())]).toList(), - 'notes': notes - .map( - (n) => [ - n.localId, - n.accountId, - n.serverId, - n.encode(), - n.hasPendingChanges, - n.revision, - n.serverId == null ? 'create' : 'update', - ], - ) - .toList(), + 'notes': notes.map((n) => n.encode()).toList(), 'removeNotes': removeNotes, }); } @@ -125,6 +126,13 @@ class NotesStore { await _call('removeAccount', id); } + Future markDisconnectPending(NextcloudAccount account) async { + await _call('markDisconnectPending', [ + account.id, + jsonEncode(account.copyWith(disconnectPending: true).toJson()), + ]); + } + Future saveAttachment( NotesAttachment attachment, Uint8List bytes, @@ -295,15 +303,396 @@ class NotesStore { Future importedNote(String accountId, String sourceKey) async => await _call('importedNote', [accountId, sourceKey]) as String?; + final _requestDepth = {}; + final _requests = >{}; + + /// SQLite owns the claim; the network operation never holds a DB transaction. + /// Nested operations in this repository share the claim, foreign stores cannot. + Future withRequestOwnership( + String accountId, + Future Function() action, { + bool removing = false, + }) => _withRequestOwnership( + accountId, + action, + removing ? 'beginRemoval' : 'beginRequest', + ); + + Future _withRequestOwnership( + String accountId, + Future Function() action, + String begin, + ) async { + if (_closing != null && !_requestDepth.containsKey(accountId)) { + throw StateError('The Notes store is closing.'); + } + final finished = Completer(); + _requests.add(finished); + _requestDepth[accountId] = (_requestDepth[accountId] ?? 0) + 1; + try { + await _call(begin, accountId); + try { + return await action(); + } finally { + await _call('endRequest', accountId); + } + } finally { + final depth = _requestDepth[accountId]! - 1; + if (depth == 0) { + _requestDepth.remove(accountId); + } else { + _requestDepth[accountId] = depth; + } + _requests.remove(finished); + finished.complete(); + } + } + Future close() => _closing ??= _close(); Future _close() async { if (_closed) return; - await _call('close'); + while (_requests.isNotEmpty) { + await Future.wait(_requests.map((request) => request.future)); + } _closed = true; - await _subscription.cancel(); - _replies.close(); - _isolate.kill(priority: Isolate.immediate); + try { + await _call('close'); + } finally { + await _subscription.cancel(); + _replies.close(); + _isolate.kill(priority: Isolate.immediate); + } + } +} + +class _NotesStoreConflict implements Exception {} + +/// Expected storage generations belong to this repository's cache, not to the +/// last read from SQLite. Reads for search/media must not authorize stale edits. +class _NotesStoreSession { + _NotesStoreSession(this.id); + final String id; + final _expected = <(String, String), int>{}; + final _rowAccounts = <(String, String), String>{}; + + static String? _processStart(int process) { + try { + final stat = File('/proc/$process/stat').readAsStringSync(); + return stat.substring(stat.lastIndexOf(')') + 2).split(' ')[19]; + } on FileSystemException catch (error) { + // Access denial or an I/O failure is not evidence that an owner died. + // Keep its claim rather than reclassifying a potentially live request. + if (error.osError?.errorCode == 2 || error.osError?.errorCode == 3) { + return null; + } + rethrow; + } + } + + void _retireDeadSessions(Database db) { + for (final row in db.select('SELECT * FROM store_sessions')) { + if (_processStart(row['process'] as int) != row['start']) { + db.execute('DELETE FROM store_sessions WHERE id=?', [row['id']]); + } + } + } + + void open(Database db) { + db.execute( + 'CREATE TABLE IF NOT EXISTS store_versions (kind TEXT NOT NULL, id TEXT NOT NULL, generation INTEGER NOT NULL, PRIMARY KEY(kind,id))', + ); + db.execute( + 'CREATE TABLE IF NOT EXISTS store_sessions (id TEXT PRIMARY KEY, process INTEGER NOT NULL, start TEXT NOT NULL)', + ); + db.execute( + 'CREATE TABLE IF NOT EXISTS request_owners (account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE, session TEXT NOT NULL REFERENCES store_sessions(id) ON DELETE CASCADE, depth INTEGER NOT NULL)', + ); + _retireDeadSessions(db); + db.execute('INSERT INTO store_sessions VALUES(?,?,?)', [ + id, + pid, + _processStart(pid) ?? + (throw StateError('Cannot establish Notes process identity.')), + ]); + } + + bool requestIsLive(Database db, String account) => db.select( + 'SELECT 1 FROM request_owners WHERE account_id=?', + [account], + ).isNotEmpty; + + void capture(Database db) { + for (final row in db.select('SELECT id,account_id FROM notes')) { + _rowAccounts[('notes', row['id'] as String)] = + row['account_id'] as String; + } + for (final row in db.select( + 'SELECT a.id,n.account_id FROM attachments a JOIN notes n ON n.id=a.note_id', + )) { + _rowAccounts[('attachments', row['id'] as String)] = + row['account_id'] as String; + } + + for (final row in db.select('SELECT * FROM store_versions')) { + _expected[(row['kind'] as String, row['id'] as String)] = + row['generation'] as int; + } + } + + int _generation(Database db, (String, String) key) { + final rows = db.select( + 'SELECT generation FROM store_versions WHERE kind=? AND id=?', + [key.$1, key.$2], + ); + return rows.isEmpty ? 0 : rows.single['generation'] as int; + } + + void _advance(Database db, (String, String) key) => db.execute( + 'INSERT INTO store_versions VALUES(?,?,1) ON CONFLICT(kind,id) DO UPDATE SET generation=generation+1', + [key.$1, key.$2], + ); + + Object? execute(Database db, String action, dynamic argument) { + if (action == 'close') { + db.execute('DELETE FROM store_sessions WHERE id=?', [id]); + db.close(); + return null; + } + if (const { + 'accounts', + 'notes', + 'attachments', + 'attachmentSize', + 'attachmentBytes', + 'writeAttachmentFile', + 'searchChunk', + 'offlineRequirements', + 'importOperations', + 'importOperation', + 'importedNote', + }.contains(action)) { + return _execute(db, action, argument); + } + final checked = <(String, String)>{}, changed = <(String, String)>{}; + final accounts = {}; + final rowAccounts = <(String, String), String>{}; + void account(String value, {bool write = false}) { + accounts.add(value); + checked.add(('accounts', value)); + if (write) changed.add(('accounts', value)); + } + + void note(String value, {bool write = false, String? accountId}) { + checked.add(('notes', value)); + if (write) changed.add(('notes', value)); + final rows = db.select('SELECT account_id FROM notes WHERE id=?', [ + value, + ]); + final owner = + accountId ?? + (rows.isEmpty ? null : rows.single['account_id'] as String); + if (owner != null) { + account(owner); + rowAccounts[('notes', value)] = owner; + } + } + + void attachment(String value, {bool write = false, String? noteId}) { + checked.add(('attachments', value)); + if (write) changed.add(('attachments', value)); + final rows = db.select('SELECT note_id FROM attachments WHERE id=?', [ + value, + ]); + final owner = + noteId ?? (rows.isEmpty ? null : rows.single['note_id'] as String); + if (owner != null) { + note(owner); + final accountId = rowAccounts[('notes', owner)]; + if (accountId != null) rowAccounts[('attachments', value)] = accountId; + } + } + + void noteJson(Map value) => note( + value['localId'] as String, + write: true, + accountId: value['accountId'] as String, + ); + db.execute('BEGIN IMMEDIATE'); + try { + _retireDeadSessions(db); + switch (action) { + case 'validateNote': + note(argument as String); + case 'commit': + final data = argument as Map; + for (final a in data['accounts'] as List) { + account(a[0] as String, write: true); + } + for (final n in data['notes'] as List) { + noteJson(jsonDecode(n as String) as Map); + } + for (final n in data['removeNotes'] as List) { + note(n as String, write: true); + for (final row in db.select( + 'SELECT id FROM attachments WHERE note_id=?', + [n], + )) { + attachment(row['id'] as String, write: true); + } + } + case 'removeAccount': + account(argument as String, write: true); + for (final row in db.select( + 'SELECT id FROM notes WHERE account_id=?', + [argument], + )) { + final noteId = row['id'] as String; + note(noteId, write: true); + for (final a in db.select( + 'SELECT id FROM attachments WHERE note_id=?', + [noteId], + )) { + attachment(a['id'] as String, write: true); + } + } + case 'markDisconnectPending': + account((argument as List)[0] as String, write: true); + case 'createWithAttachments': + final a = argument as List; + noteJson(a[0] as Map); + for (final n in a[2] as List) { + noteJson(n as Map); + } + for (final value in a[1] as List) { + attachment( + value[0] as String, + write: true, + noteId: value[1] as String, + ); + } + case 'saveAttachment' || 'saveAttachmentFile': + final a = argument as List; + attachment(a[0] as String, write: true, noteId: a[1] as String); + case 'stageAttachments': + for (final a in argument as List) { + attachment(a[0] as String, write: true, noteId: a[1] as String); + } + case 'updateAttachment': + final a = argument as List; + attachment(a[0] as String, write: true); + if (a[2] != null) noteJson(a[2] as Map); + case 'removeAttachment': + attachment(argument as String, write: true); + case 'setOfflineRequirement' || + 'beginImportOperation' || + 'completeImportOperation': + final a = argument as List; + account(a[0] as String); + final key = ( + action == 'setOfflineRequirement' ? 'offline' : 'import', + jsonEncode( + a.take(action == 'setOfflineRequirement' ? 3 : 2).toList(), + ), + ); + checked.add(key); + changed.add(key); + case 'beginRequest' || 'beginRemoval': + account(argument as String); + // Include cached identities deleted by another process, not just + // rows still present. A stale cache must not send a remote DELETE. + checked.addAll( + _rowAccounts.entries + .where((entry) => entry.value == argument) + .map((entry) => entry.key), + ); + // A stale cache must not send a remote DELETE or request based on + // another process's superseded note, identity, settings or attachment. + for (final row in db.select( + 'SELECT id FROM notes WHERE account_id=?', + [argument], + )) { + final noteId = row['id'] as String; + note(noteId); + for (final a in db.select( + 'SELECT id FROM attachments WHERE note_id=?', + [noteId], + )) { + attachment(a['id'] as String); + } + } + } + for (final key in checked) { + if (_generation(db, key) != (_expected[key] ?? 0)) { + throw _NotesStoreConflict(); + } + } + for (final value in accounts) { + final owners = db.select( + 'SELECT session,depth FROM request_owners WHERE account_id=?', + [value], + ); + final owner = owners.singleOrNull; + // A removal claim is exclusive even within this store. Positive depths + // count ordinary reentrant operations. A negative depth denotes removal. + final removalClaim = (owner?['depth'] as int? ?? 0) < 0; + if (owner != null && + (owner['session'] != id || + action == 'beginRemoval' || + (removalClaim && + action != 'markDisconnectPending' && + action != 'removeAccount'))) { + throw _NotesStoreConflict(); + } + final rows = db.select( + "SELECT json_extract(data, '\$.disconnectPending') AS pending FROM accounts WHERE id=?", + [value], + ); + if (((action == 'beginRequest' || action == 'beginRemoval') && + rows.isEmpty) || + (action == 'markDisconnectPending' && !removalClaim) || + (rows.isNotEmpty && + rows.single['pending'] == 1 && + action != 'beginRemoval' && + action != 'removeAccount')) { + throw _NotesStoreConflict(); + } + } + Object? result; + if (action == 'validateNote') { + // Validation uses the same persisted generation as writes. + } else if (action == 'beginRemoval') { + db.execute('INSERT INTO request_owners VALUES(?,?,-1)', [argument, id]); + } else if (action == 'beginRequest') { + db.execute( + 'INSERT INTO request_owners VALUES(?,?,1) ON CONFLICT(account_id) DO UPDATE SET depth=depth+1', + [argument, id], + ); + } else if (action == 'endRequest') { + db.execute( + 'UPDATE request_owners SET depth=depth-1 WHERE account_id=? AND session=?', + [argument, id], + ); + db.execute( + 'DELETE FROM request_owners WHERE account_id=? AND session=? AND depth<=0', + [argument, id], + ); + } else { + result = _execute(db, action, argument); + } + for (final key in changed) { + _advance(db, key); + } + // Capture before COMMIT, publish the cache baseline only after COMMIT. + final versions = {for (final key in changed) key: _generation(db, key)}; + db.execute('COMMIT'); + _expected.addAll(versions); + _rowAccounts.addAll(rowAccounts); + return result; + } catch (_) { + db.execute('ROLLBACK'); + rethrow; + } } } @@ -313,6 +702,7 @@ void _worker(List arguments) { final replies = arguments[2] as SendPort; Database? openedDatabase; late final Database db; + final session = _NotesStoreSession(const Uuid().v4()); try { db = sqlite3.open(path); openedDatabase = db; @@ -321,36 +711,26 @@ void _worker(List arguments) { throw StateError('Cannot protect the Nextcloud Notes database.'); } db.execute('PRAGMA foreign_keys = ON'); + db.execute('PRAGMA busy_timeout = 5000'); db.execute('PRAGMA journal_mode = WAL'); db.execute('PRAGMA synchronous = FULL'); - db.execute('PRAGMA busy_timeout = 5000'); + db.execute('BEGIN IMMEDIATE'); final version = db.select('PRAGMA user_version').first.values.first as int; - if (version > 6) { + if (version > 8) { throw StateError( 'The Notes database was created by a newer BusyMark version.', ); } if (version == 0) { - db.execute('BEGIN IMMEDIATE'); - try { - db.execute( - 'CREATE TABLE accounts (id TEXT PRIMARY KEY, data TEXT NOT NULL)', - ); - db.execute( - 'CREATE TABLE notes (id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, server_id INTEGER, data TEXT NOT NULL, UNIQUE(account_id, server_id))', - ); - db.execute( - 'CREATE TABLE outbox (note_id TEXT PRIMARY KEY REFERENCES notes(id) ON DELETE CASCADE, revision INTEGER NOT NULL, operation TEXT NOT NULL, data TEXT NOT NULL)', - ); - db.execute( - 'CREATE TABLE attachments (id TEXT PRIMARY KEY, note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, data TEXT NOT NULL, bytes BLOB NOT NULL)', - ); - db.execute('PRAGMA user_version = 1'); - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; - } + db.execute( + 'CREATE TABLE accounts (id TEXT PRIMARY KEY, data TEXT NOT NULL)', + ); + db.execute( + 'CREATE TABLE notes (id TEXT PRIMARY KEY, account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, server_id INTEGER, data TEXT NOT NULL, UNIQUE(account_id, server_id))', + ); + db.execute( + 'CREATE TABLE attachments (id TEXT PRIMARY KEY, note_id TEXT NOT NULL REFERENCES notes(id) ON DELETE CASCADE, data TEXT NOT NULL, bytes BLOB NOT NULL)', + ); } // v2 stores durable creation attempts in the existing versioned note JSON. // Older uncertain operations have no attempt and remain explicitly unresolved. @@ -360,14 +740,16 @@ void _worker(List arguments) { // Advance only inside the recovery transaction; malformed rows roll back. // A request interrupted by a crash has an uncertain creation/upload outcome. - db.execute('BEGIN IMMEDIATE'); try { _createWorkspaceSchema(db); + session.open(db); + db.execute('DROP TABLE IF EXISTS outbox'); for (final row in db.select('SELECT data FROM notes')) { final note = NextcloudNote.fromJson( jsonDecode(row['data'] as String) as Map, ); - if (note.syncState == NoteSyncState.syncing) { + if (note.syncState == NoteSyncState.syncing && + !session.requestIsLive(db, note.accountId)) { _writeNote( db, note.copyWith( @@ -376,9 +758,12 @@ void _worker(List arguments) { : NoteSyncState.pending, ), ); + session._advance(db, ('notes', note.localId)); } } - if (version < 6) db.execute('PRAGMA user_version = 6'); + session.capture(db); + // Older clients must never authenticate a pending disconnect. + if (version < 8) db.execute('PRAGMA user_version = 8'); db.execute('COMMIT'); } catch (_) { db.execute('ROLLBACK'); @@ -397,15 +782,16 @@ void _worker(List arguments) { commands.listen((dynamic message) { final request = message as List; try { - final result = _execute(db, request[1] as String, request[2]); + final result = session.execute(db, request[1] as String, request[2]); replies.send([request[0], true, result]); if (request[1] == 'close') commands.close(); - } catch (_) { + } catch (error) { // Never include note contents, SQL parameters or credentials in errors/logs. replies.send([ request[0], false, 'The durable Nextcloud Notes transaction failed.', + error is _NotesStoreConflict, ]); } }); @@ -417,19 +803,6 @@ void _writeNote(Database db, NextcloudNote note) { [note.localId, note.accountId, note.serverId, note.encode()], ); _indexNote(db, note); - if (note.hasPendingChanges) { - db.execute( - 'INSERT INTO outbox(note_id,revision,operation,data) VALUES(?,?,?,?) ON CONFLICT(note_id) DO UPDATE SET revision=excluded.revision,operation=excluded.operation,data=excluded.data', - [ - note.localId, - note.revision, - note.serverId == null ? 'create' : 'update', - note.encode(), - ], - ); - } else { - db.execute('DELETE FROM outbox WHERE note_id=?', [note.localId]); - } } Object? _execute(Database db, String action, dynamic argument) { @@ -438,32 +811,18 @@ Object? _execute(Database db, String action, dynamic argument) { final rows = db.select( "SELECT n.data FROM notes n LEFT JOIN note_search_map s ON s.id=n.id WHERE s.id IS NULL OR s.revision!=json_extract(n.data,'\$.revision') LIMIT 32", ); - db.execute('BEGIN IMMEDIATE'); - try { - for (final row in rows) { - _indexNote( - db, - NextcloudNote.fromJson( - jsonDecode(row['data'] as String) as Map, - ), - ); - } - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; + for (final row in rows) { + _indexNote( + db, + NextcloudNote.fromJson( + jsonDecode(row['data'] as String) as Map, + ), + ); } return rows.length; case 'rebuildIndex': - db.execute('BEGIN IMMEDIATE'); - try { - db.execute('DELETE FROM note_search'); - db.execute('DELETE FROM note_search_map'); - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; - } + db.execute('DELETE FROM note_search'); + db.execute('DELETE FROM note_search_map'); return null; case 'searchChunk': final a = argument as Map; @@ -577,25 +936,18 @@ Object? _execute(Database db, String action, dynamic argument) { return rows.isEmpty ? null : Map.from(rows.single); case 'completeImportOperation': final a = argument as List; - db.execute('BEGIN IMMEDIATE'); - try { - for (final key in a[2] as List) { - if (db.select( - 'SELECT note_id FROM import_items WHERE account_id=? AND source_key=?', - [a[0], key], - ).isEmpty) { - throw StateError('An import item is not durable.'); - } + for (final key in a[2] as List) { + if (db.select( + 'SELECT note_id FROM import_items WHERE account_id=? AND source_key=?', + [a[0], key], + ).isEmpty) { + throw StateError('An import item is not durable.'); } - db.execute( - "UPDATE import_operations SET state='completed' WHERE account_id=? AND id=?", - [a[0], a[1]], - ); - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; } + db.execute( + "UPDATE import_operations SET state='completed' WHERE account_id=? AND id=?", + [a[0], a[1]], + ); return null; case 'offlineRequirements': return db @@ -638,34 +990,31 @@ Object? _execute(Database db, String action, dynamic argument) { .toList(); case 'commit': final data = argument as Map; - db.execute('BEGIN IMMEDIATE'); - try { - for (final id in data['removeNotes'] as List) { - db.execute('DELETE FROM notes WHERE id=?', [id]); - } - for (final a in data['accounts'] as List) { - db.execute( - 'INSERT INTO accounts(id,data) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data', - a as List, - ); - } - for (final n in data['notes'] as List) { - _writeNote( - db, - NextcloudNote.fromJson( - jsonDecode(n[3] as String) as Map, - ), - ); - } - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; + for (final id in data['removeNotes'] as List) { + db.execute('DELETE FROM notes WHERE id=?', [id]); + } + for (final a in data['accounts'] as List) { + db.execute( + 'INSERT INTO accounts(id,data) VALUES(?,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data', + a as List, + ); + } + for (final n in data['notes'] as List) { + _writeNote( + db, + NextcloudNote.fromJson( + jsonDecode(n as String) as Map, + ), + ); } return null; case 'removeAccount': db.execute('DELETE FROM accounts WHERE id=?', [argument]); return null; + case 'markDisconnectPending': + final a = argument as List; + db.execute('UPDATE accounts SET data=? WHERE id=?', [a[1], a[0]]); + return null; case 'saveAttachmentFile': final a = argument as List; final file = File(a[3] as String); @@ -707,37 +1056,30 @@ Object? _execute(Database db, String action, dynamic argument) { return null; case 'createWithAttachments': final a = argument as List; - db.execute('BEGIN IMMEDIATE'); - try { - for (final note in a[2] as List) { - _writeNote( - db, - NextcloudNote.fromJson(Map.from(note as Map)), - ); - } + for (final note in a[2] as List) { _writeNote( db, - NextcloudNote.fromJson(Map.from(a[0] as Map)), + NextcloudNote.fromJson(Map.from(note as Map)), + ); + } + _writeNote( + db, + NextcloudNote.fromJson(Map.from(a[0] as Map)), + ); + for (final attachment in a[1] as List) { + db.execute( + 'INSERT INTO attachments(id,note_id,data,bytes) VALUES(?,?,?,?)', + (attachment as List).cast(), + ); + } + if (a.length > 3 && a[3] != null) { + final note = NextcloudNote.fromJson( + Map.from(a[0] as Map), + ); + db.execute( + 'INSERT INTO import_items(account_id,source_key,note_id) VALUES(?,?,?)', + [note.accountId, a[3], note.localId], ); - for (final attachment in a[1] as List) { - db.execute( - 'INSERT INTO attachments(id,note_id,data,bytes) VALUES(?,?,?,?)', - (attachment as List).cast(), - ); - } - if (a.length > 3 && a[3] != null) { - final note = NextcloudNote.fromJson( - Map.from(a[0] as Map), - ); - db.execute( - 'INSERT INTO import_items(account_id,source_key,note_id) VALUES(?,?,?)', - [note.accountId, a[3], note.localId], - ); - } - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; } return null; case 'attachments': @@ -750,18 +1092,11 @@ Object? _execute(Database db, String action, dynamic argument) { .map((r) => r['data']) .toList(); case 'stageAttachments': - db.execute('BEGIN IMMEDIATE'); - try { - for (final attachment in argument as List) { - db.execute( - 'INSERT INTO attachments(id,note_id,data,bytes) VALUES(?,?,?,?)', - (attachment as List).cast(), - ); - } - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; + for (final attachment in argument as List) { + db.execute( + 'INSERT INTO attachments(id,note_id,data,bytes) VALUES(?,?,?,?)', + (attachment as List).cast(), + ); } return null; case 'attachmentSize': @@ -777,26 +1112,18 @@ Object? _execute(Database db, String action, dynamic argument) { return rows.isEmpty ? null : rows.first['bytes']; case 'updateAttachment': final a = argument as List; - db.execute('BEGIN IMMEDIATE'); - try { - db.execute('UPDATE attachments SET data=? WHERE id=?', [a[1], a[0]]); - if (a[2] != null) { - _writeNote( - db, - NextcloudNote.fromJson(Map.from(a[2] as Map)), - ); - } - db.execute('COMMIT'); - } catch (_) { - db.execute('ROLLBACK'); - rethrow; + db.execute('UPDATE attachments SET data=? WHERE id=?', [a[1], a[0]]); + if (a[2] != null) { + _writeNote( + db, + NextcloudNote.fromJson(Map.from(a[2] as Map)), + ); } return null; case 'removeAttachment': db.execute('DELETE FROM attachments WHERE id=?', [argument]); return null; case 'close': - db.close(); return null; default: throw StateError('Unknown Notes storage operation.'); diff --git a/lib/src/nextcloud_notes/domain/notes_models.dart b/lib/src/nextcloud_notes/domain/notes_models.dart index 682f8140..6e7fa655 100644 --- a/lib/src/nextcloud_notes/domain/notes_models.dart +++ b/lib/src/nextcloud_notes/domain/notes_models.dart @@ -153,6 +153,7 @@ class NextcloudAccount { this.settingsAttempt, this.throttleNotBefore, this.notesWebPrettyUrls, + this.disconnectPending = false, }); final String id; @@ -167,6 +168,7 @@ class NextcloudAccount { final bool apiSupported; final NotesSettingsAttempt? settingsAttempt; final DateTime? throttleNotBefore; + final bool disconnectPending; /// Optional, backward-compatible observation of the installation's web router. final bool? notesWebPrettyUrls; @@ -195,6 +197,7 @@ class NextcloudAccount { Object? settingsAttempt = _unchanged, Object? throttleNotBefore = _unchanged, Object? notesWebPrettyUrls = _unchanged, + bool? disconnectPending, }) => NextcloudAccount( id: id, server: server, @@ -210,6 +213,7 @@ class NextcloudAccount { : lastModified as String?, lastServerCheck: lastServerCheck ?? this.lastServerCheck, capabilitiesCheckedAt: capabilitiesCheckedAt ?? this.capabilitiesCheckedAt, + disconnectPending: disconnectPending ?? this.disconnectPending, settingsAttempt: identical(settingsAttempt, _unchanged) ? this.settingsAttempt : settingsAttempt as NotesSettingsAttempt?, @@ -237,6 +241,7 @@ class NextcloudAccount { 'settingsAttempt': settingsAttempt?.toJson(), 'throttleNotBefore': throttleNotBefore?.toIso8601String(), if (notesWebPrettyUrls != null) 'notesWebPrettyUrls': notesWebPrettyUrls, + if (disconnectPending) 'disconnectPending': true, }; factory NextcloudAccount.fromJson(Map json) => @@ -256,6 +261,7 @@ class NextcloudAccount { ), apiSupported: json['apiSupported'] as bool? ?? true, notesWebPrettyUrls: json['notesWebPrettyUrls'] as bool?, + disconnectPending: json['disconnectPending'] == true, settingsAttempt: json['settingsAttempt'] == null ? null : NotesSettingsAttempt.fromJson( diff --git a/lib/src/nextcloud_notes/presentation/nextcloud_settings.dart b/lib/src/nextcloud_notes/presentation/nextcloud_settings.dart index b7fb5185..23abe999 100644 --- a/lib/src/nextcloud_notes/presentation/nextcloud_settings.dart +++ b/lib/src/nextcloud_notes/presentation/nextcloud_settings.dart @@ -12,6 +12,7 @@ import '../../workspace/workspace_controller.dart'; import '../../workspace/workspace_safety.dart'; import '../application/nextcloud_connection.dart'; import '../application/notes_settings_controller.dart'; +import '../domain/notes_models.dart'; import 'notes_sidebar.dart' show nextcloudNotesChangesProvider; import 'notes_messages.dart'; @@ -94,7 +95,7 @@ class _NextcloudNotesSettingsState final signInEnabled = actionsEnabled && !throttled; final account = connection.account == null ? null - : repository == null + : repository == null || connection.account!.disconnectPending ? connection.account : repository.accountById(connection.account!.id); return Column( @@ -134,24 +135,26 @@ class _NextcloudNotesSettingsState tooltip: '${context.l10n.nextcloudNotes} ${account.appVersion} · ${account.apiVersion}', ), - BusyMarkActionRow( - title: context.l10n.open, - enabled: actionsEnabled, - onTap: !actionsEnabled - ? null - : () => unawaited(_openAccount(account.id)), - ), - BusyMarkActionRow( - title: context.l10n.nextcloudReconnect, - enabled: signInEnabled, - onTap: !signInEnabled - ? null - : () async { - if (await confirmNotesSettingsDeparture(context)) { - await controller.reconnect(); - } - }, - ), + if (!account.disconnectPending) ...[ + BusyMarkActionRow( + title: context.l10n.open, + enabled: actionsEnabled, + onTap: !actionsEnabled + ? null + : () => unawaited(_openAccount(account.id)), + ), + BusyMarkActionRow( + title: context.l10n.nextcloudReconnect, + enabled: signInEnabled, + onTap: !signInEnabled + ? null + : () async { + if (await confirmNotesSettingsDeparture(context)) { + await controller.reconnect(); + } + }, + ), + ], BusyMarkActionRow( title: context.l10n.nextcloudDisconnect, destructive: true, @@ -214,7 +217,7 @@ class _NextcloudNotesSettingsState }, ), ], - if (account != null) ...[ + if (account != null && !account.disconnectPending) ...[ _ServerNotesSettings(accountId: account.id), if (repository?.accountError(account.id) case final error?) BusyMarkStatusBox( @@ -233,7 +236,8 @@ class _NextcloudNotesSettingsState BusyMarkStatusBox( message: connection.removedWithWarning ? context.l10n.notesRemovedWarning - : connection.removalFailed + : connection.removalFailed && + connection.failure is! NotesException ? context.l10n.notesLocalRemovalFailed : localizeNotesConnectionFailure(context, connection.failure), kind: connection.removedWithWarning diff --git a/lib/src/nextcloud_notes/presentation/notes_messages.dart b/lib/src/nextcloud_notes/presentation/notes_messages.dart index 9b1eb596..a230ea28 100644 --- a/lib/src/nextcloud_notes/presentation/notes_messages.dart +++ b/lib/src/nextcloud_notes/presentation/notes_messages.dart @@ -99,6 +99,8 @@ String localizeNotesConnectionFailure( NotesException( code: NotesFailureCode.authentication, ) => context.l10n.notesAccountAuthorizeAgain, + NotesException(code: NotesFailureCode.conflict) => + context.l10n.notesRecoveryRequired, NextcloudCapabilityException(code: NextcloudCapabilityFailure.forbidden) || NotesException( code: NotesFailureCode.forbidden, diff --git a/lib/src/platform/gtk_header_icon_service.dart b/lib/src/platform/gtk_header_icon_service.dart index 45134465..7bd3a566 100644 --- a/lib/src/platform/gtk_header_icon_service.dart +++ b/lib/src/platform/gtk_header_icon_service.dart @@ -31,6 +31,7 @@ final class GtkHeaderIconAsset { enum BusyMarkLinuxHeaderIcon { back, + home, sidebar, search, searchEntryFind, @@ -47,6 +48,7 @@ enum BusyMarkLinuxHeaderIcon { extension BusyMarkLinuxHeaderIconNames on BusyMarkLinuxHeaderIcon { List get gtkNames => switch (this) { BusyMarkLinuxHeaderIcon.back => const ['go-previous-symbolic'], + BusyMarkLinuxHeaderIcon.home => const ['go-home-symbolic'], BusyMarkLinuxHeaderIcon.sidebar => const ['sidebar-show-symbolic'], BusyMarkLinuxHeaderIcon.search => const ['system-search-symbolic'], BusyMarkLinuxHeaderIcon.searchEntryFind => const ['edit-find-symbolic'], @@ -66,7 +68,7 @@ extension BusyMarkLinuxHeaderIconNames on BusyMarkLinuxHeaderIcon { } BusyMarkLinuxHeaderIcon? _nativeHeaderIcon(IconData glyph) => switch (glyph) { - BusyMarkGlyphs.home => BusyMarkLinuxHeaderIcon.back, + BusyMarkGlyphs.home => BusyMarkLinuxHeaderIcon.home, BusyMarkGlyphs.sidebar => BusyMarkLinuxHeaderIcon.sidebar, BusyMarkGlyphs.search => BusyMarkLinuxHeaderIcon.search, BusyMarkGlyphs.clear => BusyMarkLinuxHeaderIcon.searchClear, diff --git a/lib/src/platform/header_bar_configuration.dart b/lib/src/platform/header_bar_configuration.dart deleted file mode 100644 index a347b09d..00000000 --- a/lib/src/platform/header_bar_configuration.dart +++ /dev/null @@ -1,671 +0,0 @@ -import 'dart:async'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/material.dart'; - -import '../app/busymark_design.dart'; - -enum AppViewMode { editor, source, preview, split } - -@immutable -class HeaderBarLabels { - const HeaderBarLabels({ - required this.editor, - required this.source, - required this.preview, - required this.split, - required this.viewMode, - required this.editorShortcut, - required this.editorGtkAccelerator, - required this.sourceShortcut, - required this.sourceGtkAccelerator, - required this.previewShortcut, - required this.previewGtkAccelerator, - required this.splitShortcut, - required this.splitGtkAccelerator, - required this.search, - required this.searchShortcut, - required this.refresh, - required this.menu, - required this.sidebar, - required this.sidebarShortcut, - required this.back, - required this.backShortcut, - required this.save, - required this.export, - required this.exportShortcut, - required this.exportGtkAccelerator, - required this.fullScreen, - required this.fullScreenShortcut, - required this.fullScreenGtkAccelerator, - required this.settings, - required this.settingsShortcut, - required this.settingsGtkAccelerator, - required this.syntaxReference, - required this.syntaxReferenceShortcut, - required this.syntaxReferenceGtkAccelerator, - required this.reportIssue, - required this.aboutBusyMark, - }); - - final String editor; - final String source; - final String preview; - final String split; - final String viewMode; - final String editorShortcut; - final String editorGtkAccelerator; - final String sourceShortcut; - final String sourceGtkAccelerator; - final String previewShortcut; - final String previewGtkAccelerator; - final String splitShortcut; - final String splitGtkAccelerator; - final String search; - final String searchShortcut; - final String refresh; - final String menu; - final String sidebar; - final String sidebarShortcut; - final String back; - final String backShortcut; - final String save; - final String export; - final String exportShortcut; - final String exportGtkAccelerator; - final String fullScreen; - final String fullScreenShortcut; - final String fullScreenGtkAccelerator; - final String settings; - final String settingsShortcut; - final String settingsGtkAccelerator; - final String syntaxReference; - final String syntaxReferenceShortcut; - final String syntaxReferenceGtkAccelerator; - final String reportIssue; - final String aboutBusyMark; - - Map toMap() => { - 'editor': editor, - 'source': source, - 'preview': preview, - 'split': split, - 'viewMode': viewMode, - 'editorShortcut': editorShortcut, - 'editorGtkAccelerator': editorGtkAccelerator, - 'sourceShortcut': sourceShortcut, - 'sourceGtkAccelerator': sourceGtkAccelerator, - 'previewShortcut': previewShortcut, - 'previewGtkAccelerator': previewGtkAccelerator, - 'splitShortcut': splitShortcut, - 'splitGtkAccelerator': splitGtkAccelerator, - 'search': search, - 'searchShortcut': searchShortcut, - 'refresh': refresh, - 'menu': menu, - 'sidebar': sidebar, - 'sidebarShortcut': sidebarShortcut, - 'back': back, - 'backShortcut': backShortcut, - 'save': save, - 'export': export, - 'exportShortcut': exportShortcut, - 'exportGtkAccelerator': exportGtkAccelerator, - 'fullScreen': fullScreen, - 'fullScreenShortcut': fullScreenShortcut, - 'fullScreenGtkAccelerator': fullScreenGtkAccelerator, - 'settings': settings, - 'settingsShortcut': settingsShortcut, - 'settingsGtkAccelerator': settingsGtkAccelerator, - 'syntaxReference': syntaxReference, - 'syntaxReferenceShortcut': syntaxReferenceShortcut, - 'syntaxReferenceGtkAccelerator': syntaxReferenceGtkAccelerator, - 'reportIssue': reportIssue, - 'aboutBusyMark': aboutBusyMark, - }; - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is HeaderBarLabels && mapEquals(toMap(), other.toMap()); - } - - @override - int get hashCode => Object.hashAll(toMap().entries); -} - -@immutable -class HeaderBarTooltipTheme { - const HeaderBarTooltipTheme({ - required this.backgroundColor, - required this.foregroundColor, - required this.borderColor, - required this.borderRadius, - required this.fontSize, - required this.horizontalPadding, - required this.verticalPadding, - required this.minimumHeight, - }); - - factory HeaderBarTooltipTheme.busyMark() { - return HeaderBarTooltipTheme( - backgroundColor: BusyMarkTooltipStyle.background, - foregroundColor: BusyMarkTooltipStyle.foreground, - borderColor: BusyMarkTooltipStyle.border, - borderRadius: BusyMarkRadius.tooltip, - fontSize: BusyMarkTypography.tooltipFontSize, - horizontalPadding: BusyMarkSpacing.tooltipHorizontal, - verticalPadding: BusyMarkSpacing.tooltipVertical, - minimumHeight: BusyMarkSizes.tooltipMinHeight, - ); - } - - final Color backgroundColor; - final Color foregroundColor; - final Color borderColor; - final double borderRadius; - final double fontSize; - final double horizontalPadding; - final double verticalPadding; - final double minimumHeight; - - Map toMap() => { - 'backgroundColor': _cssColor(backgroundColor), - 'foregroundColor': _cssColor(foregroundColor), - 'borderColor': _cssColor(borderColor), - 'borderRadius': borderRadius, - 'fontSize': fontSize, - 'horizontalPadding': horizontalPadding, - 'verticalPadding': verticalPadding, - 'minimumHeight': minimumHeight, - }; - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is HeaderBarTooltipTheme && - backgroundColor == other.backgroundColor && - foregroundColor == other.foregroundColor && - borderColor == other.borderColor && - borderRadius == other.borderRadius && - fontSize == other.fontSize && - horizontalPadding == other.horizontalPadding && - verticalPadding == other.verticalPadding && - minimumHeight == other.minimumHeight; - } - - @override - int get hashCode => Object.hash( - backgroundColor, - foregroundColor, - borderColor, - borderRadius, - fontSize, - horizontalPadding, - verticalPadding, - minimumHeight, - ); -} - -@immutable -class HeaderBarTheme { - const HeaderBarTheme({ - required this.preferDark, - required this.backgroundColor, - required this.sidebarBackgroundColor, - required this.foregroundColor, - required this.sidebarBorderColor, - required this.modalBarrierColor, - required this.tooltip, - }); - - factory HeaderBarTheme.fromContext(BuildContext context) { - final colors = BusyMarkSurfaceColors.of(context); - final theme = Theme.of(context); - return HeaderBarTheme( - preferDark: theme.brightness == Brightness.dark, - backgroundColor: colors.view, - sidebarBackgroundColor: colors.sidebar, - foregroundColor: colors.foreground, - sidebarBorderColor: colors.sidebarBorder, - modalBarrierColor: colors.shade, - tooltip: HeaderBarTooltipTheme.busyMark(), - ); - } - - final bool preferDark; - final Color backgroundColor; - final Color sidebarBackgroundColor; - final Color foregroundColor; - final Color sidebarBorderColor; - final Color modalBarrierColor; - final HeaderBarTooltipTheme tooltip; - - Map toMap() => { - 'preferDark': preferDark, - 'backgroundColor': _cssColor(backgroundColor), - 'sidebarBackgroundColor': _cssColor(sidebarBackgroundColor), - 'foregroundColor': _cssColor(foregroundColor), - 'sidebarBorderColor': _cssColor(sidebarBorderColor), - 'modalBarrierColor': _cssColor(modalBarrierColor), - 'tooltip': tooltip.toMap(), - }; - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is HeaderBarTheme && - preferDark == other.preferDark && - backgroundColor == other.backgroundColor && - sidebarBackgroundColor == other.sidebarBackgroundColor && - foregroundColor == other.foregroundColor && - sidebarBorderColor == other.sidebarBorderColor && - modalBarrierColor == other.modalBarrierColor && - tooltip == other.tooltip; - } - - @override - int get hashCode => Object.hashAll([ - preferDark, - backgroundColor, - sidebarBackgroundColor, - foregroundColor, - sidebarBorderColor, - modalBarrierColor, - tooltip, - ]); -} - -@immutable -class HeaderBarConfiguration { - const HeaderBarConfiguration({ - this.revision = 0, - required this.title, - required this.viewMode, - required this.searchQuery, - required this.textDirection, - required this.canRefresh, - this.canExportPdf = false, - this.canExportHtml = false, - required this.documentControlsVisible, - required this.searchActive, - required this.searchVisible, - required this.sidebarVisible, - required this.sidebarToggleVisible, - required this.backVisible, - required this.fullScreen, - required this.modalBarrierDepth, - required this.sidebarWidth, - required this.labels, - required this.theme, - }) : assert(revision >= 0), - assert(modalBarrierDepth >= 0); - - final int revision; - final String title; - final AppViewMode viewMode; - final String searchQuery; - final TextDirection textDirection; - final bool canRefresh; - final bool canExportPdf; - final bool canExportHtml; - final bool documentControlsVisible; - final bool searchActive; - final bool searchVisible; - final bool sidebarVisible; - final bool sidebarToggleVisible; - final bool backVisible; - final bool fullScreen; - final int modalBarrierDepth; - final double sidebarWidth; - final HeaderBarLabels labels; - final HeaderBarTheme theme; - - bool get modalBarrierVisible => modalBarrierDepth > 0; - - HeaderBarConfiguration copyWith({ - int? revision, - String? title, - AppViewMode? viewMode, - String? searchQuery, - TextDirection? textDirection, - bool? canRefresh, - bool? canExportPdf, - bool? canExportHtml, - bool? documentControlsVisible, - bool? searchActive, - bool? searchVisible, - bool? sidebarVisible, - bool? sidebarToggleVisible, - bool? backVisible, - bool? fullScreen, - int? modalBarrierDepth, - double? sidebarWidth, - HeaderBarLabels? labels, - HeaderBarTheme? theme, - }) { - return HeaderBarConfiguration( - revision: revision ?? this.revision, - title: title ?? this.title, - viewMode: viewMode ?? this.viewMode, - searchQuery: searchQuery ?? this.searchQuery, - textDirection: textDirection ?? this.textDirection, - canRefresh: canRefresh ?? this.canRefresh, - canExportPdf: canExportPdf ?? this.canExportPdf, - canExportHtml: canExportHtml ?? this.canExportHtml, - documentControlsVisible: - documentControlsVisible ?? this.documentControlsVisible, - searchActive: searchActive ?? this.searchActive, - searchVisible: searchVisible ?? this.searchVisible, - sidebarVisible: sidebarVisible ?? this.sidebarVisible, - sidebarToggleVisible: sidebarToggleVisible ?? this.sidebarToggleVisible, - backVisible: backVisible ?? this.backVisible, - fullScreen: fullScreen ?? this.fullScreen, - modalBarrierDepth: modalBarrierDepth ?? this.modalBarrierDepth, - sidebarWidth: sidebarWidth ?? this.sidebarWidth, - labels: labels ?? this.labels, - theme: theme ?? this.theme, - ); - } - - Map toMap() => { - 'revision': revision, - 'title': title, - 'viewMode': viewMode.name, - 'searchQuery': searchQuery, - 'textDirection': textDirection == TextDirection.rtl ? 'rtl' : 'ltr', - 'canRefresh': canRefresh, - 'canExportPdf': canExportPdf, - 'canExportHtml': canExportHtml, - 'documentControlsVisible': documentControlsVisible, - 'searchActive': searchActive, - 'searchVisible': searchVisible, - 'sidebarVisible': sidebarVisible, - 'sidebarToggleVisible': sidebarToggleVisible, - 'backVisible': backVisible, - 'fullScreen': fullScreen, - 'modalBarrierVisible': modalBarrierVisible, - 'modalBarrierDepth': modalBarrierDepth, - 'sidebarWidth': sidebarWidth, - 'labels': labels.toMap(), - 'theme': theme.toMap(), - }; - - bool hasSameContentAs(HeaderBarConfiguration other) { - return title == other.title && - viewMode == other.viewMode && - searchQuery == other.searchQuery && - textDirection == other.textDirection && - canRefresh == other.canRefresh && - canExportPdf == other.canExportPdf && - canExportHtml == other.canExportHtml && - documentControlsVisible == other.documentControlsVisible && - searchActive == other.searchActive && - searchVisible == other.searchVisible && - sidebarVisible == other.sidebarVisible && - sidebarToggleVisible == other.sidebarToggleVisible && - backVisible == other.backVisible && - fullScreen == other.fullScreen && - modalBarrierDepth == other.modalBarrierDepth && - sidebarWidth == other.sidebarWidth && - labels == other.labels && - theme == other.theme; - } - - @override - bool operator ==(Object other) { - return identical(this, other) || - other is HeaderBarConfiguration && - revision == other.revision && - hasSameContentAs(other); - } - - @override - int get hashCode => Object.hashAll([ - revision, - title, - viewMode, - searchQuery, - textDirection, - canRefresh, - canExportPdf, - canExportHtml, - documentControlsVisible, - searchActive, - searchVisible, - sidebarVisible, - sidebarToggleVisible, - backVisible, - fullScreen, - modalBarrierDepth, - sidebarWidth, - labels, - theme, - ]); -} - -typedef HeaderBarConfigurationApplier = - Future Function(HeaderBarConfiguration configuration); - -/// Serializes native header updates, coalesces pending state, and assigns the -/// monotonic revisions that make the native side latest-wins. -class HeaderBarConfigurationSynchronizer { - HeaderBarConfigurationSynchronizer({ - required HeaderBarConfigurationApplier apply, - }) : _apply = apply; - - final HeaderBarConfigurationApplier _apply; - final Map>> _waiters = {}; - - HeaderBarConfiguration? _baseConfiguration; - HeaderBarConfiguration? _desiredConfiguration; - HeaderBarConfiguration? _appliedConfiguration; - Future? _drainFuture; - var _lastRevision = 0; - var _modalBarrierDepth = 0; - - HeaderBarConfiguration? get desiredConfiguration => _desiredConfiguration; - HeaderBarConfiguration? get appliedConfiguration => _appliedConfiguration; - int get latestRevision => _lastRevision; - - bool isLatestRevision(int revision) { - return _desiredConfiguration?.revision == revision; - } - - Future setConfiguration(HeaderBarConfiguration configuration) { - _baseConfiguration = configuration.copyWith(revision: 0); - return _enqueueEffectiveConfiguration(); - } - - Future setModalBarrierDepth(int depth) { - final effectiveDepth = depth < 0 ? 0 : depth; - if (_modalBarrierDepth == effectiveDepth) { - return _waitForDesiredConfiguration(); - } - _modalBarrierDepth = effectiveDepth; - return _enqueueEffectiveConfiguration(); - } - - Future setModalBarrierVisible(bool visible) { - return setModalBarrierDepth(visible ? 1 : 0); - } - - Future _enqueueEffectiveConfiguration() { - final base = _baseConfiguration; - if (base == null) { - return Future.value(true); - } - final effective = base.copyWith( - revision: 0, - modalBarrierDepth: _modalBarrierDepth, - ); - final desired = _desiredConfiguration; - if (desired != null && desired.hasSameContentAs(effective)) { - if (_appliedConfiguration case final applied? - when applied.revision >= desired.revision) { - return Future.value(true); - } - final future = _waitForRevision(desired.revision); - _drainFuture ??= _drain(); - return future; - } - final applied = _appliedConfiguration; - if (_drainFuture == null && - applied != null && - applied.hasSameContentAs(effective)) { - return Future.value(true); - } - - final revision = ++_lastRevision; - _desiredConfiguration = effective.copyWith(revision: revision); - final future = _waitForRevision(revision); - _drainFuture ??= _drain(); - return future; - } - - Future _waitForDesiredConfiguration() { - final desired = _desiredConfiguration; - if (desired == null || - _appliedConfiguration?.revision == desired.revision) { - return Future.value(true); - } - final future = _waitForRevision(desired.revision); - _drainFuture ??= _drain(); - return future; - } - - Future _waitForRevision(int revision) { - if (_appliedConfiguration case final applied? - when applied.revision >= revision) { - return Future.value(true); - } - final completer = Completer(); - _waiters.putIfAbsent(revision, () => []).add(completer); - return completer.future; - } - - Future _drain() async { - try { - while (true) { - final target = _desiredConfiguration; - if (target == null || - _appliedConfiguration?.revision == target.revision) { - return; - } - var succeeded = false; - try { - succeeded = await _apply(target); - } on Object { - succeeded = false; - } - if (succeeded) { - _appliedConfiguration = target; - _completeWaitersThrough(target.revision, succeeded: true); - continue; - } - if (_desiredConfiguration?.revision != target.revision) { - continue; - } - _completeWaitersThrough(target.revision, succeeded: false); - return; - } - } finally { - _drainFuture = null; - } - } - - void _completeWaitersThrough(int revision, {required bool succeeded}) { - final completedRevisions = _waiters.keys - .where((candidate) => candidate <= revision) - .toList(growable: false); - for (final completedRevision in completedRevisions) { - final completers = _waiters.remove(completedRevision); - if (completers == null) { - continue; - } - for (final completer in completers) { - if (!completer.isCompleted) { - completer.complete(succeeded); - } - } - } - } -} - -class HeaderBarConfigurationDefaults extends InheritedWidget { - const HeaderBarConfigurationDefaults({ - super.key, - required this.configuration, - required super.child, - }); - - final HeaderBarConfiguration configuration; - - static HeaderBarConfiguration of(BuildContext context) { - final defaults = context - .dependOnInheritedWidgetOfExactType(); - assert(defaults != null, 'No HeaderBarConfigurationDefaults in context'); - return defaults!.configuration; - } - - @override - bool updateShouldNotify(HeaderBarConfigurationDefaults oldWidget) { - return configuration != oldWidget.configuration; - } -} - -class HeaderBarConfigurationPublisher extends StatefulWidget { - const HeaderBarConfigurationPublisher({ - super.key, - required this.synchronizer, - required this.configuration, - required this.enabled, - required this.child, - }); - - final HeaderBarConfigurationSynchronizer synchronizer; - final HeaderBarConfiguration configuration; - final bool enabled; - final Widget child; - - @override - State createState() => - _HeaderBarConfigurationPublisherState(); -} - -class _HeaderBarConfigurationPublisherState - extends State { - @override - void initState() { - super.initState(); - _publish(); - } - - @override - void didUpdateWidget(HeaderBarConfigurationPublisher oldWidget) { - super.didUpdateWidget(oldWidget); - if (widget.enabled != oldWidget.enabled || - widget.synchronizer != oldWidget.synchronizer || - widget.configuration != oldWidget.configuration) { - _publish(); - } - } - - @override - Widget build(BuildContext context) => widget.child; - - void _publish() { - if (!widget.enabled) { - return; - } - unawaited(widget.synchronizer.setConfiguration(widget.configuration)); - } -} - -String _cssColor(Color color) { - final alpha = (color.a).clamp(0.0, 1.0).toStringAsFixed(3); - return 'rgba(${(color.r * 255).round()},' - '${(color.g * 255).round()},' - '${(color.b * 255).round()},' - '$alpha)'; -} diff --git a/lib/src/platform/linux_header_bar_service.dart b/lib/src/platform/linux_header_bar_service.dart deleted file mode 100644 index d9459a42..00000000 --- a/lib/src/platform/linux_header_bar_service.dart +++ /dev/null @@ -1,433 +0,0 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:uuid/uuid.dart'; - -import 'header_bar_configuration.dart'; - -export 'header_bar_configuration.dart'; - -enum HeaderBarAction { - back, - sidebarToggle, - search, - refresh, - save, - export, - fullScreen, - menu, - settings, - syntaxReference, - reportIssue, - aboutBusyMark, - viewModeEditor, - viewModeSource, - viewModePreview, - viewModeSplit, - sidebarFiles, - sidebarToc, - sidebarOutline, - sidebarGit, - sidebarLocalHistory, - sidebarClipboardHistory, -} - -class HeaderBarActionEvent { - const HeaderBarActionEvent({required this.sequence, required this.action}); - - final int sequence; - final HeaderBarAction action; - - @override - bool operator ==(Object other) { - return other is HeaderBarActionEvent && - other.sequence == sequence && - other.action == action; - } - - @override - int get hashCode => Object.hash(sequence, action); -} - -sealed class HeaderBarSearchEvent { - const HeaderBarSearchEvent(); -} - -class HeaderBarSearchQueryChanged extends HeaderBarSearchEvent { - const HeaderBarSearchQueryChanged(this.query); - - final String query; -} - -class HeaderBarSearchSubmitted extends HeaderBarSearchEvent { - const HeaderBarSearchSubmitted(this.query); - - final String query; -} - -class HeaderBarSearchFocusChanged extends HeaderBarSearchEvent { - const HeaderBarSearchFocusChanged(this.focused); - - final bool focused; -} - -class HeaderBarSearchCleared extends HeaderBarSearchEvent { - const HeaderBarSearchCleared(); -} - -class HeaderBarSearchEscapePressed extends HeaderBarSearchEvent { - const HeaderBarSearchEscapePressed(); -} - -class LinuxHeaderBarService extends ChangeNotifier { - LinuxHeaderBarService({ - MethodChannel? channel, - @visibleForTesting String? sessionId, - }) : assert(sessionId == null || sessionId != ''), - _channel = channel ?? const MethodChannel('com.busymark.app/headerbar'), - _sessionId = sessionId ?? const Uuid().v4() { - configurationSynchronizer = HeaderBarConfigurationSynchronizer( - apply: _applyConfiguration, - ); - _channel.setMethodCallHandler(_handleNativeAction); - } - - static final LinuxHeaderBarService instance = LinuxHeaderBarService(); - - final MethodChannel _channel; - final String _sessionId; - final _actions = StreamController.broadcast(); - final _actionEvents = StreamController.broadcast(); - final _searchEvents = StreamController.broadcast(); - - late final HeaderBarConfigurationSynchronizer configurationSynchronizer; - - var _initialized = false; - var _channelReady = false; - var _available = false; - var _actionSequence = 0; - bool? _atomicConfigurationSupported; - - bool get isAvailable => _available; - bool get usesNativeHeaderBar => _available; - - Stream get actions => _actions.stream; - Stream get actionEvents => _actionEvents.stream; - Stream get searchEvents => _searchEvents.stream; - - Future initialize() async { - if (_channelReady || (_initialized && !Platform.isLinux)) { - return; - } - if (!Platform.isLinux) { - _initialized = true; - return; - } - _initialized = true; - try { - final available = - await _channel.invokeMethod('initialize', { - 'sessionId': _sessionId, - }) ?? - false; - _channelReady = true; - _setAvailable(available); - } on MissingPluginException { - _markUnavailable(); - } on Object { - _markUnavailable(); - } - } - - /// Legacy setters remain available for an older Linux runner. Product - /// screens publish a complete [HeaderBarConfiguration] instead. - Future setTitleRange(String value) { - return _invokeLegacy('setTitleRange', value); - } - - Future setViewMode(AppViewMode mode) { - return _invokeLegacy('setViewMode', mode.name); - } - - Future setCanRefresh(bool value) { - return _invokeLegacy('setCanRefresh', value); - } - - Future setCanExportPdf(bool value) { - return _invokeLegacy('setCanExportPdf', value); - } - - Future setDocumentControlsVisible(bool value) { - return _invokeLegacy('setDocumentControlsVisible', value); - } - - Future setSearchActive(bool value) { - return _invokeLegacy('setSearchActive', value); - } - - Future setSearchVisible(bool value) { - return _invokeLegacy('setSearchVisible', value); - } - - Future setSearchQuery(String value) { - return _invokeLegacy('setSearchQuery', value); - } - - Future focusSearch() async { - if (!_channelReady) { - await initialize(); - } - if (!_channelReady || !_available) { - return false; - } - try { - return await _channel.invokeMethod('focusSearch') ?? false; - } on MissingPluginException { - _markUnavailable(); - } on Object { - _markUnavailable(); - } - return false; - } - - Future setSidebarVisible(bool value) { - return _invokeLegacy('setSidebarVisible', value); - } - - Future setSidebarToggleVisible(bool value) { - return _invokeLegacy('setSidebarToggleVisible', value); - } - - Future setSidebarWidth(double value) { - return _invokeLegacy('setSidebarWidth', value); - } - - Future setTextDirection(TextDirection value) { - return _invokeLegacy( - 'setTextDirection', - value == TextDirection.rtl ? 'rtl' : 'ltr', - ); - } - - Future setBackVisible(bool value) { - return _invokeLegacy('setBackVisible', value); - } - - Future setLocalizedLabels(HeaderBarLabels labels) { - return _invokeLegacy('setLocalizedLabels', labels.toMap()); - } - - Future setTheme(HeaderBarTheme theme) { - return _invokeLegacy('setTheme', theme.toMap()); - } - - Future setModalBarrierDepth(int value) async { - if (!_available) { - return; - } - final depth = value < 0 ? 0 : value; - final hasPublishedConfiguration = - configurationSynchronizer.desiredConfiguration != null; - await configurationSynchronizer.setModalBarrierDepth(depth); - if (!hasPublishedConfiguration) { - await _invokeLegacy('setModalBarrierDepth', depth); - } - } - - Future setModalBarrierVisible(bool value) { - return setModalBarrierDepth(value ? 1 : 0); - } - - Future _applyConfiguration(HeaderBarConfiguration configuration) async { - if (!_channelReady) { - await initialize(); - } - if (!_channelReady || !_available) { - return false; - } - if (_atomicConfigurationSupported == false) { - return _applyLegacyConfiguration(configuration); - } - try { - final appliedRevision = await _channel.invokeMethod( - 'applyConfiguration', - {'sessionId': _sessionId, ...configuration.toMap()}, - ); - if (appliedRevision != configuration.revision) { - _markUnavailable(); - return false; - } - _atomicConfigurationSupported = true; - return true; - } on MissingPluginException { - _atomicConfigurationSupported = false; - return _applyLegacyConfiguration(configuration); - } on PlatformException catch (error) { - if (error.code == 'not_implemented' || - error.code == 'unimplemented' || - error.code == 'method_not_found') { - _atomicConfigurationSupported = false; - return _applyLegacyConfiguration(configuration); - } - _markUnavailable(); - return false; - } on Object { - _markUnavailable(); - return false; - } - } - - Future _applyLegacyConfiguration( - HeaderBarConfiguration configuration, - ) async { - final updates = <(String, Object?)>[ - ('setTextDirection', configuration.textDirection.name), - ('setSidebarWidth', configuration.sidebarWidth), - ('setTheme', configuration.theme.toMap()), - ('setLocalizedLabels', configuration.labels.toMap()), - ('setTitleRange', configuration.title), - ('setViewMode', configuration.viewMode.name), - ('setCanRefresh', configuration.canRefresh), - ('setCanExportPdf', configuration.canExportPdf), - ('setCanExportHtml', configuration.canExportHtml), - ('setDocumentControlsVisible', configuration.documentControlsVisible), - ('setSearchVisible', configuration.searchVisible), - ('setSidebarVisible', configuration.sidebarVisible), - ('setSidebarToggleVisible', configuration.sidebarToggleVisible), - ('setBackVisible', configuration.backVisible), - ('setSearchQuery', configuration.searchQuery), - ('setSearchActive', configuration.searchActive), - ('setModalBarrierVisible', configuration.modalBarrierVisible), - ]; - for (final (method, arguments) in updates) { - if (!configurationSynchronizer.isLatestRevision(configuration.revision)) { - return false; - } - if (!await _tryInvokeLegacy(method, arguments)) { - return false; - } - } - return configurationSynchronizer.isLatestRevision(configuration.revision); - } - - Future _invokeLegacy(String method, [Object? arguments]) async { - await _tryInvokeLegacy(method, arguments); - } - - Future _tryInvokeLegacy(String method, [Object? arguments]) async { - if (!_channelReady) { - await initialize(); - } - if (!_channelReady || !_available) { - return false; - } - try { - await _channel.invokeMethod(method, arguments); - return true; - } on MissingPluginException { - _markUnavailable(); - return false; - } on Object { - _markUnavailable(); - return false; - } - } - - void _markUnavailable() { - _initialized = false; - _channelReady = false; - _setAvailable(false); - } - - void _setAvailable(bool value) { - if (_available == value) { - return; - } - _available = value; - notifyListeners(); - } - - Future _handleNativeAction(MethodCall call) async { - final searchEvent = switch ((call.method, call.arguments)) { - ('searchQueryChanged', final String query) => HeaderBarSearchQueryChanged( - query, - ), - ('searchSubmitted', final String query) => HeaderBarSearchSubmitted( - query, - ), - ('searchFocusChanged', final bool focused) => HeaderBarSearchFocusChanged( - focused, - ), - ('searchCleared', _) => const HeaderBarSearchCleared(), - ('searchEscapePressed', _) => const HeaderBarSearchEscapePressed(), - _ => null, - }; - if (searchEvent != null) { - if (!_searchEvents.isClosed) { - _searchEvents.add(searchEvent); - } - return; - } - final action = _actionFromMethod(call.method); - if (action != null) { - _actionSequence++; - if (!_actions.isClosed) { - _actions.add(action); - } - if (!_actionEvents.isClosed) { - _actionEvents.add( - HeaderBarActionEvent(sequence: _actionSequence, action: action), - ); - } - } - } - - HeaderBarAction? _actionFromMethod(String method) { - return switch (method) { - 'back' => HeaderBarAction.back, - 'sidebarToggle' => HeaderBarAction.sidebarToggle, - 'search' => HeaderBarAction.search, - 'refresh' => HeaderBarAction.refresh, - 'save' => HeaderBarAction.save, - 'export' => HeaderBarAction.export, - 'fullScreen' => HeaderBarAction.fullScreen, - 'menu' => HeaderBarAction.menu, - 'settings' => HeaderBarAction.settings, - 'syntaxReference' => HeaderBarAction.syntaxReference, - 'reportIssue' => HeaderBarAction.reportIssue, - 'aboutBusyMark' => HeaderBarAction.aboutBusyMark, - 'viewModeEditor' => HeaderBarAction.viewModeEditor, - 'viewModeSource' => HeaderBarAction.viewModeSource, - 'viewModePreview' => HeaderBarAction.viewModePreview, - 'viewModeSplit' => HeaderBarAction.viewModeSplit, - 'sidebarFiles' => HeaderBarAction.sidebarFiles, - 'sidebarToc' => HeaderBarAction.sidebarToc, - 'sidebarOutline' => HeaderBarAction.sidebarOutline, - 'sidebarGit' => HeaderBarAction.sidebarGit, - 'sidebarLocalHistory' => HeaderBarAction.sidebarLocalHistory, - 'sidebarClipboardHistory' => HeaderBarAction.sidebarClipboardHistory, - _ => null, - }; - } -} - -final linuxHeaderBarServiceProvider = Provider((ref) { - final service = LinuxHeaderBarService.instance; - void notifyConsumers() => ref.notifyListeners(); - service.addListener(notifyConsumers); - ref.onDispose(() => service.removeListener(notifyConsumers)); - return service; -}); - -final headerBarActionsProvider = StreamProvider((ref) { - return ref.watch(linuxHeaderBarServiceProvider).actionEvents; -}); - -final headerBarSearchEventsProvider = StreamProvider(( - ref, -) { - return ref.watch(linuxHeaderBarServiceProvider).searchEvents; -}); diff --git a/lib/src/references/markdown_references.dart b/lib/src/references/markdown_references.dart index a731950a..87669a46 100644 --- a/lib/src/references/markdown_references.dart +++ b/lib/src/references/markdown_references.dart @@ -84,13 +84,16 @@ List markdownReferences({ required String identity, required String source, MarkdownMode mode = MarkdownMode.commonMark, + ParsedMarkdownDocument? parsedDocument, }) { - final parsed = const MarkdownParser().parse( - filePath: identity, - source: source, - mode: mode, - validateLocalReferences: false, - ); + final parsed = + parsedDocument ?? + const MarkdownParser().parse( + filePath: identity, + source: source, + mode: mode, + validateLocalReferences: false, + ); final context = const MarkdownSourceMapper().createInlineParserContext( documentSource: source, mode: mode, diff --git a/lib/src/references/reference_controller.dart b/lib/src/references/reference_controller.dart index 106aa3aa..68fd9685 100644 --- a/lib/src/references/reference_controller.dart +++ b/lib/src/references/reference_controller.dart @@ -28,7 +28,7 @@ final referenceBatchParserProvider = Provider( ); /// Coalesces edits and filesystem/repository notifications outside widget builds. -/// Content digests retain unchanged parsing; generations fence obsolete results. +/// Retained sources reuse unchanged parsing; generations fence obsolete results. class ReferenceController extends Notifier> { Timer? _timer; StreamSubscription? _notes; @@ -36,7 +36,54 @@ class ReferenceController extends Notifier> { final _cache = {}; @override AsyncValue build() { - ref.listen(workspaceControllerProvider, (before, after) => refresh()); + ref.listen(workspaceControllerProvider, (before, after) { + final previous = before?.workspace, next = after.workspace; + final oldBuffers = before?.documentBuffers ?? const []; + final buffers = after.documentBuffers; + if (previous?.id != next?.id || + previous?.openedAt != next?.openedAt || + !identical(previous?.files, next?.files) || + !identical(previous?.writersideProject, next?.writersideProject) || + oldBuffers.length != buffers.length || + buffers.indexed.any((entry) { + final old = oldBuffers[entry.$1], current = entry.$2; + return old.id != current.id || + old.filePath != current.filePath || + old.text != current.text || + old.remoteNote != current.remoteNote; + })) { + refresh(); + } + }); + final files = ref.read(workspaceFileMonitorProvider).events.listen((event) { + final root = ref + .read(workspaceControllerProvider) + .workspace + ?.filesystemRootPath; + if (root != null && + [ + event.path, + if (event.destinationPath != null) event.destinationPath!, + ].any((path) => p.equals(root, path) || p.isWithin(root, path)) && + (event.isDirectory || + [ + event.path, + if (event.destinationPath != null) event.destinationPath!, + ].any( + (path) => { + '.md', + '.markdown', + '.topic', + '.tree', + '.cfg', + '.list', + '.properties', + '.xml', + }.contains(p.extension(path).toLowerCase()), + ))) { + refresh(); + } + }); ref.listen(nextcloudNotesRepositoryProvider, (before, after) { _notes?.cancel(); _notes = after.value?.changes.listen((_) => refresh()); @@ -46,6 +93,7 @@ class ReferenceController extends Notifier> { _generation++; _timer?.cancel(); _notes?.cancel(); + unawaited(files.cancel()); }); refresh(); return const AsyncLoading(); @@ -162,7 +210,7 @@ class ReferenceController extends Notifier> { final changed = []; for (final document in documents) { final cached = _cache[document.identity]; - if (cached?.document.revision == document.revision && + if (cached?.document.source == document.source && cached?.document.available == document.available && cached?.document.title == document.title && cached?.document.mode == document.mode && diff --git a/lib/src/references/reference_index.dart b/lib/src/references/reference_index.dart index 1a78f0ac..2d9f5aff 100644 --- a/lib/src/references/reference_index.dart +++ b/lib/src/references/reference_index.dart @@ -77,27 +77,28 @@ class ReferencePage { } class ParsedReferenceDocument { - ParsedReferenceDocument(this.document) - : headings = document.available - ? const MarkdownParser() - .parse( - filePath: document.identity, - source: document.source, - mode: document.mode, - validateLocalReferences: false, - ) - .headings - : const [], - authored = document.available - ? markdownReferences( - identity: document.identity, - source: document.source, - mode: document.mode, - ) - : const []; + ParsedReferenceDocument(this.document) { + final parsed = document.available + ? const MarkdownParser().parse( + filePath: document.identity, + source: document.source, + mode: document.mode, + validateLocalReferences: false, + ) + : null; + headings = parsed?.headings ?? const []; + authored = parsed == null + ? const [] + : markdownReferences( + identity: document.identity, + source: document.source, + mode: document.mode, + parsedDocument: parsed, + ); + } final ReferenceDocument document; - final List headings; - final List authored; + late final List headings; + late final List authored; } /// Entirely derived; no writes to notes, source, history or synchronization. diff --git a/lib/src/search/search_activation.dart b/lib/src/search/search_activation.dart index 4b2ff3a8..239c66cc 100644 --- a/lib/src/search/search_activation.dart +++ b/lib/src/search/search_activation.dart @@ -14,7 +14,7 @@ import '../nextcloud_notes/application/nextcloud_connection.dart'; import '../nextcloud_notes/application/notes_navigation.dart'; import '../nextcloud_notes/domain/notes_search.dart'; import '../nextcloud_notes/presentation/notes_workspace_ui.dart'; -import '../workspace/document_navigation.dart'; +import '../workspace/workspace_tab_actions.dart'; import '../workspace/outline_navigation.dart'; import '../workspace/recent_navigation.dart'; import '../workspace/workspace_controller.dart'; @@ -127,7 +127,7 @@ Future activateSearchResult( session.close(); } case RecentSearchResult(:final resource): - await openRecentResource(context, ref, resource); + await openRecentResource(ref, resource); case DocumentSearchResult( :final workspaceId, :final accountId, @@ -155,7 +155,7 @@ Future activateSearchResult( acceptNavigation: currentRequest, )) { if (!currentRequest()) return; - revealOpenedDocument(ref); + ref.read(revealOpenedDocumentProvider)(); session.close(restoreFocus: false); } } else { @@ -170,7 +170,7 @@ Future activateSearchResult( acceptNavigation: currentRequest, )) { if (!currentRequest()) return; - revealOpenedDocument(ref); + ref.read(revealOpenedDocumentProvider)(); session.close(restoreFocus: false); } } @@ -194,7 +194,7 @@ Future activateSearchResult( acceptNavigation: currentRequest, )) { if (!currentRequest()) return; - revealOpenedDocument(ref); + ref.read(revealOpenedDocumentProvider)(); session.close(restoreFocus: false); } case HistorySearchResult(:final match): @@ -286,7 +286,7 @@ Future activateSearchResult( unavailable(); return; } - revealOpenedDocument(ref); + ref.read(revealOpenedDocumentProvider)(); ref .read(notesMatchNavigationProvider.notifier) .navigate( @@ -338,7 +338,7 @@ Future activateSearchResult( .setDocumentViewMode(DocumentViewModePreference.source); if (!context.mounted || !currentRequest()) return; } - revealOpenedDocument(ref); + ref.read(revealOpenedDocumentProvider)(); if (hit.start != null && hit.end != null) { ref .read(notesMatchNavigationProvider.notifier) diff --git a/lib/src/search/welcome_notes_action.dart b/lib/src/search/welcome_notes_action.dart index 413b941b..40245213 100644 --- a/lib/src/search/welcome_notes_action.dart +++ b/lib/src/search/welcome_notes_action.dart @@ -1,13 +1,13 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; import '../app/app_router.dart'; -import '../app/busymark_toast.dart'; -import '../app/localization.dart'; +import '../app/command_registry.dart'; +import '../local_history/local_history_controller.dart'; import '../nextcloud_notes/application/nextcloud_connection.dart'; +import '../workspace/workspace_navigation.dart'; import '../workspace/workspace_controller.dart'; -import '../workspace/workspace_safety.dart'; +import 'search_session.dart'; enum WelcomeNotesAction { create, browse } @@ -18,6 +18,7 @@ final welcomeNotesActionProvider = class WelcomeNotesActionController extends Notifier { bool busy = false; + @override WelcomeNotesAction? build() { final router = ref.read(appRouterProvider); @@ -44,50 +45,51 @@ class WelcomeNotesActionController extends Notifier { } Future performWelcomeNotesAction( - BuildContext context, - WidgetRef ref, + WorkspaceNavigation navigation, + Uri origin, + bool Function() currentNavigation, WelcomeNotesAction action, ) async { - final pending = ref.read(welcomeNotesActionProvider.notifier); + final container = navigation.container; + final pending = container.read(welcomeNotesActionProvider.notifier); if (pending.busy) return; pending.busy = true; try { - final origin = ref - .read(appRouterProvider) - .routeInformationProvider - .value - .uri; - if (origin.path != '/' && origin.path != '/workspace') return; - await ref.read(nextcloudConnectionProvider.notifier).reload(); - if (!context.mounted || - ref.read(appRouterProvider).routeInformationProvider.value.uri != - origin) { + final fromWorkspace = + settingsReturnTargetForUri(origin) == SettingsReturnTarget.workspace; + if (origin.path != '/' && + origin.path != '/workspace' && + origin.path != settingsRoutePath) { + return; + } + await container.read(nextcloudConnectionProvider.notifier).reload(); + if (!currentNavigation()) { pending.clear(); return; } - final activeAccount = origin.path == '/workspace' - ? ref.read(workspaceControllerProvider).workspace?.nextcloudAccountId + final activeAccount = fromWorkspace + ? container + .read(workspaceControllerProvider) + .workspace + ?.nextcloudAccountId : null; - final repository = ref.read(nextcloudNotesRepositoryProvider).value; + final repository = container.read(nextcloudNotesRepositoryProvider).value; final account = activeAccount == null - ? ref.read(nextcloudConnectionProvider).account + ? container.read(nextcloudConnectionProvider).account : repository?.accountById(activeAccount); if (activeAccount != null && account == null) { pending.clear(); - BusyMarkToastOverlay.show( - context, - message: context.l10n.searchResourceUnavailable, - ); + navigation.showUnavailable(); return; } if (account == null) { // Returning without a successful connection cancels the pending operation. - if (ref.read(welcomeNotesActionProvider) != null) { + if (container.read(welcomeNotesActionProvider) != null) { pending.clear(); return; } pending.request(action); - context.go( + navigation.router.go( '${settingsLocation(SettingsReturnTarget.welcome)}&page=nextcloudNotes', ); return; @@ -95,46 +97,68 @@ Future performWelcomeNotesAction( pending .clear(); // Claim once before any asynchronous work or pointer reactivation. bool currentRequest() => - context.mounted && - ref.read(appRouterProvider).routeInformationProvider.value.uri == - origin && + currentNavigation() && (activeAccount == null - ? ref.read(nextcloudConnectionProvider).account?.id == account.id - : ref + ? container.read(nextcloudConnectionProvider).account?.id == + account.id + : container .read(workspaceControllerProvider) .workspace ?.nextcloudAccountId == account.id && repository?.accountById(account.id) != null); - if (!await confirmSafeToContinue(context, ref) || !context.mounted) return; - if (ref.read(appRouterProvider).routeInformationProvider.value.uri != - origin) { - return; - } - final controller = ref.read(workspaceControllerProvider.notifier); - if (ref.read(workspaceControllerProvider).workspace?.nextcloudAccountId != - account.id && - !await controller.openNextcloudWorkspace( - account.id, - acceptNavigation: currentRequest, - )) { - return; + final controller = container.read(workspaceControllerProvider.notifier); + if (container + .read(workspaceControllerProvider) + .workspace + ?.nextcloudAccountId != + account.id) { + if (!await navigation.confirmDeparture(canContinue: currentRequest) || + !currentRequest() || + !await controller.openNextcloudWorkspace( + account.id, + acceptNavigation: currentRequest, + )) { + return; + } } - if (!context.mounted || - ref.read(appRouterProvider).routeInformationProvider.value.uri != - origin || - !currentRequest() || - ref.read(workspaceControllerProvider).workspace?.nextcloudAccountId != + if (!currentRequest() || + container + .read(workspaceControllerProvider) + .workspace + ?.nextcloudAccountId != account.id) { return; } - if (action == WelcomeNotesAction.create && - !await controller.createNextcloudNote( - acceptNavigation: currentRequest, - )) { - return; + container.read(searchSessionProvider.notifier).close(restoreFocus: false); + if (action == WelcomeNotesAction.create) { + container.read(localHistoryControllerProvider.notifier).clearComparison(); + if (!await controller.createNextcloudNote( + acceptNavigation: currentRequest, + focusEditor: true, + )) { + return; + } + if (!currentRequest()) return; + } + if (currentRequest()) { + final router = navigation.router; + final commands = container.read( + workspaceNavigationCommandProvider.notifier, + ); + if (action == WelcomeNotesAction.create) { + navigation.reveal(); + } else { + router.go('/workspace'); + } + if (action == WelcomeNotesAction.browse && fromWorkspace) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (router.routeInformationProvider.value.uri.path == '/workspace') { + commands.request(BusyMarkCommandIds.sidebarFiles); + } + }); + } } - if (context.mounted && currentRequest()) context.go('/workspace'); } finally { pending.busy = false; } diff --git a/lib/src/spellcheck/spelling_release_smoke.dart b/lib/src/spellcheck/spelling_release_smoke.dart index 3aefece2..ec35fe77 100644 --- a/lib/src/spellcheck/spelling_release_smoke.dart +++ b/lib/src/spellcheck/spelling_release_smoke.dart @@ -594,7 +594,6 @@ Future _exerciseRichEditor({ document: document, documentId: buffer.id, contentRevision: buffer.revision, - useExternalUndoHistory: true, spellingAnnotations: [_annotationFor(occurrence)], onDocumentChanged: (value) => publishedDocument = value, onSourceChanged: (_, _) {}, diff --git a/lib/src/visualization/visualization_card.dart b/lib/src/visualization/visualization_card.dart index 4618da38..7fa5f5c0 100644 --- a/lib/src/visualization/visualization_card.dart +++ b/lib/src/visualization/visualization_card.dart @@ -1,10 +1,10 @@ +import '../core/atomic_file_writer.dart'; import 'dart:async'; import 'dart:convert'; -import 'dart:io'; import 'dart:math' as math; import 'dart:typed_data'; -import 'package:file_selector/file_selector.dart'; +import '../app/save_destination_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; @@ -565,36 +565,45 @@ class _BusyMarkVisualizationCardState ) async { final svg = result is SvgVisualizationResult; final extension = svg ? 'svg' : 'png'; - final location = await getSaveLocation( - suggestedName: - '${widget.descriptor.kind.canonicalFence}-diagram.$extension', - initialDirectory: widget.documentPath.isEmpty - ? null - : p.dirname(widget.documentPath), - acceptedTypeGroups: [ - XTypeGroup( - label: '${svg ? 'SVG' : 'PNG'} ${context.l10n.image}', - extensions: [extension], - mimeTypes: [svg ? 'image/svg+xml' : 'image/png'], - ), - ], - confirmButtonText: context.l10n.save, - ); - if (location == null) { - return; - } - final path = p.extension(location.path).toLowerCase() == '.$extension' - ? location.path - : '${location.path}.$extension'; - final bytes = svg - ? utf8.encode(result.svg) - : (result as RasterVisualizationResult).pngBytes; - await File(path).writeAsBytes(bytes, flush: true); - if (mounted) { - BusyMarkToastOverlay.show( - this.context, - message: this.context.l10n.visualizationSaved(p.basename(path)), + try { + final destination = await pickSaveDestination( + context, + suggestedName: + '${widget.descriptor.kind.canonicalFence}-diagram.$extension', + initialDirectory: widget.documentPath.isEmpty + ? null + : p.dirname(widget.documentPath), + actionLabel: context.l10n.save, + suffix: '.$extension', + filterLabel: svg ? 'SVG' : 'PNG', + patterns: svg ? const ['*.[sS][vV][gG]'] : const ['*.[pP][nN][gG]'], + ); + if (destination == null || !mounted) return; + final bytes = svg + ? utf8.encode(result.svg) + : (result as RasterVisualizationResult).pngBytes; + await const AtomicFileWriter().writeBytes( + destination.path, + bytes, + overwrite: destination.replacesExisting, + authorization: destination, ); + if (mounted) { + BusyMarkToastOverlay.show( + this.context, + message: this.context.l10n.visualizationSaved( + p.basename(destination.path), + ), + ); + } + } on Object catch (error) { + if (mounted) { + BusyMarkToastOverlay.show( + this.context, + message: error.toString(), + priority: BusyMarkToastPriority.high, + ); + } } } diff --git a/lib/src/workspace/document_buffer.dart b/lib/src/workspace/document_buffer.dart index 9dcb42e8..296de964 100644 --- a/lib/src/workspace/document_buffer.dart +++ b/lib/src/workspace/document_buffer.dart @@ -197,7 +197,8 @@ class DocumentEditorState { } class DocumentBuffer { - const DocumentBuffer({ + DocumentBuffer({ + Object? opening, required this.id, required this.text, required this.lastSavedText, @@ -216,7 +217,8 @@ class DocumentBuffer { this.remoteTitle, this.remoteEditBase, this.readonly = false, - }) : assert(remoteNote == null || filePath == null); + }) : opening = opening ?? Object(), + assert(remoteNote == null || filePath == null); factory DocumentBuffer.file({ required String id, @@ -275,6 +277,7 @@ class DocumentBuffer { editorState: editorState, ); + final Object opening; final String id; final String? filePath; final String? untitledName; @@ -393,6 +396,7 @@ class DocumentBuffer { bool? readonly, }) { return DocumentBuffer( + opening: opening, id: id, filePath: identical(filePath, _bufferUnset) ? this.filePath diff --git a/lib/src/workspace/document_navigation.dart b/lib/src/workspace/document_navigation.dart deleted file mode 100644 index a05ac7d9..00000000 --- a/lib/src/workspace/document_navigation.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'dart:async'; - -import 'package:flutter_riverpod/flutter_riverpod.dart'; - -import '../git/application/git_controller.dart'; -import '../local_history/local_history_controller.dart'; -import 'workspace_controller.dart'; - -/// Reveal a successfully opened document using the same view transition as -/// selecting its editor tab. Resource validation and opening happen first. -void revealOpenedDocument(WidgetRef ref) { - final history = ref.read(localHistoryControllerProvider.notifier); - history.clearComparison(); - ref.read(gitControllerProvider.notifier).deactivateDiffFile(); - final buffer = ref.read(workspaceControllerProvider).activeBuffer; - if (buffer != null) unawaited(history.selectDocumentForBuffer(buffer)); -} diff --git a/lib/src/workspace/presentation/create_writerside_project_dialog.dart b/lib/src/workspace/presentation/create_writerside_project_dialog.dart new file mode 100644 index 00000000..1845c6e0 --- /dev/null +++ b/lib/src/workspace/presentation/create_writerside_project_dialog.dart @@ -0,0 +1,346 @@ +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; + +import '../../app/busymark_design.dart'; +import '../../app/localization.dart'; +import '../../core/path_utils.dart'; +import '../../writerside/writerside_project_creator.dart'; +import '../workspace_message.dart'; + +class BusyMarkCreateWritersideProjectDialog extends StatefulWidget { + const BusyMarkCreateWritersideProjectDialog({ + super.key, + required this.parentDirectoryPath, + required this.onCreate, + }); + + final String parentDirectoryPath; + final Future Function( + WritersideProjectCreateRequest request, + void Function(WorkspaceMessage) onError, + void Function(String bufferId) onPublished, + ) + onCreate; + + @override + State createState() => + _BusyMarkCreateWritersideProjectDialogState(); +} + +class _BusyMarkCreateWritersideProjectDialogState + extends State { + static final _directorySlugCharacterPattern = RegExp( + r'[\p{L}\p{M}\p{N}_-]', + unicode: true, + ); + + late final TextEditingController _projectNameController; + late final TextEditingController _directoryNameController; + late final TextEditingController _instanceNameController; + late final TextEditingController _instanceIdController; + late final TextEditingController _topicTitleController; + late String _lastGeneratedDirectoryName; + late String _lastGeneratedInstanceId; + var _directoryEdited = false; + var _syncingDirectory = false; + var _instanceIdEdited = false; + var _syncingInstanceId = false; + var _creating = false; + String? _creationError; + var _localizedDefaultsApplied = false; + + @override + void initState() { + super.initState(); + _projectNameController = TextEditingController() + ..addListener(_handleProjectNameChanged); + _lastGeneratedDirectoryName = _slugDirectoryName(''); + _directoryNameController = TextEditingController( + text: _lastGeneratedDirectoryName, + )..addListener(_handleDirectoryNameChanged); + _instanceNameController = TextEditingController() + ..addListener(_handleInstanceNameChanged); + _lastGeneratedInstanceId = 'user-guide'; + _instanceIdController = TextEditingController( + text: _lastGeneratedInstanceId, + )..addListener(_handleInstanceIdChanged); + _topicTitleController = TextEditingController() + ..addListener(_handleFieldChanged); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_localizedDefaultsApplied) { + return; + } + _localizedDefaultsApplied = true; + _instanceNameController.text = context.l10n.defaultInstanceName; + _topicTitleController.text = context.l10n.defaultStartTopicTitle; + } + + @override + void dispose() { + _projectNameController.dispose(); + _directoryNameController.dispose(); + _instanceNameController.dispose(); + _instanceIdController.dispose(); + _topicTitleController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final colors = BusyMarkSurfaceColors.of(context); + final projectError = _projectNameError(context); + final directoryError = _directoryNameError(context); + final instanceIdError = _instanceIdError(context); + final topicTitleError = _topicTitleError(context); + final canCreate = + !_creating && + projectError == null && + directoryError == null && + instanceIdError == null && + topicTitleError == null; + return PopScope( + canPop: !_creating, + child: BusyMarkModalEditorScaffold( + title: context.l10n.createWritersideProject, + cancelLabel: context.l10n.cancel, + saveLabel: context.l10n.create, + onCancel: () => Navigator.pop(context), + cancelEnabled: !_creating, + onSave: canCreate ? _submit : null, + saving: _creating, + children: [ + BusyMarkGroupedList( + filled: true, + children: [ + BusyMarkGroupedTextEntry( + label: context.l10n.projectName, + controller: _projectNameController, + textInputAction: TextInputAction.next, + errorText: projectError, + ), + BusyMarkGroupedTextEntry( + label: context.l10n.directoryName, + controller: _directoryNameController, + textDirection: TextDirection.ltr, + textInputAction: TextInputAction.next, + errorText: directoryError, + ), + BusyMarkGroupedTextEntry( + label: context.l10n.instanceName, + controller: _instanceNameController, + textInputAction: TextInputAction.next, + ), + BusyMarkGroupedTextEntry( + label: context.l10n.instanceId, + controller: _instanceIdController, + textDirection: TextDirection.ltr, + textInputAction: TextInputAction.next, + errorText: instanceIdError, + ), + BusyMarkGroupedTextEntry( + label: context.l10n.startTopicTitle, + controller: _topicTitleController, + textInputAction: TextInputAction.done, + onSubmitted: (_) { + if (canCreate) { + _submit(); + } + }, + errorText: topicTitleError, + ), + ], + ), + if (_creationError != null) ...[ + const SizedBox(height: BusyMarkSpacing.md), + BusyMarkStatusBox( + message: _creationError!, + kind: BusyMarkStatusKind.error, + ), + ], + BusyMarkGroupedList( + title: context.l10n.location, + filled: true, + children: [ + BusyMarkListTile.square( + title: Directionality( + textDirection: TextDirection.ltr, + child: SelectableText( + _targetPath, + style: Theme.of( + context, + ).textTheme.bodySmall?.copyWith(color: colors.foreground), + ), + ), + ), + ], + ), + const SizedBox(height: BusyMarkSpacing.lg), + ], + ), + ); + } + + String? _projectNameError(BuildContext context) { + if (_projectNameController.text.trim().isEmpty) { + return context.l10n.projectNameRequired; + } + return null; + } + + String? _directoryNameError(BuildContext context) { + final value = _directoryNameController.text.trim(); + if (value.isEmpty) { + return context.l10n.directoryNameRequired; + } + if (value == '.' || + value == '..' || + p.isAbsolute(value) || + value.contains('..') || + value.contains('/') || + value.contains(r'\')) { + return context.l10n.useSingleSafeDirectoryName; + } + return null; + } + + String? _instanceIdError(BuildContext context) { + final value = _instanceIdController.text.trim(); + if (!WritersideProjectCreator.isValidInstanceId(value)) { + return context.l10n.useLowercaseIdentifier; + } + return null; + } + + String? _topicTitleError(BuildContext context) { + if (_topicTitleController.text.trim().isEmpty) { + return context.l10n.startTopicTitleRequired; + } + return null; + } + + String get _targetPath { + final directoryName = _directoryNameController.text.trim(); + final safeDirectoryName = directoryName.isEmpty + ? _slugDirectoryName(_projectNameController.text) + : directoryName; + return p.join(normalizePath(widget.parentDirectoryPath), safeDirectoryName); + } + + void _handleProjectNameChanged() { + _creationError = null; + final nextDirectoryName = _slugDirectoryName(_projectNameController.text); + if (!_directoryEdited || + _directoryNameController.text == _lastGeneratedDirectoryName) { + _syncingDirectory = true; + _lastGeneratedDirectoryName = nextDirectoryName; + _directoryNameController.text = nextDirectoryName; + _syncingDirectory = false; + _directoryEdited = false; + } + setState(() {}); + } + + void _handleDirectoryNameChanged() { + _creationError = null; + if (!_syncingDirectory) { + _directoryEdited = + _directoryNameController.text != _lastGeneratedDirectoryName; + } + setState(() {}); + } + + void _handleInstanceNameChanged() { + _creationError = null; + final nextInstanceId = _slugInstanceId(_instanceNameController.text); + if (!_instanceIdEdited || + _instanceIdController.text == _lastGeneratedInstanceId) { + _syncingInstanceId = true; + _lastGeneratedInstanceId = nextInstanceId; + _instanceIdController.text = nextInstanceId; + _syncingInstanceId = false; + _instanceIdEdited = false; + } + setState(() {}); + } + + void _handleInstanceIdChanged() { + _creationError = null; + if (!_syncingInstanceId) { + _instanceIdEdited = + _instanceIdController.text != _lastGeneratedInstanceId; + } + setState(() {}); + } + + void _handleFieldChanged() { + _creationError = null; + setState(() {}); + } + + Future _submit() async { + if (_creating || + _projectNameError(context) != null || + _directoryNameError(context) != null || + _instanceIdError(context) != null || + _topicTitleError(context) != null) { + return; + } + setState(() { + _creating = true; + _creationError = null; + }); + WorkspaceMessage? error; + await widget.onCreate( + WritersideProjectCreateRequest( + parentDirectoryPath: normalizePath(widget.parentDirectoryPath), + projectName: _projectNameController.text.trim(), + directoryName: _directoryNameController.text.trim(), + instanceName: _instanceNameController.text.trim().isEmpty + ? context.l10n.defaultInstanceName + : _instanceNameController.text.trim(), + instanceId: _instanceIdController.text.trim(), + topicTitle: _topicTitleController.text.trim(), + ), + (message) => error = message, + (bufferId) { + if (mounted && ModalRoute.of(context)?.isCurrent == true) { + Navigator.pop(context, bufferId); + } + }, + ); + if (!mounted) return; + setState(() { + _creating = false; + if (error case final message?) { + _creationError = localizeWorkspaceMessage(context, message); + } + }); + } + + String _slugDirectoryName(String value) { + final buffer = StringBuffer(); + var pendingSeparator = false; + for (final rune in value.toLowerCase().trim().runes) { + final character = String.fromCharCode(rune); + if (_directorySlugCharacterPattern.hasMatch(character)) { + if (pendingSeparator && buffer.isNotEmpty) { + buffer.write('-'); + } + buffer.write(character); + pendingSeparator = false; + } else { + pendingSeparator = true; + } + } + final slug = buffer.toString().replaceAll(RegExp(r'^[-_]+|[-_]+$'), ''); + return slug.isEmpty ? 'writerside-project' : slug; + } + + String _slugInstanceId(String value) { + return WritersideProjectCreator.slugInstanceId(value); + } +} diff --git a/lib/src/workspace/presentation/settings_screen.dart b/lib/src/workspace/presentation/settings_screen.dart index 72568ee4..01d97cf5 100644 --- a/lib/src/workspace/presentation/settings_screen.dart +++ b/lib/src/workspace/presentation/settings_screen.dart @@ -1,3 +1,4 @@ +import '../../app/busymark_resource_menu.dart'; import 'keyboard_shortcuts_settings.dart'; import '../../nextcloud_notes/presentation/nextcloud_settings.dart'; import 'dart:async'; @@ -32,7 +33,6 @@ import '../../app/window_control_service.dart'; import '../../core/atomic_file_writer.dart'; import '../../feedback/presentation/feedback_dialog.dart'; import '../../platform/gtk_header_icon_service.dart'; -import '../../platform/linux_header_bar_service.dart'; import '../../spellcheck/spelling_catalog.dart'; import '../../spellcheck/spelling_session_controller.dart'; import '../../spellcheck/spelling_word_store.dart'; @@ -98,13 +98,7 @@ class _SettingsScreenState extends ConsumerState { const []; _prepareSpellingSettings(spelling, workspace?.id); final colors = BusyMarkSurfaceColors.of(context); - final headerBar = ref.watch(linuxHeaderBarServiceProvider); final title = _settingsPageLabel(context, _page); - ref.listen(headerBarActionsProvider, (previous, next) { - next.whenData((event) { - _handleHeaderBarAction(context, headerBar, event.action); - }); - }); final pageBody = switch (_page) { SettingsPage.keyboardShortcuts => const KeyboardShortcutsSettings(), SettingsPage.appearance => BusyMarkGroupedList( @@ -431,13 +425,14 @@ class _SettingsScreenState extends ConsumerState { filled: true, children: [ BusyMarkSwitchRow( - title: l10n.allowRemoteImages, - subtitle: l10n.allowRemoteImagesDescription, + title: l10n.alwaysLoadRemoteImages, + subtitle: l10n.remoteImageGlobalSettingsDetail, value: settings.allowRemoteImages, onChanged: controller.setAllowRemoteImages, leading: const Icon(BusyMarkGlyphs.image), ), - if (settings.remoteImageAllowedWorkspacePaths.isNotEmpty) + if (settings.remoteImageAllowedWorkspacePaths.isNotEmpty || + settings.remoteImageAllowedWorkspaceIds.isNotEmpty) BusyMarkActionRow( title: l10n.clearRemoteImagePermissions, subtitle: l10n.clearRemoteImagePermissionsDescription, @@ -459,19 +454,6 @@ class _SettingsScreenState extends ConsumerState { builder: (context, constraints) { final showSidebar = constraints.maxWidth >= BusyMarkSizes.settingsSidebarBreakpoint; - final headerConfiguration = HeaderBarConfigurationDefaults.of(context) - .copyWith( - title: title, - viewMode: AppViewMode.editor, - searchQuery: '', - canRefresh: false, - documentControlsVisible: false, - searchActive: false, - searchVisible: false, - sidebarVisible: showSidebar, - sidebarToggleVisible: false, - backVisible: true, - ); final content = ColoredBox( key: const ValueKey('settings-content-surface'), color: colors.view, @@ -510,8 +492,7 @@ class _SettingsScreenState extends ConsumerState { header: _SettingsFallbackHeader( title: title, onBack: _goBack, - onMenuSelected: (action) => - _handleMainMenuAction(context, headerBar, action), + onMenuSelected: (action) => _handleMainMenuAction(context, action), ), sidebarHeader: const BusyMarkLinuxBrandHeader(), sidebarBody: _SettingsSidebar( @@ -528,13 +509,8 @@ class _SettingsScreenState extends ConsumerState { onPopInvokedWithResult: (didPop, result) { if (!didPop) _goBack(); }, - child: HeaderBarConfigurationPublisher( - synchronizer: headerBar.configurationSynchronizer, - configuration: headerConfiguration, - enabled: headerBar.isAvailable, - child: BusyMarkLocalTextEditingShortcuts( - child: Scaffold(backgroundColor: colors.view, body: body), - ), + child: BusyMarkLocalTextEditingShortcuts( + child: Scaffold(backgroundColor: colors.view, body: body), ), ); }, @@ -645,49 +621,8 @@ class _SettingsScreenState extends ConsumerState { ); } - void _handleHeaderBarAction( - BuildContext context, - LinuxHeaderBarService headerBar, - HeaderBarAction action, - ) { - switch (action) { - case HeaderBarAction.back: - _goBack(); - case HeaderBarAction.aboutBusyMark: - showBusyMarkAboutDialog(context); - case HeaderBarAction.syntaxReference: - showBusyMarkSyntaxReferenceDialog(context); - case HeaderBarAction.reportIssue: - showBusyMarkFeedbackDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - ); - case HeaderBarAction.settings: - _selectPage(SettingsPage.appearance); - case HeaderBarAction.sidebarToggle: - case HeaderBarAction.search: - case HeaderBarAction.refresh: - case HeaderBarAction.save: - case HeaderBarAction.export: - case HeaderBarAction.fullScreen: - case HeaderBarAction.menu: - case HeaderBarAction.viewModeEditor: - case HeaderBarAction.viewModeSource: - case HeaderBarAction.viewModePreview: - case HeaderBarAction.viewModeSplit: - case HeaderBarAction.sidebarFiles: - case HeaderBarAction.sidebarToc: - case HeaderBarAction.sidebarOutline: - case HeaderBarAction.sidebarGit: - case HeaderBarAction.sidebarLocalHistory: - case HeaderBarAction.sidebarClipboardHistory: - break; - } - } - void _handleMainMenuAction( BuildContext context, - LinuxHeaderBarService headerBar, BusyMarkMainMenuAction action, ) { switch (action) { @@ -700,10 +635,7 @@ class _SettingsScreenState extends ConsumerState { case BusyMarkMainMenuAction.syntaxReference: showBusyMarkSyntaxReferenceDialog(context); case BusyMarkMainMenuAction.reportIssue: - showBusyMarkFeedbackDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - ); + showBusyMarkFeedbackDialog(context); case BusyMarkMainMenuAction.aboutBusyMark: showBusyMarkAboutDialog(context); } @@ -1515,7 +1447,10 @@ class _SettingsFallbackHeader extends StatelessWidget { ), title: BusyMarkLinuxHeaderTitle(title), trailing: BusyMarkLinuxHeaderControlGroup( - children: [BusyMarkMainMenuButton(onSelected: onMenuSelected)], + children: [ + ...BusyMarkResourceMenuButton.buttons, + BusyMarkMainMenuButton(onSelected: onMenuSelected), + ], ), ); } diff --git a/lib/src/workspace/presentation/welcome_screen.dart b/lib/src/workspace/presentation/welcome_screen.dart index 67766a13..0150985d 100644 --- a/lib/src/workspace/presentation/welcome_screen.dart +++ b/lib/src/workspace/presentation/welcome_screen.dart @@ -1,18 +1,17 @@ +import '../../app/busymark_resource_menu.dart'; +import '../workspace_resource_actions.dart'; import '../../app/command_registry.dart'; -import '../recent_navigation.dart'; +import 'workspace_sidebar.dart'; import '../../search/search_session.dart'; import '../../search/search_sidebar.dart'; import '../../search/welcome_notes_action.dart'; import '../../nextcloud_notes/application/nextcloud_connection.dart'; import 'dart:async'; -import 'dart:io'; -import 'package:file_selector/file_selector.dart'; import 'package:busymark/src/app/startup_path.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; -import 'package:path/path.dart' as p; import '../../app/app_settings.dart'; import '../../app/app_router.dart'; @@ -24,15 +23,10 @@ import '../../app/busymark_glyphs.dart'; import '../../app/busymark_main_menu.dart'; import '../../app/localization.dart'; import '../../app/window_control_service.dart'; -import '../../core/debug_log.dart'; -import '../../core/path_utils.dart'; import '../../feedback/presentation/feedback_dialog.dart'; import '../../platform/gtk_header_icon_service.dart'; -import '../../platform/linux_header_bar_service.dart'; -import '../../writerside/writerside_project_creator.dart'; import '../workspace_controller.dart'; import '../workspace_message.dart'; -import '../workspace_safety.dart'; class WelcomeScreen extends ConsumerStatefulWidget { const WelcomeScreen({super.key}); @@ -42,28 +36,10 @@ class WelcomeScreen extends ConsumerStatefulWidget { } class _WelcomeScreenState extends ConsumerState { - bool _navigateWhenContentReady = false; - - XTypeGroup _markdownTypes(BuildContext context) => XTypeGroup( - label: context.l10n.fileTypeMarkdown, - extensions: ['md', 'markdown'], - mimeTypes: ['text/markdown', 'text/x-markdown'], - ); @override Widget build(BuildContext context) { final state = ref.watch(workspaceControllerProvider); - ref.listen(workspaceControllerProvider, (previous, next) { - if (_navigateWhenContentReady && - previous?.isLoading == true && - !next.isLoading && - next.workspace != null && - mounted) { - _navigateWhenContentReady = false; - context.go('/workspace'); - } - }); final settings = ref.watch(appSettingsControllerProvider); - final headerBar = ref.watch(linuxHeaderBarServiceProvider); final colors = BusyMarkSurfaceColors.of(context); final search = ref.watch(searchSessionProvider); final sidebarVisible = settings.sidebarVisible || search.active; @@ -86,21 +62,21 @@ class _WelcomeScreenState extends ConsumerState { .uri .path == '/') { - unawaited(performWelcomeNotesAction(context, ref, pending)); + unawaited( + performWorkspaceResourceAction( + ref, + WorkspaceResourceAction.forNotes(pending), + ), + ); } }); } - ref.listen(headerBarActionsProvider, (previous, next) { - next.whenData((event) { - _handleHeaderBarAction(context, event.action); - }); - }); final startupPath = ref.watch(startupPathProvider); final startupNavigation = ref.read(startupNavigationGuardProvider); if (startupNavigation.claimStartupPath(startupPath)) { WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { - unawaited(_openPath(startupPath!)); + unawaited(openWorkspaceResourcePath(ref, startupPath!)); } }); } else if (startupNavigation.claimSessionRestore(startupPath)) { @@ -120,32 +96,40 @@ class _WelcomeScreenState extends ConsumerState { } final welcomeMainColor = colors.view; - final welcomeSidebar = SizedBox( - width: BusyMarkSizes.sidebarWidth, - child: BusyMarkSidebarSurface( - showEndBorder: false, - child: IndexedStack( - index: search.active ? 1 : 0, - children: [ - ExcludeFocus( - excluding: search.active, - child: SearchResultList( - recordDensity: BusyMarkRecordDensity.comfortable, - results: [ - for (final r in settings.recentWorkspaces) - RecentSearchResult(r), - ], - onActivate: (r) => openRecentResource( - context, - ref, - (r as RecentSearchResult).resource, - ), - ), + final sidebarRevealed = watchSidebarSelectorReveal( + context, + ref, + workspaceId: null, + ); + final welcomeSidebar = WorkspaceSidebar( + contextLabel: Row( + children: [ + const Icon(BusyMarkGlyphs.home, size: BusyMarkSizes.iconSm), + const SizedBox(width: BusyMarkSpacing.sm), + Expanded( + child: Text( + context.l10n.home, + key: const ValueKey('workspace-sidebar-primary-label'), + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodyMedium, ), - const SearchSidebar(), - ], - ), + ), + ], ), + items: [ + BusyMarkPopupMenuItem( + value: true, + label: context.l10n.recent, + icon: BusyMarkGlyphs.history, + mnemonic: 'E', + shortcut: 'E', + gtkAccelerator: 'e', + checked: true, + trailingCheck: true, + ), + ], + onSelected: (_) {}, + content: const RecentSidebarPanel(), ); final welcomeContent = ColoredBox( color: welcomeMainColor, @@ -172,22 +156,16 @@ class _WelcomeScreenState extends ConsumerState { trailing: Icon( BusyMarkGlyphs.forwardFor(Directionality.of(context)), ), - onTap: _createMarkdownFile, + onTap: () => _run(WorkspaceResourceAction.newMarkdown), ), BusyMarkActionRow( key: const ValueKey('welcome-new-nextcloud-note'), - title: context.l10n.nextcloudNewNote, + title: context.l10n.newNextcloudNote, subtitle: connection.account == null ? context.l10n.nextcloudNotes : 'Nextcloud · ${connection.account!.server}', leading: const Icon(BusyMarkGlyphs.newDocument), - onTap: () => unawaited( - performWelcomeNotesAction( - context, - ref, - WelcomeNotesAction.create, - ), - ), + onTap: () => _run(WorkspaceResourceAction.newNote), ), BusyMarkActionRow( title: context.l10n.createWritersideProject, @@ -196,7 +174,7 @@ class _WelcomeScreenState extends ConsumerState { trailing: Icon( BusyMarkGlyphs.forwardFor(Directionality.of(context)), ), - onTap: _createWritersideProject, + onTap: () => _run(WorkspaceResourceAction.newWriterside), ), ], ), @@ -211,7 +189,7 @@ class _WelcomeScreenState extends ConsumerState { trailing: Icon( BusyMarkGlyphs.forwardFor(Directionality.of(context)), ), - onTap: _chooseMarkdownFile, + onTap: () => _run(WorkspaceResourceAction.openMarkdown), ), BusyMarkActionRow( title: context.l10n.openFolderOrWritersideProject, @@ -220,7 +198,7 @@ class _WelcomeScreenState extends ConsumerState { trailing: Icon( BusyMarkGlyphs.forwardFor(Directionality.of(context)), ), - onTap: () => _chooseDirectory(context.l10n.open), + onTap: () => _run(WorkspaceResourceAction.openFolder), ), BusyMarkActionRow( key: const ValueKey('welcome-nextcloud-notes'), @@ -232,13 +210,7 @@ class _WelcomeScreenState extends ConsumerState { trailing: Icon( BusyMarkGlyphs.forwardFor(Directionality.of(context)), ), - onTap: () => unawaited( - performWelcomeNotesAction( - context, - ref, - WelcomeNotesAction.browse, - ), - ), + onTap: () => _run(WorkspaceResourceAction.browseNotes), ), ], ), @@ -258,38 +230,18 @@ class _WelcomeScreenState extends ConsumerState { ), ); - final headerConfiguration = HeaderBarConfigurationDefaults.of(context) - .copyWith( - title: context.l10n.appTitle, - viewMode: AppViewMode.editor, - searchQuery: search.query, - canRefresh: false, - documentControlsVisible: false, - searchActive: search.active, - searchVisible: true, - sidebarVisible: sidebarVisible, - sidebarToggleVisible: true, - backVisible: false, - ); - - return HeaderBarConfigurationPublisher( - synchronizer: headerBar.configurationSynchronizer, - configuration: headerConfiguration, - enabled: headerBar.isAvailable, - child: Scaffold( - backgroundColor: welcomeMainColor, - body: LayoutBuilder( - builder: (context, constraints) => LinuxPageFrame( + return Scaffold( + backgroundColor: welcomeMainColor, + body: LayoutBuilder( + builder: (context, constraints) { + final narrow = + constraints.maxWidth < + BusyMarkSizes.sidebarWidth + BusyMarkSizes.previewMinWidth; + return LinuxPageFrame( sidebarHeader: const BusyMarkLinuxBrandHeader(), sidebarBody: welcomeSidebar, - sidebarAvailable: - search.active || - constraints.maxWidth >= - BusyMarkSizes.sidebarWidth + BusyMarkSizes.previewMinWidth, - sidebarOverlay: - search.active && - constraints.maxWidth < - BusyMarkSizes.sidebarWidth + BusyMarkSizes.previewMinWidth, + sidebarAvailable: !narrow || search.active || sidebarRevealed, + sidebarOverlay: narrow && (search.active || sidebarRevealed), sidebarExpanded: sidebarVisible, sidebarTransitionGeneration: ref.watch( sidebarTransitionGenerationProvider, @@ -329,56 +281,23 @@ class _WelcomeScreenState extends ConsumerState { onPressed: () => ref.read(searchSessionProvider.notifier).toggle(), ), + ...BusyMarkResourceMenuButton.buttons, BusyMarkMainMenuButton( onSelected: (action) => - _handleMainMenuAction(context, headerBar, action), + _handleMainMenuAction(context, action), ), ], ), ), body: welcomeContent, - ), - ), + ); + }, ), ); } - void _handleHeaderBarAction(BuildContext context, HeaderBarAction action) { - switch (action) { - case HeaderBarAction.settings: - context.go(settingsLocation(SettingsReturnTarget.welcome)); - case HeaderBarAction.aboutBusyMark: - showBusyMarkAboutDialog(context); - case HeaderBarAction.syntaxReference: - showBusyMarkSyntaxReferenceDialog(context); - case HeaderBarAction.reportIssue: - showBusyMarkFeedbackDialog( - context, - headerBarService: ref.read(linuxHeaderBarServiceProvider), - ); - case HeaderBarAction.sidebarToggle: - _toggleSidebar(); - case HeaderBarAction.search: - ref.read(searchSessionProvider.notifier).toggle(); - case HeaderBarAction.back: - case HeaderBarAction.refresh: - case HeaderBarAction.save: - case HeaderBarAction.export: - case HeaderBarAction.fullScreen: - case HeaderBarAction.menu: - case HeaderBarAction.viewModeEditor: - case HeaderBarAction.viewModeSource: - case HeaderBarAction.viewModePreview: - case HeaderBarAction.viewModeSplit: - case HeaderBarAction.sidebarFiles: - case HeaderBarAction.sidebarToc: - case HeaderBarAction.sidebarOutline: - case HeaderBarAction.sidebarGit: - case HeaderBarAction.sidebarLocalHistory: - case HeaderBarAction.sidebarClipboardHistory: - break; - } - } + void _run(WorkspaceResourceAction action) => + unawaited(performWorkspaceResourceAction(ref, action)); void _toggleSidebar() { final settings = ref.read(appSettingsControllerProvider); @@ -391,7 +310,6 @@ class _WelcomeScreenState extends ConsumerState { void _handleMainMenuAction( BuildContext context, - LinuxHeaderBarService headerBar, BusyMarkMainMenuAction action, ) { switch (action) { @@ -404,500 +322,11 @@ class _WelcomeScreenState extends ConsumerState { case BusyMarkMainMenuAction.syntaxReference: showBusyMarkSyntaxReferenceDialog(context); case BusyMarkMainMenuAction.reportIssue: - showBusyMarkFeedbackDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - ); + showBusyMarkFeedbackDialog(context); case BusyMarkMainMenuAction.aboutBusyMark: showBusyMarkAboutDialog(context); } } - - Future _chooseMarkdownFile() async { - final selected = await openFile( - acceptedTypeGroups: [_markdownTypes(context)], - initialDirectory: _initialDirectory(), - confirmButtonText: context.l10n.open, - ); - final path = selected?.path; - if (path == null) { - return; - } - _logSelectedPickerPath(path); - await _openPath(path); - } - - Future _chooseDirectory(String confirmButtonText) async { - final path = await getDirectoryPath( - initialDirectory: _initialDirectory(), - confirmButtonText: confirmButtonText, - canCreateDirectories: false, - ); - if (path == null) { - return; - } - _logSelectedPickerPath(path); - await _openPath(path); - } - - void _logSelectedPickerPath(String rawPath) { - try { - final normalizedPath = normalizePath(rawPath); - final fileType = FileSystemEntity.typeSync(normalizedPath); - busyMarkDebugLogLines([ - '[BusyMark] Picker selected path', - '[BusyMark] raw: ${busyMarkLogPath(rawPath)}', - '[BusyMark] normalized: ${busyMarkLogPath(normalizedPath)}', - '[BusyMark] raw startsWith file://: ${isFileUriPath(rawPath)}', - '[BusyMark] raw startsWith /run/user/: ${rawPath.startsWith('/run/user/')}', - '[BusyMark] normalized startsWith /run/user/: ${normalizedPath.startsWith('/run/user/')}', - '[BusyMark] entity type: ${_fileTypeLabel(fileType)}', - ]); - } on Object catch (error, stackTrace) { - busyMarkDebugLogError( - '[BusyMark] Picker path logging failed', - error, - stackTrace, - context: {'raw': busyMarkLogPath(rawPath)}, - ); - } - } - - String _fileTypeLabel(FileSystemEntityType type) { - if (type == FileSystemEntityType.file) { - return 'file'; - } - if (type == FileSystemEntityType.directory) { - return 'directory'; - } - if (type == FileSystemEntityType.link) { - return 'link'; - } - if (type == FileSystemEntityType.notFound) { - return 'notFound'; - } - return type.toString(); - } - - Future _createMarkdownFile() async { - final safe = await confirmSafeToContinue(context, ref); - if (!safe) { - return; - } - final created = await ref - .read(workspaceControllerProvider.notifier) - .createMarkdownWorkspace(); - if (created && mounted) { - context.go('/workspace'); - } - } - - Future _createWritersideProject() async { - final safe = await confirmSafeToContinue(context, ref); - if (!safe || !mounted) { - return; - } - final parentPath = await getDirectoryPath( - initialDirectory: _initialDirectory(), - confirmButtonText: context.l10n.chooseLocation, - canCreateDirectories: true, - ); - if (parentPath == null || !mounted) { - return; - } - _logSelectedPickerPath(parentPath); - - final headerBar = ref.read(linuxHeaderBarServiceProvider); - final created = await showBusyMarkModalEditorDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - maxWidth: BusyMarkSizes.dialogWide, - builder: (context) => BusyMarkCreateWritersideProjectDialog( - parentDirectoryPath: parentPath, - onCreate: (request) => ref - .read(workspaceControllerProvider.notifier) - .createWritersideProject(request), - message: () => ref.read(workspaceControllerProvider).message, - ), - ); - if (!mounted) { - return; - } - if (created == true) { - context.go('/workspace'); - } - } - - String? _initialDirectory() { - final settings = ref.read(appSettingsControllerProvider); - final lastPath = settings.lastOpenedPath; - if (lastPath == null || lastPath.isEmpty) { - return null; - } - final extension = p.extension(lastPath); - return extension.isEmpty ? lastPath : p.dirname(lastPath); - } - - Future _openPath(String path) async { - if (path.isEmpty) { - return; - } - final safe = await confirmSafeToContinue(context, ref); - if (!safe) { - return; - } - _navigateWhenContentReady = true; - try { - // The operation still awaits bookkeeping and reports its errors. The - // listener may publish the prepared, monitored editor while that write - // is pending, without making it a fire-and-forget persistence operation. - await ref.read(workspaceControllerProvider.notifier).openPath(path); - } finally { - _navigateWhenContentReady = false; - } - if (!mounted) { - return; - } - final workspace = ref.read(workspaceControllerProvider).workspace; - if (workspace != null) { - context.go('/workspace'); - } - } -} - -class BusyMarkCreateWritersideProjectDialog extends StatefulWidget { - const BusyMarkCreateWritersideProjectDialog({ - super.key, - required this.parentDirectoryPath, - required this.onCreate, - required this.message, - }); - - final String parentDirectoryPath; - final Future Function(WritersideProjectCreateRequest request) onCreate; - final WorkspaceMessage? Function() message; - - @override - State createState() => - _BusyMarkCreateWritersideProjectDialogState(); -} - -class _BusyMarkCreateWritersideProjectDialogState - extends State { - static final _directorySlugCharacterPattern = RegExp( - r'[\p{L}\p{M}\p{N}_-]', - unicode: true, - ); - - late final TextEditingController _projectNameController; - late final TextEditingController _directoryNameController; - late final TextEditingController _instanceNameController; - late final TextEditingController _instanceIdController; - late final TextEditingController _topicTitleController; - late String _lastGeneratedDirectoryName; - late String _lastGeneratedInstanceId; - var _directoryEdited = false; - var _syncingDirectory = false; - var _instanceIdEdited = false; - var _syncingInstanceId = false; - var _creating = false; - String? _creationError; - var _localizedDefaultsApplied = false; - - @override - void initState() { - super.initState(); - _projectNameController = TextEditingController() - ..addListener(_handleProjectNameChanged); - _lastGeneratedDirectoryName = _slugDirectoryName(''); - _directoryNameController = TextEditingController( - text: _lastGeneratedDirectoryName, - )..addListener(_handleDirectoryNameChanged); - _instanceNameController = TextEditingController() - ..addListener(_handleInstanceNameChanged); - _lastGeneratedInstanceId = 'user-guide'; - _instanceIdController = TextEditingController( - text: _lastGeneratedInstanceId, - )..addListener(_handleInstanceIdChanged); - _topicTitleController = TextEditingController() - ..addListener(_handleFieldChanged); - } - - @override - void didChangeDependencies() { - super.didChangeDependencies(); - if (_localizedDefaultsApplied) { - return; - } - _localizedDefaultsApplied = true; - _instanceNameController.text = context.l10n.defaultInstanceName; - _topicTitleController.text = context.l10n.defaultStartTopicTitle; - } - - @override - void dispose() { - _projectNameController.dispose(); - _directoryNameController.dispose(); - _instanceNameController.dispose(); - _instanceIdController.dispose(); - _topicTitleController.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - final colors = BusyMarkSurfaceColors.of(context); - final projectError = _projectNameError(context); - final directoryError = _directoryNameError(context); - final instanceIdError = _instanceIdError(context); - final topicTitleError = _topicTitleError(context); - final canCreate = - !_creating && - projectError == null && - directoryError == null && - instanceIdError == null && - topicTitleError == null; - return PopScope( - canPop: !_creating, - child: BusyMarkModalEditorScaffold( - title: context.l10n.createWritersideProject, - cancelLabel: context.l10n.cancel, - saveLabel: context.l10n.create, - onCancel: () => Navigator.pop(context), - cancelEnabled: !_creating, - onSave: canCreate ? _submit : null, - saving: _creating, - children: [ - BusyMarkGroupedList( - filled: true, - children: [ - BusyMarkGroupedTextEntry( - label: context.l10n.projectName, - controller: _projectNameController, - textInputAction: TextInputAction.next, - errorText: projectError, - ), - BusyMarkGroupedTextEntry( - label: context.l10n.directoryName, - controller: _directoryNameController, - textDirection: TextDirection.ltr, - textInputAction: TextInputAction.next, - errorText: directoryError, - ), - BusyMarkGroupedTextEntry( - label: context.l10n.instanceName, - controller: _instanceNameController, - textInputAction: TextInputAction.next, - ), - BusyMarkGroupedTextEntry( - label: context.l10n.instanceId, - controller: _instanceIdController, - textDirection: TextDirection.ltr, - textInputAction: TextInputAction.next, - errorText: instanceIdError, - ), - BusyMarkGroupedTextEntry( - label: context.l10n.startTopicTitle, - controller: _topicTitleController, - textInputAction: TextInputAction.done, - onSubmitted: (_) { - if (canCreate) { - _submit(); - } - }, - errorText: topicTitleError, - ), - ], - ), - if (_creationError != null) ...[ - const SizedBox(height: BusyMarkSpacing.md), - BusyMarkStatusBox( - message: _creationError!, - kind: BusyMarkStatusKind.error, - ), - ], - BusyMarkGroupedList( - title: context.l10n.location, - filled: true, - children: [ - BusyMarkListTile.square( - title: Directionality( - textDirection: TextDirection.ltr, - child: SelectableText( - _targetPath, - style: Theme.of( - context, - ).textTheme.bodySmall?.copyWith(color: colors.foreground), - ), - ), - ), - ], - ), - const SizedBox(height: BusyMarkSpacing.lg), - ], - ), - ); - } - - String? _projectNameError(BuildContext context) { - if (_projectNameController.text.trim().isEmpty) { - return context.l10n.projectNameRequired; - } - return null; - } - - String? _directoryNameError(BuildContext context) { - final value = _directoryNameController.text.trim(); - if (value.isEmpty) { - return context.l10n.directoryNameRequired; - } - if (value == '.' || - value == '..' || - p.isAbsolute(value) || - value.contains('..') || - value.contains('/') || - value.contains(r'\')) { - return context.l10n.useSingleSafeDirectoryName; - } - return null; - } - - String? _instanceIdError(BuildContext context) { - final value = _instanceIdController.text.trim(); - if (!WritersideProjectCreator.isValidInstanceId(value)) { - return context.l10n.useLowercaseIdentifier; - } - return null; - } - - String? _topicTitleError(BuildContext context) { - if (_topicTitleController.text.trim().isEmpty) { - return context.l10n.startTopicTitleRequired; - } - return null; - } - - String get _targetPath { - final directoryName = _directoryNameController.text.trim(); - final safeDirectoryName = directoryName.isEmpty - ? _slugDirectoryName(_projectNameController.text) - : directoryName; - return p.join(normalizePath(widget.parentDirectoryPath), safeDirectoryName); - } - - void _handleProjectNameChanged() { - _creationError = null; - final nextDirectoryName = _slugDirectoryName(_projectNameController.text); - if (!_directoryEdited || - _directoryNameController.text == _lastGeneratedDirectoryName) { - _syncingDirectory = true; - _lastGeneratedDirectoryName = nextDirectoryName; - _directoryNameController.text = nextDirectoryName; - _syncingDirectory = false; - _directoryEdited = false; - } - setState(() {}); - } - - void _handleDirectoryNameChanged() { - _creationError = null; - if (!_syncingDirectory) { - _directoryEdited = - _directoryNameController.text != _lastGeneratedDirectoryName; - } - setState(() {}); - } - - void _handleInstanceNameChanged() { - _creationError = null; - final nextInstanceId = _slugInstanceId(_instanceNameController.text); - if (!_instanceIdEdited || - _instanceIdController.text == _lastGeneratedInstanceId) { - _syncingInstanceId = true; - _lastGeneratedInstanceId = nextInstanceId; - _instanceIdController.text = nextInstanceId; - _syncingInstanceId = false; - _instanceIdEdited = false; - } - setState(() {}); - } - - void _handleInstanceIdChanged() { - _creationError = null; - if (!_syncingInstanceId) { - _instanceIdEdited = - _instanceIdController.text != _lastGeneratedInstanceId; - } - setState(() {}); - } - - void _handleFieldChanged() { - _creationError = null; - setState(() {}); - } - - Future _submit() async { - if (_creating || - _projectNameError(context) != null || - _directoryNameError(context) != null || - _instanceIdError(context) != null || - _topicTitleError(context) != null) { - return; - } - setState(() { - _creating = true; - _creationError = null; - }); - final created = await widget.onCreate( - WritersideProjectCreateRequest( - parentDirectoryPath: normalizePath(widget.parentDirectoryPath), - projectName: _projectNameController.text.trim(), - directoryName: _directoryNameController.text.trim(), - instanceName: _instanceNameController.text.trim().isEmpty - ? context.l10n.defaultInstanceName - : _instanceNameController.text.trim(), - instanceId: _instanceIdController.text.trim(), - topicTitle: _topicTitleController.text.trim(), - ), - ); - if (!mounted) { - return; - } - if (created) { - Navigator.pop(context, true); - return; - } - setState(() { - _creating = false; - final message = widget.message(); - _creationError = message == null - ? context.l10n.createWritersideProjectFailed - : localizeWorkspaceMessage(context, message); - }); - } - - String _slugDirectoryName(String value) { - final buffer = StringBuffer(); - var pendingSeparator = false; - for (final rune in value.toLowerCase().trim().runes) { - final character = String.fromCharCode(rune); - if (_directorySlugCharacterPattern.hasMatch(character)) { - if (pendingSeparator && buffer.isNotEmpty) { - buffer.write('-'); - } - buffer.write(character); - pendingSeparator = false; - } else { - pendingSeparator = true; - } - } - final slug = buffer.toString().replaceAll(RegExp(r'^[-_]+|[-_]+$'), ''); - return slug.isEmpty ? 'writerside-project' : slug; - } - - String _slugInstanceId(String value) { - return WritersideProjectCreator.slugInstanceId(value); - } } BusyMarkStatusKind busyMarkWorkspaceMessageStatusKind( diff --git a/lib/src/workspace/presentation/workspace_screen.dart b/lib/src/workspace/presentation/workspace_screen.dart index 65311ff1..86d56821 100644 --- a/lib/src/workspace/presentation/workspace_screen.dart +++ b/lib/src/workspace/presentation/workspace_screen.dart @@ -1,3 +1,4 @@ +import '../../app/busymark_resource_menu.dart'; import 'package:busymark/src/git/application/shared_git_presentation.dart'; import '../../core/debug_log.dart'; import '../../app/document_view_availability.dart'; @@ -84,6 +85,7 @@ import '../../editor/document_text_direction.dart'; import '../../editor/document_thematic_break.dart'; import '../../editor/editor_text_context_menu.dart'; import '../../editor/markdown_image_view.dart'; +import '../../editor/markdown_image_permission_scope.dart'; import '../../editor/source/source_controller.dart'; import '../../editor/source/source_autocomplete.dart'; import '../../editor/source/source_document.dart'; @@ -110,7 +112,6 @@ import '../../local_history/local_history_comparison_view.dart'; import '../../local_history/local_history_controller.dart'; import '../../local_history/local_history_panel.dart'; import '../../platform/gtk_header_icon_service.dart'; -import '../../platform/linux_header_bar_service.dart'; import '../../platform/native_writerside_dialog_service.dart'; import '../../search/search_replace_service.dart'; import '../../search/workspace_search_scope.dart'; @@ -137,11 +138,13 @@ import 'document_status_bar.dart'; import '../text_format_metadata.dart'; import '../workspace_glyphs.dart'; import '../workspace_model.dart'; +import '../remote_image_permissions.dart'; import '../workspace_message.dart'; import '../workspace_safety.dart'; import '../workspace_tabs.dart'; import '../workspace_tab_actions.dart'; import 'welcome_screen.dart'; +import 'workspace_sidebar.dart'; import 'writerside_instance_dialog.dart'; import 'writerside_markdown_import_dialog.dart'; import 'writerside_toc_dialogs.dart'; @@ -182,15 +185,15 @@ final _searchNavigationTargetProvider = >(_SearchNavigationTargetController.new); // Only Commit grows the existing sidebar allocation for its full native labels. final _sidebarAllocationProvider = - NotifierProvider<_SidebarAllocation, (String, DateTime, _SidebarTab)?>( + NotifierProvider<_SidebarAllocation, (String, _SidebarTab)?>( _SidebarAllocation.new, ); -class _SidebarAllocation extends Notifier<(String, DateTime, _SidebarTab)?> { +class _SidebarAllocation extends Notifier<(String, _SidebarTab)?> { @override - (String, DateTime, _SidebarTab)? build() => null; + (String, _SidebarTab)? build() => null; void select(Workspace workspace, _SidebarTab tab) => - state = (workspace.id, workspace.openedAt, tab); + state = (workspace.id, tab); } final _sidebarShortcutRequestProvider = @@ -339,25 +342,6 @@ Future _publishWritersideTitleDialog( } } -final _sidebarSelectorRevealProvider = - NotifierProvider<_SidebarSelectorReveal, String?>( - _SidebarSelectorReveal.new, - ); - -class _SidebarSelectorReveal extends Notifier { - @override - String? build() => null; - void reveal(String workspaceId) => state = workspaceId; -} - -final _sidebarViewMenuControllerProvider = - Provider((ref) { - final controller = BusyMarkHeaderMenuController( - debugLabel: BusyMarkCommandIds.sidebarViewSelector, - ); - ref.onDispose(controller.dispose); - return controller; - }); final _contentViewMenuControllerProvider = Provider((ref) { final controller = BusyMarkHeaderMenuController( @@ -400,7 +384,6 @@ class _WorkspaceScreenContents extends ConsumerWidget { .firstOrNull; final history = ref.read(localHistoryControllerProvider); final entries = workspaceTabEntries( - workspace: state.workspace!, gitTabs: ref.watch(sharedGitReviewProvider)[state.workspace!.id] ?? const SharedGitTabs(), @@ -537,6 +520,11 @@ class _WorkspaceScreenContents extends ConsumerWidget { return const WelcomeScreen(); } final searchState = ref.watch(searchSessionProvider); + final sidebarRevealed = watchSidebarSelectorReveal( + context, + ref, + workspaceId: workspace.id, + ); final preferredViewMode = state.activeBuffer?.editorState.mode ?? settings.documentViewMode; final documentViewMode = @@ -572,7 +560,6 @@ class _WorkspaceScreenContents extends ConsumerWidget { final localHistoryState = ref.watch(localHistoryControllerProvider); final colors = BusyMarkSurfaceColors.of(context); - final headerBar = ref.watch(linuxHeaderBarServiceProvider); final settingsController = ref.read(appSettingsControllerProvider.notifier); final sidebarVisible = searchState.active || @@ -585,12 +572,11 @@ class _WorkspaceScreenContents extends ConsumerWidget { final gitVisible = request == _SidebarTab.git || request == _SidebarTab.gitLog || - allocation == (workspace.id, workspace.openedAt, _SidebarTab.git) || - allocation == (workspace.id, workspace.openedAt, _SidebarTab.gitLog); + allocation == (workspace.id, _SidebarTab.git) || + allocation == (workspace.id, _SidebarTab.gitLog); final referencesVisible = request == _SidebarTab.references || - allocation == - (workspace.id, workspace.openedAt, _SidebarTab.references); + allocation == (workspace.id, _SidebarTab.references); final sidebarWidth = gitVisible && !searchState.active ? busyMarkGitSidebarMinimumWidth(context) : referencesVisible && !searchState.active @@ -657,11 +643,6 @@ class _WorkspaceScreenContents extends ConsumerWidget { ), ], ); - ref.listen(headerBarActionsProvider, (previous, next) { - next.whenData((event) { - _handleHeaderBarAction(context, ref, event.action); - }); - }); ref.listen(workspaceNavigationCommandProvider, (_, request) { if (request == null) return; if (isBusyMarkViewSelectorCommand(request.$1)) { @@ -669,41 +650,12 @@ class _WorkspaceScreenContents extends ConsumerWidget { 'command': request.$1, }); } - if (request.$1 == BusyMarkCommandIds.sidebarViewSelector) { - final menu = ref.read(_sidebarViewMenuControllerProvider); - final wasHidden = !ref - .read(appSettingsControllerProvider) - .sidebarVisible; - ref.read(_sidebarSelectorRevealProvider.notifier).reveal(workspace.id); - ref.read(searchSessionProvider.notifier).close(restoreFocus: false); - unawaited(() async { - await settingsController.setSidebarVisible(true); - await WidgetsBinding.instance.endOfFrame; - if (wasHidden) await Future.delayed(BusyMarkMotion.sidebar); - if (context.mounted) { - menu.open( - shortcuts: - (BusyMarkCommandRegistryScope.read(context) ?? - BusyMarkCommandCatalog.metadata) - .activators(request.$1), - ); - } - }()); - return; - } if (request.$1 == BusyMarkCommandIds.contentViewSelector) { final menu = ref.read(_contentViewMenuControllerProvider); ref.read(searchSessionProvider.notifier).close(restoreFocus: false); unawaited(() async { await WidgetsBinding.instance.endOfFrame; - if (context.mounted) { - menu.open( - shortcuts: - (BusyMarkCommandRegistryScope.read(context) ?? - BusyMarkCommandCatalog.metadata) - .activators(request.$1), - ); - } + if (context.mounted) menu.open(); }()); return; } @@ -758,137 +710,114 @@ class _WorkspaceScreenContents extends ConsumerWidget { : state.isDirty ? '*${_activeFileName(context, workspace, state.activeBuffer)}' : _activeFileName(context, workspace, state.activeBuffer); - final hasSidebar = _hasWorkspaceSidebar(workspace); - final headerConfiguration = HeaderBarConfigurationDefaults.of(context) - .copyWith( - title: busyMarkBidiIsolateFor(context, title), - viewMode: _headerBarViewMode(documentViewMode), - searchQuery: searchState.query, - canRefresh: true, - canExportPdf: canExportPdf, - canExportHtml: canExportHtml, - documentControlsVisible: comparison == null, - searchActive: searchState.active, - searchVisible: true, - sidebarVisible: sidebarVisible, - sidebarToggleVisible: hasSidebar, - backVisible: !searchState.active, - ); final commandRegistry = BusyMarkCommandRegistryScope.maybeOf(context) ?? BusyMarkCommandCatalog.metadata; - return HeaderBarConfigurationPublisher( - synchronizer: headerBar.configurationSynchronizer, - configuration: headerConfiguration, - enabled: headerBar.isAvailable, - child: Shortcuts( - shortcuts: { - for (final entry in const { - BusyMarkCommandIds.sidebarFiles: _SidebarTab.files, - BusyMarkCommandIds.sidebarToc: _SidebarTab.toc, - BusyMarkCommandIds.sidebarGit: _SidebarTab.git, - BusyMarkCommandIds.localHistory: _SidebarTab.localHistory, - BusyMarkCommandIds.clipboardHistory: _SidebarTab.clipboard, - }.entries) - ...commandRegistry.bindingIntents( - entry.key, - _SelectSidebarTabIntent(entry.value), - ), + return Shortcuts( + shortcuts: { + for (final entry in const { + BusyMarkCommandIds.sidebarFiles: _SidebarTab.files, + BusyMarkCommandIds.sidebarToc: _SidebarTab.toc, + BusyMarkCommandIds.sidebarGit: _SidebarTab.git, + BusyMarkCommandIds.localHistory: _SidebarTab.localHistory, + BusyMarkCommandIds.clipboardHistory: _SidebarTab.clipboard, + }.entries) + ...commandRegistry.bindingIntents( + entry.key, + _SelectSidebarTabIntent(entry.value), + ), + }, + child: Actions( + actions: { + _SelectSidebarTabIntent: CallbackAction<_SelectSidebarTabIntent>( + onInvoke: (intent) { + _selectSidebarShortcut(ref, intent.tab); + return null; + }, + ), }, - child: Actions( - actions: { - _SelectSidebarTabIntent: CallbackAction<_SelectSidebarTabIntent>( - onInvoke: (intent) { - _selectSidebarShortcut(ref, intent.tab); - return null; - }, - ), - }, - child: FocusScope( - autofocus: true, - child: Scaffold( - backgroundColor: colors.window, - body: LayoutBuilder( - builder: (context, constraints) { - final sidebarAvailable = - constraints.maxWidth >= - BusyMarkSizes.workspaceSidebarBreakpoint || - ref.watch(_sidebarSelectorRevealProvider) == workspace.id; - return LinuxPageFrame( - key: const ValueKey('workspace-page-frame'), - sidebarWidth: sidebarWidth, - sidebarHeader: const BusyMarkLinuxBrandHeader(), - sidebarBody: sidebar, - sidebarAvailable: - sidebarAvailable || gitVisible || searchState.active, - sidebarOverlay: searchState.active && !sidebarAvailable, - sidebarExpanded: sidebarVisible, - sidebarTransitionGeneration: ref.watch( - sidebarTransitionGenerationProvider, - ), - header: BusyMarkLinuxHeaderLayout( - centerAllocation: searchState.active - ? BusyMarkLinuxHeaderCenterAllocation - .fillBetweenControls - : BusyMarkLinuxHeaderCenterAllocation - .centeredBetweenControls, - leading: BusyMarkLinuxHeaderControlGroup( - children: [ - BusyMarkLinuxHeaderIconButton( - tooltip: sidebarAvailable && settings.sidebarVisible - ? context.l10n.hideSidebar - : context.l10n.showSidebar, - icon: BusyMarkGlyphs.sidebar, - nativeIcon: BusyMarkLinuxHeaderIcon.sidebar, - selected: - sidebarAvailable && settings.sidebarVisible, - shortcut: - commandRegistry[BusyMarkCommandIds - .toggleSidebar] - ?.shortcut - ?.label, - onPressed: !sidebarAvailable - ? null - : () { - final visible = !settings.sidebarVisible; - unawaited( - settingsController.setSidebarVisible( - visible, - ), - ); - }, - ), - if (!searchState.active) - BusyMarkLinuxHeaderIconButton( - tooltip: context.l10n.back, - icon: BusyMarkGlyphs.headerBackFor( - Directionality.of(context), - ), - nativeIcon: BusyMarkLinuxHeaderIcon.back, - shortcut: commandRegistry[BusyMarkCommandIds.back] + child: FocusScope( + autofocus: true, + child: Scaffold( + backgroundColor: colors.window, + body: LayoutBuilder( + builder: (context, constraints) { + final narrow = + constraints.maxWidth < + BusyMarkSizes.workspaceSidebarBreakpoint; + final sidebarAvailable = !narrow || sidebarRevealed; + return LinuxPageFrame( + key: const ValueKey('workspace-page-frame'), + sidebarWidth: sidebarWidth, + sidebarHeader: const BusyMarkLinuxBrandHeader(), + sidebarBody: sidebar, + sidebarAvailable: + sidebarAvailable || gitVisible || searchState.active, + sidebarOverlay: + narrow && (searchState.active || sidebarRevealed), + sidebarExpanded: sidebarVisible, + sidebarTransitionGeneration: ref.watch( + sidebarTransitionGenerationProvider, + ), + header: BusyMarkLinuxHeaderLayout( + centerAllocation: searchState.active + ? BusyMarkLinuxHeaderCenterAllocation + .fillBetweenControls + : BusyMarkLinuxHeaderCenterAllocation + .centeredBetweenControls, + leading: BusyMarkLinuxHeaderControlGroup( + children: [ + BusyMarkLinuxHeaderIconButton( + tooltip: sidebarAvailable && settings.sidebarVisible + ? context.l10n.hideSidebar + : context.l10n.showSidebar, + icon: BusyMarkGlyphs.sidebar, + nativeIcon: BusyMarkLinuxHeaderIcon.sidebar, + selected: sidebarAvailable && settings.sidebarVisible, + shortcut: + commandRegistry[BusyMarkCommandIds.toggleSidebar] ?.shortcut ?.label, - onPressed: () async { - if (await confirmSafeToContinue(context, ref) && - context.mounted) { - context.go('/'); - } - }, - ), - ], - ), - title: BusyMarkRetainedCrossfade( - index: searchState.active ? 1 : 0, - duration: BusyMarkMotion.search, - children: [ - BusyMarkLinuxHeaderTitle(title), - const SearchHeaderField(), - ], - ), - trailing: BusyMarkLinuxHeaderControlGroup( - children: [ - if (!searchState.active && comparison == null) ...[ + onPressed: !sidebarAvailable + ? null + : () { + final visible = !settings.sidebarVisible; + unawaited( + settingsController.setSidebarVisible( + visible, + ), + ); + }, + ), + BusyMarkHeaderIconButton( + key: const ValueKey('workspace-home'), + tooltip: context.l10n.home, + icon: BusyMarkGlyphs.home, + nativeIcon: BusyMarkLinuxHeaderIcon.home, + applyHeaderStateColors: true, + focusBorderRadius: BusyMarkRadius.pill, + shortcut: commandRegistry[BusyMarkCommandIds.home] + ?.shortcut + ?.label, + onPressed: () => + commandRegistry.execute(BusyMarkCommandIds.home), + ), + ], + ), + title: BusyMarkRetainedCrossfade( + index: searchState.active ? 1 : 0, + duration: BusyMarkMotion.search, + children: [ + BusyMarkLinuxHeaderTitle(title), + const SearchHeaderField(), + ], + ), + trailing: BusyMarkLinuxHeaderControlGroup( + children: [ + if (!searchState.active && comparison == null) ...[ + if (state.activeBuffer != null && + localHistoryState.selectedRevision == null) BusyMarkHeaderPopupMenuButton< DocumentViewModePreference >( @@ -948,62 +877,60 @@ class _WorkspaceScreenContents extends ConsumerWidget { ); }, ), - BusyMarkHeaderIconButton( - tooltip: context.l10n.validate, - icon: BusyMarkGlyphs.diagnostics, - onPressed: () => unawaited( - _validateActiveAndShowProblems(context, ref), - ), - ), - ], BusyMarkHeaderIconButton( - tooltip: context.l10n.search, - icon: BusyMarkGlyphs.search, - selected: searchState.active, - onPressed: () => _toggleSearch(ref), - ), - BusyMarkMainMenuButton( - canExport: canExportPdf || canExportHtml, - onSelected: (action) => - _handleMainMenuAction(context, ref, action), + tooltip: context.l10n.validate, + icon: BusyMarkGlyphs.diagnostics, + onPressed: () => unawaited( + _validateActiveAndShowProblems(context, ref), + ), ), ], - ), + BusyMarkHeaderIconButton( + tooltip: context.l10n.search, + icon: BusyMarkGlyphs.search, + selected: searchState.active, + onPressed: () => _toggleSearch(ref), + ), + ...BusyMarkResourceMenuButton.buttons, + BusyMarkMainMenuButton( + canExport: canExportPdf || canExportHtml, + onSelected: (action) => + _handleMainMenuAction(context, ref, action), + ), + ], ), - body: Column( - children: [ - // The recovered document already has a review banner with - // actions. Keep other messages, including recovery damage. - if (state.message != null && - !(state.message!.code == - WorkspaceMessageCode.recoveryRestored && - state.activeBuffer?.recovered == true)) - BusyMarkStatusBox( - message: localizeWorkspaceMessage( - context, - state.message!, - ), - kind: busyMarkWorkspaceMessageStatusKind( - state.message!.code, - ), + ), + body: Column( + children: [ + if (state.message != null && + !(state.message!.code == + WorkspaceMessageCode.recoveryRestored && + state.activeBuffer?.recovered == true)) + BusyMarkStatusBox( + message: localizeWorkspaceMessage( + context, + state.message!, ), - if (ref - .read(localHistoryControllerProvider.notifier) - .warningForBuffer(state.activeBuffer?.id) - case final historyWarning?) - BusyMarkStatusBox( - message: localizeLocalHistoryWarning( - context, - historyWarning, - ), - kind: BusyMarkStatusKind.warning, + kind: busyMarkWorkspaceMessageStatusKind( + state.message!.code, ), - Expanded(child: workspaceContent), - ], - ), - ); - }, - ), + ), + if (ref + .read(localHistoryControllerProvider.notifier) + .warningForBuffer(state.activeBuffer?.id) + case final historyWarning?) + BusyMarkStatusBox( + message: localizeLocalHistoryWarning( + context, + historyWarning, + ), + kind: BusyMarkStatusKind.warning, + ), + Expanded(child: workspaceContent), + ], + ), + ); + }, ), ), ), @@ -1030,67 +957,6 @@ class _WorkspaceScreenContents extends ConsumerWidget { ref.read(_sidebarShortcutRequestProvider.notifier).select(tab); } - void _handleHeaderBarAction( - BuildContext context, - WidgetRef ref, - HeaderBarAction action, - ) { - final commands = - BusyMarkCommandRegistryScope.read(context) ?? - BusyMarkCommandCatalog.metadata; - void execute(String id) => unawaited(commands.execute(id)); - switch (action) { - case HeaderBarAction.back: - execute(BusyMarkCommandIds.back); - case HeaderBarAction.sidebarToggle: - execute(BusyMarkCommandIds.toggleSidebar); - case HeaderBarAction.refresh: - unawaited(_validateActiveAndShowProblems(context, ref)); - case HeaderBarAction.save: - execute(BusyMarkCommandIds.save); - case HeaderBarAction.export: - execute(BusyMarkCommandIds.export); - case HeaderBarAction.fullScreen: - execute(BusyMarkCommandIds.fullScreen); - case HeaderBarAction.settings: - execute(BusyMarkCommandIds.settings); - case HeaderBarAction.syntaxReference: - execute(BusyMarkCommandIds.syntaxReference); - case HeaderBarAction.reportIssue: - final headerBar = ref.read(linuxHeaderBarServiceProvider); - showBusyMarkFeedbackDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - ); - case HeaderBarAction.aboutBusyMark: - showBusyMarkAboutDialog(context); - case HeaderBarAction.viewModeEditor: - execute(BusyMarkCommandIds.viewEditor); - case HeaderBarAction.viewModeSource: - execute(BusyMarkCommandIds.viewSource); - case HeaderBarAction.viewModePreview: - execute(BusyMarkCommandIds.viewReading); - case HeaderBarAction.viewModeSplit: - execute(BusyMarkCommandIds.viewSplit); - case HeaderBarAction.sidebarFiles: - _selectSidebarShortcut(ref, _SidebarTab.files); - case HeaderBarAction.sidebarToc: - _selectSidebarShortcut(ref, _SidebarTab.toc); - case HeaderBarAction.sidebarOutline: - _selectSidebarShortcut(ref, _SidebarTab.outline); - case HeaderBarAction.sidebarGit: - _selectSidebarShortcut(ref, _SidebarTab.git); - case HeaderBarAction.sidebarLocalHistory: - _selectSidebarShortcut(ref, _SidebarTab.localHistory); - case HeaderBarAction.sidebarClipboardHistory: - _selectSidebarShortcut(ref, _SidebarTab.clipboard); - case HeaderBarAction.search: - _toggleSearch(ref); - case HeaderBarAction.menu: - break; - } - } - void _handleMainMenuAction( BuildContext context, WidgetRef ref, @@ -1106,11 +972,7 @@ class _WorkspaceScreenContents extends ConsumerWidget { case BusyMarkMainMenuAction.syntaxReference: showBusyMarkSyntaxReferenceDialog(context); case BusyMarkMainMenuAction.reportIssue: - final headerBar = ref.read(linuxHeaderBarServiceProvider); - showBusyMarkFeedbackDialog( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - ); + showBusyMarkFeedbackDialog(context); case BusyMarkMainMenuAction.aboutBusyMark: showBusyMarkAboutDialog(context); } @@ -1131,15 +993,6 @@ class _WorkspaceScreenContents extends ConsumerWidget { return p.basename(path); } - AppViewMode _headerBarViewMode(DocumentViewModePreference mode) { - return switch (mode) { - DocumentViewModePreference.editor => AppViewMode.editor, - DocumentViewModePreference.source => AppViewMode.source, - DocumentViewModePreference.preview => AppViewMode.preview, - DocumentViewModePreference.split => AppViewMode.split, - }; - } - IconData _documentViewModeIcon(DocumentViewModePreference mode) { return switch (mode) { DocumentViewModePreference.editor => BusyMarkGlyphs.editorView, @@ -1170,10 +1023,8 @@ class _WorkspaceScreenContents extends ConsumerWidget { } Future _showProblemsDialog(BuildContext context, WidgetRef ref) async { - final headerBar = ref.read(linuxHeaderBarServiceProvider); await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (dialogContext) => Consumer( builder: (context, ref, _) { final workspace = ref.watch(workspaceControllerProvider).workspace; @@ -1223,17 +1074,6 @@ class _WorkspaceScreenContents extends ConsumerWidget { } } -void _clearGitDetailSelection(WidgetRef ref) { - final gitState = ref.read(gitControllerProvider); - if (gitState.selectedDiff != null || - gitState.selectedFilePath != null || - gitState.selectedCommitHash != null || - gitState.selectedCommitFilePath != null || - gitState.openDiffFilePaths.isNotEmpty) { - ref.read(gitControllerProvider.notifier).clearSelection(); - } -} - Future _showWorkspacePathMenu( BuildContext context, { required String name, @@ -1392,7 +1232,7 @@ class _SidebarState extends ConsumerState<_Sidebar> { final _outlineKey = GlobalKey<_OutlineTabState>(); final _notesKey = GlobalKey(); late final WorkspaceController _topicActionController; - late int _tab; + late _SidebarTab _tab; late String _workspaceId; String? _activeFilePath; _WritersideTopicUsageReview? _topicUsageReview; @@ -1416,9 +1256,12 @@ class _SidebarState extends ConsumerState<_Sidebar> { _topicActionController.renameInspectedTopic = _renameInspectedTopic; _workspaceId = widget.workspace.id; _activeFilePath = widget.workspace.activeFilePath; - _tab = _initialSidebarTabIndex(widget.workspace); + _tab = _initialSidebarTab(widget.workspace); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) { + ref + .read(_sidebarAllocationProvider.notifier) + .select(widget.workspace, _tab); ref.read(_sidebarShortcutRequestProvider.notifier).clear(); } }); @@ -1432,7 +1275,7 @@ class _SidebarState extends ConsumerState<_Sidebar> { _activeFilePath = widget.workspace.activeFilePath; _topicUsageReview = null; _topicRenameReview = null; - _tab = _initialSidebarTabIndex(widget.workspace); + _tab = _initialSidebarTab(widget.workspace); return; } if (widget.workspace.activeFilePath != _activeFilePath) { @@ -1466,158 +1309,174 @@ class _SidebarState extends ConsumerState<_Sidebar> { _selectTab(next, tabs); ref.read(_sidebarShortcutRequestProvider.notifier).clear(); }); - final selectedIndex = tabs.isEmpty - ? 0 - : _tab.clamp(0, tabs.length - 1).toInt(); - final selectedTab = tabs.isEmpty ? null : tabs[selectedIndex]; - return BusyMarkSidebarSurface( - showEndBorder: false, - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, + final selectedTab = tabs.contains(_tab) + ? _tab + : _initialSidebarTab(widget.workspace); + final renameReview = selectedTab == _SidebarTab.recent + ? null + : _topicRenameReview; + final usageReview = selectedTab == _SidebarTab.recent + ? null + : _topicUsageReview; + final colors = BusyMarkSurfaceColors.of(context); + final direction = Directionality.of(context); + final workspace = widget.workspace; + final path = _workspacePath(workspace); + return WorkspaceSidebar<_SidebarTab>( + contextLabel: _SidebarHeaderLine( + key: const ValueKey('workspace-sidebar-primary-label'), + icon: WorkspaceGlyphs.forKind(workspace.kind), + text: _workspaceDisplayName(context, workspace), + tooltip: + selectedTab == _SidebarTab.git || selectedTab == _SidebarTab.gitLog + ? busyMarkLtrIsolateFor(context, path) + : null, + style: Theme.of( + context, + ).textTheme.bodyMedium?.copyWith(color: colors.foreground), + ), + items: [ + for (final tab in tabs) + BusyMarkPopupMenuItem( + value: tab, + label: _sidebarTabLabel(context, tab), + mnemonic: _sidebarTabMnemonic(tab), + enabled: _sidebarTabAvailable(ref, tab), + icon: _sidebarTabIcon(tab, direction), + iconColor: tab == _SidebarTab.git ? colors.foreground : null, + shortcut: _sidebarTabMnemonic(tab), + gtkAccelerator: _sidebarTabMnemonic(tab).toLowerCase(), + checked: tab == selectedTab, + trailingCheck: true, + ), + ], + onSelected: (tab) { + if (_sidebarTabAvailable(ref, tab)) _selectTab(tab, tabs); + }, + viewHeader: _SidebarHeader( + workspace: workspace, + selectedTab: selectedTab, + onRefineActiveDocument: () => + unawaited(_refineActiveDocumentWithAi(context)), + ), + onReviewReplacement: _reviewWorkspaceReplacement, + content: Stack( + fit: StackFit.expand, children: [ - if (!widget.searchState.active) - _SidebarHeader( - workspace: widget.workspace, - tabs: tabs, - selectedTab: selectedTab, - showTabMenu: tabs.length > 1, - onSelectTab: (tab) => _selectTab(tab, tabs), - onRefineActiveDocument: () => - unawaited(_refineActiveDocumentWithAi(context)), - ), - Expanded( - child: Stack( - fit: StackFit.expand, - children: [ - Offstage( - offstage: - widget.searchState.active || - selectedTab != _SidebarTab.outline, - child: ExcludeFocus( - excluding: - widget.searchState.active || - selectedTab != _SidebarTab.outline, - child: TickerMode( - enabled: - !widget.searchState.active && - selectedTab == _SidebarTab.outline, - child: _OutlineTab( - key: _outlineKey, - workspace: widget.workspace, - bufferId: ref - .watch(workspaceControllerProvider) - .activeBufferId, - headings: widget.outline, - ), - ), - ), - ), - Offstage( - offstage: - widget.searchState.active || - (selectedTab != _SidebarTab.git && - selectedTab != _SidebarTab.gitLog), - child: ExcludeFocus( - excluding: - widget.searchState.active || - (selectedTab != _SidebarTab.git && - selectedTab != _SidebarTab.gitLog), - child: BusyMarkSharedGitSidebar( - onSelectView: (view) => _selectTab( - view == shared.GitSidebarView.log - ? _SidebarTab.gitLog - : _SidebarTab.git, - tabs, - ), - workspace: widget.workspace, - log: selectedTab == _SidebarTab.gitLog, - active: - !widget.searchState.active && - (selectedTab == _SidebarTab.git || - selectedTab == _SidebarTab.gitLog), - ), - ), + Offstage( + offstage: + widget.searchState.active || selectedTab != _SidebarTab.outline, + child: ExcludeFocus( + excluding: + widget.searchState.active || + selectedTab != _SidebarTab.outline, + child: TickerMode( + enabled: + !widget.searchState.active && + selectedTab == _SidebarTab.outline, + child: _OutlineTab( + key: _outlineKey, + workspace: widget.workspace, + bufferId: ref + .watch(workspaceControllerProvider) + .activeBufferId, + headings: widget.outline, ), - Offstage( - offstage: - !widget.searchState.active && - (selectedTab == _SidebarTab.outline || - selectedTab == _SidebarTab.git || - selectedTab == _SidebarTab.gitLog), - child: ExcludeFocus( - excluding: - !widget.searchState.active && - (selectedTab == _SidebarTab.outline || - selectedTab == _SidebarTab.git || - selectedTab == _SidebarTab.gitLog), - child: BusyMarkKeyedCrossfade( - transitionKey: widget.searchState.active - ? 'search' - : _topicRenameReview != null - ? 'rename' - : _topicUsageReview != null - ? 'usages' - : selectedTab ?? 'empty', - child: widget.searchState.active - ? SearchSidebar( - onReviewReplacement: _reviewWorkspaceReplacement, - ) - : _topicRenameReview != null - ? _WritersideTopicRenameSidebar( - plan: _topicRenameReview!, - onBack: () => - setState(() => _topicRenameReview = null), - onDoRefactor: () => - _applyReviewedTopicRename(context), - ) - : _topicUsageReview != null - ? _WritersideTopicUsagesSidebar( - review: _topicUsageReview!, - onBack: _closeTopicUsageReview, - onOpenUsage: (usage) => - _openWritersideTopicUsage(context, usage), - onDoRefactor: () => - _resumeWritersideTopicRemoval(context), - ) - : switch (selectedTab) { - _SidebarTab.notes => NextcloudNotesSidebar( - key: _notesKey, - accountId: widget.workspace.nextcloudAccountId!, - ), - _SidebarTab.files => _FilesTab( - workspace: widget.workspace, - onShowFileHistory: _showFileHistory, - onRenameTopic: (path) => - _startWritersideTopicRename(context, path), - onRequestTopicRemoval: (target) => - _runWritersideTopicRemoval(context, target), - ), - _SidebarTab.toc => _TocTab( - workspace: widget.workspace, - onShowFileHistory: _showFileHistory, - onRenameTopic: (path) => - _startWritersideTopicRename(context, path), - onRequestTopicRemoval: (target) => - _runWritersideTopicRemoval(context, target), - ), - _SidebarTab.outline => const SizedBox.shrink(), - _SidebarTab.git || - _SidebarTab.gitLog => const SizedBox.shrink(), - _SidebarTab.clipboard => ClipboardHistoryPanel( - onEscape: () => ref - .read(clipboardInsertionRegistryProvider) - .target - ?.requestEditorFocus(), - ), - _SidebarTab.references => const ReferencesPanel(), - _SidebarTab.localHistory => - const LocalHistoryPanel(), - null => const SizedBox.shrink(), - }, - ), - ), + ), + ), + ), + Offstage( + offstage: + widget.searchState.active || + (selectedTab != _SidebarTab.git && + selectedTab != _SidebarTab.gitLog), + child: ExcludeFocus( + excluding: + widget.searchState.active || + (selectedTab != _SidebarTab.git && + selectedTab != _SidebarTab.gitLog), + child: BusyMarkSharedGitSidebar( + onSelectView: (view) => _selectTab( + view == shared.GitSidebarView.log + ? _SidebarTab.gitLog + : _SidebarTab.git, + tabs, ), - ], + workspace: widget.workspace, + log: selectedTab == _SidebarTab.gitLog, + active: + !widget.searchState.active && + (selectedTab == _SidebarTab.git || + selectedTab == _SidebarTab.gitLog), + ), + ), + ), + Offstage( + offstage: + (selectedTab == _SidebarTab.outline || + selectedTab == _SidebarTab.git || + selectedTab == _SidebarTab.gitLog), + child: ExcludeFocus( + excluding: + (selectedTab == _SidebarTab.outline || + selectedTab == _SidebarTab.git || + selectedTab == _SidebarTab.gitLog), + child: BusyMarkKeyedCrossfade( + transitionKey: renameReview != null + ? 'rename' + : usageReview != null + ? 'usages' + : selectedTab, + child: renameReview != null + ? _WritersideTopicRenameSidebar( + plan: renameReview, + onBack: () => setState(() => _topicRenameReview = null), + onDoRefactor: () => _applyReviewedTopicRename(context), + ) + : usageReview != null + ? _WritersideTopicUsagesSidebar( + review: usageReview, + onBack: _closeTopicUsageReview, + onOpenUsage: (usage) => + _openWritersideTopicUsage(context, usage), + onDoRefactor: () => + _resumeWritersideTopicRemoval(context), + ) + : switch (selectedTab) { + _SidebarTab.notes => NextcloudNotesSidebar( + key: _notesKey, + accountId: widget.workspace.nextcloudAccountId!, + ), + _SidebarTab.files => _FilesTab( + workspace: widget.workspace, + onShowFileHistory: _showFileHistory, + onRenameTopic: (path) => + _startWritersideTopicRename(context, path), + onRequestTopicRemoval: (target) => + _runWritersideTopicRemoval(context, target), + ), + _SidebarTab.toc => _TocTab( + workspace: widget.workspace, + onShowFileHistory: _showFileHistory, + onRenameTopic: (path) => + _startWritersideTopicRename(context, path), + onRequestTopicRemoval: (target) => + _runWritersideTopicRemoval(context, target), + ), + _SidebarTab.outline => const SizedBox.shrink(), + _SidebarTab.git || + _SidebarTab.gitLog => const SizedBox.shrink(), + _SidebarTab.clipboard => ClipboardHistoryPanel( + onEscape: () => ref + .read(clipboardInsertionRegistryProvider) + .target + ?.requestEditorFocus(), + ), + _SidebarTab.references => const ReferencesPanel(), + _SidebarTab.localHistory => const LocalHistoryPanel(), + _SidebarTab.recent => const RecentSidebarPanel(), + }, + ), ), ), ], @@ -1631,13 +1490,8 @@ class _SidebarState extends ConsumerState<_Sidebar> { bool showGitChanges = true, }) { ref.read(searchSessionProvider.notifier).close(restoreFocus: false); - final index = tabs.indexOf(tab); - if (index < 0) { - return; - } - setState(() { - _tab = index; - }); + if (!tabs.contains(tab)) return; + setState(() => _tab = tab); ref.read(_sidebarAllocationProvider.notifier).select(widget.workspace, tab); if (tab == _SidebarTab.outline || tab == _SidebarTab.notes) { WidgetsBinding.instance.addPostFrameCallback((_) { @@ -1761,7 +1615,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { if (!mounted || !context.mounted) return; if (applied) { setState(() => _topicRenameReview = null); - _clearGitDetailSelection(ref); } else { _showLatestWorkspaceMessage(this.context); } @@ -1807,11 +1660,9 @@ class _SidebarState extends ConsumerState<_Sidebar> { redirectTarget: initialRedirect, ); } else { - final headerBar = ref.read(linuxHeaderBarServiceProvider); final selected = await showBusyMarkModalDialog<_WritersideTopicRemovalDialogResult>( context, - headerBarService: headerBar.isAvailable ? headerBar : null, barrierDismissible: false, builder: (dialogContext) => _WritersideTopicRemovalDialog( analysis: analysis, @@ -1871,7 +1722,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { return null; } setState(() => _topicUsageReview = null); - _clearGitDetailSelection(ref); if (target.mode == WritersideTopicRemovalMode.removeFromInstance && result.orphaned && !result.deletedFile) { @@ -1895,7 +1745,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { void _closeTopicUsageReview() { setState(() => _topicUsageReview = null); - _clearGitDetailSelection(ref); } Future _resumeWritersideTopicRemoval(BuildContext context) async { @@ -1978,7 +1827,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { return; } setState(() => _topicUsageReview = null); - _clearGitDetailSelection(ref); if (review.target.mode == WritersideTopicRemovalMode.removeFromInstance && result.orphaned && !result.deletedFile) { @@ -2018,7 +1866,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { sourceOffset: usage.span?.startOffset, ), ); - _clearGitDetailSelection(ref); } void _showLatestWorkspaceMessage(BuildContext context) { @@ -2058,10 +1905,8 @@ class _SidebarState extends ConsumerState<_Sidebar> { if (!currentRequest() || widget.workspace.isRemote) return; var replacement = ''; - final headerBar = ref.read(linuxHeaderBarServiceProvider); final requested = await showBusyMarkModalEditorDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, maxWidth: BusyMarkSizes.dialogCompact, builder: (dialogContext) => BusyMarkModalEditorScaffold( title: context.l10n.workspaceReplace, @@ -2102,7 +1947,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { final preview = await showBusyMarkModalEditorDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, maxWidth: BusyMarkSizes.dialogCompact, builder: (dialogContext) => _WorkspaceReplacementProgress( future: previewFuture, @@ -2127,7 +1971,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { } final selected = await showBusyMarkModalEditorDialog>( context, - headerBarService: headerBar.isAvailable ? headerBar : null, maxWidth: BusyMarkSizes.dialogWide, maxHeight: 800, builder: (dialogContext) => @@ -2179,7 +2022,6 @@ class _SidebarState extends ConsumerState<_Sidebar> { if (result.issues.isNotEmpty) { await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (dialogContext) => BusyMarkDialogShell( title: context.l10n.workspaceReplace, maxWidth: BusyMarkSizes.dialogWide, @@ -2239,15 +2081,17 @@ class _SidebarState extends ConsumerState<_Sidebar> { ); } - int _initialSidebarTabIndex(Workspace workspace) { + _SidebarTab _initialSidebarTab(Workspace workspace) { final tabs = _sidebarTabsFor(workspace.kind); final request = ref.read(_sidebarShortcutRequestProvider); - final requestedIndex = request == null ? -1 : tabs.indexOf(request); - return requestedIndex >= 0 - ? requestedIndex - : (tabs.contains(_SidebarTab.files) - ? tabs.indexOf(_SidebarTab.files) - : _preferredSidebarTabIndex(workspace)); + if (request != null && tabs.contains(request)) return request; + return switch (workspace.kind) { + WorkspaceKind.nextcloudNotes => _SidebarTab.notes, + WorkspaceKind.markdownFolder || + WorkspaceKind.writersideModule => _SidebarTab.files, + WorkspaceKind.singleMarkdown || + WorkspaceKind.untitledMarkdown => _SidebarTab.outline, + }; } } @@ -2261,21 +2105,7 @@ enum _SidebarTab { localHistory, clipboard, references, -} - -int _preferredSidebarTabIndex(Workspace workspace) { - final tabs = _sidebarTabsFor(workspace.kind); - if (_shouldShowOutlineForOpenFile(workspace)) { - final outlineIndex = tabs.indexOf(_SidebarTab.outline); - if (outlineIndex >= 0) { - return outlineIndex; - } - } - return 0; -} - -bool _shouldShowOutlineForOpenFile(Workspace workspace) { - return workspace.activeFilePath != null && workspace.markdown != null; + recent, } bool _hasWorkspaceSidebar(Workspace workspace) { @@ -2290,18 +2120,21 @@ List<_SidebarTab> _sidebarTabsFor(WorkspaceKind kind) { _SidebarTab.localHistory, _SidebarTab.clipboard, _SidebarTab.references, + _SidebarTab.recent, ], WorkspaceKind.untitledMarkdown => const [ _SidebarTab.outline, _SidebarTab.localHistory, _SidebarTab.clipboard, _SidebarTab.references, + _SidebarTab.recent, ], WorkspaceKind.singleMarkdown => const [ _SidebarTab.outline, _SidebarTab.localHistory, _SidebarTab.clipboard, _SidebarTab.references, + _SidebarTab.recent, ], WorkspaceKind.markdownFolder => const [ _SidebarTab.files, @@ -2311,6 +2144,7 @@ List<_SidebarTab> _sidebarTabsFor(WorkspaceKind kind) { _SidebarTab.localHistory, _SidebarTab.clipboard, _SidebarTab.references, + _SidebarTab.recent, ], WorkspaceKind.writersideModule => const [ _SidebarTab.files, @@ -2321,6 +2155,7 @@ List<_SidebarTab> _sidebarTabsFor(WorkspaceKind kind) { _SidebarTab.localHistory, _SidebarTab.clipboard, _SidebarTab.references, + _SidebarTab.recent, ], }; } @@ -2336,6 +2171,7 @@ String _sidebarTabLabel(BuildContext context, _SidebarTab tab) { _SidebarTab.localHistory => context.l10n.localHistory, _SidebarTab.clipboard => context.l10n.clipboardHistory, _SidebarTab.references => context.l10n.references, + _SidebarTab.recent => context.l10n.recent, }; } @@ -2350,6 +2186,7 @@ IconData _sidebarTabIcon(_SidebarTab tab, TextDirection direction) { _SidebarTab.localHistory => BusyMarkGlyphs.sidebarLocalHistory, _SidebarTab.clipboard => BusyMarkGlyphs.copy, _SidebarTab.references => BusyMarkGlyphs.link, + _SidebarTab.recent => BusyMarkGlyphs.history, }; } @@ -2370,23 +2207,18 @@ String _sidebarTabMnemonic(_SidebarTab tab) => switch (tab) { _SidebarTab.localHistory => 'L', _SidebarTab.clipboard => 'B', _SidebarTab.references => 'R', + _SidebarTab.recent => 'E', }; class _SidebarHeader extends ConsumerWidget { const _SidebarHeader({ required this.workspace, - required this.tabs, required this.selectedTab, - required this.showTabMenu, - required this.onSelectTab, required this.onRefineActiveDocument, }); final Workspace workspace; - final List<_SidebarTab> tabs; - final _SidebarTab? selectedTab; - final bool showTabMenu; - final ValueChanged<_SidebarTab> onSelectTab; + final _SidebarTab selectedTab; final VoidCallback onRefineActiveDocument; @override @@ -2407,76 +2239,9 @@ class _SidebarHeader extends ConsumerWidget { context, ).textTheme.bodySmall?.copyWith(color: colors.mutedForeground); final direction = Directionality.of(context); - final tabMenuItems = >[ - for (final tab in tabs) - BusyMarkPopupMenuItem( - value: tab, - label: _sidebarTabLabel(context, tab), - mnemonic: _sidebarTabMnemonic(tab), - enabled: _sidebarTabAvailable(ref, tab), - icon: _sidebarTabIcon(tab, direction), - iconColor: tab == _SidebarTab.git ? colors.foreground : null, - shortcut: _sidebarTabMnemonic(tab), - gtkAccelerator: _sidebarTabMnemonic(tab).toLowerCase(), - checked: tab == selectedTab, - trailingCheck: true, - ), - ]; - final buildTabMenu = BusyMarkHeaderPopupMenuButton<_SidebarTab>.native; - final selectedTabMenuItem = selectedTab == null - ? null - : tabMenuItems.firstWhere((item) => item.menuValue == selectedTab); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: BusyMarkInsets.sidebarHeader, - child: _SidebarHeaderRow( - key: const ValueKey('workspace-sidebar-primary-row'), - child: Row( - children: [ - Expanded( - child: _SidebarHeaderLine( - key: const ValueKey('workspace-sidebar-primary-label'), - icon: WorkspaceGlyphs.forKind(workspace.kind), - text: _workspaceDisplayName(context, workspace), - tooltip: - selectedTab == _SidebarTab.git || - selectedTab == _SidebarTab.gitLog - ? busyMarkLtrIsolateFor(context, path) - : null, - style: Theme.of( - context, - ).textTheme.bodyMedium?.copyWith(color: colors.foreground), - ), - ), - if (showTabMenu && selectedTabMenuItem != null) ...[ - const SizedBox(width: BusyMarkSpacing.sm), - buildTabMenu( - key: const ValueKey('workspace-sidebar-view-menu'), - controller: ref.watch(_sidebarViewMenuControllerProvider), - tooltip: context.l10n.sidebarViewMenu, - shortcut: - (BusyMarkCommandRegistryScope.read(context) ?? - BusyMarkCommandCatalog - .metadata)[BusyMarkCommandIds - .sidebarViewSelector] - ?.shortcut - ?.label, - icon: BusyMarkGlyphs.sidebarViews, - transparent: true, - borderRadius: BusyMarkRadius.nativeHeaderButton, - highlightWhenOpen: false, - itemBuilder: (context) => tabMenuItems, - onSelected: (tab) { - if (_sidebarTabAvailable(ref, tab)) onSelectTab(tab); - }, - ), - ], - ], - ), - ), - ), if (selectedTab == _SidebarTab.files) BusyMarkSidebarHeader( key: const ValueKey('workspace-sidebar-first-content'), @@ -2584,62 +2349,48 @@ class _SidebarHeader extends ConsumerWidget { ], ); } +} - String _workspaceName(BuildContext context, Workspace workspace) { - if (workspace.isRemote) return context.l10n.nextcloudNotes; - if (workspace.kind == WorkspaceKind.untitledMarkdown) { - final filePath = workspace.markdown?.filePath; - return filePath == null || filePath.isEmpty - ? context.l10n.untitledMarkdownFileName - : filePath; - } - if (workspace.kind == WorkspaceKind.writersideModule) { - final moduleName = workspace.writersideModule?.config.moduleName?.trim(); - if (moduleName != null && moduleName.isNotEmpty) { - return moduleName; - } - } - final path = _workspacePath(workspace); - final segments = path.split('/').where((segment) => segment.isNotEmpty); - return segments.isEmpty ? path : segments.last; - } - - String _workspaceDisplayName(BuildContext context, Workspace workspace) { - final name = _workspaceName(context, workspace); +String _workspaceName(BuildContext context, Workspace workspace) { + if (workspace.isRemote) return context.l10n.nextcloudNotes; + if (workspace.kind == WorkspaceKind.untitledMarkdown) { final filePath = workspace.markdown?.filePath; - final localizedUntitled = - workspace.kind == WorkspaceKind.untitledMarkdown && - (filePath == null || filePath.isEmpty); - return localizedUntitled ? name : busyMarkLtrIsolateFor(context, name); + return filePath == null || filePath.isEmpty + ? context.l10n.untitledMarkdownFileName + : filePath; } - - String _workspacePath(Workspace workspace) { - if (workspace.kind == WorkspaceKind.singleMarkdown) { - return workspace.activeFilePath ?? - workspace.markdown?.filePath ?? - (workspace.filesystemRootPath ?? ''); + if (workspace.kind == WorkspaceKind.writersideModule) { + final moduleName = workspace.writersideModule?.config.moduleName?.trim(); + if (moduleName != null && moduleName.isNotEmpty) { + return moduleName; } - return (workspace.filesystemRootPath ?? ''); } + final path = _workspacePath(workspace); + final segments = path.split('/').where((segment) => segment.isNotEmpty); + return segments.isEmpty ? path : segments.last; } -typedef _SidebarHeaderSecondaryTapHandler = - Future Function(BuildContext context, TapUpDetails details); - -class _SidebarHeaderRow extends StatelessWidget { - const _SidebarHeaderRow({super.key, required this.child}); - - final Widget child; +String _workspaceDisplayName(BuildContext context, Workspace workspace) { + final name = _workspaceName(context, workspace); + final filePath = workspace.markdown?.filePath; + final localizedUntitled = + workspace.kind == WorkspaceKind.untitledMarkdown && + (filePath == null || filePath.isEmpty); + return localizedUntitled ? name : busyMarkLtrIsolateFor(context, name); +} - @override - Widget build(BuildContext context) { - return ConstrainedBox( - constraints: const BoxConstraints(minHeight: BusyMarkSizes.iconButton), - child: child, - ); +String _workspacePath(Workspace workspace) { + if (workspace.kind == WorkspaceKind.singleMarkdown) { + return workspace.activeFilePath ?? + workspace.markdown?.filePath ?? + (workspace.filesystemRootPath ?? ''); } + return (workspace.filesystemRootPath ?? ''); } +typedef _SidebarHeaderSecondaryTapHandler = + Future Function(BuildContext context, TapUpDetails details); + class _SidebarHeaderLine extends StatelessWidget { const _SidebarHeaderLine({ super.key, @@ -3656,9 +3407,6 @@ class _FilesTabState extends ConsumerState<_FilesTab> { await ref .read(workspaceControllerProvider.notifier) .openActiveFile(file.absolutePath); - if (mounted) { - _clearGitDetailSelection(ref); - } } : null, onMenuRequested: showMenu, @@ -3717,10 +3465,9 @@ class _FilesTabState extends ConsumerState<_FilesTab> { } final created = await ref .read(workspaceControllerProvider.notifier) - .createWorkspaceFile(directory, fileName); + .createWorkspaceFile(directory, fileName, focusSource: true); if (created) { _expandedPaths.addAll(_directoryAncestorPaths(directory)); - _clearGitDetailSelection(ref); } case _FileTreeAction.rename: final renamed = isTopic @@ -3755,7 +3502,6 @@ class _FilesTabState extends ConsumerState<_FilesTab> { }()); if (renamed) { setState(() => _cutEntry = null); - _clearGitDetailSelection(ref); } case _FileTreeAction.cut: setState(() { @@ -3786,7 +3532,6 @@ class _FilesTabState extends ConsumerState<_FilesTab> { if (moved) { setState(() => _cutEntry = null); _expandedPaths.addAll(_directoryAncestorPaths(directory)); - _clearGitDetailSelection(ref); } case _FileTreeAction.delete: final matchingEntry = _fileTreeEntryForPath(path); @@ -3923,7 +3668,6 @@ class _FilesTabState extends ConsumerState<_FilesTab> { } else if (_sameOptionalPath(_selectedPath, path)) { setState(() => _selectedPath = null); } - _clearGitDetailSelection(ref); } Iterable _directoryAncestorPaths(String absoluteDirectory) { @@ -4242,10 +3986,8 @@ Future _confirmDeleteFileTreeEntry( required String name, required bool isFolder, }) async { - final headerBar = ref.read(linuxHeaderBarServiceProvider); final confirmed = await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: isFolder ? context.l10n.confirmDeleteFolderTitle @@ -5063,9 +4805,6 @@ class _TocTabState extends ConsumerState<_TocTab> { await ref .read(workspaceControllerProvider.notifier) .openActiveFile(topicPath); - if (mounted) { - _clearGitDetailSelection(ref); - } } : hasChildren ? () { @@ -5251,7 +4990,6 @@ class _TocTabState extends ConsumerState<_TocTab> { _selectedNodePathKeys = {}; _selectionAnchorPathKey = null; }); - _clearGitDetailSelection(ref); return; } @@ -5284,7 +5022,6 @@ class _TocTabState extends ConsumerState<_TocTab> { _selectedNodePathKeys = {}; _selectionAnchorPathKey = null; }); - _clearGitDetailSelection(ref); } Future _removeTocEntries( @@ -5349,7 +5086,6 @@ class _TocTabState extends ConsumerState<_TocTab> { _selectedNodePathKeys = {}; _selectionAnchorPathKey = null; }); - _clearGitDetailSelection(ref); } Future _copyTocEntries(List<_TocTreeEntry> entries) async { @@ -5847,7 +5583,6 @@ class _TocTabState extends ConsumerState<_TocTab> { } if (renamed) { setState(() => _cutEntries = []); - _clearGitDetailSelection(ref); } case _TocTreeAction.cut: if (!canEditSelection) { @@ -5940,7 +5675,6 @@ class _TocTabState extends ConsumerState<_TocTab> { _selectedNodePathKeys = {}; _selectionAnchorPathKey = null; }); - _clearGitDetailSelection(ref); } case _TocTreeAction.removeFromToc: if (!canEditStructure) { @@ -5980,13 +5714,11 @@ class _TocTabState extends ConsumerState<_TocTab> { if (!canContinue || !mounted || !context.mounted) { return; } - final headerBar = ref.read(linuxHeaderBarServiceProvider); final dialogResult = await showBusyMarkModalEditorDialog< BusyMarkWritersideInstanceDialogResult >( context, - headerBarService: headerBar.isAvailable ? headerBar : null, maxWidth: BusyMarkSizes.dialogWide, builder: (dialogContext) => BusyMarkWritersideInstanceDialog( workspace: widget.workspace, @@ -6157,10 +5889,8 @@ class _TocTabState extends ConsumerState<_TocTab> { final referenceIdentity = rawReference == null ? null : WritersideTocNodeIdentity.fromNode(rawReference); - final headerBar = ref.read(linuxHeaderBarServiceProvider); await showBusyMarkModalEditorDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, maxWidth: 680, builder: (dialogContext) => _CreateWritersideTopicDialog( workspace: widget.workspace, @@ -6479,11 +6209,25 @@ class _TocTabState extends ConsumerState<_TocTab> { includeTitleHeading: true, ), ); - return _PreviewPane( - preview: preview, - workspace: null, - controller: previewScroll, - documentLayout: BusyMarkDocumentLayoutSpec.splitPreview, + return Consumer( + builder: (context, ref, child) { + final settings = ref.watch(appSettingsControllerProvider); + final allowed = + settings.allowRemoteImages || + settings.remoteImageAllowedWorkspaceIds.contains( + remoteImageWorkspaceId(widget.workspace), + ); + return MarkdownImagePermissionScope( + resolve: (_, _, _) => MarkdownImageActions(allowed: allowed), + child: child!, + ); + }, + child: _PreviewPane( + preview: preview, + workspace: null, + controller: previewScroll, + documentLayout: BusyMarkDocumentLayoutSpec.splitPreview, + ), ); }, onCreate: (template, title, filename) async { @@ -7208,10 +6952,8 @@ Future _confirmRemoveTocEntry( WidgetRef ref, { int count = 1, }) async { - final headerBar = ref.read(linuxHeaderBarServiceProvider); final confirmed = await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: count == 1 ? context.l10n.removeTocElement @@ -7399,7 +7141,7 @@ class _TocHeader extends StatelessWidget { padding: const EdgeInsetsDirectional.only( start: BusyMarkSpacing.sm, ), - child: _SidebarHeaderRow( + child: WorkspaceSidebarHeaderRow( child: Row( children: [ Expanded( @@ -8804,10 +8546,8 @@ Future _confirmDeleteOutlineSection( WidgetRef ref, String heading, ) async { - final headerBar = ref.read(linuxHeaderBarServiceProvider); final confirmed = await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkDialogShell( title: context.l10n.confirmDeleteSectionTitle, maxWidth: BusyMarkSizes.dialog, @@ -9090,7 +8830,6 @@ class _EditorTabStrip extends ConsumerWidget { return const SizedBox.shrink(); } final entries = workspaceTabEntries( - workspace: workspace, gitTabs: ref.watch(sharedGitReviewProvider)[workspace.id] ?? const SharedGitTabs(), @@ -9192,7 +8931,6 @@ class _EditorTabStrip extends ConsumerWidget { Workspace workspace, WorkspaceTabEntry entry, ) async { - final gitController = ref.read(gitControllerProvider.notifier); switch (entry.kind) { case WorkspaceTabKind.file: ref.read(sharedGitReviewProvider.notifier).deactivate(workspace.id); @@ -9206,7 +8944,6 @@ class _EditorTabStrip extends ConsumerWidget { .selectDocumentForBuffer(buffer), ); } - gitController.deactivateDiffFile(); return; } final activated = await ref @@ -9222,14 +8959,12 @@ class _EditorTabStrip extends ConsumerWidget { ); } } - gitController.deactivateDiffFile(); case WorkspaceTabKind.gitDiff: ref .read(sharedGitReviewProvider.notifier) .activate(workspace.id, entry.comparisonId!); case WorkspaceTabKind.localHistory: ref.read(sharedGitReviewProvider.notifier).deactivate(workspace.id); - gitController.deactivateDiffFile(); } } } @@ -9595,8 +9330,7 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { // between Undo and Redo. Editor selection restoration remains independent. _pendingInspectorHistoryRestore = null; _trackInspectedHistory(previousBuffer, nextBuffer); - final document = _wysiwygDocument(); - _refreshInspectedElement(document); + _refreshInspectedElement(); } _spelling.synchronizeOpenBuffers( widget.state.documentBuffers.map((buffer) => buffer.id), @@ -9744,10 +9478,6 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { } final colors = BusyMarkSurfaceColors.of(context); final settings = ref.watch(appSettingsControllerProvider); - final headerBar = ref.watch(linuxHeaderBarServiceProvider); - final allowRemoteImages = settings.allowsRemoteImagesForWorkspace( - _remoteImageWorkspacePath(widget.state.workspace), - ); final editorVisible = widget.viewMode == DocumentViewModePreference.editor; final wysiwygDocument = editorVisible && _canUseWysiwyg(widget.state.workspace) @@ -9761,6 +9491,20 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { widget.viewMode != DocumentViewModePreference.preview && !wysiwygVisible; final activeBuffer = widget.state.activeBuffer; + final creationFocus = ref + .read(workspaceControllerProvider.notifier) + .sourceCreationFocus(activeBuffer?.id); + if (wysiwygVisible && creationFocus?.isPending == true) { + WidgetsBinding.instance.addPostFrameCallback((_) { + final editor = _wysiwygEditorKey.currentState; + if (mounted && + editor != null && + widget.state.activeBufferId == activeBuffer?.id && + creationFocus!.consume(editor.context)) { + editor.focusNewDocument(); + } + }); + } final remoteRef = activeBuffer?.remoteNote; final repository = remoteRef == null ? null @@ -9981,7 +9725,6 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { .retain, initialSessionState: activeBuffer.editorState.wysiwygState, - useExternalUndoHistory: true, onSessionChanged: (documentId, session) { final latest = ref .read(workspaceControllerProvider) @@ -10004,7 +9747,6 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { ), ); }, - headerBarService: headerBar, workspaceRoot: _imageWorkspaceRoot( widget.state.workspace, ), @@ -10040,10 +9782,6 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { onAssetSaveRequired: () => unawaited( saveActiveToNewLocation(context, ref), ), - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: () => unawaited( - _showRemoteImagesPrompt(context, ref), - ), onDocumentChanged: (document) => _cacheWysiwygDocument( activeBuffer.id, @@ -10153,6 +9891,7 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { ), filePath: activeEditorPath, documentId: activeBuffer?.id, + creationFocus: creationFocus, clipboardInsertionRegistry: ref.read( clipboardInsertionRegistryProvider, ), @@ -10430,7 +10169,13 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { ), ), ); - return DocumentMediaScope( + final workspace = widget.state.workspace; + final controller = ref.read(workspaceControllerProvider.notifier); + final workspaceId = remoteImageWorkspaceId(workspace); + final parserPath = activeBuffer == null || workspace == null + ? null + : resolveWorkspaceDocumentContext(workspace, activeBuffer).parserPath; + final mediaScope = DocumentMediaScope( media: remoteRef == null ? null : media?.context ?? DocumentMediaContext.unavailable, @@ -10439,6 +10184,78 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { child: _withProperties(editor), ), ); + return ListenableBuilder( + listenable: controller.remoteImages, + child: mediaScope, + builder: (context, child) => MarkdownImagePermissionScope( + resolve: (source, span, renderedSource) { + final ownedSpan = span?.filePath == parserPath ? span : null; + final allowed = + allowsWorkspaceRemoteImages(settings, workspace) || + (activeBuffer != null && + controller.remoteImages.allows( + activeBuffer, + renderedSource, + ownedSpan, + source, + )); + if (allowed || + activeBuffer == null || + activeBuffer.text != renderedSource) { + return MarkdownImageActions(allowed: allowed); + } + return MarkdownImageActions( + allowed: false, + documentOpening: activeBuffer.opening, + openMenu: (anchor, position, session) async { + final target = controller.captureRemoteImagePermission( + activeBuffer, + renderedSource, + ownedSpan, + source, + workspaceId, + ); + if (target == null) return; + try { + final l10n = anchor.l10n; + final action = await showBusyMarkNativeContextMenu( + anchor, + position, + session: session, + items: >[ + BusyMarkPopupMenuItem( + value: RemoteImagePermission.image, + label: l10n.loadThisRemoteImage, + enabled: target.hasOccurrence, + ), + BusyMarkPopupMenuItem( + value: RemoteImagePermission.document, + label: l10n.loadRemoteImagesInDocument, + ), + if (target.workspaceId != null) + BusyMarkPopupMenuItem( + value: RemoteImagePermission.workspace, + label: l10n.loadRemoteImagesForWorkspace, + ), + const PopupMenuDivider(), + BusyMarkPopupMenuItem( + value: RemoteImagePermission.global, + label: l10n.alwaysLoadRemoteImages, + ), + ], + ); + if (action != null) { + await controller.grantRemoteImagePermission(target, action); + } + } finally { + controller.remoteImages.release(target); + } + }, + ); + }, + child: child!, + ), + ); } WritersidePropertySession get _propertyEdits => @@ -10477,12 +10294,11 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { _inspected = restored; } }); - final document = _wysiwygDocument(); - _refreshInspectedElement(document); + _refreshInspectedElement(); }); } - void _refreshInspectedElement(BusyDocument? document) { + void _refreshInspectedElement([BusyDocument? document]) { final live = ref.read(workspaceControllerProvider).activeBuffer; final captured = _inspected; if (live == null || @@ -10492,6 +10308,7 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { captured.matches(live.id, live.revision, live.text)) { return; } + document ??= _wysiwygDocument(); final refreshed = document == null ? null : captured.refreshUnchangedElement( @@ -10682,6 +10499,12 @@ class _EditorPreviewSplitState extends ConsumerState<_EditorPreviewSplit> { Widget _withProperties(Widget editor) { final settings = ref.watch(appSettingsControllerProvider); + if (!settings.elementPropertiesVisible) return editor; + final kind = _activeDocumentKind(widget.state.workspace); + if (kind != DocumentKind.writersideXmlTopic && + kind != DocumentKind.writersideMarkdownTopic) { + return editor; + } final document = _wysiwygDocument(); final writerside = document?.isWriterside == true || @@ -13301,23 +13124,30 @@ class _PreviewPane extends StatelessWidget { title: context.l10n.nothingToRead, ); } - return WritersidePreviewScope( - key: ValueKey(workspace?.activeFilePath), - child: DecoratedBox( - decoration: BoxDecoration(color: colors.view), - child: SelectionArea( - child: ScrollablePositionedList.builder( - key: const ValueKey('preview-document-scroll'), - itemScrollController: controller, - itemPositionsListener: itemPositionsListener, - padding: documentLayout.scrollPadding, - itemCount: document.blocks.length, - itemBuilder: (context, index) => BusyMarkDocumentContentFrame( - layout: documentLayout, - contentKey: index == 0 - ? const ValueKey('preview-document-content') - : null, - child: _keyedPreviewBlock(context, index, document.blocks[index]), + return MarkdownImageProjection( + source: document.source, + child: WritersidePreviewScope( + key: ValueKey(workspace?.activeFilePath), + child: DecoratedBox( + decoration: BoxDecoration(color: colors.view), + child: SelectionArea( + child: ScrollablePositionedList.builder( + key: const ValueKey('preview-document-scroll'), + itemScrollController: controller, + itemPositionsListener: itemPositionsListener, + padding: documentLayout.scrollPadding, + itemCount: document.blocks.length, + itemBuilder: (context, index) => BusyMarkDocumentContentFrame( + layout: documentLayout, + contentKey: index == 0 + ? const ValueKey('preview-document-content') + : null, + child: _keyedPreviewBlock( + context, + index, + document.blocks[index], + ), + ), ), ), ), @@ -14107,10 +13937,6 @@ class _PreviewInlineText extends ConsumerWidget { final baseStyle = style ?? busyMarkDocumentBodyTextStyle(context); final searchState = ref.watch(searchSessionProvider); final workspace = ref.watch(workspaceControllerProvider).workspace; - final settings = ref.watch(appSettingsControllerProvider); - final allowRemoteImages = settings.allowsRemoteImagesForWorkspace( - _remoteImageWorkspacePath(workspace), - ); final highlightQuery = searchState.textActive ? searchState.query : ''; final inlines = block.inlines.isEmpty ? [PreviewInline(kind: PreviewInlineKind.text, text: block.text)] @@ -14141,9 +13967,6 @@ class _PreviewInlineText extends ConsumerWidget { inline, workspace: workspace, highlightQuery: highlightQuery, - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: () => - unawaited(_showRemoteImagesPrompt(context, ref)), onLinkTap: (destination) => _openPreviewLink(context, ref, destination), editRevision: editRevision, @@ -14499,10 +14322,6 @@ class _PreviewImageBlock extends ConsumerWidget { : () => unawaited(_openPreviewLink(context, ref, linkDestination)); final activeFilePath = workspace?.activeFilePath ?? workspace?.markdown?.filePath; - final settings = ref.watch(appSettingsControllerProvider); - final allowRemoteImages = settings.allowsRemoteImagesForWorkspace( - _remoteImageWorkspacePath(workspace), - ); return Padding( padding: padding, child: ConstrainedBox( @@ -14511,24 +14330,22 @@ class _PreviewImageBlock extends ConsumerWidget { ), child: Align( alignment: AlignmentDirectional.centerStart, - child: _previewLinkedImage( - destination: linkDestination, - onTap: followLink, - child: MarkdownImageView( - source: source, - alt: block.text, - activeFilePath: activeFilePath ?? '', - workspaceRoot: _imageWorkspaceRoot(workspace), - writersideRoot: workspace?.writersideModule?.rootPath, - imagesDir: - workspace?.writersideModule?.effectiveImagesDir ?? 'images', - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: - followLink ?? - () => unawaited(_showRemoteImagesPrompt(context, ref)), - width: width, - maxWidth: width ?? BusyMarkSizes.documentImageMaxWidth, + child: MarkdownImageView( + source: source, + alt: block.text, + sourceSpan: _previewImageSpan(block.inlines), + activeFilePath: activeFilePath ?? '', + workspaceRoot: _imageWorkspaceRoot(workspace), + writersideRoot: workspace?.writersideModule?.rootPath, + imagesDir: + workspace?.writersideModule?.effectiveImagesDir ?? 'images', + wrapAvailableImage: (child) => _previewLinkedImage( + child: child, + destination: linkDestination, + onTap: followLink, ), + width: width, + maxWidth: width ?? BusyMarkSizes.documentImageMaxWidth, ), ), ), @@ -14546,10 +14363,6 @@ class _PreviewVideoBlock extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final activeFilePath = workspace?.activeFilePath ?? workspace?.markdown?.filePath ?? ''; - final settings = ref.watch(appSettingsControllerProvider); - final allowRemoteImages = settings.allowsRemoteImagesForWorkspace( - _remoteImageWorkspacePath(workspace), - ); final source = block.attributes['src'] ?? block.text; return Padding( padding: BusyMarkInsets.documentImageBlock, @@ -14558,14 +14371,12 @@ class _PreviewVideoBlock extends ConsumerWidget { child: BusyMarkWritersideVideoView( source: source, previewSource: block.attributes['preview-src'], + posterSpan: block.posterSpan, activeFilePath: activeFilePath, workspaceRoot: _imageWorkspaceRoot(workspace), writersideRoot: workspace?.writersideModule?.rootPath, imagesDir: workspace?.writersideModule?.effectiveImagesDir ?? 'images', - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: () => - unawaited(_showRemoteImagesPrompt(context, ref)), onOpenFailed: () => _showPreviewLinkMessage( context, context.l10n.couldNotOpenTarget(source), @@ -14598,6 +14409,14 @@ String? _imageWorkspaceRoot(Workspace? workspace) { .firstOrNull; } +SourceSpan? _previewImageSpan(List inlines) { + for (final inline in inlines) { + if (inline.kind == PreviewInlineKind.image) return inline.imageSpan; + if (_previewImageSpan(inline.children) case final span?) return span; + } + return null; +} + String _previewImageSource(PreviewBlock block) { final attributeSource = block.attributes['src']; if (attributeSource != null && attributeSource.trim().isNotEmpty) { @@ -14668,15 +14487,21 @@ Widget _previewLinkedImage({ return child; } return Semantics( + container: true, link: true, onTap: onTap, - child: MouseRegion( - cursor: SystemMouseCursors.click, - child: GestureDetector( + child: BusyMarkFocusIndicator( + child: InkWell( key: ValueKey('preview-linked-image-$destination'), - behavior: HitTestBehavior.opaque, + excludeFromSemantics: true, onTap: onTap, - child: child, + child: ConstrainedBox( + constraints: const BoxConstraints( + minWidth: BusyMarkSizes.iconButton, + minHeight: BusyMarkSizes.iconButton, + ), + child: Align(widthFactor: 1, heightFactor: 1, child: child), + ), ), ), ); @@ -14687,8 +14512,6 @@ InlineSpan _previewInlineSpan( PreviewInline inline, { required Workspace? workspace, required String highlightQuery, - required bool allowRemoteImages, - required VoidCallback? onRemoteImageBlocked, required Future Function(String destination) onLinkTap, required int editRevision, required void Function(String expressionId, String? code) onMathDiagnostic, @@ -14792,8 +14615,6 @@ InlineSpan _previewInlineSpan( child, workspace: workspace, highlightQuery: highlightQuery, - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, onLinkTap: onLinkTap, editRevision: editRevision, onMathDiagnostic: onMathDiagnostic, @@ -14919,8 +14740,6 @@ InlineSpan _previewInlineSpan( context, inline, workspace, - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: onRemoteImageBlocked, linkDestination: linkDestination, onLinkTap: onLinkTap, style: mergeStyle( @@ -14980,8 +14799,6 @@ InlineSpan _previewInlineImageSpan( BuildContext context, PreviewInline inline, Workspace? workspace, { - required bool allowRemoteImages, - required VoidCallback? onRemoteImageBlocked, required String? linkDestination, required Future Function(String destination) onLinkTap, required TextStyle? style, @@ -15002,23 +14819,23 @@ InlineSpan _previewInlineImageSpan( padding: const EdgeInsets.symmetric(horizontal: BusyMarkSpacing.xs), child: DefaultTextStyle.merge( style: style, - child: _previewLinkedImage( - destination: destination, - onTap: followLink, - child: MarkdownImageView( - source: inline.destination ?? '', - alt: inline.text, - activeFilePath: activeFilePath ?? '', - workspaceRoot: _imageWorkspaceRoot(workspace), - writersideRoot: workspace?.writersideModule?.rootPath, - imagesDir: - workspace?.writersideModule?.effectiveImagesDir ?? 'images', - allowRemoteImages: allowRemoteImages, - onRemoteImageBlocked: followLink ?? onRemoteImageBlocked, - maxWidth: BusyMarkSizes.previewMinWidth, - maxHeight: BusyMarkSizes.previewInlineImageMaxHeight, - height: BusyMarkSizes.previewInlineImageHeight, + child: MarkdownImageView( + source: inline.destination ?? '', + sourceSpan: inline.imageSpan, + alt: inline.text, + activeFilePath: activeFilePath ?? '', + workspaceRoot: _imageWorkspaceRoot(workspace), + writersideRoot: workspace?.writersideModule?.rootPath, + imagesDir: + workspace?.writersideModule?.effectiveImagesDir ?? 'images', + wrapAvailableImage: (child) => _previewLinkedImage( + child: child, + destination: destination, + onTap: followLink, ), + maxWidth: BusyMarkSizes.previewMinWidth, + maxHeight: BusyMarkSizes.previewInlineImageMaxHeight, + preferredHeight: BusyMarkSizes.previewInlineImageHeight, ), ), ), @@ -15255,7 +15072,6 @@ Future _openPreviewLink( if (!opened) { return; } - _clearGitDetailSelection(ref); } if (!context.mounted) { return; @@ -15370,76 +15186,6 @@ void _showPreviewLinkMessage(BuildContext context, String message) { ); } -enum _RemoteImagesPromptAction { cancel, allowWorkspace, allowAlways } - -Future _showRemoteImagesPrompt( - BuildContext context, - WidgetRef ref, -) async { - final workspacePath = _remoteImageWorkspacePath( - ref.read(workspaceControllerProvider).workspace, - ); - final headerBar = ref.read(linuxHeaderBarServiceProvider); - final action = await showBusyMarkModalDialog<_RemoteImagesPromptAction>( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkDialogShell( - title: context.l10n.remoteImagesBlockedTitle, - maxWidth: BusyMarkSizes.dialog, - actions: [ - BusyMarkDialogButton( - label: context.l10n.cancel, - icon: BusyMarkGlyphs.clear, - onPressed: () => - Navigator.pop(context, _RemoteImagesPromptAction.cancel), - ), - if (workspacePath != null) - BusyMarkDialogButton( - label: context.l10n.loadRemoteImagesForWorkspace, - icon: BusyMarkGlyphs.folder, - onPressed: () => Navigator.pop( - context, - _RemoteImagesPromptAction.allowWorkspace, - ), - ), - BusyMarkDialogButton( - label: context.l10n.alwaysLoadRemoteImages, - icon: BusyMarkGlyphs.image, - suggested: true, - onPressed: () => - Navigator.pop(context, _RemoteImagesPromptAction.allowAlways), - ), - ], - children: [Text(context.l10n.remoteImagesBlockedMessage)], - ), - ); - if (action == _RemoteImagesPromptAction.allowWorkspace && - workspacePath != null) { - await ref - .read(appSettingsControllerProvider.notifier) - .allowRemoteImagesForWorkspace(workspacePath); - return; - } - if (action == _RemoteImagesPromptAction.allowAlways) { - await ref - .read(appSettingsControllerProvider.notifier) - .setAllowRemoteImages(true); - } -} - -String? _remoteImageWorkspacePath(Workspace? workspace) { - if (workspace == null) { - return null; - } - final root = (workspace.filesystemRootPath ?? '').trim(); - if (root.isNotEmpty) { - return root; - } - final fallback = workspace.activeFilePath ?? workspace.markdown?.filePath; - final trimmed = fallback?.trim(); - return trimmed == null || trimmed.isEmpty ? null : trimmed; -} - String _decodePreviewAnchor(String value) { try { return Uri.decodeComponent(value); @@ -16432,7 +16178,6 @@ class _DiagnosticRow extends ConsumerWidget { .read(appSettingsControllerProvider.notifier) .setDocumentViewMode(DocumentViewModePreference.source), ); - _clearGitDetailSelection(ref); ref .read(_sourceNavigationTargetProvider.notifier) .set( diff --git a/lib/src/workspace/presentation/workspace_sidebar.dart b/lib/src/workspace/presentation/workspace_sidebar.dart new file mode 100644 index 00000000..e8bf2956 --- /dev/null +++ b/lib/src/workspace/presentation/workspace_sidebar.dart @@ -0,0 +1,191 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../app/app_settings.dart'; +import '../../app/busymark_design.dart'; +import '../../app/busymark_glyphs.dart'; +import '../../app/command_registry.dart'; +import '../../app/localization.dart'; +import '../../core/debug_log.dart'; +import '../../search/search_session.dart'; +import '../../search/search_sidebar.dart'; +import '../recent_navigation.dart'; +import '../workspace_controller.dart'; + +final _sidebarViewMenuControllerProvider = + Provider((ref) { + final controller = BusyMarkHeaderMenuController( + debugLabel: BusyMarkCommandIds.sidebarViewSelector, + ); + ref.onDispose(controller.dispose); + return controller; + }); + +typedef _SidebarContext = ({String? workspaceId}); + +final _sidebarRevealProvider = + NotifierProvider<_SidebarReveal, _SidebarContext?>(_SidebarReveal.new); + +class _SidebarReveal extends Notifier<_SidebarContext?> { + @override + _SidebarContext? build() => null; + + void reveal(_SidebarContext context) => state = context; +} + +/// Both pages own a sidebar, including when there is no workspace on Welcome. +bool watchSidebarSelectorReveal( + BuildContext context, + WidgetRef ref, { + required String? workspaceId, +}) { + final sidebarContext = (workspaceId: workspaceId); + ref.listen(workspaceNavigationCommandProvider, (_, request) { + if (request?.$1 != BusyMarkCommandIds.sidebarViewSelector) return; + busyMarkViewSelectorTrace('workspace-received', {'command': request!.$1}); + final menu = ref.read(_sidebarViewMenuControllerProvider); + ref.read(_sidebarRevealProvider.notifier).reveal(sidebarContext); + ref.read(searchSessionProvider.notifier).close(restoreFocus: false); + final settings = ref.read(appSettingsControllerProvider); + if (!settings.sidebarVisible) { + unawaited( + ref + .read(appSettingsControllerProvider.notifier) + .setSidebarVisible(true, animate: false), + ); + } + // The overlay/expanded sidebar must be laid out before reading its anchor. + unawaited(() async { + await WidgetsBinding.instance.endOfFrame; + if (context.mounted) menu.open(); + }()); + }); + return ref.watch(_sidebarRevealProvider) == sidebarContext; +} + +class WorkspaceSidebar extends ConsumerWidget { + const WorkspaceSidebar({ + super.key, + required this.contextLabel, + required this.items, + required this.onSelected, + required this.content, + this.viewHeader, + this.onReviewReplacement, + }); + + final Widget contextLabel; + final List> items; + final ValueChanged onSelected; + final Widget? viewHeader; + final Widget content; + final Future Function()? onReviewReplacement; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final searching = ref.watch(searchSessionProvider.select((s) => s.active)); + final commands = + BusyMarkCommandRegistryScope.maybeOf(context) ?? + BusyMarkCommandCatalog.metadata; + return BusyMarkSidebarSurface( + showEndBorder: false, + child: IndexedStack( + index: searching ? 1 : 0, + children: [ + ExcludeFocus( + excluding: searching, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: BusyMarkInsets.sidebarHeader, + child: WorkspaceSidebarHeaderRow( + key: const ValueKey('workspace-sidebar-primary-row'), + child: Row( + children: [ + Expanded(child: contextLabel), + const SizedBox(width: BusyMarkSpacing.sm), + BusyMarkHeaderPopupMenuButton.native( + key: const ValueKey('workspace-sidebar-view-menu'), + controller: ref.watch( + _sidebarViewMenuControllerProvider, + ), + tooltip: context.l10n.sidebarViewMenu, + shortcut: + commands[BusyMarkCommandIds.sidebarViewSelector] + ?.shortcut + ?.label, + icon: BusyMarkGlyphs.sidebarViews, + transparent: true, + borderRadius: BusyMarkRadius.nativeHeaderButton, + highlightWhenOpen: false, + itemBuilder: (_) => items, + onSelected: onSelected, + ), + ], + ), + ), + ), + if (viewHeader != null) viewHeader!, + Expanded(child: content), + ], + ), + ), + ExcludeFocus( + excluding: !searching, + child: SearchSidebar(onReviewReplacement: onReviewReplacement), + ), + ], + ), + ); + } +} + +class WorkspaceSidebarHeaderRow extends StatelessWidget { + const WorkspaceSidebarHeaderRow({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) => ConstrainedBox( + constraints: const BoxConstraints(minHeight: BusyMarkSizes.iconButton), + child: child, + ); +} + +class RecentSidebarPanel extends ConsumerWidget { + const RecentSidebarPanel({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final recent = ref.watch( + appSettingsControllerProvider.select( + (settings) => settings.recentWorkspaces, + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BusyMarkSidebarHeader( + key: const ValueKey('workspace-sidebar-first-content'), + title: context.l10n.recent, + leading: const Icon(BusyMarkGlyphs.history), + ), + Expanded( + child: SearchResultList( + recordDensity: BusyMarkRecordDensity.comfortable, + results: [ + for (final resource in recent) RecentSearchResult(resource), + ], + onActivate: (result) => openRecentResource( + ref, + (result as RecentSearchResult).resource, + ), + ), + ), + ], + ); + } +} diff --git a/lib/src/workspace/presentation/writerside_instance_dialog.dart b/lib/src/workspace/presentation/writerside_instance_dialog.dart index c4c12a9d..976a3606 100644 --- a/lib/src/workspace/presentation/writerside_instance_dialog.dart +++ b/lib/src/workspace/presentation/writerside_instance_dialog.dart @@ -11,7 +11,6 @@ import '../../app/busymark_design.dart'; import '../../app/busymark_dialogs.dart'; import '../../app/busymark_glyphs.dart'; import '../../app/localization.dart'; -import '../../platform/linux_header_bar_service.dart'; import '../../writerside/writerside_instance_service.dart'; import '../../writerside/writerside_model.dart'; import '../../writerside/writerside_project_creator.dart'; @@ -582,10 +581,8 @@ class _BusyMarkWritersideInstanceDialogState } Future _confirmIdRename(String oldId, String newId) async { - final headerBar = ref.read(linuxHeaderBarServiceProvider); final result = await showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, barrierDismissible: false, builder: (context) => BusyMarkDialogShell( title: context.l10n.instanceIdRenameWarningTitle, diff --git a/lib/src/workspace/recent_navigation.dart b/lib/src/workspace/recent_navigation.dart index eeab54b6..c7c225fa 100644 --- a/lib/src/workspace/recent_navigation.dart +++ b/lib/src/workspace/recent_navigation.dart @@ -3,100 +3,115 @@ import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:go_router/go_router.dart'; import 'package:path/path.dart' as p; import 'package:url_launcher/url_launcher.dart'; -import '../app/app_router.dart'; import '../app/app_settings.dart'; import '../app/busymark_toast.dart'; import '../app/localization.dart'; import '../nextcloud_notes/application/nextcloud_connection.dart'; -import '../nextcloud_notes/application/notes_navigation.dart'; import '../search/search_session.dart'; -import 'document_navigation.dart'; +import 'workspace_navigation.dart'; import 'workspace_controller.dart'; -import 'workspace_safety.dart'; -Future openRecentResource( - BuildContext context, - WidgetRef ref, +Future openRecentResource(WidgetRef ref, RecentResource resource) { + final navigation = ref.read(workspaceNavigationProvider); + return navigation.run( + (recent: resource.identity), + (_, currentRequest) => + _openRecentResource(navigation, resource, currentRequest), + ); +} + +Future _openRecentResource( + WorkspaceNavigation navigation, RecentResource resource, + bool Function() currentNavigation, ) async { - final controller = ref.read(workspaceControllerProvider.notifier); - final origin = ref.read(appRouterProvider).routeInformationProvider.value.uri; - final search = ref.read(searchSessionProvider); - bool currentRequest() => - context.mounted && - ref.read(appRouterProvider).routeInformationProvider.value.uri == - origin && - ref.read(searchSessionProvider).requestRevision == - search.requestRevision && - (!search.active || - ref.read(searchSessionProvider).active && - ref.read(searchSessionProvider).focusRequest == - search.focusRequest && - ref.read(searchSessionProvider).category == search.category && - ref.read(searchSessionProvider).query == search.query); - final current = ref.read(workspaceControllerProvider).workspace; - bool opened = false; - if (resource.accountId != null) { - final repository = await ref.read(nextcloudNotesRepositoryProvider.future); - if (!context.mounted || !currentRequest()) return; - final account = repository.accounts - .where((a) => a.id == resource.accountId) - .firstOrNull; - final note = resource.localId == null - ? null - : repository.noteById(resource.localId!); - if (account == null || - resource.isDocument && - (note?.accountId != resource.accountId || - isNotesRecovery(note!) || - repository.isCreationCandidateBinding(note.localId))) { - BusyMarkToastOverlay.show( - context, - message: context.l10n.searchResourceUnavailable, - ); + final container = navigation.container; + final controller = container.read(workspaceControllerProvider.notifier); + final search = container.read(searchSessionProvider); + bool currentRequest() { + if (!currentNavigation()) return false; + final live = container.read(searchSessionProvider); + return live.requestRevision == search.requestRevision && + (!search.active || + live.active && + live.focusRequest == search.focusRequest && + live.category == search.category && + live.query == search.query); + } + + final current = container.read(workspaceControllerProvider).workspace; + void unavailable() { + if (currentRequest()) { + navigation.showUnavailable(); + } + } + + late final bool opened; + if (resource.accountId case final accountId?) { + final repository = await container.read( + nextcloudNotesRepositoryProvider.future, + ); + if (!currentRequest()) return; + bool available() { + if (repository.accountById(accountId) == null) return false; + if (!resource.isDocument) return true; + final localId = resource.localId; + return localId != null && + repository.availableRecentNote(accountId, localId) != null; + } + + if (!available()) { + unavailable(); return; } - if (current?.nextcloudAccountId != resource.accountId) { - if (!await confirmSafeToContinue(context, ref) || - !context.mounted || + if (current?.nextcloudAccountId == accountId) { + opened = + resource.localId == null || + await controller.openNextcloudNote( + resource.localId!, + acceptNavigation: () => currentRequest() && available(), + ); + } else { + if (!await navigation.confirmDeparture( + canContinue: () => currentRequest() && available(), + ) || !currentRequest()) { + if (!available()) unavailable(); return; } - if (!await controller.openNextcloudWorkspace( - resource.accountId!, + opened = await controller.openNextcloudWorkspace( + accountId, + noteLocalId: resource.localId, acceptNavigation: currentRequest, - )) { - return; - } + ); } - opened = - resource.localId == null || - await controller.openNextcloudNote( - resource.localId!, - acceptNavigation: currentRequest, - ); } else { - if (!await FileSystemEntity.isFile(resource.path) && - !await Directory(resource.path).exists()) { - if (context.mounted) { - BusyMarkToastOverlay.show( - context, - message: context.l10n.searchResourceUnavailable, - ); - } + bool available() { + final type = FileSystemEntity.typeSync(resource.path); + return (resource.isDocument + ? type == FileSystemEntityType.file + : type == FileSystemEntityType.file || + type == FileSystemEntityType.directory) && + (resource.ownerRoot == null || + Directory(resource.ownerRoot!).existsSync()); + } + + if (!available()) { + unavailable(); return; } - if (!context.mounted || !currentRequest()) return; + final currentRoot = current?.filesystemRootPath; final sameOwner = - current != null && + currentRoot != null && (resource.ownerRoot != null - ? p.equals(current.rootPath, resource.ownerRoot!) - : current.files.any( - (f) => p.equals(f.absolutePath, resource.path), + ? (current!.writersideProject != null || + current.writersideModule != null) && + p.equals(currentRoot, resource.ownerRoot!) + : current!.files.any( + (file) => p.equals(file.absolutePath, resource.path), )); if (resource.isDocument && sameOwner) { opened = await controller.openActiveFile( @@ -104,36 +119,29 @@ Future openRecentResource( acceptNavigation: currentRequest, ); } else { - if (!await confirmSafeToContinue(context, ref) || - !context.mounted || + if (!await navigation.confirmDeparture( + canContinue: () => currentRequest() && available(), + ) || !currentRequest()) { + if (!available()) unavailable(); return; } + var published = false; await controller.openPath( resource.ownerRoot ?? resource.path, + documentPath: resource.ownerRoot == null ? null : resource.path, acceptNavigation: currentRequest, + onOpened: () => published = true, ); - if (!context.mounted || !currentRequest()) return; - final workspace = ref.read(workspaceControllerProvider).workspace; - if (workspace == null) return; - if (resource.ownerRoot != null && - workspace.writersideProject == null && - workspace.writersideModule == null) { - BusyMarkToastOverlay.show( - context, - message: context.l10n.searchResourceUnavailable, - ); - return; - } - opened = - resource.ownerRoot == null || - await controller.openActiveFile( - resource.path, - acceptNavigation: currentRequest, - ); + opened = published; } } - if (opened && context.mounted) { + if (!opened) { + unavailable(); + return; + } + if (currentRequest()) { + navigation.reveal(); await controller.recordRecentResource( RecentResource( path: resource.path, @@ -147,10 +155,6 @@ Future openRecentResource( lastOpenedAt: DateTime.now(), ), ); - if (!context.mounted || !currentRequest()) return; - revealOpenedDocument(ref); - ref.read(searchSessionProvider.notifier).close(restoreFocus: false); - context.go('/workspace'); } } diff --git a/lib/src/workspace/remote_image_permissions.dart b/lib/src/workspace/remote_image_permissions.dart new file mode 100644 index 00000000..e1c16a6e --- /dev/null +++ b/lib/src/workspace/remote_image_permissions.dart @@ -0,0 +1,332 @@ +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; + +import '../app/app_settings.dart'; +import '../core/source_span.dart'; +import '../core/uri_utils.dart'; +import '../editor/wysiwyg/writerside_editing_adapter.dart'; +import '../markdown/busymark_document.dart'; +import '../markdown/markdown_parser.dart'; +import 'document_buffer.dart'; +import 'workspace_model.dart'; + +String? remoteImageWorkspaceId(Workspace? workspace) => + switch (workspace?.kind) { + WorkspaceKind.markdownFolder || WorkspaceKind.writersideModule => + '${workspace!.kind.name}:${p.normalize(workspace.id)}', + WorkspaceKind.nextcloudNotes => switch (workspace!.nextcloudAccountId) { + final accountId? => 'nextcloud:$accountId', + null => null, + }, + _ => null, + }; + +bool allowsWorkspaceRemoteImages(AppSettings settings, Workspace? workspace) { + // Old grants stored only a path. A standalone file could have created a + // grant for its parent, so keep the legacy lookup separate from typed IDs. + final root = workspace?.filesystemRootPath; + final legacyPath = root != null && root.trim().isNotEmpty + ? root + : workspace?.activeFilePath ?? workspace?.markdown?.filePath; + return settings.allowsRemoteImagesForWorkspace(legacyPath) || + settings.remoteImageAllowedWorkspaceIds.contains( + remoteImageWorkspaceId(workspace), + ); +} + +enum RemoteImagePermission { image, document, workspace, global } + +typedef _Occurrence = ({int start, int end, String source}); + +class RemoteImagePermissionTarget { + RemoteImagePermissionTarget._( + this._document, + this._occurrence, + this.workspaceId, + ); + + final Object _document; + _Occurrence? _occurrence; + final String? workspaceId; + bool _valid = true; + + bool get hasOccurrence => _occurrence != null; +} + +/// Session state lives with the workspace controller. The opening token +/// survives buffer copies and Save As without becoming part of session JSON. +class RemoteImagePermissions extends ChangeNotifier { + final _documents = {}; + + bool allows( + DocumentBuffer buffer, + String? renderedSource, + SourceSpan? span, + String source, + ) { + final document = _documents[buffer.opening]; + if (document == null) return false; + if (document.allowAll) return true; + final occurrence = _occurrenceFor(buffer, renderedSource, span, source); + return occurrence != null && document.allowed.contains(occurrence); + } + + RemoteImagePermissionTarget? capture( + WorkspaceState state, + DocumentBuffer renderedBuffer, + String? renderedSource, + SourceSpan? span, + String source, + String? workspaceId, + ) { + final current = state.documentBuffers + .where((buffer) => identical(buffer.opening, renderedBuffer.opening)) + .firstOrNull; + if (current == null || + current.revision != renderedBuffer.revision || + current.text != renderedBuffer.text || + current.text != renderedSource || + workspaceId != remoteImageWorkspaceId(state.workspace) || + !isRemoteImageSource(source)) { + return null; + } + final occurrence = _occurrenceFor(current, renderedSource, span, source); + final document = _documents.putIfAbsent( + current.opening, + _DocumentPermissions.new, + ); + final target = RemoteImagePermissionTarget._( + current.opening, + occurrence, + workspaceId, + ); + document.pending.add(target); + return target; + } + + bool apply( + RemoteImagePermissionTarget target, + RemoteImagePermission permission, + WorkspaceState state, + ) { + final document = _documents[target._document]; + if (document == null || + !document.pending.remove(target) || + !target._valid || + target.workspaceId != remoteImageWorkspaceId(state.workspace) || + !state.documentBuffers.any( + (buffer) => identical(buffer.opening, target._document), + )) { + return false; + } + switch (permission) { + case RemoteImagePermission.image: + final occurrence = target._occurrence; + if (occurrence == null) return false; + document.allowed.add(occurrence); + notifyListeners(); + case RemoteImagePermission.document: + document.allowAll = true; + notifyListeners(); + case RemoteImagePermission.workspace: + return target.workspaceId != null; + case RemoteImagePermission.global: + break; + } + return true; + } + + void release(RemoteImagePermissionTarget target) { + final document = _documents[target._document]; + document?.pending.remove(target); + if (document != null && document.isEmpty) { + _documents.remove(target._document); + } + } + + void update(WorkspaceState? previous, WorkspaceState next) { + // A cancelled open may restore the suspended buffers. Keep their grants + // through the loading state and remove them when an outcome is published. + if (_documents.isEmpty || (next.isLoading && next.workspace == null)) { + return; + } + final open = { + for (final buffer in next.documentBuffers) buffer.opening: buffer, + }; + _documents.removeWhere((opening, _) => !open.containsKey(opening)); + for (final before + in previous?.documentBuffers ?? const []) { + final document = _documents[before.opening]; + final after = open[before.opening]; + if (document == null || after == null || before.text == after.text) { + continue; + } + + if (document.allowed.isEmpty && document.pending.isEmpty) continue; + final map = _UnchangedSource(before.text, after.text); + final candidates = <_Occurrence>{}; + final context = next.workspace == null + ? null + : resolveWorkspaceDocumentContext(next.workspace!, after); + if (context != null && + (document.allowed.isNotEmpty || document.pending.isNotEmpty)) { + candidates.addAll(_authoredOccurrences(context, after.text)); + } + + _Occurrence? relocate(_Occurrence? occurrence) { + if (occurrence == null) return null; + final mapped = map.relocate(occurrence); + return candidates.contains(mapped) ? mapped : null; + } + + final retained = document.allowed.map(relocate).nonNulls.toSet(); + document.allowed + ..clear() + ..addAll(retained); + for (final target in document.pending) { + target._occurrence = relocate(target._occurrence); + target._valid &= target._occurrence != null; + } + } + } + + @override + void dispose() { + _documents.clear(); + super.dispose(); + } + + _Occurrence? _occurrenceFor( + DocumentBuffer buffer, + String? renderedSource, + SourceSpan? span, + String source, + ) { + if (renderedSource != buffer.text || + span == null || + span.startOffset < 0 || + span.endOffset <= span.startOffset || + span.endOffset > buffer.text.length) { + return null; + } + return ( + start: span.startOffset, + end: span.endOffset, + source: source.trim(), + ); + } +} + +class _DocumentPermissions { + final allowed = <_Occurrence>{}; + final pending = {}; + bool allowAll = false; + bool get isEmpty => !allowAll && allowed.isEmpty && pending.isEmpty; +} + +/// The maximal unchanged prefix and suffix may overlap when identical markup +/// is inserted or removed. Use only the portions invariant under both edit +/// alignments. An edit spanning several disjoint ranges can discard grants. +class _UnchangedSource { + _UnchangedSource(String before, String after) + : delta = after.length - before.length { + final shortest = math.min(before.length, after.length); + var prefix = 0; + while (prefix < shortest && + before.codeUnitAt(prefix) == after.codeUnitAt(prefix)) { + prefix++; + } + var suffix = 0; + while (suffix < shortest && + before.codeUnitAt(before.length - suffix - 1) == + after.codeUnitAt(after.length - suffix - 1)) { + suffix++; + } + prefixEnd = math.min(prefix, shortest - suffix); + suffixStart = before.length - math.min(suffix, shortest - prefix); + } + + final int delta; + late final int prefixEnd; + late final int suffixStart; + + _Occurrence? relocate(_Occurrence occurrence) { + if (occurrence.end <= prefixEnd) return occurrence; + if (occurrence.start < suffixStart) return null; + return ( + start: occurrence.start + delta, + end: occurrence.end + delta, + source: occurrence.source, + ); + } +} + +Iterable<_Occurrence> _authoredOccurrences( + WorkspaceDocumentContext context, + String source, +) sync* { + final path = context.parserPath; + final BusyDocument? document; + try { + document = context.kind == DocumentKind.writersideXmlTopic + ? const WritersideEditingAdapter().parseXml( + filePath: path, + source: source, + ) + : const MarkdownParser() + .parse( + filePath: path, + source: source, + mode: context.markdownMode, + validateLocalReferences: false, + ) + .busyDocument; + } on Object { + return; + } + if (document == null) return; + + _Occurrence? occurrence(SourceSpan? span, String? source) { + if (span == null || span.filePath != path || !isRemoteImageSource(source)) { + return null; + } + return ( + start: span.startOffset, + end: span.endOffset, + source: source!.trim(), + ); + } + + Iterable<_Occurrence> inlines( + Iterable items, { + String? blockSource, + }) sync* { + for (final inline in items) { + if (occurrence(inline.imageSpan, blockSource ?? inline.destination) + case final image? when inline.kind == BusyInlineKind.image) { + yield image; + } + yield* inlines(inline.children, blockSource: blockSource); + } + } + + Iterable<_Occurrence> blocks(List items) sync* { + for (final block in items) { + if (occurrence(block.posterSpan, block.attributes['preview-src']) + case final poster? when block.kind == BusyBlockKind.video) { + yield poster; + } + yield* inlines( + block.inlines, + blockSource: block.kind == BusyBlockKind.image + ? block.attributes['src'] + : null, + ); + yield* blocks(block.children); + } + } + + yield* blocks(document.blocks); +} diff --git a/lib/src/workspace/workspace_controller.dart b/lib/src/workspace/workspace_controller.dart index e6fd95e4..ac39e5bb 100644 --- a/lib/src/workspace/workspace_controller.dart +++ b/lib/src/workspace/workspace_controller.dart @@ -6,16 +6,19 @@ import 'dart:io'; import 'dart:math' as math; -import 'package:flutter/foundation.dart' show mapEquals, setEquals; +import 'package:flutter/foundation.dart' + show mapEquals, setEquals, VoidCallback; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:path/path.dart' as p; import '../app/app_settings.dart'; +import '../app/busymark_deferred_editor_focus.dart'; import '../comparison/source_comparison.dart'; import '../core/debug_log.dart'; import '../core/anchored_path_guard.dart'; import '../core/atomic_file_writer.dart'; +import '../core/save_destination.dart'; import '../core/busymark_temporary_path.dart'; import '../core/busymark_exception.dart'; import '../core/diagnostic.dart'; @@ -45,6 +48,7 @@ import '../writerside/writerside_topic_file_editor.dart'; import '../writerside/writerside_toc_editor.dart'; import '../writerside/writerside_title_editor.dart'; import 'document_buffer.dart'; +import 'remote_image_permissions.dart'; import 'recovery_persistence.dart'; import 'session_persistence.dart'; import 'text_format_metadata.dart'; @@ -185,15 +189,6 @@ class SaveAllResult { enum _BufferWriteResult { saved, failed, conflict } -class WorkspaceSearchRequestController extends Notifier { - @override - int build() => 0; - - void request() { - state++; - } -} - enum ValidationStatus { published, stale, failed, busy, unavailable } class ValidationOutcome { @@ -220,6 +215,7 @@ class WorkspaceController extends Notifier { late WorkspaceService _service; late AppSettingsController _settingsController; + final remoteImages = RemoteImagePermissions(); final propertyEdits = WritersidePropertySession(); /// The mounted workspace owns inspector transitions and focus restoration. @@ -235,6 +231,7 @@ class WorkspaceController extends Notifier { bool _notesApplicationVisible = true; bool _notesWorkspaceActive = true; final _remoteDurabilityWrites = {}; + final _pendingRemoteDiscards = {}; var _restoringLocalHistorySession = false; StreamSubscription? _fileMonitorSubscription; Future? _fileMonitorLifecycle; @@ -254,6 +251,36 @@ class WorkspaceController extends Notifier { var _validationSequence = 0; var _editRevision = 0; var _activeDocumentRevision = 0; + var _writersideProjectCreation = 0; + ({String bufferId, BusyMarkDeferredEditorFocus request})? _creationFocus; + + BusyMarkDeferredEditorFocus? sourceCreationFocus(String? bufferId) => + _creationFocus?.bufferId == bufferId ? _creationFocus?.request : null; + + void _cancelCreationFocus() { + _creationFocus?.request.cancel(); + _creationFocus = null; + } + + void focusNewlyCreatedDocument(String bufferId) { + final buffer = state.activeBuffer; + if (buffer == null || buffer.id != bufferId) return; + _cancelCreationFocus(); + if (buffer.editorState.mode == DocumentViewModePreference.preview) { + updateActiveEditorMode(DocumentViewModePreference.editor); + } + _retainCreationFocus(buffer, BusyMarkDeferredEditorFocus()); + state = state.copyWith(); + } + + void _retainCreationFocus( + DocumentBuffer buffer, + BusyMarkDeferredEditorFocus? request, + ) { + if (request == null || !request.isPending) return; + _creationFocus = (bufferId: buffer.id, request: request); + } + // Removal follows workspace/request lifetime, not active-tab navigation. var _removalOperationRevision = 0; var _workspaceRefreshRevision = 0; @@ -277,6 +304,7 @@ class WorkspaceController extends Notifier { late Future _recoveryStart; final _workspaceOpenings = >{}; + var _pathOpenRequest = 0; Future _persistenceWrites = Future.value(); int get editRevision => state.activeBuffer?.revision ?? _editRevision; @@ -351,9 +379,12 @@ class WorkspaceController extends Notifier { _scheduleAutoSave(); } }); + listenSelf(remoteImages.update); ref.onDispose(() { + remoteImages.dispose(); _settingsController.processPendingProperties = null; propertyEdits.dispose(); + _cancelCreationFocus(); _fileMonitorWorkspaceGeneration++; _removalOperationRevision++; _cancelPendingDerivedRefresh(); @@ -370,6 +401,42 @@ class WorkspaceController extends Notifier { return const WorkspaceState(); } + RemoteImagePermissionTarget? captureRemoteImagePermission( + DocumentBuffer buffer, + String? renderedSource, + SourceSpan? span, + String source, + String? workspaceId, + ) => remoteImages.capture( + state, + buffer, + renderedSource, + span, + source, + workspaceId, + ); + + Future grantRemoteImagePermission( + RemoteImagePermissionTarget target, + RemoteImagePermission permission, + ) async { + if (!ref.mounted) return; + final accepted = remoteImages.apply(target, permission, state); + remoteImages.release(target); + if (!accepted) return; + switch (permission) { + case RemoteImagePermission.workspace: + await _settingsController.allowRemoteImagesForWorkspaceId( + target.workspaceId!, + ); + case RemoteImagePermission.global: + await _settingsController.setAllowRemoteImages(true); + case RemoteImagePermission.image: + case RemoteImagePermission.document: + break; + } + } + void _queueFileMonitorEvent(WorkspaceFileMonitorEvent event) { if (!_acceptFileMonitorEvents) return; _queueCapturedFileMonitorEvent( @@ -624,6 +691,7 @@ class WorkspaceController extends Notifier { String accountId, { List? restoredTabs, String? activeBufferId, + String? noteLocalId, bool Function()? acceptNavigation, }) async { if (acceptNavigation?.call() == false) return false; @@ -633,33 +701,22 @@ class WorkspaceController extends Notifier { final priorRevision = _activeDocumentRevision; try { final repository = await _ensureNotesRepository(); - if (!repository.accounts.any((account) => account.id == accountId)) { + if (repository.accountById(accountId)?.disconnectPending != false || + (noteLocalId != null && + repository.availableRecentNote(accountId, noteLocalId) == null)) { return false; } final settled = await _localHistory.flushAll(prior.documentBuffers); - if (!ref.mounted || - acceptNavigation?.call() == false || - priorRevision != _activeDocumentRevision || - !identical(prior.workspace, state.workspace) || - state.hasUnsavedChanges) { + final requestedNote = noteLocalId == null + ? null + : repository.availableRecentNote(accountId, noteLocalId); + if (!_canReplaceWorkspace(prior, priorRevision, acceptNavigation) || + state.hasUnsavedChanges || + repository.accountById(accountId)?.disconnectPending != false || + (noteLocalId != null && requestedNote == null)) { return false; } - _cancelPendingDerivedRefresh(); - _cancelAllAutoSaves(); - final operationRevision = _invalidateActiveDocumentOperations(); - await _fileMonitor.stop(); - for (final buffer in prior.documentBuffers) { - await _localHistory.handleBufferClosed( - buffer.id, - historySettled: settled, - ); - } final workspace = Workspace.nextcloudNotes(accountId); - if (!_isCurrentActiveDocumentOperation(operationRevision)) return false; - if (acceptNavigation?.call() == false) { - await _restoreCancelledNavigation(prior); - return false; - } final buffers = []; for (final tab in restoredTabs ?? const []) { final reference = tab.remoteNote; @@ -671,7 +728,9 @@ class WorkspaceController extends Notifier { buffers.add(_remoteBuffer(note, editorState: tab.editorState)); } } - if (buffers.isEmpty && restoredTabs == null) { + if (requestedNote case final note?) { + buffers.add(_remoteBuffer(note)); + } else if (buffers.isEmpty && restoredTabs == null) { final first = repository.notes .where( (note) => @@ -682,6 +741,11 @@ class WorkspaceController extends Notifier { .firstOrNull; if (first != null) buffers.add(_remoteBuffer(first)); } + _invalidateFileMonitorWorkspace(); + _cancelPendingDerivedRefresh(); + _cancelAllAutoSaves(); + final operationRevision = _invalidateActiveDocumentOperations(); + _restoredRecoveryOwnerIdsByBuffer.clear(); state = WorkspaceState( workspace: workspace, documentBuffers: buffers, @@ -689,6 +753,14 @@ class WorkspaceController extends Notifier { ? activeBufferId : buffers.firstOrNull?.id, ); + await _startMonitoring(workspace); + for (final buffer in prior.documentBuffers) { + await _localHistory.handleBufferClosed( + buffer.id, + historySettled: settled, + ); + } + if (!_isCurrentActiveDocumentOperation(operationRevision)) return false; for (final buffer in buffers) { unawaited(_localHistory.observeOpened(buffer)); } @@ -737,6 +809,12 @@ class WorkspaceController extends Notifier { Future openNextcloudNote( String localId, { bool Function()? acceptNavigation, + }) => _openNextcloudNote(localId, acceptNavigation: acceptNavigation); + + Future _openNextcloudNote( + String localId, { + bool Function()? acceptNavigation, + BusyMarkDeferredEditorFocus? creationFocus, }) async { if (acceptNavigation?.call() == false) return false; if (!propertyEdits.flush()) return false; @@ -752,7 +830,21 @@ class WorkspaceController extends Notifier { final existing = state.documentBuffers .where((buffer) => buffer.remoteNote?.localId == localId) .firstOrNull; - final buffer = existing ?? _remoteBuffer(note); + final mode = + state.activeBuffer?.editorState.mode ?? + _settingsController.state.documentViewMode; + final buffer = + existing ?? + _remoteBuffer( + note, + editorState: creationFocus == null + ? null + : DocumentEditorState( + mode: mode == DocumentViewModePreference.preview + ? DocumentViewModePreference.editor + : mode, + ), + ); if (existing == null) { // Navigation validates the live buffer after asynchronous parsing. Publish // the new logical tab first so that validation can retain newer edits. @@ -766,6 +858,7 @@ class WorkspaceController extends Notifier { documentBuffers: state.documentBuffers, openFilePaths: const [], acceptNavigation: acceptNavigation, + creationFocus: creationFocus, ); if (result) await _recordOpenedDocument(); if (result && existing == null) { @@ -809,9 +902,11 @@ class WorkspaceController extends Notifier { String? category, String content = '', bool Function()? acceptNavigation, + bool focusEditor = false, }) async { if (acceptNavigation?.call() == false) return false; if (!propertyEdits.flush()) return false; + final request = focusEditor ? BusyMarkDeferredEditorFocus() : null; try { final accountId = state.workspace?.nextcloudAccountId; if (accountId == null) return false; @@ -831,9 +926,10 @@ class WorkspaceController extends Notifier { : ''), content: content, ); - final opened = await openNextcloudNote( + final opened = await _openNextcloudNote( note.localId, acceptNavigation: acceptNavigation, + creationFocus: request, ); _scheduleRemoteSync(accountId); _publishCreatedNextcloudNote(note, repository.notes); @@ -841,6 +937,8 @@ class WorkspaceController extends Notifier { } on Object catch (error) { _reportNextcloudFailure(error); return false; + } finally { + if (_creationFocus?.request != request) request?.cancel(); } } @@ -999,9 +1097,14 @@ class WorkspaceController extends Notifier { Future refreshNextcloudNotes() async { if (state.workspace?.nextcloudAccountId == null) return; - await _ensureNotesRepository(); - _updateNotesCoordinator(); - await _notesCoordinator?.request(NotesSyncTrigger.manual); + try { + await _ensureNotesRepository(); + _updateNotesCoordinator(); + await _notesCoordinator?.request(NotesSyncTrigger.manual); + } on Object catch (error, stack) { + _reportNextcloudFailure(error); + busyMarkDebugLogError('Unexpected Nextcloud Sync failure', error, stack); + } } Future retryRejectedNextcloudNote(String localId) async { @@ -1726,7 +1829,6 @@ class WorkspaceController extends Notifier { ]; final nextWorkspace = workspace.copyWith( activeFilePath: active.filePath, - activeFileSnapshot: active.diskSnapshot, openFilePaths: openPaths, ); final reparsed = await _reparseWithDocumentBuffers( @@ -2587,15 +2689,25 @@ class WorkspaceController extends Notifier { for (final buffer in snapshot.documentBuffers) { if (buffer.isRemote && buffer.isDirty && - !_remoteDurabilityWrites.containsKey(buffer.id)) { - final saved = await _enqueueBufferWrite( - buffer.id, - () => _saveRemoteBufferSnapshot( - buffer, + !_remoteDurabilityWrites.containsKey(buffer.id) && + !_pendingRemoteDiscards.contains(buffer.id)) { + final saved = await _enqueueBufferWrite(buffer.id, () async { + if (!ref.mounted) return true; + final live = state.documentBuffers + .where((candidate) => candidate.id == buffer.id) + .firstOrNull; + if (live == null || + !live.isDirty || + live.revision != buffer.revision || + live.text != buffer.text) { + return true; + } + return _saveRemoteBufferSnapshot( + live, scheduleSync: _settingsController.state.autoSave, captureHistory: false, - ), - ); + ); + }); if (!saved) throw StateError('Could not durably store Nextcloud note'); } } @@ -3050,9 +3162,12 @@ class WorkspaceController extends Notifier { _workspaceRefreshDebounce?.cancel(); _workspaceRefreshDebounce = Timer(const Duration(milliseconds: 250), () { if (!ref.mounted) return; - // Our own filesystem writes also emit notifications. A background - // refresh must not invalidate an operation already loading its result. - if (state.isLoading || _workspaceFileOperationDepth > 0) { + // Generated files can notify the current workspace's monitor while a + // replacement is being prepared. Reconcile the retained workspace only + // after the opening settles, just as for in-place file operations. + if (state.isLoading || + _workspaceFileOperationDepth > 0 || + _workspaceOpenings.isNotEmpty) { _scheduleMonitoredWorkspaceRefresh(); return; } @@ -3150,9 +3265,7 @@ class WorkspaceController extends Notifier { workspaceGeneration: workspaceGeneration, ); if (state.activeBufferId == reloaded.id && state.workspace != null) { - final workspace = state.workspace!.copyWith( - activeFileSnapshot: disk.snapshot, - ); + final workspace = state.workspace!; final reparsed = await _reparseWithDocumentBuffers(workspace, reloaded); if (_fileMonitorOperationIsCurrent(workspaceGeneration) && state.activeBufferId == reloaded.id && @@ -3600,9 +3713,6 @@ class WorkspaceController extends Notifier { documentBuffers: _replaceBuffer(state.documentBuffers, remapped), workspace: workspace?.copyWith( activeFilePath: active ? destinationPath : workspace.activeFilePath, - activeFileSnapshot: active - ? remapped.diskSnapshot - : workspace.activeFileSnapshot, openFilePaths: remappedTabs, ), ); @@ -3649,7 +3759,6 @@ class WorkspaceController extends Notifier { )) { state = state.copyWith( workspace: reparsed.copyWith( - activeFileSnapshot: remapped.diskSnapshot, openFilePaths: state.workspace!.openFilePaths, ), preview: _safePreview(reparsed, remapped), @@ -3731,7 +3840,6 @@ class WorkspaceController extends Notifier { documentBuffers: _replaceBuffer(state.documentBuffers, remapped), workspace: workspace?.copyWith( activeFilePath: active ? destinationPath : workspace.activeFilePath, - activeFileSnapshot: active ? null : workspace.activeFileSnapshot, openFilePaths: [ for (final path in workspace.openFilePaths) p.equals(path, oldPath) ? destinationPath : path, @@ -3780,9 +3888,6 @@ class WorkspaceController extends Notifier { } state = state.copyWith( documentBuffers: _replaceBuffer(state.documentBuffers, buffer), - workspace: state.activeBufferId == buffer.id - ? state.workspace?.copyWith(activeFileSnapshot: buffer.diskSnapshot) - : state.workspace, ); _schedulePersistence(); } @@ -3840,7 +3945,7 @@ class WorkspaceController extends Notifier { source: reloaded.text, )) { final workspace = await _reparseWithDocumentBuffers( - derivedWorkspace.copyWith(activeFileSnapshot: disk.snapshot), + derivedWorkspace, reloaded, ); if (_preparedInputsCurrent(workspace, state.documentBuffers) && @@ -3934,8 +4039,25 @@ class WorkspaceController extends Notifier { /// Starts a document from Welcome, replacing the previous workspace only /// after its buffers have been resolved and their history has been flushed. - Future createMarkdownWorkspace() async { - if (!propertyEdits.flush()) return false; + Future createMarkdownWorkspace({ + bool focusSource = false, + bool Function()? acceptNavigation, + }) async { + final request = focusSource ? BusyMarkDeferredEditorFocus() : null; + try { + return await _createMarkdownWorkspace(request, acceptNavigation); + } finally { + if (_creationFocus?.request != request) request?.cancel(); + } + } + + Future _createMarkdownWorkspace( + BusyMarkDeferredEditorFocus? request, + bool Function()? acceptNavigation, + ) async { + if (acceptNavigation?.call() == false || !propertyEdits.flush()) { + return false; + } final previous = state; final previousOperation = _activeDocumentRevision; if (previous.hasUnsavedChanges || previous.isLoading) return false; @@ -3943,13 +4065,7 @@ class WorkspaceController extends Notifier { previous.documentBuffers, ); if (!ref.mounted) return false; - final liveBuffers = state.documentBuffers; - if (_activeDocumentRevision != previousOperation || - !identical(state.workspace, previous.workspace) || - liveBuffers.length != previous.documentBuffers.length || - liveBuffers.indexed.any( - (entry) => !identical(entry.$2, previous.documentBuffers[entry.$1]), - )) { + if (!_canReplaceWorkspace(previous, previousOperation, acceptNavigation)) { return false; } _invalidateFileMonitorWorkspace(); @@ -3958,28 +4074,39 @@ class WorkspaceController extends Notifier { _invalidateActiveDocumentOperations(); _removalOperationRevision++; _restoredRecoveryOwnerIdsByBuffer.clear(); - state = const WorkspaceState(); + // Publish the new local workspace directly. The old remote workspace + // must never contain a local document, even during the transition. + final creation = _createMarkdownFile(request, replaceWorkspace: true); for (final buffer in previous.documentBuffers) { await _localHistory.handleBufferClosed( buffer.id, historySettled: historySettled, ); } - await createMarkdownFile(); - return true; + return creation; } - Future createMarkdownFile() async { - if (!propertyEdits.flush()) return; - if (state.workspace?.isRemote == true) { - await createNextcloudNote(); - return; + Future createMarkdownFile({bool focusSource = false}) async { + final request = focusSource ? BusyMarkDeferredEditorFocus() : null; + try { + return await (state.workspace?.isRemote == true + ? _createMarkdownWorkspace(request, null) + : _createMarkdownFile(request)); + } finally { + if (_creationFocus?.request != request) request?.cancel(); } + } + + Future _createMarkdownFile( + BusyMarkDeferredEditorFocus? request, { + bool replaceWorkspace = false, + }) async { + if (!propertyEdits.flush() || state.isLoading) return false; _cancelPendingDerivedRefresh(); final operationRevision = _invalidateActiveDocumentOperations(); _resetSaveTracking(dirty: true); final viewModeChange = _showEditorForNewFile(); - final currentWorkspace = state.workspace; + final currentWorkspace = replaceWorkspace ? null : state.workspace; final untitledWorkspace = _service.createUntitledMarkdown(); final sequence = ++_untitledSequence; final buffer = DocumentBuffer.untitled( @@ -3991,14 +4118,11 @@ class WorkspaceController extends Notifier { ? DocumentViewModePreference.editor : _settingsController.state.documentViewMode, ); - final buffers = [...state.documentBuffers, buffer]; + final buffers = [if (!replaceWorkspace) ...state.documentBuffers, buffer]; final workspace = currentWorkspace == null ? untitledWorkspace.copyWith(markdown: null) - : currentWorkspace.copyWith( - activeFilePath: null, - activeFileSnapshot: null, - markdown: null, - ); + : currentWorkspace.copyWith(activeFilePath: null, markdown: null); + _retainCreationFocus(buffer, request); state = WorkspaceState( workspace: workspace, preview: _safePreview(workspace, buffer), @@ -4010,11 +4134,13 @@ class WorkspaceController extends Notifier { _recordActivePreviewRevision(); _schedulePersistence(); await viewModeChange; + if (!ref.mounted) return false; final reparsed = await _reparseWithDocumentBuffers( workspace, buffer, buffers: buffers, ); + if (!ref.mounted) return false; if (_preparedInputsCurrent(reparsed, state.documentBuffers) && _canPublishActiveDerivedContent( operationRevision: operationRevision, @@ -4030,51 +4156,100 @@ class WorkspaceController extends Notifier { ); _recordActivePreviewRevision(); } - await _startMonitoring(state.workspace ?? workspace); - } - - Future openPath(String path, {bool Function()? acceptNavigation}) => - _trackWorkspaceOpening( - () => _openPath(path, acceptNavigation: acceptNavigation), - ); + if (state.workspace?.id == workspace.id) { + await _startMonitoring(state.workspace!); + } + return ref.mounted && + state.documentBuffers.any((candidate) => candidate.id == buffer.id); + } + + bool _canReplaceWorkspace( + WorkspaceState prior, + int priorRevision, + bool Function()? acceptNavigation, { + bool allowDirty = false, + }) => + ref.mounted && + acceptNavigation?.call() != false && + priorRevision == _activeDocumentRevision && + state.workspace?.id == prior.workspace?.id && + state.workspace?.openedAt == prior.workspace?.openedAt && + state.documentBuffers.length == prior.documentBuffers.length && + state.documentBuffers.indexed.every( + (entry) => + identical(entry.$2, prior.documentBuffers[entry.$1]) || + (allowDirty + ? _sameClosingSource(prior.documentBuffers[entry.$1], entry.$2) + : _sameCleanClosingSource( + prior.documentBuffers[entry.$1], + entry.$2, + )), + ); + + Future openPath( + String path, { + String? documentPath, + bool Function()? acceptNavigation, + VoidCallback? onOpened, + }) => _trackWorkspaceOpening( + () => _openPath( + path, + documentPath: documentPath, + acceptNavigation: acceptNavigation, + onOpened: onOpened, + ), + ); Future _openPath( String path, { + String? documentPath, bool Function()? acceptNavigation, + VoidCallback? onOpened, }) async { - if (acceptNavigation?.call() == false) return; - if (!propertyEdits.flush()) return; + if (acceptNavigation?.call() == false || !propertyEdits.flush()) return; final prior = state; - final recoveryOwners = Map.of( - _restoredRecoveryOwnerIdsByBuffer, - ); - final closingBuffers = state.documentBuffers; - final historySettled = await _localHistory.flushAll(closingBuffers); - if (!ref.mounted || acceptNavigation?.call() == false) return; - _invalidateFileMonitorWorkspace(); - _removalOperationRevision++; - _cancelPendingDerivedRefresh(); - _cancelAllAutoSaves(); - final operationRevision = _invalidateActiveDocumentOperations(); - _resetSaveTracking(); - _restoredRecoveryOwnerIdsByBuffer.clear(); - state = const WorkspaceState(isLoading: true); - for (final buffer in closingBuffers) { - await _localHistory.handleBufferClosed( - buffer.id, - historySettled: historySettled, - ); + if (acceptNavigation != null && + (prior.hasUnsavedChanges || prior.isLoading)) { + return; } + final priorRevision = _activeDocumentRevision; + final request = ++_pathOpenRequest; + bool currentRequest() => + ref.mounted && + request == _pathOpenRequest && + acceptNavigation?.call() != false; + final closingBuffers = prior.documentBuffers; + int? operationRevision; + // Keep the existing workspace mounted while validating a prospective + // destination. Its authoring state remains usable on any read failure. + _invalidateFileMonitorWorkspace(); + state = prior.copyWith(isLoading: true, clearMessage: true); try { final workspace = await _service.openPath(path); - final active = workspace.activeFilePath; + if (!currentRequest()) return; + if (documentPath != null && + ((workspace.writersideProject == null && + workspace.writersideModule == null) || + !workspace.files.any( + (file) => p.equals(file.absolutePath, documentPath), + ))) { + throw FileSystemException( + 'Recent document is unavailable', + documentPath, + ); + } + final active = documentPath ?? workspace.activeFilePath; final load = active == null ? null : await _service.loadTextWithSnapshot(active); - final text = load?.text ?? ''; - var loadedWorkspace = load == null + if (!currentRequest()) return; + var loadedWorkspace = documentPath == null ? workspace - : workspace.copyWith(activeFileSnapshot: load.snapshot); + : workspace.copyWith( + activeFilePath: documentPath, + openFilePaths: [documentPath], + markdown: null, + ); final buffer = load == null || active == null ? null : _fileBuffer( @@ -4087,7 +4262,8 @@ class WorkspaceController extends Notifier { // editor never synchronously reparses a mismatching model during build. final markdown = loadedWorkspace.markdown; if (buffer != null && - (_writersideSourceMismatch(loadedWorkspace, buffer) || + (documentPath != null || + _writersideSourceMismatch(loadedWorkspace, buffer) || (markdown != null && p.equals(markdown.filePath, active!) && markdown.source != buffer.text))) { @@ -4097,27 +4273,35 @@ class WorkspaceController extends Notifier { {active!: buffer.text}, ); } + if (!currentRequest()) return; final preview = buffer == null ? null : _safePreview(loadedWorkspace, buffer); - if (!_isCurrentActiveDocumentOperation(operationRevision)) { - return; - } - if (acceptNavigation?.call() == false) { - await _restoreCancelledNavigation( - prior, - recoveryOwners: recoveryOwners, - ); + final historySettled = await _localHistory.flushAll(closingBuffers); + if (request != _pathOpenRequest || + !_canReplaceWorkspace(prior, priorRevision, acceptNavigation)) { return; } + _removalOperationRevision++; + _cancelPendingDerivedRefresh(); + _cancelAllAutoSaves(); + operationRevision = _invalidateActiveDocumentOperations(); + _resetSaveTracking(); + _restoredRecoveryOwnerIdsByBuffer.clear(); state = WorkspaceState( isLoading: true, workspace: loadedWorkspace, - activeText: text, preview: preview, documentBuffers: buffer == null ? const [] : [buffer], activeBufferId: buffer?.id, ); + for (final oldBuffer in closingBuffers) { + await _localHistory.handleBufferClosed( + oldBuffer.id, + historySettled: historySettled, + ); + } + if (!_isCurrentActiveDocumentOperation(operationRevision)) return; if (buffer != null) unawaited(_localHistory.observeOpened(buffer)); _recordActivePreviewRevision(); if (buffer != null && @@ -4129,6 +4313,7 @@ class WorkspaceController extends Notifier { state = state.copyWith(isLoading: false); _schedulePersistence(); _resetSaveTracking(); + onOpened?.call(); final recentPath = workspace.kind == WorkspaceKind.singleMarkdown ? workspace.activeFilePath ?? workspace.rootPath : workspace.rootPath; @@ -4149,7 +4334,10 @@ class WorkspaceController extends Notifier { stackTrace, context: {'path': busyMarkLogPath(path)}, ); - if (_isCurrentActiveDocumentOperation(operationRevision)) { + if (request == _pathOpenRequest && + _isCurrentActiveDocumentOperation( + operationRevision ?? priorRevision, + )) { state = state.copyWith( isLoading: false, message: WorkspaceMessage( @@ -4158,88 +4346,175 @@ class WorkspaceController extends Notifier { ), ); } - } - } - - Future _restoreCancelledNavigation( - WorkspaceState prior, { - Map? recoveryOwners, - }) async { - if (recoveryOwners != null) { - _restoredRecoveryOwnerIdsByBuffer - ..clear() - ..addAll(recoveryOwners); - } - state = prior; - _recordActivePreviewRevision(); - if (prior.workspace case final workspace?) { - await _startMonitoring(workspace); - } - for (final buffer in prior.documentBuffers) { - unawaited(_localHistory.observeOpened(buffer)); - _scheduleAutoSave(buffer.id); + } finally { + // A prospective path can fail or be cancelled after the old monitor + // has been invalidated. Resume the retained workspace's monitor. + if (operationRevision == null && + ref.mounted && + request == _pathOpenRequest && + state.workspace?.id == prior.workspace?.id) { + if (state.isLoading) state = state.copyWith(isLoading: false); + if (state.workspace case final workspace?) { + await _startMonitoring(workspace); + } + } } } Future createWritersideProject( - WritersideProjectCreateRequest request, - ) async { - if (!propertyEdits.flush()) return false; - _invalidateFileMonitorWorkspace(); - _removalOperationRevision++; - final closingBuffers = state.documentBuffers; - final historySettled = await _localHistory.flushAll(closingBuffers); - _cancelPendingDerivedRefresh(); - _cancelAllAutoSaves(); - final operationRevision = _invalidateActiveDocumentOperations(); - _resetSaveTracking(); - _restoredRecoveryOwnerIdsByBuffer.clear(); - state = const WorkspaceState(isLoading: true); - for (final buffer in closingBuffers) { - await _localHistory.handleBufferClosed( - buffer.id, - historySettled: historySettled, - ); + WritersideProjectCreateRequest request, { + bool Function()? acceptNavigation, + Future Function(bool Function() isCurrent)? authorizeReplacement, + void Function(WorkspaceMessage)? onError, + void Function(String bufferId)? onPublished, + }) => _trackWorkspaceOpening(() async { + if (acceptNavigation?.call() == false || + !propertyEdits.flush() || + state.isLoading || + (state.hasUnsavedChanges && authorizeReplacement == null)) { + return false; } + final previous = state; + final previousRevision = _activeDocumentRevision; + final creation = ++_writersideProjectCreation; + bool currentRequest() => + ref.mounted && + creation == _writersideProjectCreation && + acceptNavigation?.call() != false; + bool canAuthorize() => + currentRequest() && + !state.isLoading && + _canReplaceWorkspace( + previous, + previousRevision, + acceptNavigation, + allowDirty: true, + ); + + var stillAuthorized = canAuthorize; + var closingBuffers = []; + var discardingRemote = []; + var historySettled = false; + int? publishedRevision; try { - final workspace = await _service.createWritersideProject(request); - final active = workspace.activeFilePath; - final load = active == null - ? null - : await _service.loadTextWithSnapshot(active); - final text = load?.text ?? ''; - final loadedWorkspace = load == null - ? workspace - : workspace.copyWith(activeFileSnapshot: load.snapshot); - final buffer = load == null || active == null - ? null - : _fileBuffer( - active, - load, - mode: _settingsController.state.documentViewMode, - ); - final preview = buffer == null - ? null - : _safePreview(loadedWorkspace, buffer); - if (!_isCurrentActiveDocumentOperation(operationRevision)) { - return false; - } - state = WorkspaceState( - workspace: loadedWorkspace, - activeText: text, - preview: preview, - documentBuffers: buffer == null ? const [] : [buffer], - activeBufferId: buffer?.id, + final created = await _service.publishWritersideProject( + request, + authorize: () async { + if (!canAuthorize() || + (authorizeReplacement != null && + !await authorizeReplacement(canAuthorize)) || + !currentRequest()) { + return false; + } + + // Save As may promote an untitled workspace without changing the + // original openings. A discard stays deferred until publication. + final prior = state; + final priorRevision = _activeDocumentRevision; + final sameWorkspace = + prior.workspace?.id == previous.workspace?.id && + prior.workspace?.openedAt == previous.workspace?.openedAt; + final promoted = + previous.workspace?.kind == WorkspaceKind.untitledMarkdown && + prior.workspace?.kind == WorkspaceKind.singleMarkdown; + if (prior.isLoading || + (!sameWorkspace && !promoted) || + prior.activeBufferId != previous.activeBufferId || + prior.documentBuffers.length != previous.documentBuffers.length || + !prior.documentBuffers.indexed.every( + (entry) => identical( + entry.$2.opening, + previous.documentBuffers[entry.$1].opening, + ), + ) || + prior.dirtyBuffers.any( + (dirty) => !previous.dirtyBuffers.any( + (before) => _sameClosingSource(before, dirty), + ), + )) { + return false; + } + stillAuthorized = () => + currentRequest() && + !state.isLoading && + _canReplaceWorkspace( + prior, + priorRevision, + acceptNavigation, + allowDirty: true, + ); + + final remote = prior.dirtyBuffers + .where((buffer) => buffer.isRemote) + .map((buffer) => buffer.id) + .toList(); + if (remote.any(_pendingRemoteDiscards.contains)) return false; + discardingRemote = remote; + _pendingRemoteDiscards.addAll(discardingRemote); + closingBuffers = prior.documentBuffers; + for (final dirty in prior.dirtyBuffers) { + if (!_localHistory.canDiscardPristineDraft(dirty) && + !await _localHistory.captureBeforeLoss( + LocalHistoryBufferSnapshot.fromBuffer(dirty), + LocalHistoryCaptureReason.beforeDiscard, + )) { + return false; + } + } + historySettled = await _localHistory.flushAll(closingBuffers); + return stillAuthorized(); + }, + canPublish: () => stillAuthorized(), + accept: (workspace, isCurrent) async { + final active = workspace.activeFilePath!; + final load = await _service.loadTextWithSnapshot(active); + final buffer = _fileBuffer( + active, + load, + mode: _settingsController.state.documentViewMode, + ); + final preview = _safePreview(workspace, buffer); + if (!isCurrent()) return null; + + _workspaceRefreshDebounce?.cancel(); + _workspaceRefreshDebounce = null; + _invalidateFileMonitorWorkspace(); + _removalOperationRevision++; + _cancelPendingDerivedRefresh(); + _cancelAllAutoSaves(); + publishedRevision = _invalidateActiveDocumentOperations(); + _resetSaveTracking(); + _restoredRecoveryOwnerIdsByBuffer.clear(); + state = WorkspaceState( + workspace: workspace, + preview: preview, + documentBuffers: [buffer], + activeBufferId: buffer.id, + ); + return (workspace, buffer); + }, ); - if (buffer != null) unawaited(_localHistory.observeOpened(buffer)); - _recordActivePreviewRevision(); - if (buffer != null && - _writersideSourceMismatch(loadedWorkspace, buffer)) { - _requestDerivedRefresh(rebuildPreview: true); + if (created == null) return false; + final (workspace, buffer) = created; + final revision = publishedRevision!; + if (_isCurrentActiveDocumentOperation(revision)) { + unawaited(_localHistory.observeOpened(buffer)); + _recordActivePreviewRevision(); + if (_writersideSourceMismatch(workspace, buffer)) { + _requestDerivedRefresh(rebuildPreview: true); + } + _schedulePersistence(); + onPublished?.call(buffer.id); } - await _startMonitoring(loadedWorkspace); - _schedulePersistence(); - _resetSaveTracking(); + for (final old in closingBuffers) { + await _localHistory.handleBufferClosed( + old.id, + historySettled: historySettled, + ); + } + if (!_isCurrentActiveDocumentOperation(revision)) return true; + await _startMonitoring(workspace); + if (!_isCurrentActiveDocumentOperation(revision)) return true; await _publishRecent( () => _settingsController.recordOpenedWorkspace( path: workspace.rootPath, @@ -4257,18 +4532,24 @@ class WorkspaceController extends Notifier { 'directory': request.directoryName, }, ); - if (_isCurrentActiveDocumentOperation(operationRevision)) { - state = state.copyWith( - isLoading: false, - message: WorkspaceMessage( - WorkspaceMessageCode.createWritersideProjectFailed, - error: error, - ), + if (publishedRevision != null) return true; + if (stillAuthorized()) { + final message = WorkspaceMessage( + WorkspaceMessageCode.createWritersideProjectFailed, + error: error, ); + if (onError case final report?) { + report(message); + } else { + state = state.copyWith(message: message); + } } return false; + } finally { + _pendingRemoteDiscards.removeAll(discardingRemote); + if (discardingRemote.isNotEmpty && ref.mounted) _schedulePersistence(); } - } + }); Future createWritersideTopic( WritersideTopicCreateRequest request, { @@ -4518,15 +4799,20 @@ class WorkspaceController extends Notifier { Future createWorkspaceFile( String directoryPath, - String fileName, - ) async { - final created = await _runWorkspaceFileOperation((workspace) async { - return _service.createFile(workspace, directoryPath, fileName); - }); - if (created) { - await _showEditorForNewFile(); + String fileName, { + bool focusSource = false, + }) async { + final request = focusSource ? BusyMarkDeferredEditorFocus() : null; + try { + final created = await _runWorkspaceFileOperation( + (workspace) => _service.createFile(workspace, directoryPath, fileName), + creationFocus: request, + ); + if (created) await _showEditorForNewFile(); + return created; + } finally { + if (_creationFocus?.request != request) request?.cancel(); } - return created; } Future prepareMarkdownMove( @@ -5639,14 +5925,11 @@ class WorkspaceController extends Notifier { state = state.copyWith( workspace: workspace.copyWith( activeFilePath: null, - activeFileModifiedAt: null, - activeFileSnapshot: null, openFilePaths: const [], sourceOverrides: const {}, diagnostics: diagnostics, markdown: null, ), - activeText: '', preview: null, documentBuffers: const [], activeBufferId: null, @@ -5683,6 +5966,7 @@ class WorkspaceController extends Notifier { Future _openActiveFile( String path, { + BusyMarkDeferredEditorFocus? creationFocus, List? openFilePaths, List? documentBuffers, bool Function()? acceptNavigation, @@ -5726,7 +6010,6 @@ class WorkspaceController extends Notifier { final load = await _service.loadTextWithSnapshot(path); final nextWorkspace = workspace.copyWith( activeFilePath: path, - activeFileSnapshot: load.snapshot, openFilePaths: requestedOpenFilePaths, ); if (acceptNavigation?.call() == false || @@ -5785,15 +6068,14 @@ class WorkspaceController extends Notifier { : (state.workspace ?? nextWorkspace).copyWith(markdown: null)) .copyWith( activeFilePath: path, - activeFileSnapshot: load.snapshot, openFilePaths: reconciledOpenPaths, ); if (sourcesCurrent) { _preparedInputs[publishedWorkspace] = _preparedInputs[reparsed]; } + _retainCreationFocus(buffer, creationFocus); state = state.copyWith( workspace: publishedWorkspace, - activeText: load.text, preview: sourcesCurrent ? _safePreview(publishedWorkspace, buffer) : null, @@ -5841,6 +6123,7 @@ class WorkspaceController extends Notifier { required List documentBuffers, required List openFilePaths, bool Function()? acceptNavigation, + BusyMarkDeferredEditorFocus? creationFocus, }) async { if (acceptNavigation?.call() == false) return false; if (!propertyEdits.flush()) return false; @@ -5876,7 +6159,6 @@ class WorkspaceController extends Notifier { ]; final nextWorkspace = workspace.copyWith( activeFilePath: buffer.filePath, - activeFileSnapshot: buffer.diskSnapshot, openFilePaths: openFilePaths, markdown: null, ); @@ -6001,12 +6283,12 @@ class WorkspaceController extends Notifier { : (state.workspace ?? nextWorkspace).copyWith(markdown: null)) .copyWith( activeFilePath: liveBuffer.filePath, - activeFileSnapshot: liveBuffer.diskSnapshot, openFilePaths: reconciledOpenPaths, ); if (sourceStayedCurrent) { _preparedInputs[publishedWorkspace] = _preparedInputs[reparsed]; } + if (creationFocus != null) _retainCreationFocus(liveBuffer, creationFocus); state = state.copyWith( workspace: publishedWorkspace, preview: sourceStayedCurrent @@ -6049,8 +6331,11 @@ class WorkspaceController extends Notifier { // allow only that metadata refresh. Dirty discard and all source, filesystem // identity, origin and permission changes still invalidate publication. bool _sameCleanClosingSource(DocumentBuffer before, DocumentBuffer live) => - !before.isDirty && - !live.isDirty && + !before.isDirty && !live.isDirty && _sameClosingSource(before, live); + + bool _sameClosingSource(DocumentBuffer before, DocumentBuffer live) => + before.isDirty == live.isDirty && + identical(before.opening, live.opening) && before.id == live.id && before.revision == live.revision && before.text == live.text && @@ -6064,7 +6349,10 @@ class WorkspaceController extends Notifier { identical(before.format, live.format) && before.remoteNote == live.remoteNote && before.remoteTitle == live.remoteTitle && - identical(before.remoteEditBase, live.remoteEditBase) && + // Notes notifications can rebuild the wrapper around the same captured + // server state. Only a change to the provenance invalidates the close. + identical(before.remoteEditBase?.state, live.remoteEditBase?.state) && + before.remoteEditBase?.generation == live.remoteEditBase?.generation && before.readonly == live.readonly && before.recovered == live.recovered; @@ -6122,23 +6410,13 @@ class WorkspaceController extends Notifier { /// Rebuilds identities from the current editor buffers before navigation or /// refactoring; an inactive, unsaved dependency is still authoritative. Future writersideEditorIndex() async { - var project = state.workspace?.writersideProject; - if (project == null) return null; - final buffers = state.documentBuffers; - for (final module in project.modules.toList()) { - final loaded = await _service.writersideService.load( - module.rootPath, - sourceOverrides: { - ...module.sourceOverrides, - for (final buffer in buffers) - if (buffer.filePath != null && - p.isWithin(module.rootPath, buffer.filePath!)) - buffer.filePath!: buffer.text, - }, - ); - project = project!.withModule(loaded); - } - return project!.index; + final workspace = state.workspace; + if (workspace?.writersideProject == null) return null; + final prepared = await _service.withDocumentSources(workspace!, { + for (final buffer in state.documentBuffers) + if (buffer.filePath != null) buffer.filePath!: buffer.text, + }); + return prepared.writersideProject?.index; } /// Stages a rename in normal undoable document buffers. All source ranges @@ -6224,6 +6502,7 @@ class WorkspaceController extends Notifier { } void updateActiveEditorMode(DocumentViewModePreference mode) { + _cancelCreationFocus(); if (!propertyEdits.flush()) return; final buffer = state.activeBuffer; if (buffer == null || buffer.editorState.mode == mode) { @@ -6455,7 +6734,6 @@ class WorkspaceController extends Notifier { return false; } final nextWorkspace = selected.copyWith( - activeFileSnapshot: load.snapshot, openFilePaths: _openFileTabPaths(selected, path), ); final buffer = _fileBuffer( @@ -6888,11 +7166,7 @@ class WorkspaceController extends Notifier { recovered: false, ); final remainsActive = state.activeBufferId == target.bufferId; - final nextWorkspace = remainsActive - ? currentWorkspace.copyWith(activeFileSnapshot: snapshot) - : currentWorkspace; state = state.copyWith( - workspace: nextWorkspace, documentBuffers: _replaceBuffer(state.documentBuffers, savedBuffer), clearMessage: true, ); @@ -6925,8 +7199,9 @@ class WorkspaceController extends Notifier { _workspaceContainsBuffer(target.workspaceId, target.bufferId)) { state = state.copyWith( message: error is AtomicFileChangedException - ? const WorkspaceMessage( + ? WorkspaceMessage( WorkspaceMessageCode.saveBlockedFileChangedOnDisk, + error: error, ) : WorkspaceMessage(WorkspaceMessageCode.saveFailed, error: error), ); @@ -6975,7 +7250,6 @@ class WorkspaceController extends Notifier { return; } final nextWorkspace = reparsed.copyWith( - activeFileSnapshot: snapshot, openFilePaths: currentWorkspace.openFilePaths, files: currentWorkspace.files, ); @@ -7083,16 +7357,18 @@ class WorkspaceController extends Notifier { return _BufferWriteResult.conflict; } final path = target.filePath!; - if (await _service.fileChangedSince(path, current.diskSnapshot)) { + if (current.diskSnapshot == null || + await _service.fileChangedSince(path, current.diskSnapshot)) { return _BufferWriteResult.conflict; } try { - final snapshot = await _service.saveText( + final snapshot = await _service.saveTextIfUnchanged( path, target.format.formattedText( target.text, mixedNormalization: normalization, ), + expectedSnapshot: current.diskSnapshot!, ); final latest = state.documentBuffers .where((buffer) => buffer.id == target.id) @@ -7117,9 +7393,6 @@ class WorkspaceController extends Notifier { ); state = state.copyWith( documentBuffers: _replaceBuffer(state.documentBuffers, next), - workspace: state.activeBufferId == target.id - ? state.workspace?.copyWith(activeFileSnapshot: snapshot) - : state.workspace, ); await _localHistory.captureSaved( LocalHistoryBufferSnapshot( @@ -7132,6 +7405,16 @@ class WorkspaceController extends Notifier { ), ); return _BufferWriteResult.saved; + } on AtomicFileChangedException catch (error) { + if (ref.mounted) { + state = state.copyWith( + message: WorkspaceMessage( + WorkspaceMessageCode.saveBlockedFileChangedOnDisk, + error: error, + ), + ); + } + return _BufferWriteResult.conflict; } on Object { return _BufferWriteResult.failed; } @@ -7141,6 +7424,7 @@ class WorkspaceController extends Notifier { String path, { ActiveDocumentSaveTarget? target, bool overwriteExisting = false, + SaveDestination? authorization, LineEndingNormalization? mixedLineEndingNormalization, }) async { if (target != null && !isActiveDocumentSaveTargetCurrent(target)) { @@ -7156,13 +7440,16 @@ class WorkspaceController extends Notifier { _cancelPendingDerivedRefresh(); return _enqueueBufferWrite(operationTarget.bufferId, () async { final refreshedTarget = _refreshBufferSaveTarget(operationTarget); - if (refreshedTarget == null) { + if (refreshedTarget == null || + (authorization != null && + !isActiveDocumentSaveTargetCurrent(operationTarget))) { return false; } return _saveActiveAsNow( path, target: refreshedTarget, - overwriteExisting: overwriteExisting, + overwriteExisting: authorization?.replacesExisting ?? overwriteExisting, + authorization: authorization, mixedLineEndingNormalization: mixedLineEndingNormalization, ); }); @@ -7188,10 +7475,12 @@ class WorkspaceController extends Notifier { String path, { required ActiveDocumentSaveTarget target, required bool overwriteExisting, + required SaveDestination? authorization, required LineEndingNormalization? mixedLineEndingNormalization, }) async { if (target.workspaceKind == WorkspaceKind.nextcloudNotes) { try { + authorization?.requireCurrent(path); final buffer = state.documentBuffers .where((buffer) => buffer.id == target.bufferId) .firstOrNull; @@ -7207,6 +7496,10 @@ class WorkspaceController extends Notifier { destinationPath: path, media: media.context, overwrite: overwriteExisting, + authorization: authorization, + isCancelled: authorization == null + ? null + : () => !isActiveDocumentSaveTargetCurrent(target), ); // Save As exports a copy; it never promotes a remote identity to a path. return true; @@ -7244,6 +7537,7 @@ class WorkspaceController extends Notifier { String? destinationCleanupOperationId; WorkspaceFileSnapshot? protectedDestinationSnapshot; try { + authorization?.requireCurrent(path); final destinationExisted = overwriteExisting && await _service.pathExists(path); if (destinationExisted) { @@ -7310,43 +7604,54 @@ class WorkspaceController extends Notifier { )) { return false; } - if (destinationOwnedByAnotherBuffer()) return false; + bool stillCurrent() => + !destinationOwnedByAnotherBuffer() && + (authorization == null || isActiveDocumentSaveTargetCurrent(target)); + if (!stillCurrent()) return false; + authorization?.requireCurrent(path); + final text = target.format.formattedText( + target.text, + mixedNormalization: mixedLineEndingNormalization, + ); + Future onPublished() async { + historyPathCommitted = true; + historySaveAsStillCurrent = + await _commitSavedAsSourceRecoveryAfterPublication( + savedAsSourceRecoveryOwner, + ); + } + WorkspaceFileSnapshot? savedSnapshot; try { if (overwriteExisting) { - savedSnapshot = await _service.saveTextReplacingPathIfUnchanged( - path, - target.format.formattedText( - target.text, - mixedNormalization: mixedLineEndingNormalization, - ), - expectedSnapshot: protectedDestinationSnapshot!, - onPublished: () async { - historyPathCommitted = true; - historySaveAsStillCurrent = - await _commitSavedAsSourceRecoveryAfterPublication( - savedAsSourceRecoveryOwner, - ); - }, - ); + savedSnapshot = authorization == null + ? await _service.saveTextReplacingPathIfUnchanged( + path, + text, + expectedSnapshot: protectedDestinationSnapshot!, + onPublished: onPublished, + ) + : await _service.saveFormattedTextReplacingPath( + path, + text, + expectedSnapshot: protectedDestinationSnapshot!, + authorization: authorization, + stillCurrent: stillCurrent, + onPublished: onPublished, + ); } else { savedSnapshot = await _localHistory.runStagedPathDeletion( path: path, recursive: false, - filesystemOperation: () => _service.saveNewText( - path, - target.format.formattedText( - target.text, - mixedNormalization: mixedLineEndingNormalization, - ), - onPublished: () async { - historyPathCommitted = true; - historySaveAsStillCurrent = - await _commitSavedAsSourceRecoveryAfterPublication( - savedAsSourceRecoveryOwner, - ); - }, - ), + filesystemOperation: () => authorization == null + ? _service.saveNewText(path, text, onPublished: onPublished) + : _service.saveNewFormattedText( + path, + text, + authorization: authorization, + stillCurrent: stillCurrent, + onPublished: onPublished, + ), didCommit: (_) => true, committedAfterError: () async => historyPathCommitted, commitEvidenceOperationId: savedAsSourceRecoveryOwner, @@ -7443,7 +7748,6 @@ class WorkspaceController extends Notifier { final workspaceBase = openedWorkspace ?? currentWorkspace; final savedWorkspace = workspaceBase.copyWith( activeFilePath: activeBuffer?.filePath, - activeFileSnapshot: activeBuffer?.diskSnapshot, openFilePaths: tabPaths, markdown: activeBuffer?.filePath == null ? currentWorkspace.markdown @@ -7641,10 +7945,7 @@ class WorkspaceController extends Notifier { } _cancelAutoSave(operationTarget.bufferId); _cancelPendingDerivedRefresh(); - return _enqueueBufferWrite( - operationTarget.bufferId, - () => _discardBufferChangesNow(operationTarget), - ); + return _discardBufferChanges(operationTarget); } /// Discards the selected buffers without changing the active document. @@ -7673,10 +7974,7 @@ class WorkspaceController extends Notifier { ); _cancelAutoSave(buffer.id); _cancelPendingDerivedRefresh(); - final discarded = await _enqueueBufferWrite( - buffer.id, - () => _discardBufferChangesNow(target), - ); + final discarded = await _discardBufferChanges(target); if (!discarded) return false; } return true; @@ -7904,6 +8202,7 @@ class WorkspaceController extends Notifier { required LocalHistoryRevision revision, required String destinationPath, required bool overwriteExisting, + SaveDestination? authorization, }) async { if (revision.summary.documentId != document.id) return false; final path = p.normalize(p.absolute(destinationPath)); @@ -7927,11 +8226,13 @@ class WorkspaceController extends Notifier { WorkspaceFileSnapshot? createdSnapshot; void Function()? stopWatchingTarget; try { + authorization?.requireCurrent(path); if (!existed) { createdSnapshot = await _service.saveNewFormattedText( path, '', format: revision.format, + authorization: authorization, ); } var destination = state.bufferForPath(path); @@ -7964,6 +8265,7 @@ class WorkspaceController extends Notifier { } // Keep destination formatting while making the editor's canonical source // agree with the bytes that Save will produce under that policy. + if (existed) authorization?.requireCurrent(path); final restoredText = createdSnapshot != null ? revision.source : _withFinalNewlinePolicy( @@ -8015,6 +8317,7 @@ class WorkspaceController extends Notifier { } return false; } + if (existed) authorization?.requireCurrent(path); final current = state.documentBuffers .where((buffer) => buffer.id == target.bufferId) .firstOrNull!; @@ -8270,6 +8573,25 @@ class WorkspaceController extends Notifier { ); } + Future _discardBufferChanges(ActiveDocumentSaveTarget target) async { + final remote = target.workspaceKind == WorkspaceKind.nextcloudNotes; + final bufferId = target.bufferId; + // History protection persists the session while discard owns the buffer + // write queue. The protected text belongs in History, not the note outbox. + if (remote && !_pendingRemoteDiscards.add(bufferId)) return false; + try { + return await _enqueueBufferWrite( + bufferId, + () => _discardBufferChangesNow(target), + ); + } finally { + if (remote) { + _pendingRemoteDiscards.remove(bufferId); + if (ref.mounted) _schedulePersistence(); + } + } + } + Future _discardBufferChangesNow( ActiveDocumentSaveTarget operationTarget, ) async { @@ -8293,18 +8615,22 @@ class WorkspaceController extends Notifier { )) { return false; } - final latest = state.documentBuffers - .where((b) => b.id == current.id) - .firstOrNull; - if (!identical(latest, current)) return false; final cached = (await _ensureNotesRepository()).noteById( current.remoteNote!.localId, ); - if (cached == null) return false; + if (cached == null || + !ref.mounted || + !_isBufferSaveTargetCurrent(refreshedTarget)) { + return false; + } + final latest = state.documentBuffers.firstWhere( + (b) => b.id == current.id, + ); + if (latest.remoteNote != current.remoteNote) return false; state = state.copyWith( documentBuffers: _replaceBuffer( state.documentBuffers, - current + latest .replaced(cached.content) .copyWith( lastSavedText: cached.content, @@ -8366,9 +8692,7 @@ class WorkspaceController extends Notifier { return false; } state = state.copyWith( - workspace: remainsActive - ? currentWorkspace.copyWith(activeFileSnapshot: load.snapshot) - : currentWorkspace, + workspace: currentWorkspace, documentBuffers: _replaceBuffer(state.documentBuffers, discardedBuffer), clearMessage: true, ); @@ -8594,7 +8918,6 @@ class WorkspaceController extends Notifier { _acceptedRefreshRevision = refreshRevision; final publishedWorkspace = reparsed.copyWith( activeFilePath: activeBuffer?.filePath, - activeFileSnapshot: activeBuffer?.diskSnapshot, openFilePaths: tabPaths, ); _preparedInputs[publishedWorkspace] = _preparedInputs[reparsed]; @@ -8729,7 +9052,6 @@ class WorkspaceController extends Notifier { } final nextWorkspace = refreshedWorkspace.copyWith( activeFilePath: activeBuffer?.filePath, - activeFileSnapshot: activeBuffer?.diskSnapshot, openFilePaths: _refreshTabPaths(buffers), ); if (activeBuffer != null) { @@ -8760,11 +9082,13 @@ class WorkspaceController extends Notifier { Future _runWorkspaceFileOperation( Future Function(Workspace workspace) operation, { bool openForEditing = false, + BusyMarkDeferredEditorFocus? creationFocus, }) async { final workspace = state.workspace; if (workspace == null) { return false; } + final initialNavigation = _activeDocumentRevision; final before = _incorporatedDiskStates(workspace, state.documentBuffers); _reconciledNotifications = null; _workspaceFileOperationDepth++; @@ -8775,13 +9099,21 @@ class WorkspaceController extends Notifier { if (!ref.mounted || state.workspace?.id != workspace.id) { return false; } + if (initialNavigation != _activeDocumentRevision) creationFocus?.cancel(); + final expectedNavigation = _activeDocumentRevision + 1; final refreshed = await refreshWorkspaceFromDiskPreservingOpenTabs(); if (!refreshed) { return false; } await _acknowledgeHistoryOperationsAfterWorkspaceRefresh(); if (preferredActivePath != null) { - final opened = await _openActiveFile(preferredActivePath); + if (expectedNavigation != _activeDocumentRevision) { + creationFocus?.cancel(); + } + final opened = await _openActiveFile( + preferredActivePath, + creationFocus: creationFocus, + ); if (opened && openForEditing && state.activeBuffer?.filePath == preferredActivePath && @@ -9101,9 +9433,7 @@ class WorkspaceController extends Notifier { !_preparedInputsCurrent(reparsed, state.documentBuffers)) { return outcome(ValidationStatus.stale); } - final currentSnapshot = currentWorkspace.activeFileSnapshot; final validatedWorkspace = reparsed.copyWith( - activeFileSnapshot: currentSnapshot, openFilePaths: currentWorkspace.openFilePaths, files: currentWorkspace.files, runtimeDiagnostics: currentWorkspace.runtimeDiagnostics, @@ -9260,7 +9590,8 @@ class WorkspaceController extends Notifier { } if (target.isRemote) return _saveRemoteBufferSnapshot(target); final path = target.filePath!; - if (await _service.fileChangedSince(path, target.diskSnapshot)) { + if (target.diskSnapshot == null || + await _service.fileChangedSince(path, target.diskSnapshot)) { return false; } final beforeWrite = state.documentBuffers @@ -9271,9 +9602,10 @@ class WorkspaceController extends Notifier { return false; } try { - final snapshot = await _service.saveText( + final snapshot = await _service.saveTextIfUnchanged( path, target.format.formattedText(target.text), + expectedSnapshot: target.diskSnapshot!, ); final current = state.documentBuffers .where((buffer) => buffer.id == bufferId) @@ -9292,9 +9624,6 @@ class WorkspaceController extends Notifier { ); state = state.copyWith( documentBuffers: _replaceBuffer(state.documentBuffers, next), - workspace: state.activeBufferId == bufferId - ? state.workspace?.copyWith(activeFileSnapshot: snapshot) - : state.workspace, clearMessage: true, ); _schedulePersistence(); @@ -9318,6 +9647,7 @@ class WorkspaceController extends Notifier { } int _invalidateActiveDocumentOperations() { + _cancelCreationFocus(); _activeDocumentRevision++; return _activeDocumentRevision; } diff --git a/lib/src/workspace/workspace_file_monitor.dart b/lib/src/workspace/workspace_file_monitor.dart index 1ab4b649..a95fa5d2 100644 --- a/lib/src/workspace/workspace_file_monitor.dart +++ b/lib/src/workspace/workspace_file_monitor.dart @@ -244,6 +244,8 @@ bool _isBusyMarkTemporaryPath(String path) { .split(p.separator) .any( (part) => + part.startsWith('.busymark-save-') || + part.startsWith('.busymark-recovery-') || part.startsWith('.busymark-state-') || part.startsWith('.busymark-settings-') || part.startsWith('.busymark-export-'), diff --git a/lib/src/workspace/workspace_message.dart b/lib/src/workspace/workspace_message.dart index cb290131..15883a69 100644 --- a/lib/src/workspace/workspace_message.dart +++ b/lib/src/workspace/workspace_message.dart @@ -2,6 +2,7 @@ import 'package:flutter/widgets.dart'; import '../app/localization.dart'; import '../core/busymark_exception.dart'; +import '../core/atomic_file_writer.dart'; enum WorkspaceMessageCode { openFailed, @@ -44,7 +45,10 @@ String localizeWorkspaceMessage( WorkspaceMessageCode.chooseWhereToSaveMarkdown => l10n.workspaceErrorChooseWhereToSaveMarkdown, WorkspaceMessageCode.saveBlockedFileChangedOnDisk => - l10n.workspaceErrorSaveBlockedFileChangedOnDisk, + message.error is AtomicFileChangedException && + (message.error as AtomicFileChangedException).recoveryPath != null + ? '${l10n.workspaceErrorSaveBlockedFileChangedOnDisk}\n$error' + : l10n.workspaceErrorSaveBlockedFileChangedOnDisk, WorkspaceMessageCode.saveFailed => l10n.workspaceErrorSaveFailed(error), WorkspaceMessageCode.fileOperationFailed => l10n.workspaceErrorFileOperationFailed(error), diff --git a/lib/src/workspace/workspace_model.dart b/lib/src/workspace/workspace_model.dart index 8932d849..c55382ab 100644 --- a/lib/src/workspace/workspace_model.dart +++ b/lib/src/workspace/workspace_model.dart @@ -9,7 +9,6 @@ import '../writerside/writerside_model.dart'; import '../writerside/writerside_project.dart'; import 'document_buffer.dart'; import 'workspace_message.dart'; -import 'workspace_file_snapshot.dart'; export 'workspace_file_snapshot.dart'; @@ -290,16 +289,12 @@ class Workspace { this.directories = const [], List openFilePaths = const [], this.activeFilePath, - DateTime? activeFileModifiedAt, - this.activeFileSnapshot, this.markdown, this.writersideModule, this.writersideProject, this.nextcloudAccountId, }) : filesystemRootPath = rootPath, - openFilePaths = _normalizedOpenFilePaths(openFilePaths, activeFilePath), - activeFileModifiedAt = - activeFileModifiedAt ?? activeFileSnapshot?.modifiedAt; + openFilePaths = _normalizedOpenFilePaths(openFilePaths, activeFilePath); final String id; final String? filesystemRootPath; @@ -323,8 +318,6 @@ class Workspace { final WorkspaceKind kind; final DateTime openedAt; final String? activeFilePath; - final DateTime? activeFileModifiedAt; - final WorkspaceFileSnapshot? activeFileSnapshot; final List openFilePaths; final List files; final List directories; @@ -341,8 +334,6 @@ class Workspace { Workspace copyWith({ Object? activeFilePath = _copyWithUnset, - Object? activeFileModifiedAt = _copyWithUnset, - Object? activeFileSnapshot = _copyWithUnset, List? openFilePaths, List? files, List? directories, @@ -356,14 +347,6 @@ class Workspace { final nextActiveFilePath = identical(activeFilePath, _copyWithUnset) ? this.activeFilePath : activeFilePath as String?; - final nextSnapshot = identical(activeFileSnapshot, _copyWithUnset) - ? this.activeFileSnapshot - : activeFileSnapshot as WorkspaceFileSnapshot?; - final nextModifiedAt = identical(activeFileModifiedAt, _copyWithUnset) - ? identical(activeFileSnapshot, _copyWithUnset) - ? this.activeFileModifiedAt - : nextSnapshot?.modifiedAt - : activeFileModifiedAt as DateTime?; final nextMarkdown = identical(markdown, _copyWithUnset) ? this.markdown : markdown as ParsedMarkdownDocument?; @@ -379,8 +362,6 @@ class Workspace { kind: kind, openedAt: openedAt, activeFilePath: nextActiveFilePath, - activeFileModifiedAt: nextModifiedAt, - activeFileSnapshot: nextSnapshot, openFilePaths: openFilePaths ?? this.openFilePaths, files: files ?? this.files, directories: directories ?? this.directories, @@ -439,22 +420,17 @@ List _normalizedOpenFilePaths( class WorkspaceState { const WorkspaceState({ this.workspace, - String activeText = '', this.preview, this.liveOutline, - bool isDirty = false, this.documentBuffers = const [], this.activeBufferId, this.isLoading = false, this.message, - }) : _legacyActiveText = activeText, - _legacyIsDirty = isDirty; + }); final Workspace? workspace; - final String _legacyActiveText; final PreviewDocument? preview; final ActiveDocumentOutline? liveOutline; - final bool _legacyIsDirty; final List documentBuffers; final String? activeBufferId; final bool isLoading; @@ -473,13 +449,11 @@ class WorkspaceState { return null; } - String get activeText => activeBuffer?.text ?? _legacyActiveText; + String get activeText => activeBuffer?.text ?? ''; - bool get isDirty => activeBuffer?.isDirty ?? _legacyIsDirty; + bool get isDirty => activeBuffer?.isDirty ?? false; - bool get hasUnsavedChanges => documentBuffers.isEmpty - ? _legacyIsDirty - : documentBuffers.any((buffer) => buffer.isDirty); + bool get hasUnsavedChanges => documentBuffers.any((buffer) => buffer.isDirty); List get dirtyBuffers => List.unmodifiable(documentBuffers.where((buffer) => buffer.isDirty)); @@ -495,10 +469,8 @@ class WorkspaceState { WorkspaceState copyWith({ Workspace? workspace, - String? activeText, Object? preview = _copyWithUnset, Object? liveOutline = _copyWithUnset, - bool? isDirty, List? documentBuffers, Object? activeBufferId = _copyWithUnset, bool? isLoading, @@ -516,10 +488,8 @@ class WorkspaceState { : this.liveOutline; return WorkspaceState( workspace: workspace ?? this.workspace, - activeText: activeText ?? _legacyActiveText, preview: nextPreview, liveOutline: nextLiveOutline, - isDirty: isDirty ?? _legacyIsDirty, documentBuffers: documentBuffers ?? this.documentBuffers, activeBufferId: identical(activeBufferId, _copyWithUnset) ? this.activeBufferId diff --git a/lib/src/workspace/workspace_navigation.dart b/lib/src/workspace/workspace_navigation.dart new file mode 100644 index 00000000..bd2d5aed --- /dev/null +++ b/lib/src/workspace/workspace_navigation.dart @@ -0,0 +1,127 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; + +import '../app/app_router.dart'; +import '../app/busymark_toast.dart'; +import '../app/localization.dart'; +import '../nextcloud_notes/presentation/nextcloud_settings.dart'; +import '../search/search_session.dart'; +import 'workspace_controller.dart'; +import 'workspace_safety.dart'; +import 'workspace_tab_actions.dart'; + +final workspaceNavigationProvider = Provider(WorkspaceNavigation.new); + +/// Owns resource navigation for the lifetime of the window. Its dialogs use +/// the root navigator even when a header, search row or workspace disappears. +class WorkspaceNavigation { + WorkspaceNavigation(this._ref) : router = _ref.read(appRouterProvider) { + var location = router.routeInformationProvider.value.uri; + void routeChanged() { + final next = router.routeInformationProvider.value.uri; + if (next == location) return; + location = next; + _intent = null; + _revision++; + } + + router.routeInformationProvider.addListener(routeChanged); + _ref.onDispose(() { + router.routeInformationProvider.removeListener(routeChanged); + }); + } + + final Ref _ref; + ProviderContainer get container => _ref.container; + final GoRouter router; + int _revision = 0; + Object? _intent; + Future? _finishing; + + BuildContext? get dialogContext => + router.routerDelegate.navigatorKey.currentContext; + + Future run( + Object intent, + Future Function(Uri origin, bool Function() isCurrent) navigate, + ) async { + if (_intent == intent) return; + _intent = intent; + final revision = ++_revision; + final origin = router.routeInformationProvider.value.uri; + final previous = _finishing; + final finished = Completer(); + _finishing = finished.future; + bool current() => _ref.mounted && revision == _revision; + try { + // Let a superseded operation release any controller loading state + // before the next intent starts against that workspace. + if (previous != null) await previous; + if (current()) await navigate(origin, current); + } finally { + if (identical(_finishing, finished.future)) _finishing = null; + if (revision == _revision) _intent = null; + finished.complete(); + } + } + + Future confirmDeparture({ + required bool Function() canContinue, + bool deferDiscard = false, + }) async { + final context = dialogContext; + return context != null && + canContinue() && + await confirmWorkspaceDeparture( + context, + container, + canContinue: canContinue, + deferDiscard: deferDiscard, + ); + } + + Future goHome() => run(this, (origin, isCurrent) async { + final context = dialogContext; + if (origin.path == '/' || + context == null || + (router.routerDelegate.navigatorKey.currentState?.canPop() ?? false)) { + return; + } + if (origin.path == settingsRoutePath && + !await confirmNotesSettingsDeparture(context)) { + return; + } + if (!isCurrent()) return; + if (settingsReturnTargetForUri(origin) == SettingsReturnTarget.workspace && + !await confirmDeparture(canContinue: isCurrent)) { + return; + } + if (isCurrent()) router.go('/'); + }); + + void reveal({bool focusNewDocument = false}) { + _ref.read(revealOpenedDocumentProvider)(); + _ref.read(searchSessionProvider.notifier).close(restoreFocus: false); + if (focusNewDocument) { + final id = _ref.read(workspaceControllerProvider).activeBufferId; + if (id != null) { + _ref + .read(workspaceControllerProvider.notifier) + .focusNewlyCreatedDocument(id); + } + } + router.go('/workspace'); + } + + void showUnavailable() { + final context = dialogContext; + if (context == null) return; + BusyMarkToastOverlay.show( + context, + message: context.l10n.searchResourceUnavailable, + ); + } +} diff --git a/lib/src/workspace/workspace_resource_actions.dart b/lib/src/workspace/workspace_resource_actions.dart new file mode 100644 index 00000000..fcbbd1ab --- /dev/null +++ b/lib/src/workspace/workspace_resource_actions.dart @@ -0,0 +1,183 @@ +import 'package:file_selector/file_selector.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:path/path.dart' as p; + +import '../app/app_router.dart'; +import '../app/app_settings.dart'; +import '../app/busymark_design.dart'; +import '../app/busymark_dialogs.dart'; +import '../app/localization.dart'; +import '../nextcloud_notes/presentation/nextcloud_settings.dart'; +import '../search/welcome_notes_action.dart'; +import 'presentation/create_writerside_project_dialog.dart'; +import 'workspace_controller.dart'; +import 'workspace_navigation.dart'; + +enum WorkspaceResourceAction { + newMarkdown, + newNote, + newWriterside, + openMarkdown, + openFolder, + browseNotes; + + static WorkspaceResourceAction forNotes(WelcomeNotesAction action) => + switch (action) { + WelcomeNotesAction.create => newNote, + WelcomeNotesAction.browse => browseNotes, + }; +} + +Future performWorkspaceResourceAction( + WidgetRef ref, + WorkspaceResourceAction action, +) { + final navigation = ref.read(workspaceNavigationProvider); + return navigation.run(action, (origin, currentRequest) async { + final context = navigation.dialogContext; + if (context == null) return; + final container = navigation.container; + final controller = container.read(workspaceControllerProvider.notifier); + final lastPath = container + .read(appSettingsControllerProvider) + .lastOpenedPath; + final initialDirectory = lastPath == null || lastPath.isEmpty + ? null + : p.extension(lastPath).isEmpty + ? lastPath + : p.dirname(lastPath); + final l10n = context.l10n; + + Future canDepartSettings() async => + currentRequest() && + (origin.path != settingsRoutePath || + await confirmNotesSettingsDeparture(context)) && + currentRequest(); + + Future confirmDeparture({ + bool deferDiscard = false, + bool Function()? canContinue, + }) => navigation.confirmDeparture( + canContinue: () => currentRequest() && canContinue?.call() != false, + deferDiscard: deferDiscard, + ); + + switch (action) { + case WorkspaceResourceAction.newMarkdown: + if (!await canDepartSettings()) return; + final replacesWorkspace = + settingsReturnTargetForUri(origin) == + SettingsReturnTarget.welcome || + container.read(workspaceControllerProvider).workspace?.isRemote == + true; + if (replacesWorkspace && + (!await confirmDeparture() || !currentRequest())) { + return; + } + final created = replacesWorkspace + ? await controller.createMarkdownWorkspace( + acceptNavigation: currentRequest, + ) + : await controller.createMarkdownFile(); + if (created && currentRequest()) { + navigation.reveal(focusNewDocument: true); + } + case WorkspaceResourceAction.newNote: + case WorkspaceResourceAction.browseNotes: + if (!await canDepartSettings()) return; + await performWelcomeNotesAction( + navigation, + origin, + currentRequest, + action == WorkspaceResourceAction.newNote + ? WelcomeNotesAction.create + : WelcomeNotesAction.browse, + ); + case WorkspaceResourceAction.newWriterside: + final parentPath = await getDirectoryPath( + initialDirectory: initialDirectory, + confirmButtonText: l10n.chooseLocation, + canCreateDirectories: true, + ); + if (parentPath == null || + !await canDepartSettings() || + !context.mounted) { + return; + } + final bufferId = await showBusyMarkModalEditorDialog( + context, + maxWidth: BusyMarkSizes.dialogWide, + builder: (context) => BusyMarkCreateWritersideProjectDialog( + parentDirectoryPath: parentPath, + onCreate: (request, onError, onPublished) => + controller.createWritersideProject( + request, + authorizeReplacement: (isCurrent) => confirmDeparture( + deferDiscard: true, + canContinue: isCurrent, + ), + acceptNavigation: currentRequest, + onError: onError, + onPublished: onPublished, + ), + ), + ); + if (bufferId != null && + currentRequest() && + container.read(workspaceControllerProvider).activeBufferId == + bufferId) { + navigation.reveal(focusNewDocument: true); + } + case WorkspaceResourceAction.openMarkdown: + case WorkspaceResourceAction.openFolder: + final path = action == WorkspaceResourceAction.openMarkdown + ? (await openFile( + acceptedTypeGroups: [ + XTypeGroup( + label: l10n.fileTypeMarkdown, + extensions: const ['md', 'markdown'], + mimeTypes: const ['text/markdown', 'text/x-markdown'], + ), + ], + initialDirectory: initialDirectory, + confirmButtonText: l10n.open, + ))?.path + : await getDirectoryPath( + initialDirectory: initialDirectory, + confirmButtonText: l10n.open, + canCreateDirectories: false, + ); + if (path != null && await canDepartSettings()) { + await _openPath(navigation, path, currentRequest); + } + } + }); +} + +Future openWorkspaceResourcePath(WidgetRef ref, String path) { + if (path.isEmpty) return Future.value(); + final navigation = ref.read(workspaceNavigationProvider); + return navigation.run(( + path: path, + ), (_, currentRequest) => _openPath(navigation, path, currentRequest)); +} + +Future _openPath( + WorkspaceNavigation navigation, + String path, + bool Function() currentRequest, +) async { + if (!await navigation.confirmDeparture(canContinue: currentRequest) || + !currentRequest()) { + return; + } + await navigation.container + .read(workspaceControllerProvider.notifier) + .openPath( + path, + acceptNavigation: currentRequest, + onOpened: () { + if (currentRequest()) navigation.reveal(); + }, + ); +} diff --git a/lib/src/workspace/workspace_safety.dart b/lib/src/workspace/workspace_safety.dart index db3aa4fe..520851ef 100644 --- a/lib/src/workspace/workspace_safety.dart +++ b/lib/src/workspace/workspace_safety.dart @@ -1,5 +1,7 @@ +import '../core/save_destination.dart'; import '../app/busymark_native_controls.dart'; -import 'package:file_selector/file_selector.dart'; +import '../core/atomic_file_writer.dart'; +import '../app/save_destination_picker.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:path/path.dart' as p; @@ -10,7 +12,6 @@ import '../app/busymark_dialogs.dart'; import '../app/busymark_design.dart'; import '../app/busymark_glyphs.dart'; import '../app/localization.dart'; -import '../platform/linux_header_bar_service.dart'; import 'workspace_controller.dart'; import 'workspace_message.dart'; import 'workspace_model.dart'; @@ -20,31 +21,47 @@ enum _UnsavedChangesAction { cancel, discard, save } enum _OverwriteAction { cancel, overwrite } -XTypeGroup _markdownSaveType(BuildContext context) => XTypeGroup( - label: context.l10n.fileTypeMarkdown, - extensions: ['md', 'markdown'], - mimeTypes: ['text/markdown', 'text/x-markdown'], +Future confirmSafeToContinue( + BuildContext context, + WidgetRef ref, { + bool Function()? canContinue, +}) => confirmWorkspaceDeparture( + context, + _container(ref), + canContinue: canContinue, ); -Future confirmSafeToContinue(BuildContext context, WidgetRef ref) async { - if (!await ref.read(busyMarkGitDismissalProvider).mayDismiss() || - !context.mounted) { +Future confirmWorkspaceDeparture( + BuildContext context, + ProviderContainer container, { + bool Function()? canContinue, + bool deferDiscard = false, +}) async { + if (!await container.read(busyMarkGitDismissalProvider).mayDismiss() || + !context.mounted || + canContinue?.call() == false) { return false; } - if (!ref.read(workspaceControllerProvider.notifier).propertyEdits.flush()) { + if (!container + .read(workspaceControllerProvider.notifier) + .propertyEdits + .flush()) { return false; } - final state = ref.read(workspaceControllerProvider); - if (!state.hasUnsavedChanges) { - return true; - } + final state = container.read(workspaceControllerProvider); + if (!state.hasUnsavedChanges) return true; return _confirmUnsavedChanges( context, - ref, + container, dirtyBufferIds: state.dirtyBuffers.map((buffer) => buffer.id).toList(), + canContinue: canContinue, + deferDiscard: deferDiscard, ); } +ProviderContainer _container(WidgetRef ref) => + ProviderScope.containerOf(ref.context, listen: false); + /// Covers every affected tab, including inactive dirty tree/topic buffers. Future confirmSafeToChangeWorkspaceFiles( BuildContext context, @@ -54,7 +71,7 @@ Future confirmSafeToChangeWorkspaceFiles( final affected = paths.toList(); return _confirmUnsavedChanges( context, - ref, + _container(ref), dirtyBufferIds: [ for (final buffer in ref.read(workspaceControllerProvider).dirtyBuffers) if (buffer.filePath != null && @@ -86,7 +103,7 @@ Future confirmSafeToRefactorWritersideProject( if (workspace == null) return Future.value(false); return _confirmUnsavedChanges( context, - ref, + _container(ref), withoutActivatingBuffers: true, dirtyBufferIds: [ for (final buffer in state.dirtyBuffers) @@ -108,7 +125,11 @@ Future confirmSafeToCloseActiveDocument( if (active == null || !active.isDirty) { return true; } - return _confirmUnsavedChanges(context, ref, dirtyBufferIds: [active.id]); + return _confirmUnsavedChanges( + context, + _container(ref), + dirtyBufferIds: [active.id], + ); } /// Resolves only dirty documents in the requested close set, including @@ -121,7 +142,7 @@ Future confirmSafeToCloseDocumentBuffers( final requested = bufferIds.toSet(); return _confirmUnsavedChanges( context, - ref, + _container(ref), dirtyBufferIds: [ for (final buffer in ref.read(workspaceControllerProvider).dirtyBuffers) if (requested.contains(buffer.id)) buffer.id, @@ -131,11 +152,13 @@ Future confirmSafeToCloseDocumentBuffers( Future _confirmUnsavedChanges( BuildContext context, - WidgetRef ref, { + ProviderContainer container, { required List dirtyBufferIds, bool withoutActivatingBuffers = false, + bool Function()? canContinue, + bool deferDiscard = false, }) async { - final initialState = ref.read(workspaceControllerProvider); + final initialState = container.read(workspaceControllerProvider); final dirtyBuffers = [ for (final id in dirtyBufferIds) if (initialState.documentBuffers @@ -152,49 +175,24 @@ Future _confirmUnsavedChanges( final initialRevisions = { for (final buffer in dirtyBuffers) buffer.id: buffer.revision, }; - final headerBar = ref.read(linuxHeaderBarServiceProvider); final action = await showBusyMarkModalDialog<_UnsavedChangesAction>( context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkNativeDialogShell( - title: context.l10n.unsavedChanges, - maxWidth: BusyMarkSizes.dialog, - actions: [ - BusyMarkNativeActionButton( - role: BusyMarkNativeActionRole.standard, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(BusyMarkGlyphs.clear, size: BusyMarkSizes.iconSm), - const SizedBox(width: BusyMarkSpacing.sm), - Text(context.l10n.cancel), - ], - ), + builder: (context) => BusyMarkAlert( + heading: context.l10n.unsavedChanges, + responses: [ + BusyMarkAlertResponse( + label: context.l10n.cancel, onPressed: () => Navigator.pop(context, _UnsavedChangesAction.cancel), ), - BusyMarkNativeActionButton( - role: BusyMarkNativeActionRole.destructive, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(BusyMarkGlyphs.delete, size: BusyMarkSizes.iconSm), - const SizedBox(width: BusyMarkSpacing.sm), - Text(context.l10n.discard), - ], - ), + BusyMarkAlertResponse( + label: context.l10n.discard, + destructive: true, onPressed: () => Navigator.pop(context, _UnsavedChangesAction.discard), ), - BusyMarkNativeActionButton( - role: BusyMarkNativeActionRole.suggested, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(BusyMarkGlyphs.save, size: BusyMarkSizes.iconSm), - const SizedBox(width: BusyMarkSpacing.sm), - Text(context.l10n.save), - ], - ), + BusyMarkAlertResponse( + label: context.l10n.save, + suggested: true, onPressed: () => Navigator.pop(context, _UnsavedChangesAction.save), ), ], @@ -246,8 +244,10 @@ Future _confirmUnsavedChanges( ), ); - if (!context.mounted || !ref.context.mounted) return false; - final currentState = ref.read(workspaceControllerProvider); + if (canContinue?.call() == false || !context.mounted) { + return false; + } + final currentState = container.read(workspaceControllerProvider); final currentDirtyIds = currentState.dirtyBuffers .map((buffer) => buffer.id) .toSet(); @@ -266,30 +266,35 @@ Future _confirmUnsavedChanges( } if (action == _UnsavedChangesAction.discard) { + if (deferDiscard) return true; if (withoutActivatingBuffers) { - return ref + return container .read(workspaceControllerProvider.notifier) .discardDocumentBuffers(dirtyBufferIds); } - return _discardDirtyDocuments(ref, dirtyBufferIds); + return _discardDirtyDocuments(container, dirtyBufferIds); } if (action == _UnsavedChangesAction.save) { if (!context.mounted) { return false; } return withoutActivatingBuffers - ? _saveDirtyDocumentsWithoutActivation(context, ref, dirtyBufferIds) - : _saveDirtyDocuments(context, ref, dirtyBufferIds); + ? _saveDirtyDocumentsWithoutActivation( + context, + container, + dirtyBufferIds, + ) + : _saveDirtyDocuments(context, container, dirtyBufferIds); } return false; } Future _saveDirtyDocumentsWithoutActivation( BuildContext context, - WidgetRef ref, + ProviderContainer container, List bufferIds, ) async { - final controller = ref.read(workspaceControllerProvider.notifier); + final controller = container.read(workspaceControllerProvider.notifier); final firstResult = await controller.saveAll(bufferIds: bufferIds); if (firstResult.failedBufferIds.isNotEmpty || firstResult.conflictBufferIds.isNotEmpty) { @@ -299,7 +304,7 @@ Future _saveDirtyDocumentsWithoutActivation( final normalizations = {}; for (final bufferId in firstResult.normalizationRequiredBufferIds) { if (!context.mounted) return false; - final buffer = ref + final buffer = container .read(workspaceControllerProvider) .documentBuffers .where((candidate) => candidate.id == bufferId) @@ -307,7 +312,6 @@ Future _saveDirtyDocumentsWithoutActivation( if (buffer == null || !buffer.isDirty) continue; final normalization = await _chooseMixedLineEndingNormalizationForFormat( context, - ref, buffer.format, ); if (normalization == null) return false; @@ -320,7 +324,7 @@ Future _saveDirtyDocumentsWithoutActivation( if (!normalizedResult.succeeded) return false; } return bufferIds.every((id) { - final buffer = ref + final buffer = container .read(workspaceControllerProvider) .documentBuffers .where((candidate) => candidate.id == id) @@ -331,13 +335,15 @@ Future _saveDirtyDocumentsWithoutActivation( Future _saveDirtyDocuments( BuildContext context, - WidgetRef ref, + ProviderContainer container, List bufferIds, ) async { - final controller = ref.read(workspaceControllerProvider.notifier); - final originalActiveId = ref.read(workspaceControllerProvider).activeBufferId; + final controller = container.read(workspaceControllerProvider.notifier); + final originalActiveId = container + .read(workspaceControllerProvider) + .activeBufferId; for (final bufferId in bufferIds) { - final current = ref + final current = container .read(workspaceControllerProvider) .documentBuffers .where((buffer) => buffer.id == bufferId) @@ -347,14 +353,14 @@ Future _saveDirtyDocuments( } if (!await controller.activateDocumentBuffer(bufferId) || !context.mounted || - !await saveActiveWithOverwriteConfirmation(context, ref)) { - await _restoreActiveBuffer(ref, controller, originalActiveId); + !await _saveActiveWithOverwriteConfirmation(context, container)) { + await _restoreActiveBuffer(container, controller, originalActiveId); return false; } } - await _restoreActiveBuffer(ref, controller, originalActiveId); + await _restoreActiveBuffer(container, controller, originalActiveId); return bufferIds.every((id) { - final buffer = ref + final buffer = container .read(workspaceControllerProvider) .documentBuffers .where((candidate) => candidate.id == id) @@ -364,13 +370,15 @@ Future _saveDirtyDocuments( } Future _discardDirtyDocuments( - WidgetRef ref, + ProviderContainer container, List bufferIds, ) async { - final controller = ref.read(workspaceControllerProvider.notifier); - final originalActiveId = ref.read(workspaceControllerProvider).activeBufferId; + final controller = container.read(workspaceControllerProvider.notifier); + final originalActiveId = container + .read(workspaceControllerProvider) + .activeBufferId; for (final bufferId in bufferIds) { - final current = ref + final current = container .read(workspaceControllerProvider) .documentBuffers .where((buffer) => buffer.id == bufferId) @@ -379,7 +387,7 @@ Future _discardDirtyDocuments( continue; } if (!await controller.activateDocumentBuffer(bufferId)) { - await _restoreActiveBuffer(ref, controller, originalActiveId); + await _restoreActiveBuffer(container, controller, originalActiveId); return false; } final target = controller.captureActiveDocumentSaveTarget(); @@ -387,21 +395,21 @@ Future _discardDirtyDocuments( ? await controller.closeDocumentBuffer(bufferId, discard: true) : await controller.discardActiveChanges(target: target); if (!discarded) { - await _restoreActiveBuffer(ref, controller, originalActiveId); + await _restoreActiveBuffer(container, controller, originalActiveId); return false; } } - await _restoreActiveBuffer(ref, controller, originalActiveId); + await _restoreActiveBuffer(container, controller, originalActiveId); return true; } Future _restoreActiveBuffer( - WidgetRef ref, + ProviderContainer container, WorkspaceController controller, String? bufferId, ) async { if (bufferId != null && - ref + container .read(workspaceControllerProvider) .documentBuffers .any((buffer) => buffer.id == bufferId)) { @@ -432,8 +440,18 @@ Future saveActiveWithOverwriteConfirmation( BuildContext context, WidgetRef ref, { ActiveDocumentSaveTarget? target, +}) => _saveActiveWithOverwriteConfirmation( + context, + _container(ref), + target: target, +); + +Future _saveActiveWithOverwriteConfirmation( + BuildContext context, + ProviderContainer container, { + ActiveDocumentSaveTarget? target, }) async { - final controller = ref.read(workspaceControllerProvider.notifier); + final controller = container.read(workspaceControllerProvider.notifier); if (!controller.propertyEdits.flush()) return false; final operationTarget = target ?? controller.captureActiveDocumentSaveTarget(); @@ -442,11 +460,10 @@ Future saveActiveWithOverwriteConfirmation( return false; } if (operationTarget.needsSaveLocation) { - return _saveActiveAs(context, ref, operationTarget); + return _saveActiveAs(context, container, operationTarget); } final normalization = await _chooseMixedLineEndingNormalization( context, - ref, operationTarget, ); if (operationTarget.format.hasMixedLineEndings && normalization == null) { @@ -461,7 +478,7 @@ Future saveActiveWithOverwriteConfirmation( if (saved) { return true; } - final state = ref.read(workspaceControllerProvider); + final state = container.read(workspaceControllerProvider); if (!controller.isActiveDocumentSaveTargetCurrent(operationTarget) || state.message?.code != WorkspaceMessageCode.saveBlockedFileChangedOnDisk) { @@ -470,25 +487,27 @@ Future saveActiveWithOverwriteConfirmation( if (!context.mounted) { return false; } - final headerBar = ref.read(linuxHeaderBarServiceProvider); final action = await showBusyMarkModalDialog<_OverwriteAction>( context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkNativeDialogShell( - title: context.l10n.fileChangedOnDisk, - maxWidth: BusyMarkSizes.dialog, - actions: [ - BusyMarkNativeDialogButton( + builder: (context) => BusyMarkAlert( + heading: context.l10n.fileChangedOnDisk, + responses: [ + BusyMarkAlertResponse( label: context.l10n.cancel, onPressed: () => Navigator.pop(context, _OverwriteAction.cancel), ), - BusyMarkNativeDialogButton( + BusyMarkAlertResponse( label: context.l10n.overwrite, destructive: true, onPressed: () => Navigator.pop(context, _OverwriteAction.overwrite), ), ], - children: [Text(context.l10n.fileChangedOnDiskMessage)], + children: [ + Text(context.l10n.fileChangedOnDiskMessage), + if (state.message?.error case final AtomicFileChangedException error + when error.recoveryPath != null) + Text(error.toString()), + ], ), ); if (action != _OverwriteAction.overwrite) { @@ -505,26 +524,26 @@ Future saveActiveToNewLocation( BuildContext context, WidgetRef ref, ) async { - final controller = ref.read(workspaceControllerProvider.notifier); + final container = _container(ref); + final controller = container.read(workspaceControllerProvider.notifier); final target = controller.captureActiveDocumentSaveTarget(); if (target == null) { return false; } - return _saveActiveAs(context, ref, target); + return _saveActiveAs(context, container, target); } Future _saveActiveAs( BuildContext context, - WidgetRef ref, + ProviderContainer container, ActiveDocumentSaveTarget target, ) async { - final controller = ref.read(workspaceControllerProvider.notifier); + final controller = container.read(workspaceControllerProvider.notifier); if (!controller.isActiveDocumentSaveTargetCurrent(target)) { return false; } final normalization = await _chooseMixedLineEndingNormalization( context, - ref, target, ); if (target.format.hasMixedLineEndings && normalization == null) { @@ -534,62 +553,51 @@ Future _saveActiveAs( return false; } final activePath = target.path; - final location = await getSaveLocation( - acceptedTypeGroups: [_markdownSaveType(context)], + final destination = await pickSaveDestination( + context, suggestedName: activePath == null || activePath.isEmpty ? context.l10n.untitledMarkdownFileName : p.basename(activePath), initialDirectory: activePath == null || activePath.isEmpty ? null : p.dirname(activePath), - confirmButtonText: context.l10n.save, + actionLabel: context.l10n.save, + suffix: '.md', + filterLabel: context.l10n.fileTypeMarkdown, + patterns: const ['*.[mM][dD]', '*.[mM][aA][rR][kK][dD][oO][wW][nN]'], + suffixOnlyWhenMissing: true, + kind: target.workspaceKind == WorkspaceKind.nextcloudNotes + ? SaveDestinationKind.file + : SaveDestinationKind.fileOrSymbolicLink, + isCurrent: () => controller.isActiveDocumentSaveTargetCurrent(target), ); - if (location == null) { + if (destination == null || + !controller.isActiveDocumentSaveTargetCurrent(target)) { return false; } - final savePath = p.normalize(_withMarkdownExtension(location.path)); - final exists = await controller.savePathExists(savePath, target: target); - if (!controller.isActiveDocumentSaveTargetCurrent(target)) { - return false; - } - var overwriteExisting = false; - if (exists) { - if (!context.mounted) { - return false; - } - final action = await _confirmSaveAsOverwrite(context, ref, savePath); - if (action != _OverwriteAction.overwrite || - !controller.isActiveDocumentSaveTargetCurrent(target)) { - return false; - } - overwriteExisting = true; - } return controller.saveActiveAs( - savePath, + destination.path, target: target, - overwriteExisting: overwriteExisting, + overwriteExisting: destination.replacesExisting, + authorization: destination, mixedLineEndingNormalization: normalization, ); } Future _chooseMixedLineEndingNormalization( BuildContext context, - WidgetRef ref, ActiveDocumentSaveTarget target, -) => _chooseMixedLineEndingNormalizationForFormat(context, ref, target.format); +) => _chooseMixedLineEndingNormalizationForFormat(context, target.format); Future _chooseMixedLineEndingNormalizationForFormat( BuildContext context, - WidgetRef ref, TextFormatMetadata format, ) async { if (!format.hasMixedLineEndings) { return null; } - final headerBar = ref.read(linuxHeaderBarServiceProvider); return showBusyMarkModalDialog( context, - headerBarService: headerBar.isAvailable ? headerBar : null, builder: (context) => BusyMarkNativeDialogShell( title: context.l10n.normalizeLineEndings, maxWidth: BusyMarkSizes.dialog, @@ -612,38 +620,3 @@ Future _chooseMixedLineEndingNormalizationForFormat( ), ); } - -Future<_OverwriteAction?> _confirmSaveAsOverwrite( - BuildContext context, - WidgetRef ref, - String savePath, -) { - final headerBar = ref.read(linuxHeaderBarServiceProvider); - return showBusyMarkModalDialog<_OverwriteAction>( - context, - headerBarService: headerBar.isAvailable ? headerBar : null, - builder: (context) => BusyMarkNativeDialogShell( - title: context.l10n.warning, - maxWidth: BusyMarkSizes.dialog, - actions: [ - BusyMarkNativeDialogButton( - label: context.l10n.cancel, - onPressed: () => Navigator.pop(context, _OverwriteAction.cancel), - ), - BusyMarkNativeDialogButton( - label: context.l10n.overwrite, - destructive: true, - onPressed: () => Navigator.pop(context, _OverwriteAction.overwrite), - ), - ], - children: [Text(context.l10n.errorPathAlreadyExists(savePath))], - ), - ); -} - -String _withMarkdownExtension(String path) { - if (p.extension(path).isNotEmpty) { - return path; - } - return '$path.md'; -} diff --git a/lib/src/workspace/workspace_service.dart b/lib/src/workspace/workspace_service.dart index 6d624ce2..49a90900 100644 --- a/lib/src/workspace/workspace_service.dart +++ b/lib/src/workspace/workspace_service.dart @@ -6,10 +6,12 @@ import 'package:path/path.dart' as p; import '../core/anchored_path_guard.dart'; import '../core/atomic_file_writer.dart'; +import '../core/save_destination.dart'; import '../core/busymark_exception.dart'; import '../core/debug_log.dart'; import '../core/diagnostic.dart'; import '../core/linux_atomic_file_api.dart'; +import '../core/recoverable_file_replacement.dart'; import '../core/path_utils.dart'; import '../markdown/busymark_document.dart'; import '../markdown/document_outline.dart'; @@ -122,6 +124,7 @@ class WorkspaceService { this.writersideDocumentRenderer = const WritersideDocumentRenderer(), this.scanOptions = const WorkspaceScanOptions(), Future Function(String targetPath)? beforeNewFilePublish, + this.beforeDisplacedValidation, Future Function(String targetPath, int committedCount)? afterBatchFileCommit, }) : writersideService = writersideService ?? const WritersideModuleService(), @@ -129,6 +132,9 @@ class WorkspaceService { _beforeNewFilePublish = beforeNewFilePublish, _afterBatchFileCommit = afterBatchFileCommit; + final Future Function(String targetPath, String displacedPath)? + beforeDisplacedValidation; + final MarkdownParser markdownParser; final MarkdownPreviewBuilder previewBuilder; final WritersideModuleService writersideService; @@ -223,13 +229,30 @@ class WorkspaceService { Future createWritersideProject( WritersideProjectCreateRequest request, - ) async { - final result = await writersideProjectCreator.create(request); - return _openWriterside( - result.rootPath, - activeFilePath: result.startTopicPath, - ); - } + ) async => (await publishWritersideProject( + request, + authorize: () async => true, + canPublish: () => true, + accept: (workspace, _) async => workspace, + ))!; + + Future publishWritersideProject( + WritersideProjectCreateRequest request, { + required Future Function() authorize, + required bool Function() canPublish, + required Future Function(Workspace, bool Function() isCurrent) accept, + }) => writersideProjectCreator.createTransaction( + request, + authorize: authorize, + canPublish: canPublish, + accept: (project, isCurrent) async { + final workspace = await _openWriterside( + project.rootPath, + activeFilePath: project.startTopicPath, + ); + return isCurrent() ? accept(workspace, isCurrent) : null; + }, + ); Future createWritersideTopic( Workspace workspace, @@ -896,62 +919,6 @@ class WorkspaceService { ); } - Future> writersideTopicRenameAffectedPaths( - Workspace workspace, { - required String topicPath, - required String topicModuleRoot, - }) async { - final project = await _writersideProjectService.load( - workspace.rootPath, - preferredModuleRoot: topicModuleRoot, - ); - final module = project.modules - .where((candidate) => p.equals(candidate.rootPath, topicModuleRoot)) - .singleOrNull; - if (module == null) { - throw const BusyMarkException('writerside.topic.module-not-open'); - } - final topic = _writersideTopicForPath(module, topicPath); - final paths = {topic.filePath}; - for (final usage in project.index.references) { - final topicPart = usage.value.split('#').first; - if (topicPart.isNotEmpty && - project.index - .definitions( - topicPart, - moduleId: usage.moduleId, - origin: usage.origin, - kind: WritersideSymbolKind.topic, - filePath: usage.filePath, - referenceOffset: usage.span.startOffset, - ) - .any((symbol) => p.equals(symbol.filePath, topic.filePath))) { - paths.add(usage.filePath); - } - } - for (final candidate in project.modules) { - final moduleId = project.index.modulesById.entries - .where((entry) => p.equals(entry.value.rootPath, candidate.rootPath)) - .map((entry) => entry.key) - .single; - for (final instance in candidate.instances) { - final startPage = instance.startPage; - if (startPage != null && - project.index - .definitions( - startPage, - moduleId: moduleId, - kind: WritersideSymbolKind.topic, - filePath: instance.sourceTreePath, - ) - .any((symbol) => p.equals(symbol.filePath, topic.filePath))) { - paths.add(instance.sourceTreePath); - } - } - } - return paths.toList()..sort(); - } - Future deleteWritersideTopicFile( Workspace workspace, String topicPath, @@ -1064,9 +1031,6 @@ class WorkspaceService { (module.topics.isEmpty ? null : module.topics.first.filePath); return workspace.copyWith( activeFilePath: activeFile, - activeFileSnapshot: activeFile == null - ? null - : await fileSnapshot(activeFile), openFilePaths: activeFile == null ? workspace.openFilePaths : [...workspace.openFilePaths, activeFile], @@ -1209,10 +1173,6 @@ class WorkspaceService { ); } - Future fileModifiedAt(String path) async { - return (await File(path).stat()).modified; - } - Future fileSnapshot(String path) async { final file = File(path); final bytes = await file.readAsBytes(); @@ -1260,6 +1220,8 @@ class WorkspaceService { String text, { TextFormatMetadata? format, LineEndingNormalization? mixedNormalization, + SaveDestination? authorization, + bool Function()? stillCurrent, Future Function()? onPublished, }) async { final bytes = _encodeDocumentText( @@ -1271,6 +1233,11 @@ class WorkspaceService { try { final stat = await staged.file.stat(); await _beforeNewFilePublish?.call(path); + if (stillCurrent?.call() == false || + authorization?.replacesExisting == true) { + throw AtomicFileChangedException(path); + } + authorization?.requireCurrent(path); await _publishNewFileWithoutReplace(staged.file, path); await onPublished?.call(); return _snapshotFromBytes(stat, bytes); @@ -1308,6 +1275,8 @@ class WorkspaceService { TextFormatMetadata? format, LineEndingNormalization? mixedNormalization, WorkspaceFileSnapshot? expectedSnapshot, + SaveDestination? authorization, + bool Function()? stillCurrent, Future Function()? onPublished, }) async { final bytes = _encodeDocumentText( @@ -1315,6 +1284,10 @@ class WorkspaceService { format: format, mixedNormalization: mixedNormalization, ); + if (authorization != null && + (!authorization.replacesExisting || expectedSnapshot == null)) { + throw ArgumentError('A replacement requires an approved existing entry'); + } final staged = await _stageNewSave(path, bytes); var preserveStagedFile = false; try { @@ -1325,15 +1298,24 @@ class WorkspaceService { final expectedLinkResolvedPath = targetType == FileSystemEntityType.link ? await Link(path).resolveSymbolicLinks() : null; + final reviewed = + authorization ?? + (expectedSnapshot != null && + Platform.isLinux && + targetType == FileSystemEntityType.file + ? SaveDestination.inspect(path) + : null); if (targetType == FileSystemEntityType.file) { await _copyFileMode(await File(path).stat(), staged.file); } await _validateExpectedSnapshot(path, expectedSnapshot); final target = File(p.absolute(path)); await _beforeNewFilePublish?.call(path); + if (stillCurrent?.call() == false) throw AtomicFileChangedException(path); + authorization?.requireCurrent(path); if (expectedSnapshot != null) { final atomicApi = LinuxAtomicFileApi.instance; - if (!Platform.isLinux || !atomicApi.isAvailable) { + if (!Platform.isLinux) { throw UnsupportedError( 'Conflict-safe replacement requires Linux renameat2.', ); @@ -1343,19 +1325,51 @@ class WorkspaceService { target.absolute.path, ); if (exchangeError != null) { + if (exchangeError == LinuxAtomicFileApi.fileMissingError) { + throw AtomicFileChangedException(path); + } + if (reviewed != null && + atomicApi.exchangeUnsupported( + exchangeError, + p.dirname(target.path), + )) { + await replaceFileWithoutExchange( + staged: staged.file, + destination: reviewed, + acceptDisplaced: (displaced) => _displacedEntryMatchesExpected( + displaced, + targetPath: target.path, + expectedType: targetType, + expectedLinkTarget: expectedLinkTarget, + expectedLinkResolvedPath: expectedLinkResolvedPath, + expectedSnapshot: expectedSnapshot, + ), + checkBeforeCommit: () { + if (stillCurrent?.call() == false) { + throw AtomicFileChangedException(path); + } + }, + ); + await onPublished?.call(); + return _snapshotFromBytes(await target.stat(), bytes); + } throw FileSystemException( 'Could not commit conditional file replacement', path, OSError('atomic exchange failed', exchangeError), ); } - if (!await _displacedEntryMatchesExpected( - staged.file.path, - expectedType: targetType, - expectedLinkTarget: expectedLinkTarget, - expectedLinkResolvedPath: expectedLinkResolvedPath, - expectedSnapshot: expectedSnapshot, - )) { + // Retain displaced state even if an injected or real validation fails. + preserveStagedFile = true; + if (authorization?.acceptsDisplaced(staged.file.path) == false || + !await _displacedEntryMatchesExpected( + staged.file.path, + targetPath: target.path, + expectedType: targetType, + expectedLinkTarget: expectedLinkTarget, + expectedLinkResolvedPath: expectedLinkResolvedPath, + expectedSnapshot: expectedSnapshot, + )) { preserveStagedFile = !await _rollbackConditionalReplacement( staged: staged.file, target: target, @@ -1369,6 +1383,7 @@ class WorkspaceService { } else { await staged.file.rename(target.path); } + preserveStagedFile = false; await onPublished?.call(); return _snapshotFromBytes(await target.stat(), bytes); } finally { @@ -1378,12 +1393,14 @@ class WorkspaceService { Future _displacedEntryMatchesExpected( String path, { + required String targetPath, required FileSystemEntityType expectedType, required String? expectedLinkTarget, required String? expectedLinkResolvedPath, required WorkspaceFileSnapshot expectedSnapshot, }) async { try { + await beforeDisplacedValidation?.call(targetPath, path); final displacedType = await FileSystemEntity.type( path, followLinks: false, @@ -1445,6 +1462,15 @@ class WorkspaceService { WorkspaceFileSnapshot? expectedSnapshot, }) async { final savePath = await _saveTargetPath(path); + if (expectedSnapshot != null) { + return saveFormattedTextReplacingPath( + savePath, + text, + format: format, + mixedNormalization: mixedNormalization, + expectedSnapshot: expectedSnapshot, + ); + } final target = File(savePath); final existingStat = await target.stat(); final bytes = _encodeDocumentText( @@ -1563,23 +1589,21 @@ class WorkspaceService { OSError('atomic exchange failed', error), ); } + // The temporary path owns displaced user data as soon as exchange + // succeeds, including when the following read or stat fails. + committed.add(write); + await beforeDisplacedValidation?.call( + write.target.path, + write.stagedFile.path, + ); final displacedBytes = await write.stagedFile.readAsBytes(); final displacedSnapshot = _snapshotFromBytes( await write.stagedFile.stat(), displacedBytes, ); if (displacedSnapshot.differsFrom(write.expectedSnapshot)) { - final conflict = await _rollbackBatchWrite(write); - if (conflict != null) { - preservedArtifacts.add(conflict.preservedPath); - throw WorkspaceBatchPartialApplicationConflict( - files: [conflict], - cause: WorkspaceBatchWriteConflict(write.requestPath), - ); - } throw WorkspaceBatchWriteConflict(write.requestPath); } - committed.add(write); await _afterBatchFileCommit?.call(write.target.path, committed.length); validateBeforeCommit?.call(); } @@ -1990,7 +2014,9 @@ class WorkspaceService { if (Platform.isWindows) { return; } - final mode = (sourceStat.mode & 0xfff).toRadixString(8); + final permissions = sourceStat.mode & 0xfff; + if (((await target.stat()).mode & 0xfff) == permissions) return; + final mode = permissions.toRadixString(8); final result = await Process.run('chmod', [mode, target.path]); if (result.exitCode != 0) { throw FileSystemException( @@ -2539,7 +2565,6 @@ class WorkspaceService { kind: WorkspaceKind.singleMarkdown, openedAt: DateTime.now(), activeFilePath: filePath, - activeFileSnapshot: load.snapshot, openFilePaths: [filePath], files: [await _documentFile(filePath, rootPath)], diagnostics: markdown.diagnostics, @@ -2589,9 +2614,6 @@ class WorkspaceService { kind: WorkspaceKind.markdownFolder, openedAt: DateTime.now(), activeFilePath: firstMarkdown?.filePath, - activeFileSnapshot: firstMarkdown == null - ? null - : await fileSnapshot(firstMarkdown.filePath), openFilePaths: firstMarkdown == null ? const [] : [firstMarkdown.filePath], @@ -2640,9 +2662,6 @@ class WorkspaceService { kind: WorkspaceKind.writersideModule, openedAt: DateTime.now(), activeFilePath: firstTopic, - activeFileSnapshot: firstTopic == null - ? null - : await fileSnapshot(firstTopic), openFilePaths: firstTopic == null ? const [] : [firstTopic], files: files, directories: directories, diff --git a/lib/src/workspace/workspace_tab_actions.dart b/lib/src/workspace/workspace_tab_actions.dart index f65654b8..a3d8ff98 100644 --- a/lib/src/workspace/workspace_tab_actions.dart +++ b/lib/src/workspace/workspace_tab_actions.dart @@ -1,9 +1,10 @@ +import 'dart:async'; + import '../app/git_dismissal.dart'; import '../git/application/shared_git_tabs.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import '../git/application/git_controller.dart'; import '../local_history/local_history_controller.dart'; import 'workspace_controller.dart'; import 'workspace_model.dart'; @@ -19,7 +20,6 @@ List _tabs(WidgetRef ref, WorkspaceState state) { if (workspace == null) return const []; final history = ref.read(localHistoryControllerProvider); return workspaceTabEntries( - workspace: workspace, gitTabs: ref.read(sharedGitReviewProvider)[workspace.id] ?? const SharedGitTabs(), @@ -50,6 +50,22 @@ bool _tabSurvivedFirstSave( buffer.filePath!.isNotEmpty, ); +/// Reveal a successfully opened document using the same view transition as +/// selecting its editor tab. Resource validation and opening happen first. +final revealOpenedDocumentProvider = Provider( + (ref) => () { + final history = ref.read(localHistoryControllerProvider.notifier); + history.clearComparison(); + final state = ref.read(workspaceControllerProvider); + final buffer = state.activeBuffer; + if (buffer == null) return; + if (state.workspace case final workspace?) { + ref.read(sharedGitReviewProvider.notifier).deactivate(workspace.id); + } + unawaited(history.selectDocumentForBuffer(buffer)); + }, +); + /// Validates a tab captured before an asynchronous menu was presented. bool isWorkspaceTabCurrent( WidgetRef ref, @@ -125,7 +141,6 @@ Future _closeTabs( }; // Capture controllers before destructive awaits. Callers must supply a ref // owned by WorkspaceScreen or the app, never the disappearing tab strip. - final git = ref.read(gitControllerProvider.notifier); final history = ref.read(localHistoryControllerProvider.notifier); var operationWorkspace = initial.workspace!; var documentsFinished = false; @@ -268,7 +283,6 @@ Future _closeTabs( !currentWorkspace()) { return false; } - git.deactivateDiffFile(); } final remaining = _tabs(ref, ref.read(workspaceControllerProvider)); if (remaining.isNotEmpty && diff --git a/lib/src/workspace/workspace_tabs.dart b/lib/src/workspace/workspace_tabs.dart index a69f8c73..ab6f3366 100644 --- a/lib/src/workspace/workspace_tabs.dart +++ b/lib/src/workspace/workspace_tabs.dart @@ -1,6 +1,5 @@ import '../git/application/shared_git_tabs.dart'; import 'document_buffer.dart'; -import 'workspace_model.dart'; enum WorkspaceTabKind { file, gitDiff, localHistory } @@ -20,7 +19,7 @@ class WorkspaceTabEntry { const WorkspaceTabEntry.file({ required String path, required bool active, - String? bufferId, + required String bufferId, String? untitledName, bool dirty = false, }) : this._( @@ -67,13 +66,12 @@ class WorkspaceTabEntry { final String? comparisonId, comparisonLabel; final SharedGitReview? review; - String get key => '${kind.name}:${comparisonId ?? bufferId ?? path}'; + String get key => '${kind.name}:${comparisonId ?? bufferId!}'; } List workspaceTabEntries({ - required Workspace workspace, SharedGitTabs gitTabs = const SharedGitTabs(), - List? documentBuffers, + required List documentBuffers, String? activeBufferId, String? localHistoryRevisionId, String? localHistoryDocumentName, @@ -81,25 +79,15 @@ List workspaceTabEntries({ final diffActive = gitTabs.active != null; final localHistoryActive = !diffActive && localHistoryRevisionId != null; return [ - if (documentBuffers != null) - for (final buffer in documentBuffers) - WorkspaceTabEntry.file( - path: buffer.filePath ?? '', - bufferId: buffer.id, - untitledName: buffer.untitledName, - dirty: buffer.isDirty, - active: - !diffActive && !localHistoryActive && buffer.id == activeBufferId, - ) - else - for (final path in workspace.openFilePaths) - WorkspaceTabEntry.file( - path: path, - active: - !diffActive && - !localHistoryActive && - path == workspace.activeFilePath, - ), + for (final buffer in documentBuffers) + WorkspaceTabEntry.file( + path: buffer.filePath ?? '', + bufferId: buffer.id, + untitledName: buffer.untitledName, + dirty: buffer.isDirty, + active: + !diffActive && !localHistoryActive && buffer.id == activeBufferId, + ), for (final review in gitTabs.entries) WorkspaceTabEntry.gitDiff( path: review.comparison.path.display, diff --git a/lib/src/writerside/writerside_document_parser.dart b/lib/src/writerside/writerside_document_parser.dart index 98218d5d..1052320e 100644 --- a/lib/src/writerside/writerside_document_parser.dart +++ b/lib/src/writerside/writerside_document_parser.dart @@ -302,8 +302,14 @@ WritersideDocumentNode _rebaseNode( startOffset: offset + original.startOffset, endOffset: offset + original.endOffset, ); + BusyInline inline(BusyInline original) => original.copyWith( + imageSpan: original.imageSpan == null ? null : span(original.imageSpan!), + children: original.children.map(inline).toList(), + ); BusyBlock block(BusyBlock original) => original.copyWith( sourceSpan: original.sourceSpan == null ? null : span(original.sourceSpan!), + posterSpan: original.posterSpan == null ? null : span(original.posterSpan!), + inlines: original.inlines.map(inline).toList(), children: original.children.map(block).toList(), ); if (node is WritersideMarkdownBlockNode) { diff --git a/lib/src/writerside/writerside_document_renderer.dart b/lib/src/writerside/writerside_document_renderer.dart index e8e9da1f..a3826cb6 100644 --- a/lib/src/writerside/writerside_document_renderer.dart +++ b/lib/src/writerside/writerside_document_renderer.dart @@ -662,6 +662,7 @@ class _WritersideRenderSession { BusyBlock( id: _nodeId(element), kind: BusyBlockKind.video, + posterSpan: element.span, attributes: attributes, sourceSpan: element.span, ), @@ -1188,6 +1189,7 @@ class _WritersideRenderSession { kind: BusyInlineKind.image, text: image.attributes['alt'] ?? '', destination: image.attributes['src'], + imageSpan: image.span, attributes: _attributes(image), ); } diff --git a/lib/src/writerside/writerside_project_creator.dart b/lib/src/writerside/writerside_project_creator.dart index 6c2bb533..24f1a390 100644 --- a/lib/src/writerside/writerside_project_creator.dart +++ b/lib/src/writerside/writerside_project_creator.dart @@ -4,7 +4,10 @@ import 'package:path/path.dart' as p; import '../core/anchored_path_guard.dart'; import '../core/busymark_exception.dart'; +import '../core/linux_atomic_file_api.dart'; +import '../core/linux_file_identity.dart'; import '../core/path_utils.dart'; +import '../core/save_destination.dart'; class WritersideProjectCreateRequest { const WritersideProjectCreateRequest({ @@ -99,76 +102,235 @@ class WritersideProjectCreator { Future create( WritersideProjectCreateRequest request, - ) async { + ) async => (await createTransaction( + request, + authorize: () async => true, + canPublish: () => true, + accept: (project, _) async => project, + ))!; + + /// Prepare the generated tree privately, and retain ownership until the + /// caller accepts the project at its final paths. A null result rolls back + /// publication, for example after a competing navigation or an initial read + /// failure. An existing empty destination keeps its original directory. + Future createTransaction( + WritersideProjectCreateRequest request, { + required Future Function() authorize, + required bool Function() canPublish, + required Future Function( + WritersideProjectCreateResult, + bool Function() isCurrent, + ) + accept, + }) async { final validated = _validate(request); - final parentAnchor = await _parentAnchor(validated.parentDirectoryPath); - final requestedRootPath = p.join( - parentAnchor.rootPath, - validated.directoryName, + final parent = await _parentAnchor(validated.parentDirectoryPath); + final resolution = await _projectPath( + parent, + p.join(parent.rootPath, validated.directoryName), ); - final rootResolution = await _projectPath(parentAnchor, requestedRootPath); - final rootPath = rootResolution.path; - final rootDirectory = Directory(rootPath); - final rootType = rootResolution.type; - if (rootType == FileSystemEntityType.directory) { - if (!await _isDirectoryEmpty(rootDirectory)) { - throw BusyMarkException( - 'writerside.project.target-directory-not-empty', - args: {'path': rootPath}, - ); - } - } else if (rootType == FileSystemEntityType.notFound) { - await rootDirectory.create(); - } else { + final root = Directory(resolution.path); + if (resolution.type != FileSystemEntityType.notFound && + resolution.type != FileSystemEntityType.directory) { throw BusyMarkException( 'writerside.project.target-path-not-directory', - args: {'path': rootPath}, + args: {'path': root.path}, ); } - final rootAnchor = await _projectRootAnchor(parentAnchor, rootPath); - - final treeFileName = '${validated.instanceId}.tree'; - final configPath = p.join(rootAnchor.rootPath, 'writerside.cfg'); - final treePath = p.join(rootAnchor.rootPath, treeFileName); - final topicPath = p.join( - rootAnchor.rootPath, - 'topics', - validated.topicFileName, + final destination = SaveDestination.inspect( + root.path, + kind: SaveDestinationKind.directory, ); - - await _createProjectDirectory(rootAnchor, 'topics'); - await _createProjectDirectory(rootAnchor, 'images'); - await _createProjectDirectory(rootAnchor, 'cfg'); - - await _writeNewFile( - rootAnchor, - configPath, - _writersideConfig( + if (destination.replacesExisting && !await _isDirectoryEmpty(root)) { + throw BusyMarkException( + 'writerside.project.target-directory-not-empty', + args: {'path': root.path}, + ); + } + if (!await authorize() || !canPublish()) return null; + + destination.requireCurrent(root.path); + final parentId = _identity(parent.rootPath); + final staging = await Directory( + parent.rootPath, + ).createTemp('.busymark-writerside-'); + final stagingId = _identity(staging.path); + final moved = []; + final entries = {}; + final tree = '${validated.instanceId}.tree'; + final topic = p.join('topics', validated.topicFileName); + final files = { + 'writerside.cfg': _writersideConfig( moduleName: validated.moduleName, - treeFileName: treeFileName, + treeFileName: tree, ), - ); - await _writeNewFile( - rootAnchor, - treePath, - _writersideTree( + tree: _writersideTree( instanceId: validated.instanceId, instanceName: validated.instanceName, topicFileName: validated.topicFileName, ), - ); - await _writeNewFile( - rootAnchor, - topicPath, - _startTopic(title: validated.topicTitle), - ); + topic: _startTopic(title: validated.topicTitle), + }; + String? publishedRootId; + try { + final privateRoot = await _projectRootAnchor(parent, staging.path); + if (!_owns(staging.path, stagingId)) { + throw FileSystemException( + 'Project staging directory changed', + staging.path, + ); + } + // Keep the temporary boundary private while giving the published + // project the same creation permissions as an ordinary directory. + await _createProjectDirectory(privateRoot, 'project'); + final stage = await _projectRootAnchor( + privateRoot, + p.join(staging.path, 'project'), + ); + final stageId = _identity(stage.rootPath); + const directories = ['topics', 'images', 'cfg']; + for (final name in directories) { + await _createProjectDirectory(stage, name); + entries[name] = _identity(p.join(stage.rootPath, name)); + } + for (final entry in files.entries) { + await _writeNewFile( + stage, + p.join(stage.rootPath, entry.key), + entry.value, + ); + entries[entry.key] = _identity(p.join(stage.rootPath, entry.key)); + } + if (!canPublish()) return null; + destination.requireCurrent(root.path); + if (!_owns(staging.path, stagingId) || !_owns(stage.rootPath, stageId)) { + throw FileSystemException( + 'Project staging directory changed', + staging.path, + ); + } + if (destination.replacesExisting) { + publishedRootId = _identity(root.path); + for (final name in [...directories, 'writerside.cfg', tree]) { + _publish( + p.join(stage.rootPath, name), + p.join(root.path, name), + directory: directories.contains(name), + ); + moved.add(name); + } + } else { + _publish(stage.rootPath, root.path, directory: true); + publishedRootId = stageId; + moved.addAll(entries.keys); + } + final rootId = publishedRootId; + bool isCurrent() { + if (!canPublish()) return false; + if (!_owns(parent.rootPath, parentId) || + !_owns(root.path, rootId) || + !entries.entries.every( + (entry) => _owns(p.join(root.path, entry.key), entry.value), + )) { + throw FileSystemException( + 'Generated project changed during creation', + root.path, + ); + } + return true; + } + + if (!isCurrent()) return null; + final result = await accept( + WritersideProjectCreateResult( + rootPath: root.path, + configPath: p.join(root.path, 'writerside.cfg'), + treePath: p.join(root.path, tree), + startTopicPath: p.join(root.path, topic), + ), + isCurrent, + ); + if (result != null) publishedRootId = null; + return result; + } finally { + final sameParent = _owns(parent.rootPath, parentId); + if (sameParent && + publishedRootId != null && + _owns(root.path, publishedRootId)) { + // Delete only generated entries we actually moved. Checking the + // directory and file identities protects replacements, and removing + // directories without recursion preserves any concurrent additions. + for (final path in files.keys) { + final top = p.split(path).first; + if (!moved.contains(top)) continue; + if (top != path && !_owns(p.join(root.path, top), entries[top]!)) { + continue; + } + final file = File(p.join(root.path, path)); + try { + if (_owns(file.path, entries[path]!) && + file.readAsStringSync() == files[path] && + _owns(file.path, entries[path]!)) { + file.deleteSync(); + } + } on FileSystemException { + // A concurrent writer can make a generated entry unsafe to remove. + } on FormatException { + // A generated file with changed bytes now belongs to the writer. + } + } + for (final path in moved.where((path) => !files.containsKey(path))) { + _removeOwnedDirectory(p.join(root.path, path), entries[path]!); + } + if (!destination.replacesExisting) { + _removeOwnedDirectory(root.path, publishedRootId); + } + } + if (sameParent && _owns(staging.path, stagingId)) { + // createTemp allocated this private tree for this transaction. + try { + staging.deleteSync(recursive: true); + } on FileSystemException { + // A filesystem failure must not discard an accepted project. + } + } + } + } + + String _identity(String path) => + LinuxFileIdentity.read(path) ?? + (throw FileSystemException('Cannot establish project ownership', path)); - return WritersideProjectCreateResult( - rootPath: rootAnchor.rootPath, - configPath: configPath, - treePath: treePath, - startTopicPath: topicPath, + bool _owns(String path, String identity) { + try { + return LinuxFileIdentity.read(path) == identity; + } on FileSystemException { + return false; + } + } + + void _removeOwnedDirectory(String path, String identity) { + if (!_owns(path, identity)) return; + try { + Directory(path).deleteSync(); + } on FileSystemException { + // A nonempty directory contains data outside this transaction. + } + } + + void _publish(String stage, String target, {required bool directory}) { + final error = LinuxAtomicFileApi.instance.publishNoReplace( + stage, + target, + directory: directory, ); + if (error != null) { + throw FileSystemException( + 'Could not publish the Writerside project', + target, + OSError('No-replace publication failed', error), + ); + } } Future _parentAnchor(String path) async { diff --git a/lib/src/writerside/writerside_topic_file_editor.dart b/lib/src/writerside/writerside_topic_file_editor.dart index 7a7e56b0..997eed03 100644 --- a/lib/src/writerside/writerside_topic_file_editor.dart +++ b/lib/src/writerside/writerside_topic_file_editor.dart @@ -119,18 +119,6 @@ class WritersideTopicFileRenameResult { final bool updatedXmlTopicId; } -class WritersideTopicFileDeleteResult { - const WritersideTopicFileDeleteResult({ - required this.deletedTopicPath, - required this.updatedTreePaths, - required this.removedTocEntries, - }); - - final String deletedTopicPath; - final List updatedTreePaths; - final int removedTocEntries; -} - /// Mutates a resolved Writerside topic file and every semantically resolved /// project reference supplied to the rename transaction. /// @@ -417,38 +405,6 @@ class WritersideTopicFileEditor { ); } - Future delete({ - required WritersideModule module, - required WritersideTopic topic, - }) async { - final snapshot = await _currentModuleSnapshot(module, topic); - final context = await _mutationContext(snapshot); - final treeMutation = await _deleteTreeEdits(context); - final appliedTreeEdits = <_TreeEdit>[]; - try { - await _applyTreeEdits( - context.anchor, - treeMutation.edits, - applied: appliedTreeEdits, - ); - await _ensureTreesAtExpectedSources(context, treeMutation.edits); - await _ensureConfigurationUnchanged(context); - await _ensureTopicSourcesUnchanged(context); - await _deleteUnchangedTopicSource(context); - } on Object { - await _rollbackTreeEdits(context.anchor, appliedTreeEdits); - rethrow; - } - - return WritersideTopicFileDeleteResult( - deletedTopicPath: context.topicPath, - updatedTreePaths: List.unmodifiable([ - for (final edit in treeMutation.edits) edit.path, - ]), - removedTocEntries: treeMutation.removedTocEntries, - ); - } - Future<_CurrentModuleSnapshot> _currentModuleSnapshot( WritersideModule suppliedModule, WritersideTopic requestedTopic, @@ -1951,114 +1907,6 @@ class WritersideTopicFileEditor { return '$replacement$suffix'; } - Future<_DeleteTreeMutation> _deleteTreeEdits(_MutationContext context) async { - for (final tree in context.trees) { - final startPage = tree.document.rootElement.getAttribute('start-page'); - if (startPage != null && - _referenceTargetsTopic(context, startPage, tree.path)) { - throw BusyMarkException( - 'writerside.topic-file.is-start-page', - args: {'topic': startPage, 'treePath': tree.path}, - ); - } - } - - final edits = <_TreeEdit>[]; - var removedTocEntries = 0; - for (final tree in context.trees) { - final removed = _removeTopicTocElements( - context, - tree.document.rootElement, - tree.path, - ); - if (removed == 0) { - continue; - } - removedTocEntries += removed; - edits.add( - _TreeEdit( - path: tree.path, - originalSource: tree.source, - updatedSource: _xmlSource(tree.document), - ), - ); - } - return _DeleteTreeMutation( - edits: edits, - removedTocEntries: removedTocEntries, - ); - } - - int _removeTopicTocElements( - _MutationContext context, - XmlElement parent, - String treePath, - ) { - var removed = 0; - final children = parent.childElements - .where((element) => element.name.local == 'toc-element') - .toList(); - for (final child in children) { - removed += _removeTopicTocElements(context, child, treePath); - final reference = child.getAttribute('topic'); - if (reference == null || - !_referenceTargetsTopic(context, reference, treePath)) { - continue; - } - final index = parent.children.indexOf(child); - final promoted = child.childElements - .where((element) => element.name.local == 'toc-element') - .map((element) => element.copy()) - .toList(); - parent.children.removeAt(index); - parent.children.insertAll(index, promoted); - removed += 1; - } - return removed; - } - - bool _referenceTargetsTopic( - _MutationContext context, - String reference, - String treePath, - ) { - final normalizedReference = _normalizedReference(reference); - var matches = context.module.topics - .where( - (candidate) => - _normalizedReference(candidate.fileName) == normalizedReference, - ) - .toList(); - if (matches.isEmpty) { - if (p.dirname(normalizedReference) != '.') { - return false; - } - matches = context.module.topics - .where( - (candidate) => - p.basename(_normalizedReference(candidate.fileName)) == - normalizedReference, - ) - .toList(); - } - final targetMatches = matches - .where( - (candidate) => - p.equals(normalizePath(candidate.filePath), context.topicPath), - ) - .length; - if (targetMatches == 0) { - return false; - } - if (matches.length != 1 || targetMatches != 1) { - throw BusyMarkException( - 'writerside.topic-file.ambiguous-reference', - args: {'reference': reference, 'treePath': treePath}, - ); - } - return true; - } - _RenamedTopicSource _renamedTopicSource({ required String path, required String source, @@ -2264,58 +2112,6 @@ class WritersideTopicFileEditor { } } - Future _ensureTreesAtExpectedSources( - _MutationContext context, - List<_TreeEdit> edits, - ) async { - final updatedSources = { - for (final edit in edits) edit.path: edit.updatedSource, - }; - for (final tree in context.trees) { - final expectedSource = updatedSources[tree.path] ?? tree.source; - final resolution = await _resolvePath( - context.anchor, - tree.path, - allowRoot: false, - ); - if (resolution.type != FileSystemEntityType.file || - await File(resolution.path).readAsString() != expectedSource) { - throw BusyMarkException( - 'writerside.topic-file.tree-changed', - args: {'path': resolution.path}, - ); - } - } - } - - Future _ensureConfigurationUnchanged(_MutationContext context) async { - final current = await _configurationSources(context.module.rootPath); - if (!_sameStringMap(current, context.configurationSources)) { - throw BusyMarkException( - 'writerside.topic-file.tree-changed', - args: {'path': context.module.config.filePath}, - ); - } - } - - Future _ensureTopicSourcesUnchanged( - _MutationContext context, { - Map additionalSources = const {}, - }) async { - final expected = { - ...context.topicSources, - for (final entry in additionalSources.entries) - normalizePath(entry.key): entry.value, - }; - final current = await _topicSources(context.anchor, context.module); - if (!_sameStringMap(current, expected)) { - throw BusyMarkException( - 'writerside.topic-file.topic-inventory-changed', - args: {'path': context.module.rootPath}, - ); - } - } - Future _ensureReferenceContextsUnchanged( List<_ReferenceModuleContext> contexts, List<_TreeEdit> edits, { @@ -2703,16 +2499,6 @@ class _TreeEdit { final String updatedSource; } -class _DeleteTreeMutation { - const _DeleteTreeMutation({ - required this.edits, - required this.removedTocEntries, - }); - - final List<_TreeEdit> edits; - final int removedTocEntries; -} - class _RenamedTopicSource { const _RenamedTopicSource({ required this.source, diff --git a/lib/src/writerside/writerside_topic_removal_service.dart b/lib/src/writerside/writerside_topic_removal_service.dart index d82552d9..2eaf676e 100644 --- a/lib/src/writerside/writerside_topic_removal_service.dart +++ b/lib/src/writerside/writerside_topic_removal_service.dart @@ -293,8 +293,15 @@ class WritersideTopicRemovalService { this.moduleService = const WritersideModuleService(), this.projectService, this.treeDirectoryLister, + this.beforeFileExchange, + this.afterFileExchange, }); + final Future Function(String targetPath, String displacedPath)? + beforeFileExchange; + final Future Function(String targetPath, String displacedPath)? + afterFileExchange; + final WritersideModuleService moduleService; final WritersideProjectService? projectService; final WorkspaceDirectoryLister? treeDirectoryLister; @@ -942,9 +949,15 @@ class WritersideTopicRemovalService { edit.original, expected: edit.updated, ); - } on Object { - // Never overwrite a file changed by another process during rollback. - rollbackFailures.add(edit.path); + } on Object catch (rollbackError) { + // Preserve recovery locations from a failed rollback exchange too. + rollbackFailures.add( + rollbackError is BusyMarkException && + rollbackError.code == + 'writerside.topic-removal.rollback-failed' + ? '${rollbackError.args['paths']}' + : edit.path, + ); } } if (rollbackFailures.isNotEmpty) { @@ -2561,6 +2574,7 @@ class WritersideTopicRemovalService { } final stat = await File(path).stat(); File? temporary; + var preserveTemporary = false; try { for (var attempt = 0; attempt < 100; attempt += 1) { final candidate = File( @@ -2606,6 +2620,7 @@ class WritersideTopicRemovalService { validateBeforeCommit?.call(); final atomicApi = LinuxAtomicFileApi.instance; if (atomicApi.isAvailable) { + await beforeFileExchange?.call(checked.path, temporary.path); final exchangeError = atomicApi.exchange(temporary.path, checked.path); if (exchangeError != null) { throw FileSystemException( @@ -2614,50 +2629,39 @@ class WritersideTopicRemovalService { path, ); } - final replacedType = await FileSystemEntity.type( - temporary.path, - followLinks: false, - ); - final replacedStat = replacedType == FileSystemEntityType.file - ? await temporary.stat() - : null; - final replacedMatches = - replacedType == FileSystemEntityType.file && - replacedStat != null && - (replacedStat.mode & 0xfff) == (stat.mode & 0xfff) && - await temporary.readAsString() == expected; - if (!replacedMatches) { - final restoreError = atomicApi.exchange(temporary.path, checked.path); - if (restoreError != null) { - throw BusyMarkException( - 'writerside.topic-removal.rollback-failed', - args: {'paths': '${temporary.path}, ${checked.path}'}, - ); + // From this point the temporary path contains displaced user data. + // Retain it on every validation/cleanup failure; never exchange blindly + // over a destination another writer may already have replaced again. + preserveTemporary = true; + try { + await afterFileExchange?.call(checked.path, temporary.path); + final replacedType = await FileSystemEntity.type( + temporary.path, + followLinks: false, + ); + final replacedStat = replacedType == FileSystemEntityType.file + ? await temporary.stat() + : null; + if (replacedType != FileSystemEntityType.file || + replacedStat == null || + (replacedStat.mode & 0xfff) != (stat.mode & 0xfff) || + await temporary.readAsString() != expected) { + throw StateError('Displaced source changed'); } + await temporary.delete(); + } on Object { throw BusyMarkException( - 'writerside.topic-file.tree-changed', - args: {'path': path}, + 'writerside.topic-removal.rollback-failed', + args: {'paths': '${temporary.path}, ${checked.path}'}, ); } - try { - await temporary.delete(); - } on Object catch (error, stackTrace) { - final restoreError = atomicApi.exchange(temporary.path, checked.path); - if (restoreError != null) { - throw BusyMarkException( - 'writerside.topic-removal.rollback-failed', - args: {'paths': '${temporary.path}, ${checked.path}'}, - ); - } - Error.throwWithStackTrace(error, stackTrace); - } temporary = null; return; } await temporary.rename(checked.path); temporary = null; } finally { - if (temporary != null && await temporary.exists()) { + if (!preserveTemporary && temporary != null && await temporary.exists()) { await temporary.delete(); } } diff --git a/linux/io.busystack.busymark.metainfo.xml b/linux/io.busystack.busymark.metainfo.xml index 39bc9634..02c196ef 100644 --- a/linux/io.busystack.busymark.metainfo.xml +++ b/linux/io.busystack.busymark.metainfo.xml @@ -88,6 +88,7 @@ https://github.com/busystack/busymark/issues + diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt index 841fe6dc..7547ea60 100644 --- a/linux/runner/CMakeLists.txt +++ b/linux/runner/CMakeLists.txt @@ -15,6 +15,7 @@ add_executable(${BINARY_NAME} "gtk_window_preferences.cc" "linux_chrome_host.cc" "rich_clipboard_host.cc" + "save_chooser_host.cc" "secure_credential_host.cc" "video_player_host.cc" "web_render_host.cc" diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc index 63f42fc6..4cbd73ea 100644 --- a/linux/runner/my_application.cc +++ b/linux/runner/my_application.cc @@ -15,6 +15,7 @@ #include "linux_chrome_host.h" #include "native_shortcut_metadata.h" #include "rich_clipboard_host.h" +#include "save_chooser_host.h" #include "secure_credential_host.h" #include "video_player_host.h" #include "web_render_host.h" @@ -59,6 +60,7 @@ struct _MyApplication { BusyMarkLinuxChromeHost* chrome_host; FlMethodChannel* native_menu_channel; FlMethodChannel* writerside_dialog_channel; + FlMethodChannel* save_chooser_channel; FlMethodChannel* asset_input_channel; FlMethodChannel* secure_credential_channel; FlMethodChannel* rich_clipboard_channel; @@ -292,16 +294,120 @@ struct NativeMenuHandlerData { GtkWidget* view; NativeMenuSession* active; GdkEvent* trigger_event; + GHashTable* keys; gulong event_signal_id; }; -static gboolean native_menu_capture_trigger_event(GtkWidget*, - GdkEvent* event, - gpointer user_data) { +enum class NativeMenuKeyOwner { + kNone, + kView, + kViewBeforeMenu, + kMenu, + kMenuModifier, +}; + +struct NativeMenuKeyState { + NativeMenuKeyOwner owner; + guint32 press_time; + guint32 release_time; + bool saw_release; +}; + +static NativeMenuKeyState* native_menu_key_state(NativeMenuHandlerData* data, + GdkEventKey* event) { + const auto key = GUINT_TO_POINTER(event->hardware_keycode); + auto* state = static_cast( + g_hash_table_lookup(data->keys, key)); + if (state == nullptr) { + state = g_new0(NativeMenuKeyState, 1); + g_hash_table_insert(data->keys, key, state); + } + return state; +} + +// GDK timestamps wrap. FlView may put an unhandled event back in the GTK +// queue, so a redispatched release can arrive after the next press. +static bool key_time_before(guint32 first, guint32 second) { + return static_cast(first - second) < 0; +} + +static bool is_current_key_release(const NativeMenuKeyState* state, + guint32 time) { + return (!state->saw_release || key_time_before(state->release_time, time)) && + (state->owner == NativeMenuKeyOwner::kNone || + !key_time_before(time, state->press_time)); +} + +static void record_key_release(NativeMenuKeyState* state, guint32 time) { + state->owner = NativeMenuKeyOwner::kNone; + state->release_time = time; + state->saw_release = true; +} + +static bool is_momentary_modifier(guint keyval) { + switch (keyval) { + case GDK_KEY_Shift_L: + case GDK_KEY_Shift_R: + case GDK_KEY_Control_L: + case GDK_KEY_Control_R: + case GDK_KEY_Alt_L: + case GDK_KEY_Alt_R: + case GDK_KEY_Meta_L: + case GDK_KEY_Meta_R: + case GDK_KEY_Super_L: + case GDK_KEY_Super_R: + case GDK_KEY_ISO_Level3_Shift: + case GDK_KEY_Mode_switch: + return true; + default: + return false; + } +} + +static void deliver_menu_event_to_view(NativeMenuHandlerData* data, + GdkEvent* event) { + if (data->view != nullptr && gtk_widget_get_realized(data->view)) { + gtk_widget_event(data->view, event); + } +} + +static gboolean native_menu_view_event(GtkWidget*, + GdkEvent* event, + gpointer user_data) { auto* data = static_cast(user_data); - if (event == nullptr || - (event->type != GDK_BUTTON_PRESS && event->type != GDK_KEY_PRESS && - event->type != GDK_TOUCH_BEGIN)) { + if (event->type == GDK_KEY_RELEASE) { + auto* state = native_menu_key_state(data, &event->key); + if (is_current_key_release(state, event->key.time)) { + const bool pressed_in_menu = state->owner == NativeMenuKeyOwner::kMenu; + record_key_release(state, event->key.time); + // An activation or Escape can ungrab the keyboard before the key comes + // back up. FlView never saw this press and must not see its release. + if (pressed_in_menu) return GDK_EVENT_STOP; + } + return GDK_EVENT_PROPAGATE; + } + if (event->type == GDK_FOCUS_CHANGE && !event->focus_change.in && + data->active == nullptr) { + g_hash_table_remove_all(data->keys); + } + if (event->type == GDK_KEY_PRESS) { + auto* state = native_menu_key_state(data, &event->key); + // A press that crossed the menu boundary can still be repeating when + // focus returns to FlView. Wait for a new press before dispatching it. + if (state->owner == NativeMenuKeyOwner::kViewBeforeMenu || + state->owner == NativeMenuKeyOwner::kMenu) { + return GDK_EVENT_STOP; + } + if (state->owner == NativeMenuKeyOwner::kView || + state->owner == NativeMenuKeyOwner::kMenuModifier || + (state->saw_release && + !key_time_before(state->release_time, event->key.time))) { + return GDK_EVENT_PROPAGATE; + } + state->owner = NativeMenuKeyOwner::kView; + state->press_time = event->key.time; + } else if (event->type != GDK_BUTTON_PRESS && + event->type != GDK_TOUCH_BEGIN) { return GDK_EVENT_PROPAGATE; } g_clear_pointer(&data->trigger_event, gdk_event_free); @@ -309,6 +415,61 @@ static gboolean native_menu_capture_trigger_event(GtkWidget*, return GDK_EVENT_PROPAGATE; } +static gboolean native_menu_route_key_event(GtkWidget*, + GdkEvent* event, + gpointer user_data) { + auto* data = static_cast(user_data); + if (event->type != GDK_KEY_PRESS && event->type != GDK_KEY_RELEASE) { + return GDK_EVENT_PROPAGATE; + } + auto* state = native_menu_key_state(data, &event->key); + if (event->type == GDK_KEY_RELEASE && + !is_current_key_release(state, event->key.time)) { + return GDK_EVENT_STOP; + } + if (state->owner == NativeMenuKeyOwner::kView || + state->owner == NativeMenuKeyOwner::kViewBeforeMenu) { + // GtkMenu's grab receives the real release of a press already delivered + // to FlView. Deliver that event to FlView's normal key handler so both + // the embedder and Dart clear the physical key. Consume held-key repeats + // here so they cannot activate a GTK mnemonic or accelerator. + if (event->type == GDK_KEY_RELEASE) { + deliver_menu_event_to_view(data, event); + } + return GDK_EVENT_STOP; + } + if (state->owner == NativeMenuKeyOwner::kMenuModifier) { + if (event->type == GDK_KEY_RELEASE) { + deliver_menu_event_to_view(data, event); + return GDK_EVENT_STOP; + } + // FlView may redispatch the same modifier press after processing it. + return event->key.time == state->press_time ? GDK_EVENT_STOP + : GDK_EVENT_PROPAGATE; + } + if (event->type == GDK_KEY_PRESS) { + if (state->saw_release && + !key_time_before(state->release_time, event->key.time)) { + return GDK_EVENT_STOP; + } + if (state->owner == NativeMenuKeyOwner::kNone) { + state->press_time = event->key.time; + if (is_momentary_modifier(event->key.keyval)) { + // Forward this pair as well. A subsequent release sent to FlView + // carries the current modifier mask, which would otherwise make the + // embedder infer a press with no reliable left/right identity. + state->owner = NativeMenuKeyOwner::kMenuModifier; + deliver_menu_event_to_view(data, event); + } else { + state->owner = NativeMenuKeyOwner::kMenu; + } + } + } else { + record_key_release(state, event->key.time); + } + return GDK_EVENT_PROPAGATE; +} + static void native_menu_session_respond(NativeMenuSession* session, gint selected_index) { if (session->method_call == nullptr) { @@ -829,14 +990,25 @@ static gboolean set_native_submenu_availability(GtkWidget* menu, return valid; } -static void set_native_menu_direction(GtkWidget* widget, gpointer data) { - gtk_widget_set_direction(widget, static_cast(GPOINTER_TO_INT(data))); +struct NativeMenuSetup { + GtkTextDirection direction; + NativeMenuHandlerData* owner; +}; + +static void configure_native_menu(GtkWidget* widget, gpointer user_data) { + auto* setup = static_cast(user_data); + gtk_widget_set_direction(widget, setup->direction); + if (GTK_IS_MENU(widget)) { + g_signal_connect(widget, "event", G_CALLBACK(native_menu_route_key_event), + setup->owner); + } if (GTK_IS_MENU_ITEM(widget)) { GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(widget)); - if (submenu != nullptr) set_native_menu_direction(submenu, data); + if (submenu != nullptr) configure_native_menu(submenu, user_data); } if (GTK_IS_CONTAINER(widget)) { - gtk_container_foreach(GTK_CONTAINER(widget), set_native_menu_direction, data); + gtk_container_foreach(GTK_CONTAINER(widget), configure_native_menu, + user_data); } } @@ -974,7 +1146,8 @@ static void show_native_menu(NativeMenuHandlerData* data, g_signal_connect(session->menu, "key-press-event", G_CALLBACK(native_menu_mnemonic_key_cb), session); gtk_menu_attach_to_widget(GTK_MENU(session->menu), data->view, nullptr); - set_native_menu_direction(session->menu, GINT_TO_POINTER(direction)); + NativeMenuSetup setup{direction, data}; + configure_native_menu(session->menu, &setup); gtk_widget_show_all(session->menu); if (!set_native_submenu_availability(session->menu, entries, TRUE)) { fl_method_call_respond_error(method_call, "invalid-menu", @@ -1007,6 +1180,20 @@ static void show_native_menu(NativeMenuHandlerData* data, open_above ? (rtl ? GDK_GRAVITY_SOUTH_EAST : GDK_GRAVITY_SOUTH_WEST) : (rtl ? GDK_GRAVITY_NORTH_EAST : GDK_GRAVITY_NORTH_WEST), data->trigger_event); + if (gtk_widget_get_mapped(session->menu)) { + // Pause repeats from FlView's held presses across the grab. For example, + // F9 must not become Toggle Sidebar if the popup is closed with the mouse + // after Ctrl and Shift have been released while F9 stays down. + g_hash_table_foreach( + data->keys, + [](gpointer, gpointer value, gpointer) { + auto* state = static_cast(value); + if (state->owner == NativeMenuKeyOwner::kView) { + state->owner = NativeMenuKeyOwner::kViewBeforeMenu; + } + }, + nullptr); + } if (focus_first) { gtk_menu_shell_select_first(GTK_MENU_SHELL(session->menu), TRUE); } else { @@ -1028,6 +1215,7 @@ static void native_menu_handler_data_free(gpointer user_data) { reinterpret_cast(&data->view)); } g_clear_pointer(&data->trigger_event, gdk_event_free); + g_hash_table_unref(data->keys); g_free(data); } @@ -1060,11 +1248,13 @@ static void register_native_menu_channel(MyApplication* self, FlView* view) { kNativeMenuChannel, FL_METHOD_CODEC(codec)); auto* data = g_new0(NativeMenuHandlerData, 1); data->view = GTK_WIDGET(view); + data->keys = + g_hash_table_new_full(g_direct_hash, g_direct_equal, nullptr, g_free); g_object_add_weak_pointer(G_OBJECT(data->view), reinterpret_cast(&data->view)); data->event_signal_id = g_signal_connect(data->view, "event", - G_CALLBACK(native_menu_capture_trigger_event), data); + G_CALLBACK(native_menu_view_event), data); fl_method_channel_set_method_call_handler( self->native_menu_channel, native_menu_method_call_cb, data, native_menu_handler_data_free); @@ -1224,6 +1414,7 @@ static void my_application_activate(GApplication* application) { register_native_menu_channel(self, view); self->writerside_dialog_channel = busymark_writerside_dialog_channel_new(view, window); + self->save_chooser_channel = busymark_save_chooser_channel_new(view, window); register_asset_input_channel(self, view); self->rich_clipboard_channel = busymark_rich_clipboard_channel_new(view); self->secure_credential_channel = @@ -1283,6 +1474,7 @@ static void my_application_dispose(GObject* object) { g_clear_object(&self->native_surface_css_provider); g_clear_object(&self->native_menu_channel); g_clear_object(&self->writerside_dialog_channel); + g_clear_object(&self->save_chooser_channel); g_clear_object(&self->asset_input_channel); g_clear_object(&self->rich_clipboard_channel); g_clear_object(&self->secure_credential_channel); diff --git a/linux/runner/save_chooser_host.cc b/linux/runner/save_chooser_host.cc new file mode 100644 index 00000000..572bbaf4 --- /dev/null +++ b/linux/runner/save_chooser_host.cc @@ -0,0 +1,311 @@ +#include "save_chooser_host.h" + +#include +#include + +#include +#include + +namespace { + +constexpr char kActiveChooser[] = "busymark-active-save-chooser"; + +const gchar* string_arg(FlValue* args, const gchar* key) { + FlValue* value = fl_value_lookup_string(args, key); + return value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_STRING + ? fl_value_get_string(value) + : nullptr; +} + +bool bool_arg(FlValue* args, const gchar* key) { + FlValue* value = fl_value_lookup_string(args, key); + return value != nullptr && fl_value_get_type(value) == FL_VALUE_TYPE_BOOL && + fl_value_get_bool(value); +} + +void set_string(FlValue* value, const char* key, const gchar* string) { + fl_value_set_string_take(value, key, string == nullptr + ? fl_value_new_null() + : fl_value_new_string(string)); +} + +bool read_stamp(const gchar* path, int flags, struct statx& stamp) { + constexpr unsigned int required = STATX_TYPE | STATX_MODE | STATX_INO | + STATX_SIZE | STATX_MTIME | STATX_CTIME; + return statx(AT_FDCWD, path, flags, required | STATX_BTIME, &stamp) == 0 && + (stamp.stx_mask & required) == required; +} + +std::string timestamp(const struct statx_timestamp& time) { + return std::to_string(time.tv_sec) + ":" + std::to_string(time.tv_nsec); +} + +std::string identity(const struct statx& stamp) { + std::string result = std::to_string(stamp.stx_dev_major) + ":" + + std::to_string(stamp.stx_dev_minor) + ":" + + std::to_string(static_cast(stamp.stx_ino)); + if (stamp.stx_mask & STATX_BTIME) result += ":" + timestamp(stamp.stx_btime); + return result; +} + +std::string version(const struct statx& stamp) { + return identity(stamp) + "/" + std::to_string(stamp.stx_mode) + "/" + + std::to_string(stamp.stx_size) + "/" + timestamp(stamp.stx_mtime) + + "/" + timestamp(stamp.stx_ctime); +} + +FlValue* selection(const gchar* path, bool replacing, bool allow_link) { + g_autofree gchar* folder = g_path_get_dirname(path); + struct statx parent; + if (!g_utf8_validate(path, -1, nullptr) || !read_stamp(folder, 0, parent) || + !S_ISDIR(parent.stx_mode)) { + return nullptr; + } + g_autoptr(FlValue) result = fl_value_new_map(); + set_string(result, "path", path); + set_string(result, "parent", identity(parent).c_str()); + if (replacing) { + struct statx entry; + if (!read_stamp(path, AT_SYMLINK_NOFOLLOW, entry)) return nullptr; + if (allow_link && S_ISLNK(entry.stx_mode)) { + g_autofree gchar* target = g_file_read_link(path, nullptr); + struct statx referent; + if (target == nullptr || !g_utf8_validate(target, -1, nullptr) || + !read_stamp(path, 0, referent) || + !S_ISREG(referent.stx_mode)) { + return nullptr; + } + set_string(result, "linkTarget", target); + set_string(result, "referent", version(referent).c_str()); + } else if (!S_ISREG(entry.stx_mode)) { + return nullptr; + } + set_string(result, "entry", version(entry).c_str()); + } + return g_steal_pointer(&result); +} + +struct SaveChooser { + FlMethodCall* call; + FlValue* review = nullptr; + std::string reviewed_path; + std::string suffix; + bool suffix_only_when_missing; + bool allow_link; + bool replied = false; + + ~SaveChooser() { + g_clear_pointer(&review, fl_value_unref); + g_object_unref(call); + } +}; + +void finish(GtkWidget* dialog, SaveChooser* state, FlValue* result, + const gchar* error = nullptr) { + state->replied = true; + if (error != nullptr) { + fl_method_call_respond_error(state->call, error, nullptr, nullptr, nullptr); + } else { + fl_method_call_respond_success(state->call, result, nullptr); + } + gtk_widget_destroy(dialog); +} + +void dialog_destroyed(GtkWidget* widget, gpointer data) { + auto* state = static_cast(data); + GtkWindow* parent = gtk_window_get_transient_for(GTK_WINDOW(widget)); + if (parent != nullptr) g_object_set_data(G_OBJECT(parent), kActiveChooser, nullptr); + if (!state->replied) { + fl_method_call_respond_success(state->call, nullptr, nullptr); + } +} + +// Keep the amended name in the chooser. GTK then validates that pathname +// itself and prompts only if that exact destination exists. +bool amend_name(GtkFileChooser* chooser, const gchar* path, + const SaveChooser* state) { + if (state->suffix.empty()) return false; + g_autofree gchar* name = g_path_get_basename(path); + const gchar* extension = strrchr(name, '.'); + if (extension != nullptr && extension != name && + (state->suffix_only_when_missing || + g_ascii_strcasecmp(extension, state->suffix.c_str()) == 0)) { + return false; + } + g_autofree gchar* folder = g_path_get_dirname(path); + g_autofree gchar* current = gtk_file_chooser_get_current_folder(chooser); + if (g_strcmp0(folder, current) != 0) { + gtk_file_chooser_set_current_folder(chooser, folder); + } + const std::string amended = std::string(name) + state->suffix; + gtk_file_chooser_set_current_name(chooser, amended.c_str()); + return true; +} + +bool confirm_replacement(GtkWindow* chooser, const gchar* path) { + g_autofree gchar* file = g_filename_display_basename(path); + g_autofree gchar* parent = g_path_get_dirname(path); + g_autofree gchar* folder = g_filename_display_basename(parent); + g_autoptr(GtkWidget) prompt = GTK_WIDGET(g_object_ref_sink(gtk_message_dialog_new( + chooser, static_cast(GTK_DIALOG_MODAL | + GTK_DIALOG_DESTROY_WITH_PARENT), + GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE, + g_dgettext("gtk30", "A file named “%s” already exists. Do you want to " + "replace it?"), + file))); + GtkDialog* dialog = GTK_DIALOG(prompt); + gtk_message_dialog_format_secondary_text( + GTK_MESSAGE_DIALOG(prompt), + g_dgettext("gtk30", "The file already exists in “%s”. Replacing it will " + "overwrite its contents."), + folder); + GtkWidget* cancel = gtk_dialog_add_button( + dialog, g_dgettext("gtk30", "_Cancel"), GTK_RESPONSE_CANCEL); + gtk_dialog_add_button(dialog, g_dgettext("gtk30", "_Replace"), + GTK_RESPONSE_ACCEPT); + gtk_dialog_set_default_response(dialog, GTK_RESPONSE_CANCEL); + gtk_widget_grab_focus(cancel); + const int answer = gtk_dialog_run(dialog); + gtk_widget_destroy(prompt); + return answer == GTK_RESPONSE_ACCEPT; +} + +GtkFileChooserConfirmation confirm_overwrite(GtkFileChooser* chooser, + gpointer data) { + auto* state = static_cast(data); + g_clear_pointer(&state->review, fl_value_unref); + state->reviewed_path.clear(); + g_autofree gchar* path = gtk_file_chooser_get_filename(chooser); + if (path == nullptr || amend_name(chooser, path, state)) { + return GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN; + } + // GTK's built-in prompt defaults to Replace and can be bypassed by a failed + // folder metadata lookup. Require a positive response from the native dialog. + g_autoptr(GtkWidget) parent = GTK_WIDGET(g_object_ref(chooser)); + g_autoptr(FlValue) review = selection(path, true, state->allow_link); + if (!confirm_replacement(GTK_WINDOW(parent), path) || state->replied) { + return GTK_FILE_CHOOSER_CONFIRMATION_SELECT_AGAIN; + } + state->reviewed_path = path; + state->review = g_steal_pointer(&review); + return GTK_FILE_CHOOSER_CONFIRMATION_ACCEPT_FILENAME; +} + +void response(GtkDialog* dialog, gint response_id, gpointer data) { + auto* state = static_cast(data); + GtkWidget* widget = GTK_WIDGET(dialog); + if (response_id != GTK_RESPONSE_ACCEPT) { + finish(widget, state, nullptr); + return; + } + GtkFileChooser* chooser = GTK_FILE_CHOOSER(dialog); + g_autofree gchar* path = gtk_file_chooser_get_filename(chooser); + if (path == nullptr) { + finish(widget, state, nullptr, "invalid-destination"); + return; + } + if (amend_name(chooser, path, state)) { + g_clear_pointer(&state->review, fl_value_unref); + state->reviewed_path.clear(); + return; + } + if (state->reviewed_path == path) { + finish(widget, state, state->review, + state->review == nullptr ? "invalid-destination" : nullptr); + return; + } + g_autoptr(FlValue) result = selection(path, false, state->allow_link); + finish(widget, state, result, + result == nullptr ? "invalid-destination" : nullptr); +} + +void add_filter(GtkFileChooser* chooser, FlValue* args) { + const auto* label = string_arg(args, "filterLabel"); + auto* patterns = fl_value_lookup_string(args, "patterns"); + if (label == nullptr || patterns == nullptr || + fl_value_get_type(patterns) != FL_VALUE_TYPE_LIST || + fl_value_get_length(patterns) == 0) { + return; + } + GtkFileFilter* filter = gtk_file_filter_new(); + gtk_file_filter_set_name(filter, label); + for (size_t index = 0; index < fl_value_get_length(patterns); ++index) { + auto* value = fl_value_get_list_value(patterns, index); + if (fl_value_get_type(value) == FL_VALUE_TYPE_STRING) { + gtk_file_filter_add_pattern(filter, fl_value_get_string(value)); + } + } + gtk_file_chooser_add_filter(chooser, filter); + GtkFileFilter* all_files = gtk_file_filter_new(); + gtk_file_filter_set_name(all_files, g_dgettext("gtk30", "All Files")); + gtk_file_filter_add_pattern(all_files, "*"); + gtk_file_chooser_add_filter(chooser, all_files); + gtk_file_chooser_set_filter(chooser, filter); +} + +void method_call(FlMethodChannel*, FlMethodCall* call, gpointer data) { + if (g_strcmp0(fl_method_call_get_name(call), "save") != 0) { + fl_method_call_respond_not_implemented(call, nullptr); + return; + } + GtkWindow* parent = GTK_WINDOW(data); + if (g_object_get_data(G_OBJECT(parent), kActiveChooser) != nullptr) { + fl_method_call_respond_success(call, nullptr, nullptr); + return; + } + FlValue* args = fl_method_call_get_args(call); + if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) { + fl_method_call_respond_error(call, "invalid-arguments", nullptr, nullptr, + nullptr); + return; + } + const gchar* action = string_arg(args, "actionLabel"); + const gchar* cancel = string_arg(args, "cancelLabel"); + const gchar* name = string_arg(args, "suggestedName"); + const gchar* suffix = string_arg(args, "suffix"); + if (action == nullptr || cancel == nullptr || name == nullptr) { + fl_method_call_respond_error(call, "invalid-arguments", nullptr, nullptr, + nullptr); + return; + } + GtkWidget* dialog = gtk_file_chooser_dialog_new( + action, parent, GTK_FILE_CHOOSER_ACTION_SAVE, cancel, GTK_RESPONSE_CANCEL, + action, GTK_RESPONSE_ACCEPT, nullptr); + auto* state = new SaveChooser{ + FL_METHOD_CALL(g_object_ref(call)), nullptr, {}, + suffix != nullptr ? suffix : "", bool_arg(args, "suffixOnlyWhenMissing"), + bool_arg(args, "allowLink")}; + g_object_set_data_full(G_OBJECT(dialog), "busymark-save-chooser", state, + [](gpointer state) { + delete static_cast(state); + }); + g_object_set_data(G_OBJECT(parent), kActiveChooser, dialog); + gtk_window_set_modal(GTK_WINDOW(dialog), TRUE); + gtk_window_set_destroy_with_parent(GTK_WINDOW(dialog), TRUE); + gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT); + GtkFileChooser* chooser = GTK_FILE_CHOOSER(dialog); + gtk_file_chooser_set_do_overwrite_confirmation(chooser, TRUE); + if (const gchar* folder = string_arg(args, "initialDirectory")) { + gtk_file_chooser_set_current_folder(chooser, folder); + } + gtk_file_chooser_set_current_name(chooser, name); + add_filter(chooser, args); + g_signal_connect(dialog, "confirm-overwrite", G_CALLBACK(confirm_overwrite), + state); + g_signal_connect(dialog, "response", G_CALLBACK(response), state); + g_signal_connect(dialog, "destroy", G_CALLBACK(dialog_destroyed), state); + gtk_widget_show(dialog); +} + +} // namespace + +FlMethodChannel* busymark_save_chooser_channel_new(FlView* view, + GtkWindow* parent) { + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + FlMethodChannel* channel = fl_method_channel_new( + fl_engine_get_binary_messenger(fl_view_get_engine(view)), + "busymark/save_chooser", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel, method_call, parent, + nullptr); + return channel; +} diff --git a/linux/runner/save_chooser_host.h b/linux/runner/save_chooser_host.h new file mode 100644 index 00000000..c2ba42b2 --- /dev/null +++ b/linux/runner/save_chooser_host.h @@ -0,0 +1,10 @@ +#ifndef BUSYMARK_SAVE_CHOOSER_HOST_H_ +#define BUSYMARK_SAVE_CHOOSER_HOST_H_ + +#include +#include + +FlMethodChannel* busymark_save_chooser_channel_new(FlView* view, + GtkWindow* parent); + +#endif diff --git a/pubspec.yaml b/pubspec.yaml index 5ec74aee..1df6255e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: busymark description: Local-first Markdown and Writerside-compatible documentation editor. publish_to: 'none' -version: 0.7.1 +version: 0.7.2 environment: sdk: ">=3.12.1 <4.0.0" diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 8f2508b8..bf3f4d70 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -1,6 +1,6 @@ name: busymark title: BusyMark -version: "0.7.1" +version: "0.7.2" summary: Markdown and Writerside documentation editor # Snap Store listing translations are managed outside this Flutter package. # Update store metadata when approved translated listing text is supplied. diff --git a/test/fixtures/clipboard/browser_list_ownership.html b/test/fixtures/clipboard/browser_list_ownership.html new file mode 100644 index 00000000..6593947f --- /dev/null +++ b/test/fixtures/clipboard/browser_list_ownership.html @@ -0,0 +1,14 @@ +
    +
  • Design
    • Outline
    • Review
  • +
  • Test
  • +
+
    +
  • Ship
  • +
  • Document
  • +
+
  1. Third
  2. Fourth
+
  1. Restart
  2. Continue
+
    +
  • First paragraph

    Second paragraph

  • +
  • Last item

  • +
diff --git a/test/fixtures/clipboard/synthetic_browser_job.html b/test/fixtures/clipboard/synthetic_browser_job.html new file mode 100644 index 00000000..4683248b --- /dev/null +++ b/test/fixtures/clipboard/synthetic_browser_job.html @@ -0,0 +1,5 @@ + +

Example Developer

+

About the role

Build tools with the team.
Office hours vary.

+
Application details

Keep this selected interface text.
+
void main() {}
diff --git a/test/src/app_router_test.dart b/test/src/app_router_test.dart index 407d1cac..7bc97a73 100644 --- a/test/src/app_router_test.dart +++ b/test/src/app_router_test.dart @@ -1,15 +1,11 @@ -import 'dart:async'; - import 'package:busymark/l10n/generated/app_localizations_en.dart'; import 'package:busymark/src/app/app_settings.dart'; import 'package:busymark/src/app/app_router.dart'; import 'package:busymark/src/app/busymark_app.dart'; import 'package:busymark/src/app/busymark_shortcuts.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/workspace/presentation/settings_screen.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; -import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -93,12 +89,9 @@ void main() { testWidgets( 'Settings opened from Welcome returns to Welcome with a stale workspace', (tester) async { - final headerBar = _FallbackHeaderBarService(); - await tester.pumpWidget( ProviderScope( overrides: [ - linuxHeaderBarServiceProvider.overrideWithValue(headerBar), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -142,9 +135,6 @@ void main() { await tester.pumpWidget( ProviderScope( overrides: [ - linuxHeaderBarServiceProvider.overrideWithValue( - _FallbackHeaderBarService(), - ), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore( AppSettings.defaults() @@ -162,7 +152,7 @@ void main() { for (var index = 0; index < 30; index += 1) { await tester.pump(const Duration(milliseconds: 100)); if (find - .byTooltip('${l10n.back} (${BusyMarkAppShortcuts.back.label})') + .byTooltip('${l10n.home} (${BusyMarkAppShortcuts.home.label})') .evaluate() .isNotEmpty) { break; @@ -170,37 +160,23 @@ void main() { } expect( - find.byTooltip('${l10n.back} (${BusyMarkAppShortcuts.back.label})'), + find.byTooltip('${l10n.home} (${BusyMarkAppShortcuts.home.label})'), findsOneWidget, ); await tester.tap( - find.byTooltip('${l10n.back} (${BusyMarkAppShortcuts.back.label})'), + find.byTooltip('${l10n.home} (${BusyMarkAppShortcuts.home.label})'), ); await tester.pumpAndSettle(); await tester.pump(const Duration(milliseconds: 500)); expect(find.text(l10n.createMarkdownFile), findsOneWidget); expect( - find.byTooltip('${l10n.back} (${BusyMarkAppShortcuts.back.label})'), + find.byTooltip('${l10n.home} (${BusyMarkAppShortcuts.home.label})'), findsNothing, ); }); } -class _FallbackHeaderBarService extends LinuxHeaderBarService { - _FallbackHeaderBarService() - : super(channel: const MethodChannel('test.busymark/headerbar.router')); - - @override - bool get isAvailable => false; - - @override - bool get usesNativeHeaderBar => false; - - @override - Stream get actions => const Stream.empty(); -} - class _StaleWorkspaceController extends WorkspaceController { @override WorkspaceState build() { diff --git a/test/src/app_settings_test.dart b/test/src/app_settings_test.dart index 0115a41d..23a62174 100644 --- a/test/src/app_settings_test.dart +++ b/test/src/app_settings_test.dart @@ -1,3 +1,5 @@ +import 'package:busymark/src/workspace/remote_image_permissions.dart'; +import 'package:busymark/src/workspace/workspace_model.dart'; import 'package:busymark/src/app/command_registry.dart'; import 'package:busymark/src/app/keymap_controller.dart'; import 'package:busymark/src/app/shortcut_binding.dart'; @@ -1845,6 +1847,72 @@ void main() { expect(store.value['remoteImageAllowedWorkspacePaths'], isEmpty); }); + test( + 'typed remote-image grants reload independently of legacy paths and global settings', + () async { + Workspace local(String path, WorkspaceKind kind) => Workspace( + id: path, + rootPath: kind == WorkspaceKind.singleMarkdown ? p.dirname(path) : path, + kind: kind, + openedAt: DateTime(2026), + files: const [], + diagnostics: const [], + ); + final folder = local('/tmp/allowed', WorkspaceKind.markdownFolder); + final writerside = local('/tmp/allowed', WorkspaceKind.writersideModule); + final standalone = local( + '/tmp/allowed/readme.md', + WorkspaceKind.singleMarkdown, + ); + final legacy = local( + '/tmp/legacy/readme.md', + WorkspaceKind.singleMarkdown, + ); + final nextcloud = Workspace.nextcloudNotes('account-for-notes'); + final otherAccount = Workspace.nextcloudNotes('other-account'); + final store = _MemorySettingsStore() + ..value = { + 'remoteImageAllowedWorkspacePaths': ['/tmp/legacy'], + }; + + final original = ProviderContainer( + overrides: [localSettingsStoreProvider.overrideWithValue(store)], + ); + final controller = original.read(appSettingsControllerProvider.notifier); + await Future.delayed(Duration.zero); + for (final workspace in [folder, nextcloud]) { + await controller.allowRemoteImagesForWorkspaceId( + remoteImageWorkspaceId(workspace)!, + ); + } + await controller.setAllowRemoteImages(true); + original.dispose(); + + final restarted = ProviderContainer( + overrides: [localSettingsStoreProvider.overrideWithValue(store)], + ); + addTearDown(restarted.dispose); + final reopened = restarted.read(appSettingsControllerProvider.notifier); + await Future.delayed(Duration.zero); + AppSettings read() => restarted.read(appSettingsControllerProvider); + expect(allowsWorkspaceRemoteImages(read(), standalone), isTrue); + await reopened.setAllowRemoteImages(false); + expect(remoteImageWorkspaceId(standalone), isNull); + for (final workspace in [folder, legacy, nextcloud]) { + expect(allowsWorkspaceRemoteImages(read(), workspace), isTrue); + } + for (final workspace in [standalone, writerside, otherAccount]) { + expect(allowsWorkspaceRemoteImages(read(), workspace), isFalse); + } + + await reopened.clearRemoteImageWorkspacePermissions(); + expect(store.value['remoteImageAllowedWorkspacePaths'], isEmpty); + expect(store.value['remoteImageAllowedWorkspaceIds'], isEmpty); + expect(allowsWorkspaceRemoteImages(read(), legacy), isFalse); + expect(allowsWorkspaceRemoteImages(read(), nextcloud), isFalse); + }, + ); + test( 'Git workspace trust persists, normalizes, and can be cleared', () async { diff --git a/test/src/app_smoke_test.dart b/test/src/app_smoke_test.dart index b0ccfdc0..1a1b2af6 100644 --- a/test/src/app_smoke_test.dart +++ b/test/src/app_smoke_test.dart @@ -1,3 +1,6 @@ +import '../support/controlled_image_http_client.dart'; +import 'package:busymark/src/core/save_destination.dart'; +import 'package:busymark/src/app/linux/linux_page_frame.dart'; import 'package:busymark/src/workspace/presentation/workspace_screen.dart'; import 'package:busymark/src/references/reference_controller.dart'; import 'package:busymark/src/git/application/shared_git_presentation.dart'; @@ -53,6 +56,7 @@ import 'package:busymark/src/editor/document_list_marker.dart'; import 'package:busymark/src/editor/document_text_geometry.dart'; import 'package:busymark/src/editor/document_thematic_break.dart'; import 'package:busymark/src/editor/markdown_image_view.dart'; +import 'package:busymark/src/editor/markdown_image_permission_scope.dart'; import 'package:busymark/src/editor/source/source_editor.dart'; import 'package:busymark/src/editor/source_highlighter.dart' show BusyMarkSourceEditingController; @@ -76,7 +80,6 @@ import 'package:busymark/src/markdown/markdown_model.dart'; import 'package:busymark/src/markdown/markdown_parser.dart'; import 'package:busymark/src/platform/linux_gtk_accent_service.dart'; import 'package:busymark/src/platform/gtk_header_icon_service.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/platform/rich_clipboard_service.dart'; import 'package:busymark/src/spellcheck/spelling_dictionary_downloader.dart'; import 'package:busymark/src/spellcheck/spelling_session_controller.dart'; @@ -111,7 +114,6 @@ import '../support/widget_async.dart'; import '../support/shared_git_read_fixture.dart'; void main() { - late _FallbackHeaderBarService headerBarService; final l10n = AppLocalizationsEn(); setUp(() { @@ -127,7 +129,6 @@ void main() { const MethodChannel(nativeWritersideDialogChannelName), (_) async => throw MissingPluginException(), ); - headerBarService = _FallbackHeaderBarService(); }); testWidgets( @@ -137,7 +138,7 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Heading\n\nDocument text\n', }); final container = harness.container; @@ -156,12 +157,25 @@ void main() { LogicalKeyboardKey key, { bool control = true, bool shift = true, + bool expectMenu = false, }) async { if (control) { await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); } if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyEvent(key); + await tester.sendKeyDownEvent(key); + if (expectMenu) { + await pumpUntil( + tester, + () => menus.isOpen, + operation: 'open the selector while the shortcut is held', + ); + final presentations = menus.packets.length; + await tester.sendKeyRepeatEvent(key); + await tester.pumpAndSettle(); + expect(menus.packets, hasLength(presentations)); + } + await tester.sendKeyUpEvent(key); if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); if (control) { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); @@ -169,12 +183,18 @@ void main() { await tester.pumpAndSettle(); } - await chord(LogicalKeyboardKey.f9); - await pumpUntil( - tester, - () => menus.isOpen, - operation: 'open Sidebar View with its registered shortcut', + await chord(LogicalKeyboardKey.f10, expectMenu: true); + expect(menus.isOpen, isTrue); + expect( + container.read(appSettingsControllerProvider).sidebarVisible, + isFalse, ); + expect(menus.contains('Reading'), isTrue); + menus.close(); + await tester.pumpAndSettle(); + + await chord(LogicalKeyboardKey.f9, expectMenu: true); + expect(menus.isOpen, isTrue); expect( container.read(appSettingsControllerProvider).sidebarVisible, isTrue, @@ -188,6 +208,7 @@ void main() { 'Local History': 'L', 'Clipboard History': 'B', 'References': 'R', + 'Recent': 'E', }; expect({ for (final e in menus.entries) e['label']: e['mnemonic'], @@ -200,7 +221,7 @@ void main() { await tester.pumpAndSettle(); expect(find.byTooltip('Sidebar view (Ctrl+Shift+F9)'), findsOneWidget); expect(find.byTooltip('Hide sidebar (F9)'), findsOneWidget); - await chord(LogicalKeyboardKey.f10); + await chord(LogicalKeyboardKey.f10, expectMenu: true); expect(menus.isOpen, isTrue); expect( {for (final e in menus.entries) e['label']: e['mnemonic']}, @@ -254,11 +275,21 @@ void main() { expect(menus.isOpen, isFalse); await chord(LogicalKeyboardKey.f10); expect(menus.isOpen, isFalse); - await chord(LogicalKeyboardKey.f6, control: false, shift: false); + await chord( + LogicalKeyboardKey.f6, + control: false, + shift: false, + expectMenu: true, + ); expect(menus.isOpen, isTrue); menus.close(); await tester.pumpAndSettle(); - await chord(LogicalKeyboardKey.f8, control: false, shift: false); + await chord( + LogicalKeyboardKey.f8, + control: false, + shift: false, + expectMenu: true, + ); expect(menus.isOpen, isTrue); menus.close(); await tester.pumpAndSettle(); @@ -291,7 +322,7 @@ void main() { 'configuration content selector preserves letters and rejects unavailable view responses', (tester) async { const source = '\n'; - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Document\n', 'settings.cfg': source, }); @@ -358,7 +389,7 @@ void main() { testWidgets( 'focused Source opens its context menu with Shift+F10 and Menu, excluding Ctrl+Shift+F10', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Keyboard context\n', }); final container = harness.container; @@ -376,15 +407,14 @@ void main() { final menus = NativeMenuProbe(tester); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyEvent(LogicalKeyboardKey.f10); - await tester.pump(); - expect(menus.isOpen, isFalse, reason: 'wait for Shift release'); - await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.f10); await pumpUntil( tester, () => menus.isOpen, - operation: 'open the focused Source context menu', + operation: 'open the focused Source context menu on keydown', ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.f10); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(menus.contains(l10n.selectAll), isTrue); expect(menus.contains(l10n.source), isFalse); menus.close(); @@ -393,9 +423,7 @@ void main() { await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyEvent(LogicalKeyboardKey.f10); - await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.f10); await pumpUntil( tester, () => menus.isOpen, @@ -407,6 +435,11 @@ void main() { 'R', 'D', ]); + await tester.sendKeyUpEvent(LogicalKeyboardKey.f10); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pumpAndSettle(); + expect(menus.isOpen, isTrue); expect(menus.packets, hasLength(2)); menus.close(); await tester.pumpAndSettle(); @@ -434,7 +467,7 @@ void main() { testWidgets( 'selector Settings show effective opener bindings and preserve unrelated overrides', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Document\n', }); final container = harness.container; @@ -517,7 +550,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settings), workspaceServiceProvider.overrideWithValue( _StartupWorkspaceService(), @@ -644,7 +676,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(store), localHistoryStoreProvider.overrideWithValue( MemoryLocalHistoryStore(), @@ -831,6 +862,7 @@ void main() { ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); + container.dispose(); await tester.pump(const Duration(seconds: 1)); }, ); @@ -839,11 +871,9 @@ void main() { testWidgets( 'effective keymap changes Source execution, disables defaults and updates native metadata', (tester) async { - final (:container, :events) = await _pumpSearchRegression( - tester, - headerBarService, - {'a.md': 'needle other'}, - ); + final (:container) = await _pumpSearchRegression(tester, { + 'a.md': 'needle other', + }); final saveHandler = container .read(busyMarkCommandRegistryProvider)['file.save']! .execute; @@ -1114,7 +1144,7 @@ void main() { testWidgets( 'capture releases dispatch even when native key-up skips focus delivery', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'unchanged', }); final owner = Object(); @@ -1153,7 +1183,7 @@ void main() { testWidgets( 'capture suppresses the real workspace search route until key release', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'selected text', }); final container = harness.container; @@ -1226,7 +1256,7 @@ void main() { testWidgets( 'shortcut Settings respects pending property edits before leaving the workspace', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'Original text', }); final container = harness.container; @@ -1302,7 +1332,7 @@ void main() { testWidgets( 'Actions keeps its captured target and selected command when a binding changes', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'selected text', }); final container = harness.container; @@ -1385,9 +1415,7 @@ void main() { testWidgets('application reassignment receives a retired editor combination', ( tester, ) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { - 'a.md': 'Text', - }); + final harness = await _pumpSearchRegression(tester, {'a.md': 'Text'}); final container = harness.container; final keymap = container.read(keymapControllerProvider.notifier); container.read(searchSessionProvider.notifier).close(restoreFocus: false); @@ -1488,7 +1516,7 @@ void main() { testWidgets( 'effective keymap replaces sidebar keypad aliases and tree deletion keys', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Heading\nText', 'b.md': 'Other', }); @@ -1621,7 +1649,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue( _StartupWorkspaceService(), @@ -1711,7 +1738,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -1817,9 +1843,22 @@ void main() { expect(parsed.blocks.single.attributes['level'], '2'); expect(parsed.blocks.single.plainText, 'About the job'); } - bool? saved; - unawaited(workspace.saveActive().then((value) => saved = value)); - await _waitForSearchCondition(tester, () => saved != null); + final saving = workspace.saveActive(); + final saved = await tester.runAsync(() async { + // Save crosses real file I/O and callbacks queued on the widget clock. + // Drive both until the controller reports the transaction result. + var finished = false; + final result = saving.whenComplete(() => finished = true); + Future flushFramesUntilSaved() async { + while (!finished) { + await tester.pump(); + if (!finished) await Future.delayed(Duration.zero); + } + } + + final (value, _) = await (result, flushFramesUntilSaved()).wait; + return value; + }); expect(saved, isTrue); await tester.pumpAndSettle(); expect(file.readAsStringSync(), savedSource); @@ -1853,6 +1892,8 @@ void main() { BusyBlockKind.heading, ); await tester.pumpWidget(const SizedBox.shrink()); + container.dispose(); + await tester.pump(); }, ); @@ -1886,7 +1927,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -1954,10 +1994,6 @@ void main() { field.controller!.selection, TextSelection.collapsed(offset: 1 + count), ); - final dynamic editorState = tester.state( - find.byType(BusyMarkWysiwygEditor), - ); - expect(editorState.debugUndoSnapshotCount, 0); expect(workspace.undoActiveBuffer(), isTrue); await tester.pumpAndSettle(); expect( @@ -2050,6 +2086,8 @@ void main() { expected, ); await tester.pumpWidget(const SizedBox.shrink()); + container.dispose(); + await tester.pump(); }, ); } @@ -2060,7 +2098,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -2170,7 +2207,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/workspace-paste.md'), @@ -2432,7 +2468,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settings), workspaceServiceProvider.overrideWithValue( const _SearchWorkspaceService(''), @@ -2519,14 +2554,6 @@ void main() { fields.last.controller!.selection, const TextSelection.collapsed(offset: 0), ); - expect( - tester - .state( - find.byType(BusyMarkWysiwygEditor), - ) - .debugUndoSnapshotCount, - 0, - ); await shortcut(LogicalKeyboardKey.keyZ); expect(source(), beforeEnter); check(recognized: false); @@ -2551,10 +2578,7 @@ void main() { ) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -2599,10 +2623,7 @@ void main() { ) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -2614,7 +2635,7 @@ void main() { expect(find.text(l10n.openMarkdownFile), findsOneWidget); expect(find.text(l10n.markdownFolderOrWritersideProject), findsOneWidget); expect(find.text(l10n.browseNotes), findsOneWidget); - expect(find.text(l10n.nextcloudNewNote), findsOneWidget); + expect(find.text(l10n.newNextcloudNote), findsOneWidget); expect( tester.getTopLeft(find.text(l10n.markdownFolderOrWritersideProject)).dy, lessThan(tester.getTopLeft(find.text(l10n.browseNotes)).dy), @@ -2687,7 +2708,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -2760,7 +2780,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -2790,7 +2809,7 @@ void main() { await tester.pumpAndSettle(); } await tester.tap( - find.byTooltip('${l10n.back} (${BusyMarkAppShortcuts.back.label})'), + find.byTooltip('${l10n.home} (${BusyMarkAppShortcuts.home.label})'), ); await tester.pumpAndSettle(); expect(find.text(l10n.createMarkdownFile), findsOneWidget); @@ -2819,7 +2838,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), nativeWindowControllerProvider.overrideWithValue(nativeWindow), ], child: const BusyMarkApp(), @@ -2885,10 +2903,7 @@ void main() { testWidgets('Alt+Left activates the header Back command', (tester) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -2922,8 +2937,140 @@ void main() { expect(find.byKey(const ValueKey('settings-page-selector')), findsNothing); }); + testWidgets('Home and Settings Back have distinct customizable routes', ( + tester, + ) async { + final fixture = Directory.systemTemp.createTempSync('busymark-home-'); + addTearDown(() => fixture.deleteSync(recursive: true)); + final file = File(p.join(fixture.path, 'original.md')) + ..writeAsStringSync('# Original'); + final settings = _MemorySettingsStore() + ..value = AppSettings.defaults().copyWith(autoSave: false).toJson(); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + startupPathProvider.overrideWithValue(file.path), + localSettingsStoreProvider.overrideWithValue(settings), + localHistoryStoreProvider.overrideWithValue(MemoryLocalHistoryStore()), + documentSessionStoreProvider.overrideWithValue( + MemoryDocumentSessionStore(), + ), + documentRecoveryStoreProvider.overrideWithValue( + MemoryDocumentRecoveryStore(), + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), + ), + ); + final router = container.read(appRouterProvider); + final controller = container.read(workspaceControllerProvider.notifier); + String path() => router.routeInformationProvider.value.uri.path; + Finder home() => find.byKey(const ValueKey('workspace-home')); + Finder back() => find.byWidgetPredicate( + (widget) => + widget is BusyMarkLinuxHeaderIconButton && + widget.tooltip == l10n.back, + ); + Future alt(LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pumpAndSettle(); + } + + await pumpUntil( + tester, + () => home().evaluate().isNotEmpty, + operation: 'open the initial workspace', + ); + expect( + tester.widget(home()).nativeIcon, + BusyMarkLinuxHeaderIcon.home, + ); + expect( + tester.widget(home()).icon, + BusyMarkGlyphs.home, + ); + expect(find.byTooltip('${l10n.home} (Alt+Home)'), findsOneWidget); + final iconButton = tester.widget( + find.descendant(of: home(), matching: find.byType(IconButton)), + ); + final foreground = iconButton.style!.foregroundColor!.resolve({})!; + expect( + iconButton.style!.backgroundColor!.resolve({WidgetState.hovered}), + foreground.withValues( + alpha: foreground.a * BusyMarkLinuxHeaderStyle.hoverBackgroundStrength, + ), + ); + expect( + iconButton.style!.backgroundColor!.resolve({WidgetState.pressed}), + foreground.withValues( + alpha: + foreground.a * BusyMarkLinuxHeaderStyle.pressedBackgroundStrength, + ), + ); + + expect(back(), findsNothing); + _expectHeaderGeometry(tester); + await alt(LogicalKeyboardKey.arrowLeft); + expect(path(), '/workspace'); + + router.go(settingsLocation(SettingsReturnTarget.workspace)); + await tester.pumpAndSettle(); + expect(back(), findsOneWidget); + expect(home(), findsNothing); + await alt(LogicalKeyboardKey.arrowLeft); + expect(path(), '/workspace'); + + controller.updateActiveText('# Dirty'); + await tester.pumpAndSettle(); + await tester.tap(home()); + await tester.pumpAndSettle(); + expect(find.text(l10n.unsavedChanges), findsOneWidget); + await tester.tap(find.text(l10n.cancel)); + await tester.pumpAndSettle(); + expect(path(), '/workspace'); + expect(container.read(workspaceControllerProvider).activeText, '# Dirty'); + + router.go(settingsLocation(SettingsReturnTarget.workspace)); + await tester.pumpAndSettle(); + await alt(LogicalKeyboardKey.home); + expect(find.text(l10n.unsavedChanges), findsOneWidget); + await tester.tap(find.text(l10n.discard)); + await pumpUntil( + tester, + () => path() == '/', + operation: 'finish Home from Settings after Discard', + ); + expect(home(), findsNothing); + expect(back(), findsNothing); + expect(file.readAsStringSync(), '# Original'); + + final changed = await container + .read(keymapControllerProvider.notifier) + .update( + BusyMarkCommandIds.home, + const BusyMarkKeyBinding(LogicalKeyboardKey.f6), + expected: const {}, + ); + expect(changed.status, KeymapUpdateStatus.saved); + router.go('/workspace'); + await tester.pumpAndSettle(); + expect(find.byTooltip('${l10n.home} (F6)'), findsOneWidget); + await alt(LogicalKeyboardKey.home); + expect(path(), '/workspace'); + await tester.sendKeyEvent(LogicalKeyboardKey.f6); + await tester.pumpAndSettle(); + expect(path(), '/'); + }); + testWidgets( - 'restored capture failure stays owned across Back create discard create', + 'restored capture failure stays owned across Home create discard create', (tester) async { final root = (await tester.runAsync( () => Directory.systemTemp.createTemp('busymark-history-navigation-'), @@ -2952,7 +3099,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settings), localHistoryStoreProvider.overrideWithValue(store), localHistoryTimerFactoryProvider.overrideWithValue( @@ -3000,14 +3146,14 @@ void main() { ); await tester.pumpAndSettle(); expect(find.textContaining('could not capture'), findsOneWidget); - Future back() async { + Future goHome() async { await container .read(busyMarkCommandRegistryProvider) - .execute(BusyMarkCommandIds.back); + .execute(BusyMarkCommandIds.home); await tester.pumpAndSettle(); } - await back(); + await goHome(); expect(find.text(l10n.createMarkdownFile), findsOneWidget); await tester.tap(find.text(l10n.createMarkdownFile)); await _pumpUntilCondition( @@ -3028,7 +3174,7 @@ void main() { expect(firstDraft.id, isNot(originalId)); expect(history.warningForBuffer(firstDraft.id), isNull); expect(find.textContaining('could not capture'), findsNothing); - await back(); + await goHome(); expect(find.text(l10n.discard), findsOneWidget); await tester.tap(find.text(l10n.discard)); await tester.pumpAndSettle(); @@ -3093,10 +3239,7 @@ void main() { testWidgets('Escape closes header popup menus', (tester) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -3144,10 +3287,7 @@ void main() { ) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -3184,10 +3324,7 @@ void main() { ) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -3257,7 +3394,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), nativeWindowControllerProvider.overrideWithValue(nativeWindow), ], @@ -3432,11 +3568,13 @@ void main() { expect(settingsStore.value['autoSave'], isTrue); expect(tester.widget(autoSaveRow).value, isTrue); - final header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), + expect(find.text(l10n.editor), findsWidgets); + expect( + tester + .widget(find.byType(LinuxPageFrame)) + .sidebarAvailable, + isFalse, ); - expect(header.configuration.title, l10n.editor); - expect(header.configuration.sidebarVisible, isFalse); expect( find.byKey(const ValueKey('settings-page-selector')), findsOneWidget, @@ -3676,10 +3814,7 @@ void main() { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -3711,12 +3846,15 @@ void main() { expect(appearanceTile.selected, isTrue); expect(editorTile.selected, isFalse); - var header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), + expect( + tester + .widget(find.byType(LinuxPageFrame)) + .sidebarExpanded, + isTrue, ); - expect(header.configuration.sidebarVisible, isTrue); - expect(header.configuration.sidebarToggleVisible, isFalse); - expect(header.configuration.title, l10n.appearance); + expect(find.byTooltip(l10n.showSidebar), findsNothing); + expect(find.byTooltip(l10n.hideSidebar), findsNothing); + expect(find.text(l10n.appearance), findsWidgets); await tester.tap(find.byKey(const ValueKey('settings-navigation-editor'))); await tester.pumpAndSettle(); @@ -3741,11 +3879,13 @@ void main() { ], ); expect(find.text(l10n.autoSave), findsOneWidget); - header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), + expect( + tester + .widget(find.byType(LinuxPageFrame)) + .sidebarExpanded, + isTrue, ); - expect(header.configuration.sidebarVisible, isTrue); - expect(header.configuration.title, l10n.editor); + expect(find.text(l10n.editor), findsWidgets); expect(find.text(l10n.spellingDictionaries), findsOneWidget); expect(find.byType(BusyMarkSidebarSurface), findsOneWidget); @@ -3755,11 +3895,13 @@ void main() { tester.widget(find.byType(BusyMarkClamp)).scrollable, isTrue, ); - header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), + expect( + tester + .widget(find.byType(LinuxPageFrame)) + .sidebarExpanded, + isTrue, ); - expect(header.configuration.sidebarVisible, isTrue); - expect(header.configuration.title, l10n.editor); + expect(find.text(l10n.editor), findsWidgets); expect( tester .widget( @@ -3768,11 +3910,13 @@ void main() { .selected, isTrue, ); - header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), + expect( + tester + .widget(find.byType(LinuxPageFrame)) + .sidebarExpanded, + isTrue, ); - expect(header.configuration.sidebarVisible, isTrue); - expect(header.configuration.title, l10n.editor); + expect(find.text(l10n.editor), findsWidgets); final dictionariesNavigation = find.byKey( const ValueKey('settings-spelling-dictionaries'), @@ -3791,10 +3935,7 @@ void main() { .selected, isTrue, ); - header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), - ); - expect(header.configuration.title, l10n.spellingDictionaries); + expect(find.text(l10n.spellingDictionaries), findsWidgets); expect(find.text(l10n.importSpellingDictionary), findsOneWidget); expect(find.text(l10n.spellingDictionaryProblems), findsNothing); @@ -3802,10 +3943,7 @@ void main() { find.byTooltip('${l10n.back} (${BusyMarkAppShortcuts.back.label})'), ); await tester.pumpAndSettle(); - header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), - ); - expect(header.configuration.title, l10n.editor); + expect(find.text(l10n.editor), findsWidgets); expect(find.text(l10n.autoSave), findsOneWidget); }); @@ -3836,7 +3974,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), spellingSessionControllerProvider.overrideWith((ref) => spelling), ], @@ -4007,7 +4144,6 @@ void main() { var catalogResumed = false; final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: _MemorySettingsStore(), downloadFile: _copySettingsDictionaryDownload, catalogLoader: @@ -4090,7 +4226,6 @@ void main() { (tester) async { final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: _MemorySettingsStore(), downloadFile: _copySettingsDictionaryDownload, ); @@ -4194,7 +4329,6 @@ void main() { ) async { final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: _MemorySettingsStore(), downloadFile: _copySettingsDictionaryDownload, ); @@ -4277,7 +4411,6 @@ void main() { .toJson(); final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: settingsStore, downloadFile: ({ @@ -4349,7 +4482,6 @@ void main() { .toJson(); final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: settingsStore, downloadFile: ({ @@ -4421,7 +4553,6 @@ void main() { .toJson(); final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: settingsStore, downloadFile: ({ @@ -4465,7 +4596,6 @@ void main() { var downloadCount = 0; final harness = await _pumpSettingsSpellingHarness( tester, - headerBarService: headerBarService, settingsStore: _MemorySettingsStore(), projectLanguage: 'en-Test', downloadFile: @@ -4529,13 +4659,11 @@ void main() { ..value = AppSettings.defaults() .copyWith(themeModePreference: preference) .toJson(); - headerBarService = _FallbackHeaderBarService(); await tester.pumpWidget( ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), ], child: const BusyMarkApp(), @@ -4555,9 +4683,6 @@ void main() { final surface = tester.widget(surfaceFinder); final surfaceContext = tester.element(surfaceFinder); final colors = BusyMarkSurfaceColors.of(surfaceContext); - final header = tester.widget( - find.byType(HeaderBarConfigurationPublisher), - ); expect( Theme.of(surfaceContext).brightness, @@ -4566,7 +4691,6 @@ void main() { : Brightness.light, ); expect(surface.color, colors.view); - expect(surface.color, header.configuration.theme.backgroundColor); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); @@ -4582,7 +4706,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), ], child: const BusyMarkApp(), @@ -4641,7 +4764,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), ], child: const BusyMarkApp(), @@ -4666,6 +4788,7 @@ void main() { testWidgets('Writerside project dialog syncs generated fields until edited', ( tester, ) async { + final menus = NativeMenuProbe(tester); final temp = Directory.systemTemp.createTempSync('busymark-create-dialog-'); const fileSelectorChannel = MethodChannel( 'plugins.flutter.io/file_selector', @@ -4689,10 +4812,7 @@ void main() { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -4704,14 +4824,7 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); - final newDialog = find.byType(BusyMarkDialogShell); - expect(newDialog, findsOneWidget); - await tester.tap( - find.descendant( - of: newDialog, - matching: find.text(l10n.createWritersideProject), - ), - ); + menus.select(l10n.createWritersideProject); await tester.pumpAndSettle(); expect(find.text(l10n.createWritersideProject), findsWidgets); @@ -4839,7 +4952,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(store), ], child: const BusyMarkApp(), @@ -4947,10 +5059,7 @@ void main() { final l10n = AppLocalizationsEn(); await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -5252,10 +5361,7 @@ void main() { ) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -5295,7 +5401,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), ], child: const BusyMarkApp(), @@ -5359,7 +5464,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(store), ], child: const BusyMarkApp(), @@ -5435,7 +5539,6 @@ void main() { ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), ], child: const BusyMarkApp(), @@ -5479,10 +5582,7 @@ void main() { testWidgets('about dialog shows the BusyMark logo', (tester) async { await tester.pumpWidget( ProviderScope( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - ], + overrides: [..._smokeAccentOverrides], child: const BusyMarkApp(), ), ); @@ -5539,20 +5639,117 @@ void main() { expect(logoSize.height, lessThanOrEqualTo(BusyMarkSizes.aboutLogoViewport)); }); - testWidgets('Ctrl+N chooses between Markdown and Writerside creation', ( + testWidgets( + 'New and Open pointer and held shortcuts share the header anchor', + (tester) async { + final menus = NativeMenuProbe(tester); + final service = _StartupWorkspaceService(); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), + workspaceServiceProvider.overrideWithValue(service), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), + ), + ); + await tester.pumpAndSettle(); + + final search = find.byTooltip(l10n.search); + final open = find.byTooltip('Open (Ctrl+O)'); + final create = find.byTooltip('New (Ctrl+N)'); + final main = find.byTooltip(l10n.mainMenu); + expect(tester.getCenter(search).dx, lessThan(tester.getCenter(open).dx)); + expect(tester.getCenter(open).dx, lessThan(tester.getCenter(create).dx)); + expect(tester.getCenter(create).dx, lessThan(tester.getCenter(main).dx)); + + for (final (button, key, entries) in [ + ( + create, + LogicalKeyboardKey.keyN, + { + 'M': l10n.createMarkdownFile, + 'N': l10n.newNextcloudNote, + 'W': l10n.createWritersideProject, + }, + ), + ( + open, + LogicalKeyboardKey.keyO, + { + 'M': l10n.openMarkdownFile, + 'F': l10n.openFolderOrWritersideProject, + 'N': l10n.browseNotes, + }, + ), + ]) { + await tester.tap(button); + await tester.pumpAndSettle(); + final pointer = menus.packets.last; + expect(pointer['focusFirst'], isFalse); + expect({ + for (final row in menus.entries) row['mnemonic']: row['label'], + }, entries); + menus.close(); + await tester.pumpAndSettle(); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(key); + await tester.pumpAndSettle(); + final shortcut = menus.packets.last; + expect(shortcut['focusFirst'], isTrue); + expect(shortcut['anchor'], pointer['anchor']); + expect(shortcut['entries'], pointer['entries']); + final count = menus.packets.length; + await tester.sendKeyRepeatEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyRepeatEvent(key); + await tester.sendKeyUpEvent(key); + await tester.pumpAndSettle(); + expect(menus.packets, hasLength(count)); + expect(menus.isOpen, isTrue); + menus.close(); + await tester.pumpAndSettle(); + } + expect(service.untitledCount, 0); + expect(find.byType(BusyMarkDialogShell), findsNothing); + + await container + .read(appSettingsControllerProvider.notifier) + .saveShortcutOverrides({ + BusyMarkCommandIds.newDocument: const BusyMarkKeyBinding( + LogicalKeyboardKey.f6, + alt: true, + ), + }); + await tester.pumpAndSettle(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.f6); + await tester.pumpAndSettle(); + expect(menus.isOpen, isTrue); + expect(menus.contains(l10n.newNextcloudNote), isTrue); + expect(find.byTooltip('New (Alt+F6)'), findsOneWidget); + await tester.sendKeyUpEvent(LogicalKeyboardKey.f6); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + menus.close(); + await tester.pumpAndSettle(); + }, + ); + + testWidgets('Welcome Markdown creation focuses the visual editor', ( tester, ) async { final service = _StartupWorkspaceService(); - final settingsStore = _MemorySettingsStore() - ..value = AppSettings.defaults() - .copyWith(defaultSpellingLanguage: null) - .toJson(); await tester.pumpWidget( ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - localSettingsStoreProvider.overrideWithValue(settingsStore), + localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), ], child: const BusyMarkApp(), @@ -5560,70 +5757,40 @@ void main() { ); await tester.pumpAndSettle(); - await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); - await tester.sendKeyDownEvent(LogicalKeyboardKey.keyN); - await tester.sendKeyUpEvent(LogicalKeyboardKey.keyN); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.tap(find.text(l10n.createMarkdownFile)); await tester.pumpAndSettle(); - - final newDialog = find.byType(BusyMarkDialogShell); - final createMarkdown = find.descendant( - of: newDialog, - matching: find.text(l10n.createMarkdownFile), - ); - final createWriterside = find.descendant( - of: newDialog, - matching: find.text(l10n.createWritersideProject), - ); - expect(service.untitledCount, 0); - expect(newDialog, findsOneWidget); - expect(createMarkdown, findsOneWidget); - expect(createWriterside, findsOneWidget); - expect( - find.descendant( - of: newDialog, - matching: find.byIcon(BusyMarkGlyphs.newDocument), - ), - findsOneWidget, + final fields = find.descendant( + of: find.byType(BusyMarkWysiwygEditor), + matching: find.byType(EditableText), ); expect( - find.descendant( - of: newDialog, - matching: find.byIcon(BusyMarkGlyphs.writersideProject), - ), - findsOneWidget, + tester + .widgetList(fields) + .where((field) => field.focusNode.hasPrimaryFocus), + hasLength(1), ); - - await tester.tap(createMarkdown); - await tester.pumpAndSettle(); - + tester.testTextInput.enterText('Typed in Editor'); + await tester.pump(); expect(service.untitledCount, 1); - expect(find.text(l10n.createMarkdownFile), findsNothing); - expect(find.text(l10n.untitledMarkdownFileName), findsWidgets); - expect(find.byKey(const ValueKey('editor-tab-strip')), findsNothing); - expect(find.byKey(const ValueKey('document-status-bar')), findsOneWidget); - expect(find.text('LF'), findsOneWidget); - expect( - find.byKey(const ValueKey('document-spelling-language-status')), - findsOneWidget, - ); - expect(find.text(l10n.spellingLanguageUnsetStatus), findsOneWidget); - final spellingBanner = find.byKey(const ValueKey('spelling-banner')); - expect(spellingBanner, findsOneWidget); - expect(tester.widget(spellingBanner).revealed, isFalse); + expect(find.text('Typed in Editor'), findsWidgets); }); testWidgets('Ctrl+N keeps unsaved documents in independent tabs', ( tester, ) async { final service = _StartupWorkspaceService(); + final menus = NativeMenuProbe(tester); final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() - ..value = AppSettings.defaults().copyWith(autoSave: false).toJson(), + ..value = AppSettings.defaults() + .copyWith( + autoSave: false, + documentViewMode: DocumentViewModePreference.source, + ) + .toJson(), ), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue( @@ -5655,33 +5822,32 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); - final firstNewDialog = find.byType(BusyMarkDialogShell); - expect( - find.descendant( - of: firstNewDialog, - matching: find.text(l10n.createMarkdownFile), - ), - findsOneWidget, - ); - expect( - find.descendant( - of: firstNewDialog, - matching: find.text(l10n.createWritersideProject), - ), - findsOneWidget, - ); + expect(menus.contains(l10n.createMarkdownFile), isTrue); + expect(menus.contains(l10n.createWritersideProject), isTrue); expect(find.text(l10n.unsavedChanges), findsNothing); + menus.select(l10n.createMarkdownFile); + await tester.pumpAndSettle(); - await tester.tap( - find.descendant( - of: firstNewDialog, - matching: find.text(l10n.createMarkdownFile), - ), + final source = find.descendant( + of: find.byType(BusyMarkSourceEditor), + matching: find.byType(EditableText), ); - await tester.pumpAndSettle(); + final field = tester.widget(source); + expect(field.focusNode.hasPrimaryFocus, isTrue); + expect( + field.controller.selection, + const TextSelection.collapsed(offset: 0), + ); + expect(tester.testTextInput.hasAnyClients, isTrue); + tester.testTextInput.enterText('Typed into new tab'); + await tester.pump(); expect(find.text(l10n.unsavedChanges), findsNothing); expect(service.untitledCount, 1); + expect( + container.read(workspaceControllerProvider).activeText, + 'Typed into new tab', + ); expect( container.read(workspaceControllerProvider).documentBuffers, hasLength(2), @@ -5700,16 +5866,32 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); - await tester.tap( - find.descendant( - of: find.byType(BusyMarkDialogShell), - matching: find.text(l10n.createMarkdownFile), - ), - ); + menus.select(l10n.createMarkdownFile); await tester.pumpAndSettle(); expect(find.text(l10n.unsavedChanges), findsNothing); expect(service.untitledCount, 2); + final nextField = tester.widget(source); + expect(nextField.focusNode, isNot(same(field.focusNode))); + expect(nextField.focusNode.hasPrimaryFocus, isTrue); + expect( + nextField.controller.selection, + const TextSelection.collapsed(offset: 0), + ); + expect(tester.testTextInput.hasAnyClients, isTrue); + tester.testTextInput.enterText('Second created tab'); + await tester.pump(); + expect( + container.read(workspaceControllerProvider).activeText, + 'Second created tab', + ); + expect( + container + .read(workspaceControllerProvider) + .documentBuffers + .map((b) => b.text), + containsAll(['# Dirty\n', 'Typed into new tab']), + ); expect( container.read(workspaceControllerProvider).documentBuffers, hasLength(3), @@ -5717,9 +5899,113 @@ void main() { await tester.pump(const Duration(milliseconds: 800)); }); + testWidgets('Files New File opens the Dual Source field ready to type', ( + tester, + ) async { + final folder = Directory.systemTemp.createTempSync('busymark-files-new-'); + addTearDown(() => folder.deleteSync(recursive: true)); + final existing = File(p.join(folder.path, 'existing.md')) + ..writeAsStringSync('# Existing\n'); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + localSettingsStoreProvider.overrideWithValue( + _MemorySettingsStore() + ..value = AppSettings.defaults() + .copyWith( + autoSave: false, + documentViewMode: DocumentViewModePreference.split, + ) + .toJson(), + ), + startupPathProvider.overrideWithValue(folder.path), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), + ), + ); + await pumpUntil( + tester, + () => find.byType(BusyMarkSourceEditor).evaluate().isNotEmpty, + operation: 'Open a real Markdown folder', + ); + final menus = NativeMenuProbe(tester); + final viewSelector = find.byTooltip( + '${l10n.sidebarViewMenu} (Ctrl+Shift+F9)', + ); + await tester.tap(viewSelector); + await tester.pumpAndSettle(); + await menus.activate(l10n.files); + await tester.pumpAndSettle(); + Future openNewFile() async { + await tester.tap( + find.widgetWithText(BusyMarkSidebarTreeRow, 'existing.md'), + buttons: kSecondaryButton, + kind: PointerDeviceKind.mouse, + ); + await tester.pumpAndSettle(); + expect( + menus.matching(l10n.newFile), + hasLength(1), + reason: + 'Native menu entries: ${menus.entries.map((entry) => entry['label'])}', + ); + await menus.activate(l10n.newFile); + await tester.pumpAndSettle(); + expect(find.text(l10n.newFile), findsOneWidget); + } + + await openNewFile(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(File(p.join(folder.path, 'untitled.md')).existsSync(), isFalse); + + await openNewFile(); + final dialog = find.byType(BusyMarkModalEditorScaffold); + await tester.tap( + find.descendant(of: dialog, matching: find.text(l10n.create)), + ); + await pumpUntil( + tester, + () => + container.read(workspaceControllerProvider).activeBuffer?.filePath == + p.join(folder.path, 'untitled.md'), + operation: 'New File opens its new buffer', + ); + await tester.pumpAndSettle(); + final source = tester.widget( + find.descendant( + of: find.byType(BusyMarkSourceEditor), + matching: find.byType(EditableText), + ), + ); + expect(source.focusNode.hasPrimaryFocus, isTrue); + expect( + source.controller.selection, + const TextSelection.collapsed(offset: 0), + ); + expect(tester.testTextInput.hasAnyClients, isTrue); + tester.testTextInput.enterText('Typed into Files-created Source'); + await tester.pump(); + final state = container.read(workspaceControllerProvider); + expect(state.activeText, 'Typed into Files-created Source'); + expect( + state.activeBuffer!.editorState.mode, + DocumentViewModePreference.split, + ); + expect(existing.readAsStringSync(), '# Existing\n'); + await tester.pumpWidget(const SizedBox()); + container.dispose(); + }); + testWidgets('Ctrl+N creates real CommonMark inside a Writerside workspace', ( tester, ) async { + final menus = NativeMenuProbe(tester); const yaruWindowChannel = MethodChannel('yaru_window'); const yaruWindowEventsChannel = MethodChannel('yaru_window/events'); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger @@ -5743,7 +6029,6 @@ void main() { final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults().copyWith(autoSave: false).toJson(), @@ -5781,14 +6066,7 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pump(); await tester.pump(const Duration(seconds: 1)); - await tester.runAsync( - () => tester.tap( - find.descendant( - of: find.byType(BusyMarkDialogShell), - matching: find.text(l10n.createMarkdownFile), - ), - ), - ); + menus.select(l10n.createMarkdownFile); await tester.pump(); await tester.pump(const Duration(seconds: 1)); @@ -6007,7 +6285,16 @@ code ))!; final workspaceState = WorkspaceState( workspace: workspace, - activeText: '# Nested\n', + documentBuffers: [ + DocumentBuffer( + id: 'fixture', + filePath: workspace.activeFilePath, + text: '# Nested\n', + lastSavedText: '# Nested\n', + dirty: false, + ), + ], + activeBufferId: 'fixture', ); final controller = _MutableWorkspaceController(workspaceState); final nativeCalls = []; @@ -6039,7 +6326,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -7123,14 +7409,28 @@ code ))!; final controller = _MutableWorkspaceController( - WorkspaceState(workspace: workspace, activeText: topicSource), + WorkspaceState( + workspace: workspace, + documentBuffers: [ + DocumentBuffer( + id: 'fixture', + editorState: const DocumentEditorState( + mode: DocumentViewModePreference.source, + ), + filePath: workspace.activeFilePath, + text: topicSource, + lastSavedText: topicSource, + dirty: false, + ), + ], + activeBufferId: 'fixture', + ), ) ..topicRenamePlans['setup.topic'] = setupPlan ..simulateTopicRename = true; final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -7277,7 +7577,7 @@ code expect(File(topicPath).readAsStringSync(), topicSource); expect(File(p.join(topics.path, 'setup.topic')).existsSync(), isFalse); - controller.clearDocumentBuffersForTest(); + controller.removeProjectDirtyBufferForTest(); await openPopup(firstRow); await nativeMenus.activate(l10n.renameTopicFile); await tester.pumpAndSettle(); @@ -7547,7 +7847,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceControllerProvider.overrideWith(() => controller), ], @@ -7711,7 +8010,6 @@ code sharedGitClientFactoryProvider.overrideWithValue( ({required authorize, prompts}) => sharedClient, ), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -7760,7 +8058,6 @@ code }); await tester.pumpAndSettle(); if (git && openGitComparisons) { - container.read(gitControllerProvider.notifier).clearSelection(); final workspace = container.read(workspaceControllerProvider).workspace!; final comparisons = [ for (final path in ['README.md', 'guide.md']) @@ -8333,7 +8630,6 @@ code ({required authorize, prompts}) => client, ), ..._smokeAccentOverrides.skip(2), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -8451,10 +8747,7 @@ code same(staged), ); await _chooseNativeSidebar(tester, l10n.gitHostGitLog); - await _chooseInspectorCommit( - tester, - gitState.projectHistory.commits.first.subject, - ); + await _chooseInspectorCommit(tester, _sidebarCommit.subject); await pumpUntil( tester, () => find @@ -8576,7 +8869,6 @@ code ({required authorize, prompts}) => client, ), ..._smokeAccentOverrides.skip(2), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -8754,7 +9046,6 @@ code git: true, openGitComparisons: false, ); - h.container.read(gitControllerProvider.notifier).clearSelection(); final editor = find.byWidgetPredicate( (widget) => widget is TextField && @@ -9235,14 +9526,6 @@ code ); final after = h.container.read(workspaceControllerProvider); expect(_comparisonTabs(h.container).entries, isEmpty); - expect( - h.container.read(gitControllerProvider).openDiffFilePaths, - isEmpty, - ); - expect( - h.container.read(gitControllerProvider).selectedDiffForDisplay, - isNull, - ); expect( h.container.read(localHistoryControllerProvider).selectedRevisionId, isNull, @@ -9733,7 +10016,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -9878,6 +10160,40 @@ code await tester.pump(const Duration(milliseconds: 800)); }); + testWidgets('Recent reveals the existing document behind a Git comparison', ( + tester, + ) async { + final h = await tabWorkspace(tester, count: 1, git: true); + final before = h.container.read(workspaceControllerProvider); + final review = _comparisonTabs(h.container).active!; + final document = before.activeBuffer!; + final resource = RecentResource( + path: document.filePath!, + kind: 'markdown', + document: true, + lastOpenedAt: DateTime.now(), + ); + await h.controller.recordRecentResource(resource); + await _chooseNativeSidebar(tester, l10n.recent); + await tester.pumpAndSettle(); + expect(_comparisonTabs(h.container).active, same(review)); + + await tester.tap( + find.byKey(ValueKey(RecentSearchResult(resource).identity)), + ); + await pumpUntil( + tester, + () => _comparisonTabs(h.container).active == null, + operation: 'reveal the existing authoring document from Recent', + ); + final after = h.container.read(workspaceControllerProvider); + expect(after.documentBuffers.single.id, document.id); + expect(after.activeText, document.text); + expect(after.workspace!.id, before.workspace!.id); + expect(_comparisonTabs(h.container).entries, contains(review)); + expect(find.byKey(const ValueKey('document-status-bar')), findsOneWidget); + }); + testWidgets('Git diff files are shown as separate editor tabs', ( tester, ) async { @@ -10009,7 +10325,6 @@ code ({required authorize, prompts}) => client, ), ..._smokeAccentOverrides.skip(2), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -10070,13 +10385,10 @@ code final parentReview = _comparisonTabs(container).active!; final parentComparison = parentReview.comparison; expect(find.byType(shared.GitFileHistoryView), findsNothing); - final entry = historyState.fileHistory.entries.single; - expect( - parentComparison.left.revision!.value, - entry.commit.parentHashes.single, - ); - expect(parentComparison.right.revision!.value, entry.commit.fullHash); - expect(parentComparison.leftPath!.utf8Path, entry.pathInParent); + final entry = _historyCommit; + expect(parentComparison.left.revision!.value, entry.parents.single.value); + expect(parentComparison.right.revision!.value, entry.oid.value); + expect(parentComparison.leftPath!.utf8Path, 'README.md'); await tester.pump(); await pumpUntil( tester, @@ -10118,7 +10430,7 @@ code 'reopen historical selection without retargeting the first tab', ); final row = find.ancestor( - of: find.text(entry.commit.subject), + of: find.text(entry.subject), matching: find.byType(shared.GitActionRow), ); await _chooseNativeGitMenu( @@ -10138,8 +10450,8 @@ code expect(currentReview.id, isNot(parentReview.id)); expect(_comparisonTabs(container).entries.first, same(parentReview)); expect(find.byType(shared.GitFileHistoryView), findsNothing); - expect(currentComparison.left.revision!.value, entry.commit.fullHash); - expect(currentComparison.leftPath!.utf8Path, entry.pathAtCommit); + expect(currentComparison.left.revision!.value, entry.oid.value); + expect(currentComparison.leftPath!.utf8Path, 'README.md'); expect(currentComparison.right.kind, shared.ContentKind.workingTree); await tester.pump(); await pumpUntil( @@ -10226,7 +10538,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -10298,7 +10609,6 @@ code overrides: [ ..._smokeAccentOverrides.skip(1), sharedGitDraftStoreProvider.overrideWithValue(store), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -10539,7 +10849,6 @@ code _SwitchingSharedGitReadFixture(first.path), ), sharedGitDraftStoreProvider.overrideWithValue(store), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore(), ), @@ -10784,7 +11093,6 @@ code overrides: [ ..._smokeAccentOverrides.skip(1), sharedGitDraftStoreProvider.overrideWithValue(store), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue( _MemorySettingsStore() ..value = AppSettings.defaults() @@ -10930,6 +11238,104 @@ code ); } + testWidgets('remounted sidebar allocates the displayed view at scaled text', ( + tester, + ) async { + tester.view.physicalSize = const Size(1500, 1100); + tester.view.devicePixelRatio = 1; + tester.platformDispatcher.textScaleFactorTestValue = 1.5; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + final temp = Directory.systemTemp.createTempSync('busymark_sidebar_mount_'); + addTearDown(() => temp.deleteSync(recursive: true)); + final file = File('${temp.path}/Intro.md')..writeAsStringSync('# Intro\n'); + final service = _TabbedWorkspaceService( + rootPath: temp.path, + paths: [file.path], + ); + final settings = _MemorySettingsStore() + ..value = AppSettings.defaults() + .copyWith( + localeTag: 'ja', + autoSave: false, + validateOnEdit: false, + trustedGitWorkspacePaths: [temp.path], + ) + .toJson(); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + localSettingsStoreProvider.overrideWithValue(settings), + workspaceServiceProvider.overrideWithValue(service), + startupPathProvider.overrideWithValue(temp.path), + gitControllerProvider.overrideWith( + () => _PresetGitController(_gitSidebarShortcutState(temp.path)), + ), + ], + ); + addTearDown(container.dispose); + Future mount(String key) => tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: BusyMarkApp(key: ValueKey(key)), + ), + ); + await mount('initial'); + await pumpUntil( + tester, + () => + !container.read(workspaceControllerProvider).isLoading && + container.read(workspaceControllerProvider).activeBuffer != null, + operation: 'open sidebar allocation fixture', + ); + await tester.pumpAndSettle(); + await _executeViewCommand(tester, BusyMarkCommandIds.sidebarGit); + await pumpUntil( + tester, + () => find.byType(shared.GitCommitView).evaluate().isNotEmpty, + operation: 'open shared Commit', + ); + await tester.pumpAndSettle(); + final frame = find.byKey(const ValueKey('workspace-page-frame')); + expect( + tester.widget(frame).sidebarWidth, + greaterThan(BusyMarkSizes.sidebarWidth), + ); + final buffer = container.read(workspaceControllerProvider).activeBuffer!; + service.openedAt = DateTime(2026, 2); + expect( + await tester.runAsync( + container + .read(workspaceControllerProvider.notifier) + .refreshWorkspaceFromDiskPreservingOpenTabs, + ), + isTrue, + ); + await tester.pumpAndSettle(); + expect( + container.read(workspaceControllerProvider).workspace!.openedAt, + service.openedAt, + ); + expect(find.byType(shared.GitCommitView), findsOneWidget); + expect( + tester.widget(frame).sidebarWidth, + busyMarkGitSidebarMinimumWidth(tester.element(frame)), + ); + await tester.pumpWidget(const SizedBox.shrink()); + await mount('remounted'); + await tester.pumpAndSettle(); + expect(find.text('Intro.md'), findsWidgets); + expect(find.byType(shared.GitCommitView), findsNothing); + expect( + tester.widget(frame).sidebarWidth, + BusyMarkSizes.sidebarWidth, + ); + final current = container.read(workspaceControllerProvider).activeBuffer!; + expect(current.id, buffer.id); + expect(current.text, buffer.text); + }); + testWidgets('sidebar view commands select workspace sidebar tabs', ( tester, ) async { @@ -10970,7 +11376,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -11046,7 +11451,7 @@ code _expectHeaderControlGap( tester, leftTooltip: l10n.hideSidebar, - rightTooltip: l10n.back, + rightTooltip: l10n.home, ); _expectHeaderControlGap( tester, @@ -11058,17 +11463,23 @@ code leftTooltip: l10n.validate, rightTooltip: l10n.search, ); - _expectHeaderControlGap( - tester, - leftTooltip: l10n.search, - rightTooltip: l10n.mainMenu, - ); + final openMenu = '${l10n.open} (Ctrl+O)'; + final newMenu = '${l10n.newResource} (Ctrl+N)'; + for (final (left, right) in [ + (l10n.search, openMenu), + (openMenu, newMenu), + (newMenu, l10n.mainMenu), + ]) { + _expectHeaderControlGap(tester, leftTooltip: left, rightTooltip: right); + } _expectHeaderGeometry(tester); for (final tooltip in [ - l10n.back, + l10n.home, '${l10n.contentViewMenu} (Ctrl+Shift+F10)', l10n.validate, l10n.search, + openMenu, + newMenu, l10n.mainMenu, ]) { await _expectNeutralHeaderControl(tester, tooltip, selected: false); @@ -11404,7 +11815,7 @@ code ); expect(find.text(l10n.gitReturnToDocument), findsNothing); expect(find.byType(shared.GitLogView), findsNothing); - expect(container.read(gitControllerProvider).selectedView, GitView.changes); + expect(find.byType(shared.GitCommitView), findsOneWidget); await setDocumentViewMode(DocumentViewModePreference.editor); await selectSidebarCommand(LogicalKeyboardKey.digit3); @@ -11546,7 +11957,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue( const _SearchWorkspaceService('alpha beta\n'), @@ -11819,7 +12229,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue( const _SearchWorkspaceService('First\n\nSecond\n\nThird\n'), @@ -11979,7 +12388,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceControllerProvider.overrideWith(() => controller), gitControllerProvider.overrideWith( @@ -12374,7 +12782,6 @@ code final repository = GitRepositoryInfo( rootPath: temp.path, gitDirPath: '${temp.path}/.git', - currentBranch: 'main', ); final service = _TabbedWorkspaceService( rootPath: temp.path, @@ -12383,7 +12790,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -12476,7 +12882,6 @@ code final repository = GitRepositoryInfo( rootPath: temp.path, gitDirPath: '${temp.path}/.git', - currentBranch: 'main', ); final service = _TabbedWorkspaceService( rootPath: temp.path, @@ -12485,7 +12890,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -12605,12 +13009,23 @@ code () => const WorkspaceService().openPath(temp.path), ))!; final controller = _MutableWorkspaceController( - WorkspaceState(workspace: openedWorkspace, activeText: '# Readme\n'), + WorkspaceState( + workspace: openedWorkspace, + documentBuffers: [ + DocumentBuffer( + id: 'fixture', + filePath: openedWorkspace.activeFilePath, + text: '# Readme\n', + lastSavedText: '# Readme\n', + dirty: false, + ), + ], + activeBufferId: 'fixture', + ), ); final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceControllerProvider.overrideWith(() => controller), ], @@ -12691,7 +13106,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -12757,7 +13171,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -12842,7 +13255,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceControllerProvider.overrideWith(() => controller), ], @@ -12939,14 +13351,25 @@ code () => const WorkspaceService().openPath(root.path), ))!; final controller = _MutableWorkspaceController( - WorkspaceState(workspace: workspace, activeText: '# Start\n'), + WorkspaceState( + workspace: workspace, + documentBuffers: [ + DocumentBuffer( + id: 'fixture', + filePath: workspace.activeFilePath, + text: '# Start\n', + lastSavedText: '# Start\n', + dirty: false, + ), + ], + activeBufferId: 'fixture', + ), ); final settingsStore = _MemorySettingsStore() ..value = AppSettings.defaults().copyWith(localeTag: 'ar').toJson(); final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceControllerProvider.overrideWith(() => controller), ], @@ -13082,7 +13505,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), workspaceControllerProvider.overrideWith(() => controller), ], ); @@ -13162,7 +13584,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), workspaceControllerProvider.overrideWith(() => controller), ], ); @@ -13215,7 +13636,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -13318,7 +13738,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settings), workspaceServiceProvider.overrideWithValue( service ?? _SearchWorkspaceService(initialSource), @@ -13362,25 +13781,172 @@ code ) .first; - Future historyKey(WidgetTester tester, {bool redo = false}) async { - await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); - if (redo) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyEvent(LogicalKeyboardKey.keyZ); - if (redo) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); - } - - for (final mode in [ - DocumentViewModePreference.source, - DocumentViewModePreference.editor, - ]) { - testWidgets('${mode.name} exhausted keyboard history is a consumed no-op', ( - tester, - ) async { - final container = await historyApp(tester, mode); - final workspace = container.read(workspaceControllerProvider.notifier); - final field = historyField(mode); - await tester.tap(field); + testWidgets( + 'Writerside creation keeps the dirty editor on failure and focuses the new topic on success', + (tester) async { + final menus = NativeMenuProbe(tester); + final root = Directory.systemTemp.createTempSync( + 'busymark-create-from-editor-', + ); + addTearDown(() => root.deleteSync(recursive: true)); + final original = File(p.join(root.path, 'original.md')) + ..writeAsStringSync('# Original'); + final occupied = Directory(p.join(root.path, 'occupied'))..createSync(); + final existing = File(p.join(occupied.path, 'keep.txt')) + ..writeAsStringSync('Keep'); + const channel = MethodChannel('plugins.flutter.io/file_selector'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (_) async => root.path, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ), + ); + + final container = await historyApp( + tester, + DocumentViewModePreference.source, + service: const WorkspaceService(), + startupPath: original.path, + ); + final editorFields = find.descendant( + of: find.byType(BusyMarkSourceEditor), + matching: find.byType(TextField), + ); + await pumpUntil( + tester, + () => + !container.read(workspaceControllerProvider).isLoading && + editorFields.evaluate().isNotEmpty, + operation: 'finish opening the original editor', + frameStep: const Duration(milliseconds: 20), + ); + final editor = editorFields.first; + await tester.enterText(editor, '# Dirty original'); + await tester.pumpAndSettle(); + final oldFocus = tester.widget(editor).focusNode!; + final originalOpening = container + .read(workspaceControllerProvider) + .activeBuffer! + .opening; + + Future submit(String projectName) async { + await tester.tap(find.byKey(const ValueKey('header-new-menu'))); + await tester.pump(); + await menus.choose(l10n.createWritersideProject); + final dialog = find.byType(BusyMarkModalEditorScaffold); + await tester.enterText( + find + .descendant(of: dialog, matching: find.byType(EditableText)) + .first, + projectName, + ); + await tester.pump(); + await tester.tap( + find.descendant(of: dialog, matching: find.text(l10n.create)), + ); + } + + await submit('Occupied'); + final error = find.descendant( + of: find.byType(BusyMarkModalEditorScaffold), + matching: find.textContaining( + l10n.errorTargetDirectoryNotEmpty(occupied.path), + ), + ); + await pumpUntil( + tester, + () => error.evaluate().isNotEmpty, + operation: 'show the creation failure in the live dialog', + frameStep: const Duration(milliseconds: 20), + ); + expect( + find.textContaining(l10n.errorTargetDirectoryNotEmpty(occupied.path)), + findsOneWidget, + ); + expect( + container.read(workspaceControllerProvider).activeText, + '# Dirty original', + ); + expect(existing.readAsStringSync(), 'Keep'); + await tester.tap(find.text(l10n.cancel)); + await tester.pumpAndSettle(); + expect(FocusManager.instance.primaryFocus, same(oldFocus)); + expect( + container.read(workspaceControllerProvider).activeBuffer!.opening, + same(originalOpening), + ); + + await submit('New project'); + await pumpUntil( + tester, + () => find.text(l10n.discard).evaluate().isNotEmpty, + operation: 'authorize replacing the dirty workspace', + frameStep: const Duration(milliseconds: 20), + diagnostics: () { + final state = container.read(workspaceControllerProvider); + return 'dirty=${state.hasUnsavedChanges}; ' + 'loading=${state.isLoading}; message=${state.message?.error}'; + }, + ); + await tester.tap(find.text(l10n.discard)); + await pumpUntil( + tester, + () { + final state = container.read(workspaceControllerProvider); + return state.workspace?.kind == WorkspaceKind.writersideModule && + find.byType(BusyMarkModalEditorScaffold).evaluate().isEmpty; + }, + operation: 'activate the generated topic', + frameStep: const Duration(milliseconds: 20), + diagnostics: () { + final state = container.read(workspaceControllerProvider); + return 'kind=${state.workspace?.kind}; message=${state.message?.error}; ' + 'focus=${FocusManager.instance.primaryFocus?.debugLabel}'; + }, + ); + await pumpUntil( + tester, + () => + editorFields.evaluate().isNotEmpty && + tester.widget(editor).focusNode?.hasFocus == true, + operation: 'focus the generated topic', + frameStep: const Duration(milliseconds: 20), + diagnostics: () => + 'focus=${FocusManager.instance.primaryFocus?.debugLabel}; ' + 'view=${container.read(workspaceControllerProvider).activeBuffer?.editorState.mode}', + ); + expect( + container.read(workspaceControllerProvider).activeText, + contains(l10n.defaultStartTopicTitle), + ); + expect(original.readAsStringSync(), '# Original'); + expect(tester.takeException(), isNull); + }, + ); + + Future historyKey(WidgetTester tester, {bool redo = false}) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + if (redo) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyZ); + if (redo) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + } + + for (final mode in [ + DocumentViewModePreference.source, + DocumentViewModePreference.editor, + ]) { + testWidgets('${mode.name} exhausted keyboard history is a consumed no-op', ( + tester, + ) async { + final container = await historyApp(tester, mode); + final workspace = container.read(workspaceControllerProvider.notifier); + final field = historyField(mode); + await tester.tap(field); await tester.showKeyboard(field); for (final text in ['abcd', 'abcde', 'abcdef']) { tester.testTextInput.updateEditingValue( @@ -14432,7 +14998,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -14584,7 +15149,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -14707,7 +15271,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -14823,7 +15386,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -14899,7 +15461,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/editing-toolbar-menu.md'), @@ -15093,7 +15654,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/shared-frame.md'), @@ -15294,7 +15854,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/empty-paragraphs.md'), @@ -15420,7 +15979,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/explicit-blank-line.md'), @@ -15517,7 +16075,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/wrap-parity.md'), @@ -15632,7 +16189,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/shared-quote.md'), @@ -15738,7 +16294,6 @@ code final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/shared-code-block.md'), @@ -15880,7 +16435,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/shared-block-geometry.md'), @@ -16100,7 +16654,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceControllerProvider.overrideWith(() => controller), ], @@ -16194,7 +16747,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/structured-quote.md'), @@ -16300,7 +16852,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(temp.path), @@ -16395,7 +16946,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/editor-tab.md'), @@ -16483,7 +17033,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settings), nativeWindowControllerProvider.overrideWithValue(nativeWindow), localHistoryStoreProvider.overrideWithValue( @@ -16565,12 +17114,12 @@ After break. testWidgets('window close still warns when active changes are unsaved', ( tester, ) async { + final menus = NativeMenuProbe(tester); final nativeWindow = _FakeNativeWindowController(); await tester.pumpWidget( ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), nativeWindowControllerProvider.overrideWithValue(nativeWindow), ], @@ -16588,12 +17137,7 @@ After break. await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); - await tester.tap( - find.descendant( - of: find.byType(BusyMarkDialogShell), - matching: find.text(l10n.createMarkdownFile), - ), - ); + menus.select(l10n.createMarkdownFile); await tester.pumpAndSettle(); nativeWindow.listeners.single.onWindowClose(); @@ -16610,7 +17154,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), nativeWindowControllerProvider.overrideWithValue(nativeWindow), workspaceServiceProvider.overrideWithValue(service), @@ -16656,7 +17199,6 @@ After break. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -16755,7 +17297,6 @@ Body. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -16897,7 +17438,6 @@ Gamma body. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -17200,7 +17740,6 @@ Gamma body. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue( _SearchWorkspaceService(source), @@ -17428,7 +17967,6 @@ Gamma body. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -17577,7 +18115,6 @@ Draft paragraph. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), ], @@ -17645,7 +18182,6 @@ Draft paragraph. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -17721,7 +18257,6 @@ Draft paragraph. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), ], ); @@ -17791,107 +18326,221 @@ Draft paragraph. ); }); - testWidgets('Reading linked block and inline images open their targets', ( - tester, - ) async { - final binding = TestWidgetsFlutterBinding.ensureInitialized(); - binding.platformDispatcher.defaultRouteNameTestValue = '/workspace'; - addTearDown(() { - binding.platformDispatcher.defaultRouteNameTestValue = '/'; - }); - const rootPath = '/tmp/busymark-linked-images'; - const readmePath = '$rootPath/README.md'; - const blockTargetPath = '$rootPath/block-guide.md'; - const inlineTargetPath = '$rootPath/inline-guide.md'; - const source = ''' -[![Block logo](block-logo.png)](block-guide.md) - -Before [![Inline logo](inline-logo.png)](inline-guide.md) after. + for (final remote in [false, true]) { + testWidgets('Reading linked block and inline images (remote: $remote)', ( + tester, + ) async { + final menus = NativeMenuProbe(tester); + await _withControlledImageClient((http) async { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + binding.platformDispatcher.defaultRouteNameTestValue = '/workspace'; + addTearDown(() { + binding.platformDispatcher.defaultRouteNameTestValue = '/'; + }); + const rootPath = '/tmp/busymark-linked-images'; + const readmePath = '$rootPath/README.md'; + const blockTargetPath = '$rootPath/block-guide.md'; + const inlineTargetPath = '$rootPath/inline-guide.md'; + final imageOrigin = remote ? 'https://example.com/' : ''; + final source = + ''' +[![Block logo](${imageOrigin}block-logo.png)](block-guide.md) + +Before [![Inline logo](${imageOrigin}inline-logo.png)](inline-guide.md) after. '''; - final parsed = const MarkdownParser().parse( - filePath: readmePath, - source: source, - ); - final workspace = Workspace( - id: readmePath, - rootPath: rootPath, - kind: WorkspaceKind.singleMarkdown, - openedAt: DateTime(2026), - activeFilePath: readmePath, - openFilePaths: const [readmePath], - files: [ - for (final path in const [ - readmePath, - blockTargetPath, - inlineTargetPath, - ]) - DocumentFile( - absolutePath: path, - relativePath: p.basename(path), - kind: DocumentKind.markdown, - size: 1, - lastModified: DateTime(2026), + final parsed = const MarkdownParser().parse( + filePath: readmePath, + source: source, + ); + final workspace = Workspace( + id: readmePath, + rootPath: rootPath, + kind: WorkspaceKind.singleMarkdown, + openedAt: DateTime(2026), + activeFilePath: readmePath, + openFilePaths: const [readmePath], + files: [ + for (final path in const [ + readmePath, + blockTargetPath, + inlineTargetPath, + ]) + DocumentFile( + absolutePath: path, + relativePath: p.basename(path), + kind: DocumentKind.markdown, + size: 1, + lastModified: DateTime(2026), + ), + ], + diagnostics: parsed.diagnostics, + markdown: parsed, + ); + final controller = _MutableWorkspaceController( + WorkspaceState( + workspace: workspace, + // Production owns an active document buffer for this Reading surface. + // Keep the image-link regression in that same command/view context. + documentBuffers: [ + DocumentBuffer( + id: 'linked-images', + filePath: readmePath, + text: source, + lastSavedText: source, + dirty: false, + editorState: const DocumentEditorState( + mode: DocumentViewModePreference.preview, + ), + ), + ], + activeBufferId: 'linked-images', + preview: const MarkdownPreviewBuilder().build(parsed), ), - ], - diagnostics: parsed.diagnostics, - markdown: parsed, - ); - final controller = _MutableWorkspaceController( - WorkspaceState( - workspace: workspace, - activeText: source, - // Production owns an active document buffer for this Reading surface. - // Keep the image-link regression in that same command/view context. - documentBuffers: [ - DocumentBuffer( - id: 'linked-images', - filePath: readmePath, - text: source, - lastSavedText: source, - dirty: false, - editorState: const DocumentEditorState( - mode: DocumentViewModePreference.preview, - ), + ); + final settingsStore = _MemorySettingsStore() + ..value = AppSettings.defaults() + .copyWith(documentViewMode: DocumentViewModePreference.preview) + .toJson(); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + localSettingsStoreProvider.overrideWithValue(settingsStore), + workspaceControllerProvider.overrideWith(() => controller), + ], + ); + addTearDown(container.dispose); + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), ), - ], - activeBufferId: 'linked-images', - preview: const MarkdownPreviewBuilder().build(parsed), - ), - ); - final settingsStore = _MemorySettingsStore() - ..value = AppSettings.defaults() - .copyWith(documentViewMode: DocumentViewModePreference.preview) - .toJson(); - final container = ProviderContainer( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - localSettingsStoreProvider.overrideWithValue(settingsStore), - workspaceControllerProvider.overrideWith(() => controller), - ], - ); - addTearDown(container.dispose); + ); + await tester.pumpAndSettle(); - await tester.pumpWidget( - UncontrolledProviderScope( - container: container, - child: const BusyMarkApp(), - ), - ); - await tester.pumpAndSettle(); + expect(find.byType(MarkdownImageView), findsNWidgets(2)); + expect( + tester + .widgetList(find.byType(MarkdownImageView)) + .map((image) => image.alt), + ['Block logo', 'Inline logo'], + ); + final blocked = find.text(l10n.remoteImageBlocked); + if (remote) { + expect(blocked, findsNWidgets(2)); + expect(http.requests, isEmpty); + for (final destination in ['block-guide.md', 'inline-guide.md']) { + expect( + find.byKey(ValueKey('preview-linked-image-$destination')), + findsNothing, + ); + } - expect(find.byType(MarkdownImageView), findsNWidgets(2)); - for (final (destination, expectedPath) in const [ - ('block-guide.md', blockTargetPath), - ('inline-guide.md', inlineTargetPath), - ]) { - await tester.tap( - find.byKey(ValueKey('preview-linked-image-$destination')), - ); - await tester.pump(); - expect(controller.openedFilePath, expectedPath); - } - }); + await tester.tap(blocked.first); + await tester.pump(); + expect(menus.isOpen, isTrue); + expect(menus.contains(l10n.loadRemoteImagesForWorkspace), isFalse); + expect(menus.entries.map((entry) => entry['label']), [ + l10n.loadThisRemoteImage, + l10n.loadRemoteImagesInDocument, + '', + l10n.alwaysLoadRemoteImages, + ]); + expect(menus.packets.last['focusFirst'], isTrue); + expect( + (menus.packets.last['anchor'] as Map)['width'], + greaterThan(0), + ); + expect(http.requests, isEmpty); + final focused = FocusManager.instance.primaryFocus; + menus.close(); + await tester.pump(); + expect(FocusManager.instance.primaryFocus, same(focused)); + + final pointer = tester.getCenter(blocked.last); + final rightClick = await tester.startGesture( + pointer, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + await tester.pump(kPressTimeout + const Duration(milliseconds: 50)); + expect(menus.isOpen, isFalse); + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + await rightClick.up(); + await tester.pump(); + expect(menus.isOpen, isTrue); + expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); + expect(menus.packets.last['anchor'], { + 'x': pointer.dx, + 'y': pointer.dy, + 'width': 0.0, + 'height': 0.0, + }); + menus.close(); + await tester.pump(); + expect(controller.openedFilePath, isNull); + expect(http.requests, isEmpty); + + for (final key in [ + LogicalKeyboardKey.contextMenu, + LogicalKeyboardKey.f10, + LogicalKeyboardKey.space, + LogicalKeyboardKey.enter, + ]) { + if (key == LogicalKeyboardKey.f10) { + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + } + await tester.sendKeyEvent(key); + if (key == LogicalKeyboardKey.f10) { + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + } + await tester.pump(); + expect(menus.isOpen, isTrue, reason: key.keyLabel); + expect(http.requests, isEmpty); + if (key != LogicalKeyboardKey.enter) { + menus.close(); + await tester.pump(); + } + } + await menus.choose(l10n.loadThisRemoteImage); + expect(blocked, findsOneWidget); + expect(http.requests.map((request) => request.path), [ + '/inline-logo.png', + ]); + expect(controller.openedFilePath, isNull); + expect( + find.byKey(const ValueKey('preview-linked-image-block-guide.md')), + findsNothing, + ); + + await tester.tap(blocked); + await tester.pump(); + await menus.choose(l10n.loadThisRemoteImage); + expect(blocked, findsNothing); + expect(http.requests.map((request) => request.path), [ + '/inline-logo.png', + '/block-logo.png', + ]); + expect(controller.openedFilePath, isNull); + expect( + container.read(appSettingsControllerProvider).allowRemoteImages, + isFalse, + ); + } + + for (final (destination, expectedPath) in const [ + ('block-guide.md', blockTargetPath), + ('inline-guide.md', inlineTargetPath), + ]) { + await tester.tap( + find.byKey(ValueKey('preview-linked-image-$destination')), + ); + await tester.pump(); + expect(controller.openedFilePath, expectedPath); + } + }); + }); + } testWidgets('new empty document leaves remembered preview mode for editor', ( tester, @@ -17903,7 +18552,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(_StartupWorkspaceService()), ], @@ -17932,59 +18580,660 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. expect(find.byKey(const ValueKey('preview-document-scroll')), findsNothing); }); - testWidgets('blocked remote image prompt allows the current workspace', ( - tester, - ) async { - const startupPath = '/tmp/remote-image.md'; - final service = _SearchWorkspaceService( - '![Remote](https://example.com/logo.png)\n', - ); - final settingsStore = _MemorySettingsStore() - ..value = AppSettings.defaults() - .copyWith(documentViewMode: DocumentViewModePreference.preview) - .toJson(); - final container = ProviderContainer( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), - localSettingsStoreProvider.overrideWithValue(settingsStore), - workspaceServiceProvider.overrideWithValue(service), - startupPathProvider.overrideWithValue(startupPath), - ], - ); - addTearDown(container.dispose); - - await tester.pumpWidget( - UncontrolledProviderScope( - container: container, - child: const BusyMarkApp(), + testWidgets( + 'remote image grants follow unsaved document and occurrence lifetimes', + (tester) async { + final menus = NativeMenuProbe(tester); + await _withControlledImageClient((http) async { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + binding.platformDispatcher.defaultRouteNameTestValue = '/workspace'; + addTearDown( + () => binding.platformDispatcher.defaultRouteNameTestValue = '/', + ); + final root = Directory.systemTemp.createTempSync( + 'busymark-image-scopes-', + ); + addTearDown(() => root.deleteSync(recursive: true)); + final settingsStore = _MemorySettingsStore() + ..value = AppSettings.defaults() + .copyWith( + autoSave: false, + validateOnEdit: false, + automaticSpelling: false, + ) + .toJson(); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + startupPathProvider.overrideWithValue(null), + localSettingsStoreProvider.overrideWithValue(settingsStore), + localHistoryStoreProvider.overrideWithValue( + MemoryLocalHistoryStore(), + ), + documentSessionStoreProvider.overrideWithValue( + MemoryDocumentSessionStore(), + ), + documentRecoveryStoreProvider.overrideWithValue( + MemoryDocumentRecoveryStore(), + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), + ), + ); + final controller = container.read(workspaceControllerProvider.notifier); + DocumentBuffer buffer() => + container.read(workspaceControllerProvider).activeBuffer!; + await tabOperation(tester, controller.createMarkdownFile); + const url = 'HTTPS://example.com/lifetime.png'; + const markup = '![Same]($url)'; + const source = 'Introduction\n\n$markup\n\n$markup\n'; + controller.updateActiveText(source); + await tester.pumpAndSettle(); + + final blocked = find.text(l10n.remoteImageBlocked); + final network = find.byWidgetPredicate( + (widget) => widget is Image && widget.image is NetworkImage, + ); + expect(blocked, findsNWidgets(2)); + expect(http.requests, isEmpty); + final beforePermission = buffer(); + await tester.tap(blocked.first); + await tester.pump(); + await menus.choose(l10n.loadThisRemoteImage); + expect(network, findsOneWidget); + expect(blocked, findsOneWidget); + expect(http.requests, [Uri.parse(url)]); + expect(buffer().text, beforePermission.text); + expect(buffer().dirty, beforePermission.dirty); + expect( + buffer().editorState.undoState.undo, + same(beforePermission.editorState.undoState.undo), + ); + await tester.tap(blocked); + await tester.pump(); + expect(menus.isOpen, isTrue); + menus.close(); + await tester.pumpAndSettle(); + expect(buffer().text, beforePermission.text); + expect(http.requests, [Uri.parse(url)]); + final opening = buffer().opening; + + await tester.enterText( + historyField(DocumentViewModePreference.editor), + 'Edited introduction', + ); + await tester.pumpAndSettle(); + expect(blocked, findsOneWidget); + expect(network, findsOneWidget); + + Future show(DocumentViewModePreference mode) async { + controller.updateActiveEditorMode(mode); + await tabOperation(tester, controller.validateActive); + await tester.pumpAndSettle(); + } + + for (final mode in [ + DocumentViewModePreference.preview, + DocumentViewModePreference.split, + DocumentViewModePreference.editor, + ]) { + await show(mode); + expect(blocked, findsOneWidget, reason: mode.name); + expect(network, findsOneWidget, reason: mode.name); + } + + final firstId = buffer().id; + final edited = buffer().text; + await tabOperation(tester, controller.createMarkdownFile); + controller.updateActiveText(source); + await tester.pumpAndSettle(); + expect(blocked, findsNWidgets(2)); + expect(network, findsNothing); + await tester.tap(blocked.first); + await tester.pump(); + await menus.choose(l10n.loadRemoteImagesInDocument); + expect(network, findsNWidgets(2)); + expect(buffer().isUntitled, isTrue); + expect( + container.read(appSettingsControllerProvider).allowRemoteImages, + isFalse, + ); + await tabOperation( + tester, + () => controller.activateDocumentBuffer(firstId), + ); + await tester.pumpAndSettle(); + expect(network, findsOneWidget); + + final path = p.join(root.path, 'saved.md'); + expect( + await tabOperation(tester, () => controller.saveActiveAs(path)), + isTrue, + ); + await tester.pumpAndSettle(); + expect(buffer().opening, same(opening)); + expect(buffer().id, firstId); + expect(buffer().filePath, path); + expect(network, findsOneWidget); + expect(blocked, findsOneWidget); + + await tester.tap(blocked); + await tester.pump(); + expect(menus.contains(l10n.loadRemoteImagesForWorkspace), isFalse); + controller.updateActiveText( + edited.replaceAll(url, 'https://example.com/changed.png'), + ); + await menus.choose(l10n.alwaysLoadRemoteImages); + expect( + container.read(appSettingsControllerProvider).allowRemoteImages, + isFalse, + ); + expect(network, findsNothing); + expect(blocked, findsNWidgets(2)); + expect(http.requests, [Uri.parse(url)]); + + await tester.tap(blocked.first); + await tester.pump(); + await menus.choose(l10n.loadRemoteImagesInDocument); + expect(network, findsNWidgets(2)); + controller.updateActiveText( + '${buffer().text}\n![New](https://example.com/after-grant.png)\n', + ); + await tester.pumpAndSettle(); + expect(blocked, findsNothing); + expect(http.requests.map((url) => url.path), [ + '/lifetime.png', + '/changed.png', + '/after-grant.png', + ]); + expect(settingsStore.value['allowRemoteImages'], false); + expect(settingsStore.value['remoteImageAllowedWorkspaceIds'], isEmpty); + + expect( + await tabOperation( + tester, + () => controller.closeDocumentBuffer(firstId, discard: true), + ), + isTrue, + ); + await tabOperation(tester, () => controller.openPath(path)); + await tester.pumpAndSettle(); + final firstFileOpening = buffer().opening; + final fileId = buffer().id; + expect(blocked, findsNWidgets(2)); + await tester.tap(blocked.first); + await tester.pump(); + await menus.choose(l10n.loadThisRemoteImage); + expect(network, findsOneWidget); + expect( + await tabOperation( + tester, + () => controller.closeDocumentBuffer(fileId), + ), + isTrue, + ); + await tabOperation(tester, () => controller.openPath(path)); + await tester.pumpAndSettle(); + expect(buffer().id, fileId); + expect(buffer().opening, isNot(same(firstFileOpening))); + expect(blocked, findsNWidgets(2)); + expect(network, findsNothing); + }); + }, + ); + + testWidgets( + 'remote image workspace grant includes drafts and revokes immediately', + (tester) async { + final menus = NativeMenuProbe(tester); + await _withControlledImageClient((http) async { + final root = Directory.systemTemp.createTempSync( + 'busymark-image-workspace-', + ); + addTearDown(() => root.deleteSync(recursive: true)); + final other = Directory(p.join(root.path, 'other'))..createSync(); + const source = '![First](https://example.com/workspace.png)\n'; + final standalone = File(p.join(root.path, 'standalone.md')) + ..writeAsStringSync(source); + File(p.join(other.path, 'other.md')).writeAsStringSync(source); + + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + startupPathProvider.overrideWithValue(null), + localSettingsStoreProvider.overrideWithValue( + _MemorySettingsStore() + ..value = AppSettings.defaults() + .copyWith( + autoSave: false, + validateOnEdit: false, + automaticSpelling: false, + ) + .toJson(), + ), + localHistoryStoreProvider.overrideWithValue( + MemoryLocalHistoryStore(), + ), + documentSessionStoreProvider.overrideWithValue( + MemoryDocumentSessionStore(), + ), + documentRecoveryStoreProvider.overrideWithValue( + MemoryDocumentRecoveryStore(), + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), + ), + ); + await tester.pumpAndSettle(); + final controller = container.read(workspaceControllerProvider.notifier); + final settings = container.read(appSettingsControllerProvider.notifier); + final blocked = find.text(l10n.remoteImageBlocked); + await tabOperation(tester, () => controller.openPath(root.path)); + container.read(appRouterProvider).go('/workspace'); + await tester.pumpAndSettle(); + expect( + container.read(workspaceControllerProvider).workspace?.kind, + WorkspaceKind.markdownFolder, + ); + await tabOperation(tester, controller.createMarkdownFile); + controller.updateActiveText(source); + expect(container.read(workspaceControllerProvider).activeText, source); + container.read(appRouterProvider).go('/workspace'); + await tester.pumpAndSettle(); + expect(blocked, findsOneWidget); + + await tester.tap(blocked); + await tester.pump(); + expect(menus.contains(l10n.loadRemoteImagesForWorkspace), isTrue); + await menus.choose(l10n.loadRemoteImagesForWorkspace); + expect(blocked, findsNothing); + expect(http.requests, [Uri.parse('https://example.com/workspace.png')]); + + await tabOperation(tester, () => controller.openPath(standalone.path)); + await tester.pumpAndSettle(); + await tester.tap(blocked); + await tester.pump(); + expect(menus.contains(l10n.loadRemoteImagesForWorkspace), isFalse); + await menus.choose(l10n.alwaysLoadRemoteImages); + expect( + container.read(appSettingsControllerProvider).allowRemoteImages, + isTrue, + ); + expect(blocked, findsNothing); + await settings.setAllowRemoteImages(false); + await tester.pumpAndSettle(); + expect(blocked, findsOneWidget); + for (final path in [other.path, standalone.path]) { + await tabOperation(tester, () => controller.openPath(path)); + container.read(appRouterProvider).go('/workspace'); + await tester.pumpAndSettle(); + expect(blocked, findsOneWidget); + } + await tabOperation(tester, () => controller.openPath(root.path)); + container.read(appRouterProvider).go('/workspace'); + await tester.pumpAndSettle(); + expect(blocked, findsNothing); + await settings.clearRemoteImageWorkspacePermissions(); + await tester.pumpAndSettle(); + expect(blocked, findsOneWidget); + expect(http.requests, hasLength(1)); + }); + }, + ); + + testWidgets( + 'nested HTML uses the same remote image occurrence in all views', + (tester) async { + final menus = NativeMenuProbe(tester); + await _withControlledImageClient((http) async { + const source = ''' +
+

One first inline.

+
second
+
+'''; + final container = await historyApp( + tester, + DocumentViewModePreference.editor, + initialSource: source, + ); + final controller = container.read(workspaceControllerProvider.notifier); + final blocked = find.text(l10n.remoteImageBlocked); + expect(blocked, findsNWidgets(2)); + expect(http.requests, isEmpty); + await tester.tap(blocked.first); + await tester.pump(); + await menus.choose(l10n.loadThisRemoteImage); + expect(blocked, findsOneWidget); + for (final mode in [ + DocumentViewModePreference.preview, + DocumentViewModePreference.split, + ]) { + controller.updateActiveEditorMode(mode); + await tabOperation(tester, controller.validateActive); + await tester.pumpAndSettle(); + expect(blocked, findsOneWidget); + expect( + find.text('second\nhttps://example.com/html-occurrence.png'), + findsNothing, + ); + } + expect(http.requests, [ + Uri.parse('https://example.com/html-occurrence.png'), + ]); + }); + }, + ); + + testWidgets('Open completes after Discard disposes the initiating header', ( + tester, + ) async { + final menus = NativeMenuProbe(tester); + final service = _GatedResourceService('picked.md'); + const picker = MethodChannel('plugins.flutter.io/file_selector'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + picker, + (_) async => ['picked.md'], + ); + addTearDown(() { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + picker, + null, + ); + if (!service.release.isCompleted) service.release.complete(); + }); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + startupPathProvider.overrideWithValue(null), + workspaceServiceProvider.overrideWithValue(service), + workspaceFileMonitorProvider.overrideWithValue( + _SearchTestFileMonitor(), + ), + localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), + localHistoryStoreProvider.overrideWithValue(MemoryLocalHistoryStore()), + documentSessionStoreProvider.overrideWithValue( + MemoryDocumentSessionStore(), + ), + documentRecoveryStoreProvider.overrideWithValue( + MemoryDocumentRecoveryStore(), + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), ), ); - for (var i = 0; i < 20; i += 1) { - await tester.pump(const Duration(milliseconds: 100)); - if (find.text(l10n.remoteImageBlocked).evaluate().isNotEmpty) { - break; - } - } + final controller = container.read(workspaceControllerProvider.notifier); + await tabOperation(tester, controller.createMarkdownFile); + controller.updateActiveText('# Discardable draft'); + container.read(appRouterProvider).go('/workspace'); + await tester.pumpAndSettle(); + final button = find.byKey(const ValueKey('header-open-menu')); + final initiatingHeader = tester.element(button); + await tester.tap(button); + await tester.pump(); + menus.select(l10n.openMarkdownFile); + await tester.pumpAndSettle(); + await tester.tap(find.text(l10n.discard)); + await pumpUntil( + tester, + () => service.entered.isCompleted && !initiatingHeader.mounted, + operation: 'dispose the dirty document header during Open', + ); + expect(container.read(workspaceControllerProvider).workspace, isNull); + service.release.complete(); + await pumpUntil(tester, () { + final live = container.read(workspaceControllerProvider); + return !live.isLoading && live.activeBuffer?.filePath == 'picked.md'; + }, operation: 'finish the authorized Open'); + expect(find.byKey(const ValueKey('workspace-page-frame')), findsOneWidget); + expect(tester.takeException(), isNull); + }); - expect(find.text(l10n.remoteImageBlocked), findsOneWidget); + testWidgets( + 'Recent reveals the new workspace after its row is disposed behind Local History', + (tester) async { + NativeMenuProbe(tester); + final fixture = Directory.systemTemp.createTempSync( + 'busymark-recent-retained-', + ); + addTearDown(() => fixture.deleteSync(recursive: true)); + final destination = File(p.join(fixture.path, 'replacement.md')) + ..writeAsStringSync('# Replacement'); + final service = _GatedResourceService(destination.path); + addTearDown(() { + if (!service.release.isCompleted) service.release.complete(); + }); + final historyStore = MemoryLocalHistoryStore(); + await historyStore.capture( + LocalHistoryCaptureRequest( + path: p.join(fixture.path, 'deleted.md'), + displayName: 'Deleted document', + source: 'retained needle', + format: TextFormatMetadata.utf8Lf, + capturedAt: DateTime.now().toUtc(), + reason: LocalHistoryCaptureReason.saved, + ), + const LocalHistoryPolicy(), + ); + await historyStore.markDeleted( + p.join(fixture.path, 'deleted.md'), + recursive: false, + ); + final container = ProviderContainer( + overrides: [ + ..._smokeAccentOverrides, + startupPathProvider.overrideWithValue('first.md'), + workspaceServiceProvider.overrideWithValue(service), + workspaceFileMonitorProvider.overrideWithValue( + _SearchTestFileMonitor(), + ), + localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), + localHistoryStoreProvider.overrideWithValue(historyStore), + documentSessionStoreProvider.overrideWithValue( + MemoryDocumentSessionStore(), + ), + documentRecoveryStoreProvider.overrideWithValue( + MemoryDocumentRecoveryStore(), + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const BusyMarkApp(), + ), + ); + await pumpUntil( + tester, + () => find + .byKey(const ValueKey('workspace-page-frame')) + .evaluate() + .isNotEmpty, + operation: 'open the starting document', + ); + await container.read(localHistoryControllerProvider.notifier).refresh(); + final session = container.read(searchSessionProvider.notifier); + session.openHistory(); + session.query('retained needle'); + await _waitForSearchCondition( + tester, + () => container.read(searchSessionProvider).results.isNotEmpty, + ); + final result = container.read(searchSessionProvider).results.single; + final resultRow = find.byKey(ValueKey(result.identity)); + await tester.tap(resultRow); + await tester.pump(kDoubleTapMinTime + const Duration(milliseconds: 1)); + await tester.tap(resultRow); + await _waitForSearchCondition( + tester, + () => find.byType(LocalHistoryComparisonView).evaluate().isNotEmpty, + ); + expect( + find.byKey(const ValueKey('local-history-panel-header')), + findsNothing, + ); + session.close(restoreFocus: false); - await tester.tap(find.text(l10n.remoteImageBlocked)); - await tester.pumpAndSettle(); + final recent = RecentResource( + path: destination.path, + kind: 'singleMarkdown', + lastOpenedAt: DateTime.now(), + ); + final controller = container.read(workspaceControllerProvider.notifier); + await controller.recordRecentResource(recent); + await tester.pumpAndSettle(); + await _chooseNativeSidebar(tester, l10n.recent); + final recentRow = find.byKey( + ValueKey(RecentSearchResult(recent).identity), + ); + final initiatingRow = tester.element(recentRow); + await tester.tap(recentRow); + await pumpUntil( + tester, + () => service.entered.isCompleted, + operation: 'start opening from Recent', + ); + await container + .read(appSettingsControllerProvider.notifier) + .removeRecentWorkspace(recent.identity); + await tester.pumpAndSettle(); + expect(initiatingRow.mounted, isFalse); + expect(find.byType(LocalHistoryComparisonView), findsOneWidget); - expect(find.text(l10n.remoteImagesBlockedTitle), findsOneWidget); + service.release.complete(); + await pumpUntil(tester, () { + final live = container.read(workspaceControllerProvider); + return !live.isLoading && + live.activeBuffer?.filePath == destination.path && + container.read(localHistoryControllerProvider).selectedRevisionId == + null; + }, operation: 'reveal the Recent document and retire the comparison'); + expect(find.byType(LocalHistoryComparisonView), findsNothing); + expect(tester.takeException(), isNull); + }, + ); - await tester.tap(find.text(l10n.loadRemoteImagesForWorkspace)); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + testWidgets('Open uses the native Markdown and folder choosers', ( + tester, + ) async { + final fixture = Directory.systemTemp.createTempSync('busymark-open-menu-'); + addTearDown(() => fixture.deleteSync(recursive: true)); + final document = File(p.join(fixture.path, 'picked.md')) + ..writeAsStringSync('# Picked'); + final service = _StartupWorkspaceService(); + final menus = NativeMenuProbe(tester); + final calls = []; + const picker = MethodChannel('plugins.flutter.io/file_selector'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(picker, ( + call, + ) async { + calls.add(call.method); + return switch (call.method) { + 'openFile' => [document.path], + 'getDirectoryPath' => fixture.path, + _ => throw StateError(call.method), + }; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + picker, + null, + ), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + ..._smokeAccentOverrides, + localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), + workspaceServiceProvider.overrideWithValue(service), + ], + child: const BusyMarkApp(), + ), + ); + await tester.pumpAndSettle(); + for (final (label, expectedPath) in [ + (l10n.openMarkdownFile, document.path), + (l10n.openFolderOrWritersideProject, fixture.path), + ]) { + await tester.tap(find.byKey(const ValueKey('header-open-menu'))); + await tester.pumpAndSettle(); + menus.select(label); + await _waitForSearchCondition( + tester, + () => service.openedPath == expectedPath, + ); + await tester.pumpAndSettle(); + } + expect(calls, ['openFile', 'getDirectoryPath']); + expect(find.byKey(const ValueKey('workspace-page-frame')), findsOneWidget); + }); + testWidgets('Welcome reveals its remapped Sidebar View in a narrow window', ( + tester, + ) async { + final menus = NativeMenuProbe(tester); + await tester.binding.setSurfaceSize(const Size(530, 720)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final settings = _MemorySettingsStore() + ..value = AppSettings.defaults() + .copyWith( + sidebarVisible: false, + shortcutOverrides: { + BusyMarkCommandIds.sidebarViewSelector: const BusyMarkKeyBinding( + LogicalKeyboardKey.f6, + ), + }, + ) + .toJson(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + ..._smokeAccentOverrides, + localSettingsStoreProvider.overrideWithValue(settings), + ], + child: const BusyMarkApp(), + ), + ); + await tester.pumpAndSettle(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.f6); + await pumpUntil( + tester, + () => menus.isOpen, + operation: 'reveal Welcome sidebar on keydown', + ); + expect(menus.entries.single['label'], l10n.recent); + expect(menus.entries.single['selected'], isTrue); + expect(menus.entries.single['mnemonic'], 'E'); + expect(find.text(l10n.home), findsOneWidget); + expect(find.byTooltip('${l10n.sidebarViewMenu} (F6)'), findsOneWidget); + await tester.sendKeyUpEvent(LogicalKeyboardKey.f6); + menus.close(); + await tester.pumpAndSettle(); expect( - settingsStore.value['remoteImageAllowedWorkspacePaths'], - contains(startupPath), + find.byKey(const ValueKey('workspace-content-view-menu')), + findsNothing, ); + expect(tester.takeException(), isNull); }); - testWidgets('Ctrl+O open chooser lists recent workspaces', (tester) async { + testWidgets('Recent is a separate global sidebar view', (tester) async { + final menus = NativeMenuProbe(tester); const startupPath = 'test/fixtures/markdown/basic.md'; final recentDirectory = Directory.systemTemp.createTempSync( 'busymark-recent-docs-', @@ -18007,7 +19256,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue(startupPath), @@ -18035,8 +19283,33 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); - expect(find.text(l10n.openMarkdownFile), findsOneWidget); - expect(find.text(l10n.recent), findsOneWidget); + expect(menus.contains(l10n.openMarkdownFile), isTrue); + expect(menus.contains(l10n.recent), isFalse); + expect(menus.contains(p.basename(recentPath)), isFalse); + menus.close(); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('workspace-sidebar-view-menu'))); + await tester.pumpAndSettle(); + expect( + menus.entries.singleWhere((entry) => entry['selected'] == true)['label'], + l10n.outline, + ); + expect( + menus.entries.singleWhere( + (entry) => entry['label'] == l10n.recent, + )['mnemonic'], + 'E', + ); + menus.select(l10n.recent); + await tester.pumpAndSettle(); + expect(find.text(p.basename(recentPath)), findsOneWidget); + expect(service.openedPath, startupPath); + final search = container.read(searchSessionProvider.notifier); + search.open(category: SearchCategory.recent); + await tester.pumpAndSettle(); + search.close(); + await tester.pumpAndSettle(); expect(find.text(p.basename(recentPath)), findsOneWidget); await tester.tap(find.text(p.basename(recentPath))); @@ -18086,7 +19359,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), startupPathProvider.overrideWithValue(null), ], @@ -18198,42 +19470,74 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. } }); - testWidgets( - 'shared Markdown image renderer blocks remote images by default', - (tester) async { - var promptCount = 0; - + testWidgets('blocked remote image keeps compact accessible details', ( + tester, + ) async { + final source = + 'https://example.com/images/${'featured-article-photograph-' * 12}.png'; + const alt = 'Portrait of W. S. Gilbert'; + final semantics = tester.ensureSemantics(); + try { await tester.pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: Scaffold( - body: MarkdownImageView( - source: 'https://example.com/logo.png', - alt: 'Logo', - activeFilePath: 'doc.md', - workspaceRoot: null, - writersideRoot: null, - imagesDir: 'images', - allowRemoteImages: false, - onRemoteImageBlocked: () { - promptCount += 1; - }, + body: Align( + alignment: Alignment.topLeft, + child: MarkdownImagePermissionScope( + resolve: (_, _, _) => MarkdownImageActions( + allowed: false, + openMenu: (_, _, _) async {}, + ), + child: MarkdownImageView( + source: source, + alt: alt, + activeFilePath: 'doc.md', + workspaceRoot: null, + writersideRoot: null, + imagesDir: 'images', + maxHeight: 120, + preferredHeight: 96, + ), + ), ), ), ), ); - await tester.pump(); - + final image = find.byType(MarkdownImageView); expect(find.text(l10n.remoteImageBlocked), findsOneWidget); + expect(find.byIcon(BusyMarkGlyphs.imageBlocked), findsOneWidget); + expect(find.byIcon(BusyMarkGlyphs.imageMissing), findsNothing); expect(find.byType(Image), findsNothing); - - await tester.tap(find.text(l10n.remoteImageBlocked)); - await tester.pump(); - - expect(promptCount, 1); - }, - ); + expect(find.byType(Scrollable), findsNothing); + expect(find.textContaining(source), findsNothing); + expect(tester.getSize(image).height, lessThan(60)); + expect(find.byIcon(BusyMarkGlyphs.downArrow), findsNothing); + expect(find.byTooltip(l10n.remoteImageBlockedTooltip), findsOneWidget); + expect( + find.bySemanticsLabel('${l10n.remoteImageBlocked}\n$alt\n$source'), + findsOneWidget, + ); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(mouse.removePointer); + await mouse.addPointer(location: tester.getCenter(image)); + await tester.pump(const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.text(l10n.remoteImageBlocked)) + .style + ?.decoration, + TextDecoration.underline, + ); + expect(find.text(l10n.remoteImageBlockedTooltip), findsOneWidget); + expect(find.textContaining(source), findsNothing); + expect(tester.takeException(), isNull); + } finally { + semantics.dispose(); + } + }); testWidgets( 'shared Markdown image renderer resolves absolute paths with spaces', @@ -18615,12 +19919,9 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. addTearDown(tester.view.resetDevicePixelRatio); final original = '# Group\n${List.generate(count, (i) => 'cat $i\n').join()}'; - final harness = await _pumpSearchRegression( - tester, - headerBarService, - {'a.md': original}, - mode: mode, - ); + final harness = await _pumpSearchRegression(tester, { + 'a.md': original, + }, mode: mode); final container = harness.container; final session = container.read(searchSessionProvider.notifier); session.open(category: SearchCategory.file); @@ -18835,7 +20136,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. addTearDown(tester.view.resetDevicePixelRatio); final original = 'cat\n${'gap\n' * 200}cat\n${'tail\n' * 200}cat\n'; final modified = original.replaceRange(0, 3, 'wolf'); - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': original, 'b.md': 'other cat buffer\n', }, mode: mode); @@ -18992,7 +20293,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. } } - testWidgets('Welcome, Recent search and Open use the same mixed chronology', ( + testWidgets('Welcome and Recent search use the same mixed chronology', ( tester, ) async { final settings = _MemorySettingsStore() @@ -19029,7 +20330,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. overrides: [ ..._smokeAccentOverrides, startupPathProvider.overrideWithValue(null), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settings), ], ); @@ -19069,24 +20369,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. expectChronologicalRows(); search.close(); await tester.pumpAndSettle(); - final opening = container - .read(busyMarkCommandRegistryProvider) - .execute(BusyMarkCommandIds.open); - await tester.pumpAndSettle(); - final recentRows = tester - .widgetList( - find.descendant( - of: find.byType(BusyMarkDialogShell), - matching: find.byType(BusyMarkActionRow), - ), - ) - .where((r) => r.title.contains('entry')) - .map((r) => r.title.replaceAll('\u2066', '').replaceAll('\u2069', '')) - .toList(); - expect(recentRows, ['Newest entry', 'Middle entry', 'Oldest entry']); - await tester.sendKeyEvent(LogicalKeyboardKey.escape); - await tester.pumpAndSettle(); - await opening; + expectChronologicalRows(); }); for (final mode in [ @@ -19133,7 +20416,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), workspaceFileMonitorProvider.overrideWith( (ref) => _SearchTestFileMonitor(), ), @@ -19294,7 +20576,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. } await store.remapPath('/retired/same.md', '/deleted/same.md'); await store.markDeleted('/deleted/same.md', recursive: false); - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Live heading\nlive source\n', }, historyStore: store); final container = harness.container; @@ -19408,9 +20690,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. (tester) async { const text = '# Alpha\n## Shared\nalpha body\n# Beta\n## Shared\nbeta body\n'; - final harness = await _pumpSearchRegression(tester, headerBarService, { - 'a.md': text, - }); + final harness = await _pumpSearchRegression(tester, {'a.md': text}); final container = harness.container; final session = container.read(searchSessionProvider.notifier); Future outlineShortcut() async { @@ -19510,7 +20790,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'unified search scopes, query isolation and explicit shortcut destinations', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': '# Alpha\nneedle alpha\n', 'b.md': '# Beta\nneedle beta\n', }); @@ -19741,7 +21021,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'unified Actions formats captured Source selection and rejects a later selection', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'cat dog\n', }); final container = harness.container; @@ -19888,9 +21168,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'unified search overlay retains source controller and initial hidden sidebar', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { - 'a.md': 'needle\n', - }); + final harness = await _pumpSearchRegression(tester, {'a.md': 'needle\n'}); final container = harness.container; container.read(searchSessionProvider.notifier).close(); await container @@ -19937,7 +21215,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue( @@ -19984,6 +21261,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); expect(find.byType(TextField).evaluate().length, initialTextFields + 1); + expect(headerButton(l10n.home), findsOneWidget); expect(headerButton(l10n.back), findsNothing); expect(headerButton(l10n.validate), findsNothing); expect( @@ -19995,7 +21273,8 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. await tester.tap(headerButton(l10n.search)); await tester.pumpAndSettle(); expect(find.byType(TextField).evaluate().length, initialTextFields); - expect(headerButton(l10n.back), findsOneWidget); + expect(headerButton(l10n.home), findsOneWidget); + expect(headerButton(l10n.back), findsNothing); expect(editorFocus.hasFocus, isTrue); expect(headerButton(l10n.validate), findsOneWidget); expect( @@ -20020,102 +21299,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. expect(editorFocus.hasFocus, isTrue); }); - testWidgets( - 'native header Search action toggles search and Back visibility', - (tester) async { - if (!Platform.isLinux) { - return; - } - const channelName = 'test.busymark/headerbar-search-toggle'; - const channel = MethodChannel(channelName); - const codec = StandardMethodCodec(); - final nativeHeaderBarService = LinuxHeaderBarService( - channel: channel, - sessionId: 'search-toggle-session', - ); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - if (call.method == 'initialize' || call.method == 'focusSearch') { - return true; - } - if (call.method == 'applyConfiguration') { - final configuration = Map.from( - call.arguments! as Map, - ); - return configuration['revision']; - } - return null; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - channel.setMethodCallHandler(null); - }); - await nativeHeaderBarService.initialize(); - - final container = ProviderContainer( - overrides: [ - ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue( - nativeHeaderBarService, - ), - localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), - workspaceServiceProvider.overrideWithValue( - _StartupWorkspaceService(), - ), - startupPathProvider.overrideWithValue( - 'test/fixtures/markdown/basic.md', - ), - ], - ); - addTearDown(container.dispose); - - await tester.pumpWidget( - UncontrolledProviderScope( - container: container, - child: const BusyMarkApp(), - ), - ); - await tester.pump(); - for (var i = 0; i < 20; i += 1) { - await tester.pump(const Duration(milliseconds: 100)); - if (find - .byKey(const ValueKey('workspace-page-frame')) - .evaluate() - .isNotEmpty) { - break; - } - } - - HeaderBarConfiguration configuration() => tester - .widget( - find.byType(HeaderBarConfigurationPublisher), - ) - .configuration; - - expect(configuration().searchActive, isFalse); - expect(configuration().backVisible, isTrue); - - Future pressNativeSearch() async { - await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - channelName, - codec.encodeMethodCall(const MethodCall('search')), - (_) {}, - ); - await tester.pump(const Duration(milliseconds: 100)); - } - - await pressNativeSearch(); - expect(configuration().searchActive, isTrue); - expect(configuration().backVisible, isFalse); - - await pressNativeSearch(); - expect(configuration().searchActive, isFalse); - expect(configuration().backVisible, isTrue); - }, - ); - testWidgets( 'workspace search awaits non-active file reads without blocking builds', (tester) async { @@ -20134,7 +21317,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. workspaceFileMonitorProvider.overrideWith( (ref) => _SearchTestFileMonitor(), ), - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue( @@ -20233,13 +21415,22 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'document text native submit uses exact payload and selected sidebar occurrence', (tester) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': 'cat\n cat \n cat \n', }); session.container .read(searchSessionProvider.notifier) .open(category: SearchCategory.file); - session.events.add(const HeaderBarSearchSubmitted(' cat ')); + final queryField = find.descendant( + of: find.byKey(const ValueKey('shared-search-query')), + matching: find.byType(TextField), + ); + await tester.enterText(queryField, ' cat '); + await _waitForSearchCondition( + tester, + () => session.container.read(searchSessionProvider).results.isNotEmpty, + ); + await tester.testTextInput.receiveAction(TextInputAction.search); await _waitForSearchCondition( tester, () => _searchSourceController(tester).searchResult.totalMatchCount == 2, @@ -20249,12 +21440,9 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. () => find.text(l10n.searchResultLine('a.md', 3)).evaluate().isNotEmpty, ); expect( - tester - .widget( - find.byType(HeaderBarConfigurationPublisher), - ) - .configuration - .searchQuery, + ProviderScope.containerOf( + tester.element(find.byType(BusyMarkApp)), + ).read(searchSessionProvider).query, ' cat ', ); await tester.tap(find.text(l10n.searchResultLine('a.md', 3))); @@ -20279,7 +21467,12 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. session.container.read(workspaceControllerProvider).activeText == 'cat\n cat \n dog \n', ); - session.events.add(const HeaderBarSearchSubmitted(' ')); + await tester.enterText(queryField, ' '); + await _waitForSearchCondition( + tester, + () => session.container.read(searchSessionProvider).results.isNotEmpty, + ); + await tester.testTextInput.receiveAction(TextInputAction.search); await _waitForSearchCondition( tester, () => @@ -20294,11 +21487,11 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'workspace search preserves query and lands on unopened destination', (tester) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': 'First file\n', 'b.md': 'Before\nsecond needle result\n', }); - session.events.add(const HeaderBarSearchQueryChanged('needle')); + session.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => find.text('second needle result').evaluate().isNotEmpty, @@ -20337,12 +21530,9 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. () => find.text('second needle result').evaluate().isNotEmpty, ); expect( - tester - .widget( - find.byType(HeaderBarConfigurationPublisher), - ) - .configuration - .searchQuery, + ProviderScope.containerOf( + tester.element(find.byType(BusyMarkApp)), + ).read(searchSessionProvider).query, 'needle', ); await tester.pumpWidget(const SizedBox()); @@ -20363,11 +21553,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. 'a.md': 'Before\noriginal needle result\n', 'b.md': '# B\n', }; - final harness = await _pumpSearchRegression( - tester, - headerBarService, - sources, - ); + final harness = await _pumpSearchRegression(tester, sources); final container = harness.container; final controller = container.read(workspaceControllerProvider.notifier); final original = container @@ -20376,7 +21562,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. await controller.openActiveFile( '${_SearchRegressionService.root}/b.md', ); - harness.events.add(const HeaderBarSearchQueryChanged('needle')); + harness.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => @@ -20466,7 +21652,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'cancelled closed-tab result cannot navigate or publish feedback', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'original needle result\n', 'b.md': '# B\n', }); @@ -20479,7 +21665,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final destination = container .read(workspaceControllerProvider) .activeBuffer!; - harness.events.add(const HeaderBarSearchQueryChanged('needle')); + harness.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => @@ -20546,7 +21732,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets('workspace search observes edits to inactive buffers', ( tester, ) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': 'First file\n', 'b.md': 'disk needle\n', }); @@ -20561,7 +21747,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. controller.updateDocumentText(buffer.id, 'unsaved needle\n'); await controller.openActiveFile('${_SearchRegressionService.root}/a.md'); await tester.pump(); - session.events.add(const HeaderBarSearchQueryChanged('needle')); + session.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => find.text('unsaved needle').evaluate().isNotEmpty, @@ -20592,11 +21778,11 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'workspace search reports limits and continues into later files', (tester) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': List.generate(80, (i) => 'needle $i').join('\n'), 'b.md': 'later needle\n', }); - session.events.add(const HeaderBarSearchQueryChanged('needle')); + session.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => find.text(l10n.workspaceSearchShowMore).evaluate().isNotEmpty, @@ -20632,7 +21818,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. (tester) async { final session = await _pumpSearchRegression( tester, - headerBarService, { 'a.md': 'active\n', 'large.md': 'large needle', @@ -20641,7 +21826,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. oversized: {'large.md'}, unreadable: {'unreadable.md'}, ); - session.events.add(const HeaderBarSearchQueryChanged('needle')); + session.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => find @@ -20651,7 +21836,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. ); expect(find.text(l10n.noResults), findsNothing); expect(find.textContaining('large.md\nunreadable.md'), findsOneWidget); - session.events.add(const HeaderBarSearchQueryChanged('[')); + session.container.read(searchSessionProvider.notifier).query('['); await _waitForSearchCondition( tester, () => !session.container.read(searchSessionProvider).searching, @@ -20669,19 +21854,19 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'workspace search cancels rapid literal queries while UI keeps building', (tester) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': 'active\n', 'b.md': '${'a' * 100}b\n', }); - session.events.add(const HeaderBarSearchQueryChanged('needle')); + session.container.read(searchSessionProvider.notifier).query('needle'); await tester.pump(); - session.events.add(const HeaderBarSearchQueryChanged(r'^(a+)+$')); + session.container.read(searchSessionProvider.notifier).query(r'^(a+)+$'); await tester.pump(const Duration(milliseconds: 1)); await session.container .read(appSettingsControllerProvider.notifier) .setWordWrap(false); await tester.pump(); - session.events.add(const HeaderBarSearchQueryChanged('active')); + session.container.read(searchSessionProvider.notifier).query('active'); await _waitForSearchCondition( tester, () => @@ -20700,11 +21885,11 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'workspace search replacement review loads an asynchronous plan', (tester) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': 'cat cat\n', 'b.md': 'cat\n', }); - session.events.add(const HeaderBarSearchQueryChanged('cat')); + session.container.read(searchSessionProvider.notifier).query('cat'); await _waitForSearchCondition( tester, () => find.text(l10n.workspaceReplace).evaluate().isNotEmpty, @@ -20761,7 +21946,7 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'preview search highlights preserve Unicode offsets and literal case-insensitive matching', (tester) async { - final harness = await _pumpSearchRegression(tester, headerBarService, { + final harness = await _pumpSearchRegression(tester, { 'a.md': 'İ needle Cat catalog .*\n', }, mode: DocumentViewModePreference.preview); bool hasHighlight(InlineSpan span, String text) => @@ -20809,11 +21994,11 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. testWidgets( 'literal workspace search bounds malformed Markdown snippets around the match', (tester) async { - final session = await _pumpSearchRegression(tester, headerBarService, { + final session = await _pumpSearchRegression(tester, { 'a.md': 'Active document\n', 'b.md': 'First line\n${'[' * 40000}needle\n', }); - session.events.add(const HeaderBarSearchQueryChanged('needle')); + session.container.read(searchSessionProvider.notifier).query('needle'); await _waitForSearchCondition( tester, () => find.text(l10n.searchResultLine('b.md', 2)).evaluate().isNotEmpty, @@ -20883,7 +22068,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/search-scroll.md'), @@ -20971,7 +22155,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/large-preview.md'), @@ -21049,7 +22232,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/search-code-scroll.md'), @@ -21124,7 +22306,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/search-readme-scroll.md'), @@ -21196,7 +22377,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/list-spacing.md'), @@ -21281,7 +22461,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/nested-list.md'), @@ -21329,7 +22508,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/raw-html-table.md'), @@ -21374,7 +22552,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/aligned-table.md'), @@ -21422,7 +22599,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue('/tmp/search-readme-scroll.md'), @@ -21473,7 +22649,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. ProviderScope( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), workspaceServiceProvider.overrideWithValue(service), startupPathProvider.overrideWithValue( @@ -21505,16 +22680,12 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final temp = Directory.systemTemp.createTempSync('busymark_untitled_save_'); final saveFile = File('${temp.path}/created.md'); const editedText = '# Created\n\nDraft text.'; - const fileSelectorChannel = MethodChannel( - 'plugins.flutter.io/file_selector', - ); + const fileSelectorChannel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( fileSelectorChannel, (call) async { - expect(call.method, 'getSavePath'); - final args = call.arguments as Map; - expect(args['suggestedName'], l10n.untitledMarkdownFileName); - return saveFile.path; + expect(call.method, 'save'); + return SaveDestination.inspect(saveFile.path).chooserReview; }, ); addTearDown(() { @@ -21535,7 +22706,6 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), workspaceServiceProvider.overrideWithValue(service), ], @@ -21560,8 +22730,16 @@ Before [![Inline logo](inline-logo.png)](inline-guide.md) after. } final sourceField = find.byType(TextField).last; - await tester.tap(sourceField); - await tester.enterText(sourceField, editedText); + final editable = tester.widget( + find.descendant(of: sourceField, matching: find.byType(EditableText)), + ); + expect(editable.focusNode.hasPrimaryFocus, isTrue); + expect( + editable.controller.selection, + const TextSelection.collapsed(offset: 0), + ); + expect(tester.testTextInput.hasAnyClients, isTrue); + tester.testTextInput.enterText(editedText); await tester.pump(); expect(container.read(workspaceControllerProvider).activeText, editedText); @@ -21994,20 +23172,6 @@ class _NavigationHistoryStore extends MemoryLocalHistoryStore { } } -class _FallbackHeaderBarService extends LinuxHeaderBarService { - _FallbackHeaderBarService() - : super(channel: const MethodChannel('test.busymark/headerbar')); - - @override - bool get isAvailable => false; - - @override - bool get usesNativeHeaderBar => false; - - @override - Stream get actions => const Stream.empty(); -} - class _HistoryTestTimer implements Timer { _HistoryTestTimer(this.duration, this.callback); @@ -22062,6 +23226,7 @@ class _MutableWorkspaceController extends WorkspaceController { }) { state = state.copyWith( documentBuffers: [ + ...state.documentBuffers, DocumentBuffer( id: 'topic-rename-dirty', filePath: path, @@ -22070,12 +23235,16 @@ class _MutableWorkspaceController extends WorkspaceController { dirty: true, ), ], - activeBufferId: null, ); } - void clearDocumentBuffersForTest() { - state = state.copyWith(documentBuffers: const [], activeBufferId: null); + void removeProjectDirtyBufferForTest() { + state = state.copyWith( + documentBuffers: [ + for (final buffer in state.documentBuffers) + if (buffer.id != 'topic-rename-dirty') buffer, + ], + ); } @override @@ -22184,7 +23353,15 @@ class _MutableWorkspaceController extends WorkspaceController { edit.replacement, ); } - state = state.copyWith(activeText: source, isDirty: true); + state = state.copyWith( + documentBuffers: [ + for (final buffer in state.documentBuffers) + if (buffer.id == state.activeBufferId) + buffer.edited(source) + else + buffer, + ], + ); return true; } @@ -22296,9 +23473,17 @@ class _MutableWorkspaceController extends WorkspaceController { final activePath = refreshed.activeFilePath; state = WorkspaceState( workspace: refreshed, - activeText: activePath == null - ? '' - : File(activePath).readAsStringSync(), + documentBuffers: [ + if (activePath != null) + DocumentBuffer( + id: 'renamed', + filePath: activePath, + text: File(activePath).readAsStringSync(), + lastSavedText: File(activePath).readAsStringSync(), + dirty: false, + ), + ], + activeBufferId: activePath == null ? null : 'renamed', ); return true; } on Object catch (error) { @@ -22475,6 +23660,23 @@ class _MutableWorkspaceController extends WorkspaceController { } } +class _GatedResourceService extends _StartupWorkspaceService { + _GatedResourceService(this.gatedPath); + + final String gatedPath; + final entered = Completer(); + final release = Completer(); + + @override + Future openPath(String path) async { + if (path == gatedPath) { + entered.complete(); + await release.future; + } + return super.openPath(path); + } +} + class _StartupWorkspaceService extends WorkspaceService { String? openedPath; String? savedPath; @@ -22499,7 +23701,6 @@ class _StartupWorkspaceService extends WorkspaceService { kind: WorkspaceKind.singleMarkdown, openedAt: DateTime(2026), activeFilePath: path, - activeFileModifiedAt: DateTime(2026), files: [ DocumentFile( absolutePath: path, @@ -22561,6 +23762,21 @@ class _StartupWorkspaceService extends WorkspaceService { required WorkspaceFileSnapshot expectedSnapshot, }) => saveText(path, text); + @override + Future saveNewFormattedText( + String path, + String text, { + TextFormatMetadata? format, + LineEndingNormalization? mixedNormalization, + SaveDestination? authorization, + bool Function()? stillCurrent, + Future Function()? onPublished, + }) { + authorization?.requireCurrent(path); + expect(stillCurrent?.call(), isNot(false)); + return saveNewText(path, text, onPublished: onPublished); + } + @override Future saveNewText( String path, @@ -22640,7 +23856,7 @@ class _SwitchingGitController extends _PresetGitController { class _SwitchingSharedGitReadFixture extends SharedGitReadFixture { _SwitchingSharedGitReadFixture(String firstRoot) - : super(_gitSidebarShortcutState(firstRoot)); + : super(_gitSidebarShortcutState(firstRoot), commits: [_sidebarCommit]); @override Future discover( @@ -22671,6 +23887,7 @@ class _TabbedWorkspaceService extends WorkspaceService { final WorkspaceKind kind; final String rootPath; final List paths; + DateTime openedAt = DateTime(2026); final _sources = {}; String? savedPath; String? savedText; @@ -22692,9 +23909,8 @@ class _TabbedWorkspaceService extends WorkspaceService { id: rootPath, rootPath: rootPath, kind: kind, - openedAt: DateTime(2026), + openedAt: openedAt, activeFilePath: paths.first, - activeFileModifiedAt: DateTime(2026), openFilePaths: [paths.first], files: files, diagnostics: const [], @@ -22830,19 +24046,14 @@ BusyMarkSourceEditingController _searchSourceController(WidgetTester tester) => .whereType() .single; -Future< - ({ProviderContainer container, StreamController events}) -> -_pumpSearchRegression( +Future<({ProviderContainer container})> _pumpSearchRegression( WidgetTester tester, - LinuxHeaderBarService headerBar, Map sources, { Set oversized = const {}, Set unreadable = const {}, DocumentViewModePreference mode = DocumentViewModePreference.source, LocalHistoryStore? historyStore, }) async { - final events = StreamController.broadcast(); final settings = _MemorySettingsStore() ..value = AppSettings.defaults() .copyWith(autoSave: false, documentViewMode: mode) @@ -22854,8 +24065,6 @@ _pumpSearchRegression( workspaceFileMonitorProvider.overrideWith( (ref) => _SearchTestFileMonitor(), ), - linuxHeaderBarServiceProvider.overrideWithValue(headerBar), - headerBarSearchEventsProvider.overrideWith((ref) => events.stream), localSettingsStoreProvider.overrideWithValue(settings), if (historyStore != null) localHistoryStoreProvider.overrideWithValue(historyStore), @@ -22873,7 +24082,6 @@ _pumpSearchRegression( ); addTearDown(() { container.dispose(); - unawaited(events.close()); }); await tester.pumpWidget( UncontrolledProviderScope(container: container, child: const BusyMarkApp()), @@ -22882,13 +24090,16 @@ _pumpSearchRegression( tester, () => container.read(workspaceControllerProvider).activeBuffer != null && - find.byType(HeaderBarConfigurationPublisher).evaluate().isNotEmpty, + find + .byKey(const ValueKey('workspace-page-frame')) + .evaluate() + .isNotEmpty, ); container .read(searchSessionProvider.notifier) .open(category: SearchCategory.workspace); await tester.pump(); - return (container: container, events: events); + return (container: container); } class _SearchTestFileMonitor extends WorkspaceFileMonitor { @@ -22980,7 +24191,6 @@ class _SearchWorkspaceService extends WorkspaceService { kind: WorkspaceKind.singleMarkdown, openedAt: DateTime(2026), activeFilePath: path, - activeFileModifiedAt: DateTime(2026), files: [ DocumentFile( absolutePath: path, @@ -23033,7 +24243,6 @@ class _DeferredWorkspaceSearchService extends WorkspaceService { kind: WorkspaceKind.singleMarkdown, openedAt: DateTime(2026), activeFilePath: activePath, - activeFileModifiedAt: DateTime(2026), files: [ DocumentFile( absolutePath: activePath, @@ -23122,148 +24331,40 @@ class _PresetGitController extends GitController { } } - @override - Future> loadBranches() async { - branchLoadCount += 1; - return state.branches.isEmpty - ? const [ - GitBranch(name: 'main', current: true), - GitBranch(name: 'docs', current: false), - ] - : state.branches; - } - - @override - Future loadFileHistory(String absolutePath) async { - loadedFileHistoryPath = absolutePath; - final repositoryRoot = state.repositoryInfo?.rootPath; - final repoRelativePath = - repositoryRoot != null && absolutePath.startsWith('$repositoryRoot/') - ? absolutePath.substring(repositoryRoot.length + 1) - : absolutePath; - state = state.copyWith( - scopedFilePath: repoRelativePath, - selectedCommitFilePath: null, - openDiffFilePaths: const [], - selectedView: GitView.fileHistory, - fileHistory: GitFileHistoryState( - currentPath: repoRelativePath, - entries: [ - GitFileHistoryEntry( - commit: GitCommitSummary( - fullHash: '45a2b81a41822ad4171f62205ef996f5752a3bbd', - shortHash: '45a2b81', - authorName: 'BusyMark Test', - authorEmail: 'test@example.invalid', - authorDate: DateTime(2026), - subject: 'File history test commit', - parentHashes: const [], - ), - pathAtCommit: repoRelativePath, - pathInParent: repoRelativePath, - status: GitDiffFileStatus.modified, - ), - ], - ), - ); - } - @override Future stageFiles(List repoRelativePaths) async { stagedPaths = repoRelativePaths; } - - @override - Future compareFileHistoryWithCurrent() async { - compareWithCurrentCount += 1; - state = state.copyWith( - fileHistory: state.fileHistory.copyWith( - comparisonType: GitComparisonType.commitVersusCurrent, - ), - ); - } - - @override - Future selectFileHistoryCommit(String hash) async { - commitComparisonCount += 1; - state = state.copyWith( - fileHistory: state.fileHistory.copyWith( - selectedCommitHash: hash, - comparisonType: GitComparisonType.commitChange, - ), - ); - } } -GitState _gitFileHistoryDiffState(String rootPath) { - final repository = GitRepositoryInfo( - rootPath: rootPath, - gitDirPath: '$rootPath/.git', - currentBranch: 'main', - ); - const hash = '45a2b81a41822ad4171f62205ef996f5752a3bbd'; - final commit = GitCommitSummary( - fullHash: hash, - shortHash: '45a2b81', - authorName: 'BusyMark Test', - authorEmail: 'test@example.invalid', - authorDate: DateTime(2026), - subject: 'File history test commit', - parentHashes: const ['30af618a6e962623a0098ad6a33b468f33dc49c7'], - ); - final file = _readmeCodeBlockDiffFile(); - final diff = GitDiff( - title: 'README.md', - files: [file], - rawPatch: '', - hasBinaryFiles: false, - fileSnapshots: const {'README.md': '# Readme change\n'}, - ); - return GitState( - availability: const GitAvailability( - available: true, - executablePath: '/usr/bin/git', - version: '2.50.0', - ), - repositoryInfo: repository, - statusSnapshot: GitStatusSnapshot( - repositoryInfo: repository, - files: const [], - ), - selectedView: GitView.fileHistory, - scopedFilePath: 'README.md', - fileHistory: GitFileHistoryState( - currentPath: 'README.md', - entries: [ - GitFileHistoryEntry( - commit: commit, - pathAtCommit: 'README.md', - pathInParent: 'README.md', - status: GitDiffFileStatus.modified, - ), - ], - selectedCommitHash: hash, - comparison: GitHistoricalFileComparison( - oldPath: 'README.md', - newPath: 'README.md', - oldContent: '# Readme old\n', - newContent: '# Readme change\n', - diff: diff, - ), - ), - selectedCommitFilePath: 'README.md', - openDiffFilePaths: const ['README.md'], - ); -} +GitState _gitFileHistoryDiffState(String rootPath) => + _gitSidebarShortcutState(rootPath); +final _historyCommit = shared.GitCommit( + oid: shared.GitOid('45a2b81a41822ad4171f62205ef996f5752a3bbd'), + parents: [shared.GitOid('30af618a6e962623a0098ad6a33b468f33dc49c7')], + subject: 'File history test commit', + author: 'BusyMark Test', + email: 'test@example.invalid', + date: DateTime(2026), +); +final _sidebarCommit = shared.GitCommit( + oid: shared.GitOid('21e982c772a5cf43f4a99de6d7db9fb1283f50d1'), + parents: [], + subject: 'Sidebar history shortcut commit', + author: 'BusyMark Test', + email: 'test@example.invalid', + date: DateTime(2026), +); +final shared.Json _historyEntry = { + 'commit': _historyCommit.toJson(), + 'pathAtCommit': shared.RepoPath.text('README.md').toJson(), + 'pathInParent': shared.RepoPath.text('README.md').toJson(), +}; GitState _gitDiffState(String rootPath) { final repository = GitRepositoryInfo( rootPath: rootPath, gitDirPath: '$rootPath/.git', - currentBranch: 'main', - upstreamBranch: 'origin/main', - aheadCount: 2, - behindCount: 3, ); return GitState( availability: const GitAvailability( @@ -23292,102 +24393,6 @@ GitState _gitDiffState(String rootPath) { ), ], ), - selectedChange: const GitChangeSelection( - path: 'guide.md', - comparison: GitComparisonType.unstaged, - ), - changeDiff: GitDiff( - title: 'Update docs', - files: [ - _readmeCodeBlockDiffFile(), - _gitDiffFile('guide.md', '# Guide old', '# Guide change'), - ], - rawPatch: '', - hasBinaryFiles: false, - fileSnapshots: const { - 'README.md': - '# Readme change\n\n' - '```bash\n' - 'echo before\n' - 'echo added\n' - 'echo after\n' - '```\n\n' - 'Unchanged context after change.\n', - 'guide.md': '# Guide change\n\nGuide context.\n', - }, - ), - selectedCommitFilePath: 'guide.md', - openDiffFilePaths: const ['README.md', 'guide.md'], - ); -} - -GitDiffFile _readmeCodeBlockDiffFile() { - return const GitDiffFile( - oldPath: 'README.md', - newPath: 'README.md', - status: GitDiffFileStatus.modified, - hunks: [ - GitDiffHunk( - oldStart: 1, - oldCount: 1, - newStart: 1, - newCount: 1, - heading: 'git checkout 30af618a6e962623a0098ad6a33b468f33dc49c7', - lines: [ - GitDiffLine( - kind: GitDiffLineKind.removed, - content: '# Readme old', - oldLineNumber: 1, - ), - GitDiffLine( - kind: GitDiffLineKind.added, - content: '# Readme change', - newLineNumber: 1, - ), - ], - ), - GitDiffHunk( - oldStart: 3, - oldCount: 4, - newStart: 3, - newCount: 5, - heading: '', - lines: [ - GitDiffLine( - kind: GitDiffLineKind.context, - content: '```bash', - oldLineNumber: 3, - newLineNumber: 3, - ), - GitDiffLine( - kind: GitDiffLineKind.context, - content: 'echo before', - oldLineNumber: 4, - newLineNumber: 4, - ), - GitDiffLine( - kind: GitDiffLineKind.added, - content: 'echo added', - newLineNumber: 5, - ), - GitDiffLine( - kind: GitDiffLineKind.context, - content: 'echo after', - oldLineNumber: 5, - newLineNumber: 6, - ), - GitDiffLine( - kind: GitDiffLineKind.context, - content: '```', - oldLineNumber: 6, - newLineNumber: 7, - ), - ], - ), - ], - binary: false, - additions: 2, - deletions: 1, ); } @@ -23395,7 +24400,6 @@ GitState _gitSidebarShortcutState(String rootPath) { final repository = GitRepositoryInfo( rootPath: rootPath, gitDirPath: '$rootPath/.git', - currentBranch: 'main', ); return GitState( availability: const GitAvailability( @@ -23408,56 +24412,6 @@ GitState _gitSidebarShortcutState(String rootPath) { repositoryInfo: repository, files: const [], ), - projectHistory: GitProjectHistoryState( - commits: [ - GitCommitSummary( - fullHash: '21e982c772a5cf43f4a99de6d7db9fb1283f50d1', - shortHash: '21e982c', - authorName: 'BusyMark Test', - authorEmail: 'test@example.invalid', - authorDate: DateTime(2026), - subject: 'Sidebar history shortcut commit', - parentHashes: const [], - ), - ], - ), - ); -} - -GitDiffFile _gitDiffFile( - String path, - String oldContent, - String newContent, { - String hunkHeading = '', -}) { - return GitDiffFile( - oldPath: path, - newPath: path, - status: GitDiffFileStatus.modified, - hunks: [ - GitDiffHunk( - oldStart: 1, - oldCount: 1, - newStart: 1, - newCount: 3, - heading: hunkHeading, - lines: [ - GitDiffLine( - kind: GitDiffLineKind.removed, - content: oldContent, - oldLineNumber: 1, - ), - GitDiffLine( - kind: GitDiffLineKind.added, - content: newContent, - newLineNumber: 1, - ), - ], - ), - ], - binary: false, - additions: 1, - deletions: 1, ); } @@ -23547,7 +24501,6 @@ class _SettingsSpellingHarness { Future<_SettingsSpellingHarness> _pumpSettingsSpellingHarness( WidgetTester tester, { - required LinuxHeaderBarService headerBarService, required _MemorySettingsStore settingsStore, required SpellingDictionaryFileDownload downloadFile, String? projectLanguage, @@ -23606,7 +24559,6 @@ Future<_SettingsSpellingHarness> _pumpSettingsSpellingHarness( final container = ProviderContainer( overrides: [ ..._smokeAccentOverrides, - linuxHeaderBarServiceProvider.overrideWithValue(headerBarService), localSettingsStoreProvider.overrideWithValue(settingsStore), systemAccentColorProvider.overrideWith((ref) => const Stream.empty()), spellingSessionControllerProvider.overrideWith((ref) => spelling), @@ -23843,9 +24795,8 @@ final _smokeAccentOverrides = [ : ref.read(gitControllerProvider); return SharedGitReadFixture( state, - fileHistoryState: state.repositoryInfo == null - ? null - : _gitFileHistoryDiffState(state.repositoryInfo!.rootPath), + commits: [_sidebarCommit], + fileHistory: [_historyEntry], ); }, ), @@ -23858,7 +24809,8 @@ final _smokeAccentOverrides = [ ]; class _SearchableGitReadFixture extends SharedGitReadFixture { - _SearchableGitReadFixture(super.state); + _SearchableGitReadFixture(super.state) + : super(commits: [_sidebarCommit], fileHistory: [_historyEntry]); Completer? discoveryGate; shared.GitException? discoveryError; final discoveryEntered = Completer(); @@ -24091,6 +25043,10 @@ Future _chooseNativeGitMenu( class _HistoryComparisonReadFixture extends _ComparisonTabReadFixture { _HistoryComparisonReadFixture(super.state); @override + List get commits => [_historyCommit]; + @override + List get fileHistory => [_historyEntry]; + @override Future content( shared.RepositoryId repository, shared.RepoPath path, @@ -24105,7 +25061,7 @@ class _HistoryComparisonReadFixture extends _ComparisonTabReadFixture { cancellation: cancellation, ); } - final entry = state.fileHistory.entries.single; + final entry = _historyCommit; return shared.GitContent( path: path, version: version, @@ -24113,7 +25069,7 @@ class _HistoryComparisonReadFixture extends _ComparisonTabReadFixture { token: version.label, mode: '100644', bytes: utf8.encode( - version.revision?.value == entry.commit.parentHashes.single + version.revision?.value == entry.parents.single.value ? '# Before\nold text\n' : '# After\nneedle comparison\n', ), @@ -24128,3 +25084,21 @@ Future _executeViewCommand(WidgetTester tester, String id) async { final container = ProviderScope.containerOf(context, listen: false); await container.read(busyMarkCommandRegistryProvider).execute(id); } + +Future _withControlledImageClient( + Future Function(ControlledImageHttpClient) run, +) async { + final previous = debugNetworkImageHttpClientProvider; + final client = ControlledImageHttpClient(); + final cache = PaintingBinding.instance.imageCache; + cache.clear(); + cache.clearLiveImages(); + debugNetworkImageHttpClientProvider = () => client; + try { + await run(client); + } finally { + debugNetworkImageHttpClientProvider = previous; + cache.clear(); + cache.clearLiveImages(); + } +} diff --git a/test/src/asset_ingestion_service_test.dart b/test/src/asset_ingestion_service_test.dart index 62485116..a12cbfd0 100644 --- a/test/src/asset_ingestion_service_test.dart +++ b/test/src/asset_ingestion_service_test.dart @@ -12,6 +12,75 @@ void main() { 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', ); + test( + 'cross-process lock contention leaves the Dart event loop responsive', + () async { + final root = await Directory.systemTemp.createTemp( + 'asset-lock-contention-', + ); + addTearDown(() => root.delete(recursive: true)); + final document = File(p.join(root.path, 'note.md')) + ..writeAsStringSync(''); + final lock = File( + p.join( + root.path, + 'images', + '.busymark-asset-transactions', + 'directory.lock', + ), + ); + await lock.parent.create(recursive: true); + final holder = await Process.start('python3', [ + '-c', + 'import fcntl,sys,time\nf=open(sys.argv[1],"a")\nfcntl.lockf(f,fcntl.LOCK_EX)\nprint("locked",flush=True)\ntime.sleep(1.5)', + lock.path, + ]); + addTearDown(() => holder.kill()); + expect( + await holder.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .first, + 'locked', + ); + final clock = Stopwatch()..start(); + final publication = const AssetIngestionService().ingestBytes( + bytes: png, + suggestedFileName: 'image.png', + request: AssetIngestionRequest( + documentFilePath: document.path, + workspaceKind: AssetWorkspaceKind.standalone, + ), + origin: AssetIngestionOrigin.screenshotPaste, + ); + await Future.delayed(const Duration(milliseconds: 100)); + expect( + clock.elapsedMilliseconds, + lessThan(1000), + reason: 'Lock waiting must not block the event loop', + ); + expect( + File(p.join(root.path, 'images', 'image.png')).existsSync(), + isFalse, + ); + expect(await holder.exitCode, 0); + final asset = await publication; + await const AssetIngestionService().commit(asset); + expect(await File(asset.absolutePath).readAsBytes(), png); + // A second operation proves that the lock descriptor was released. + final reused = await const AssetIngestionService().ingestBytes( + bytes: png, + suggestedFileName: 'image.png', + request: AssetIngestionRequest( + documentFilePath: document.path, + workspaceKind: AssetWorkspaceKind.standalone, + ), + origin: AssetIngestionOrigin.screenshotPaste, + ); + expect(reused.reusedExisting, isTrue); + }, + ); + test('ingests workspace images with safe names and portable paths', () async { final workspace = await Directory.systemTemp.createTemp('busymark-assets-'); addTearDown(() => workspace.delete(recursive: true)); diff --git a/test/src/busymark_design_test.dart b/test/src/busymark_design_test.dart index c9fd6013..b527b7b3 100644 --- a/test/src/busymark_design_test.dart +++ b/test/src/busymark_design_test.dart @@ -2333,7 +2333,7 @@ void main() { isEmpty, ); expect(popups.every((popup) => !popup.transparent), isTrue); - expect(popups.every((popup) => popup.elevated), isTrue); + expect(popups.every((popup) => !popup.elevated), isTrue); expect( popups.every( (popup) => popup.foregroundColor == BusyMarkLinuxPalette.white, @@ -2428,7 +2428,7 @@ void main() { ); expect(actions, isNotEmpty); expect(actions.every((button) => !button.transparent), isTrue); - expect(actions.every((button) => button.elevated), isTrue); + expect(actions.every((button) => !button.elevated), isTrue); expect( actions.every( (button) => button.foregroundColor == BusyMarkLinuxPalette.white, @@ -2454,19 +2454,30 @@ void main() { find.descendant(of: toolbar, matching: find.byType(YaruIconButton)), ); expect(renderedButtons, isNotEmpty); - final expectedElevation = - theme.cardTheme.elevation ?? BusyMarkElevation.surface; + expect( + find.descendant( + of: toolbar, + matching: find.byWidgetPredicate( + (widget) => widget is PhysicalShape && widget.elevation > 0, + ), + ), + findsNothing, + ); for (final button in renderedButtons) { - expect(button.style?.backgroundColor?.resolve({}), accent); - expect(button.style?.elevation?.resolve({}), expectedElevation); - expect( - button.style?.shadowColor?.resolve({}), - theme.colorScheme.shadow, - ); - expect( - button.style?.surfaceTintColor?.resolve({}), - BusyMarkLinuxPalette.transparent, - ); + for (final states in [ + {}, + {WidgetState.hovered}, + {WidgetState.pressed}, + {WidgetState.focused}, + {WidgetState.disabled}, + ]) { + expect(button.style?.elevation?.resolve(states), isNull); + expect(button.style?.shadowColor?.resolve(states), isNull); + expect( + button.style?.backgroundColor?.resolve(states), + states.contains(WidgetState.disabled) ? disabledBackground : accent, + ); + } expect( button.style?.foregroundColor?.resolve({}), BusyMarkLinuxPalette.white, diff --git a/test/src/busymark_dialogs_test.dart b/test/src/busymark_dialogs_test.dart index 9977ea03..b3db7324 100644 --- a/test/src/busymark_dialogs_test.dart +++ b/test/src/busymark_dialogs_test.dart @@ -1,15 +1,12 @@ import 'package:busymark/src/app/command_registry.dart'; import 'package:busymark/src/app/keymap_controller.dart'; import 'package:busymark/src/app/shortcut_binding.dart'; -import 'dart:async'; import 'package:busymark/src/app/app_theme.dart'; import 'package:busymark/src/app/busymark_design.dart'; import 'package:busymark/src/app/busymark_dialogs.dart'; import 'package:busymark/src/app/busymark_shortcuts.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -17,28 +14,7 @@ import '../support/desktop_focus.dart'; void main() { _delayedModalFocusRegressions(); - testWidgets('delayed modal barrier release respects a newer focus owner', ( - tester, - ) async { - const channel = MethodChannel('com.busymark.test/focus-modal-barrier'); - final release = Completer(); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( - call, - ) async { - if (call.method == 'initialize') return true; - if (call.method == 'setModalBarrierDepth' && call.arguments == 0) { - await release.future; - } - return null; - }); - addTearDown( - () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - channel, - null, - ), - ); - final service = LinuxHeaderBarService(channel: channel); - await service.initialize(); + testWidgets('modal closure respects a newer focus owner', (tester) async { final previous = FocusNode(); final newer = FocusNode(); addTearDown(previous.dispose); @@ -65,7 +41,6 @@ void main() { await tester.pumpAndSettle(); final result = showBusyMarkModalDialog( host, - headerBarService: service, builder: (_) => const Text('Modal focus test'), ); await tester.pumpAndSettle(); @@ -74,7 +49,6 @@ void main() { newer.requestFocus(); await tester.pumpAndSettle(); expect(FocusManager.instance.primaryFocus, same(newer)); - release.complete(); await result; await tester.pumpAndSettle(); expect(FocusManager.instance.primaryFocus, same(newer)); @@ -152,20 +126,6 @@ void main() { ); testWidgets('modal dialogs stop app and editor shortcuts', (tester) async { - const channel = MethodChannel('com.busymark.test/modal-shortcuts'); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( - call, - ) async { - return call.method == 'initialize' ? true : null; - }); - addTearDown(() { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - channel, - null, - ); - }); - final headerBar = LinuxHeaderBarService(channel: channel); - await headerBar.initialize(); var appShortcutInvocations = 0; var editorShortcutInvocations = 0; @@ -205,7 +165,6 @@ void main() { onPressed: () { showBusyMarkModalDialog( context, - headerBarService: headerBar, builder: (dialogContext) => TextButton( autofocus: true, onPressed: () => Navigator.pop(dialogContext), @@ -298,195 +257,6 @@ void main() { await result; }); - testWidgets('overlapping dialogs synchronize native modal depth', ( - tester, - ) async { - const channel = MethodChannel('com.busymark.test/modal-barrier'); - final barrierDepths = []; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( - call, - ) async { - if (call.method == 'initialize') { - return true; - } - if (call.method == 'setModalBarrierDepth') { - barrierDepths.add(call.arguments as int); - } - return null; - }); - addTearDown(() { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - channel, - null, - ); - }); - final headerBar = LinuxHeaderBarService(channel: channel); - await headerBar.initialize(); - late BuildContext hostContext; - - await tester.pumpWidget( - MaterialApp( - home: Builder( - builder: (context) { - hostContext = context; - return const Scaffold(body: SizedBox.expand()); - }, - ), - ), - ); - - final first = showBusyMarkModalDialog( - hostContext, - headerBarService: headerBar, - builder: (_) => const Text('First dialog'), - ); - await tester.pumpAndSettle(); - final second = showBusyMarkModalDialog( - hostContext, - headerBarService: headerBar, - builder: (_) => const Text('Second dialog'), - ); - await tester.pumpAndSettle(); - - expect(barrierDepths, [1, 2]); - - Navigator.of(hostContext, rootNavigator: true).pop(); - await tester.pumpAndSettle(); - await second; - expect(barrierDepths, [1, 2, 1]); - - Navigator.of(hostContext, rootNavigator: true).pop(); - await tester.pumpAndSettle(); - await first; - expect(barrierDepths, [1, 2, 1, 0]); - }); - - testWidgets('serializes rapid manual native barrier transitions', ( - tester, - ) async { - const channel = MethodChannel('com.busymark.test/serialized-modal-barrier'); - final firstUpdate = Completer(); - final transitions = []; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( - call, - ) async { - if (call.method == 'initialize') { - return true; - } - if (call.method == 'setModalBarrierDepth') { - transitions.add(call.arguments as int); - if (transitions.length == 1) { - await firstUpdate.future; - } - } - return null; - }); - addTearDown(() { - if (!firstUpdate.isCompleted) { - firstUpdate.complete(); - } - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - channel, - null, - ); - }); - final headerBar = LinuxHeaderBarService(channel: channel); - addTearDown(headerBar.dispose); - await headerBar.initialize(); - - final acquire = acquireBusyMarkModalBarrier(headerBar); - await tester.pump(); - expect(transitions, [1]); - - final release = releaseBusyMarkModalBarrier(headerBar); - await tester.pump(); - expect(transitions, [ - 1, - ], reason: 'the native hide must wait for the in-flight native show'); - - firstUpdate.complete(); - await Future.wait([acquire, release]); - expect(transitions, [1, 0]); - }); - - testWidgets('failed native barrier acquisition rolls back and can retry', ( - tester, - ) async { - final headerBar = _FailingModalBarrierService(); - addTearDown(headerBar.dispose); - - await expectLater( - acquireBusyMarkModalBarrier(headerBar), - throwsA(isA()), - ); - expect(headerBar.transitions, [1, 0]); - - await acquireBusyMarkModalBarrier(headerBar); - await releaseBusyMarkModalBarrier(headerBar); - expect(headerBar.transitions, [1, 0, 1, 0]); - }); - - testWidgets('modal coordinator resolves the service from ProviderScope', ( - tester, - ) async { - const channel = MethodChannel('com.busymark.test/automatic-modal-barrier'); - final calls = []; - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( - call, - ) async { - calls.add(call); - return call.method == 'initialize' ? true : null; - }); - addTearDown(() { - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - channel, - null, - ); - }); - final headerBar = LinuxHeaderBarService(channel: channel); - addTearDown(headerBar.dispose); - await headerBar.initialize(); - late BuildContext hostContext; - - await tester.pumpWidget( - ProviderScope( - overrides: [linuxHeaderBarServiceProvider.overrideWithValue(headerBar)], - child: MaterialApp( - home: Builder( - builder: (context) { - hostContext = context; - return const Scaffold(body: SizedBox.expand()); - }, - ), - ), - ), - ); - - final result = showBusyMarkModalDialog( - hostContext, - builder: (_) => const Text('Automatic barrier dialog'), - ); - await tester.pumpAndSettle(); - - expect( - calls - .where((call) => call.method == 'setModalBarrierDepth') - .map((call) => call.arguments), - [1], - ); - - Navigator.of(hostContext, rootNavigator: true).pop(); - await tester.pumpAndSettle(); - await result; - - expect( - calls - .where((call) => call.method == 'setModalBarrierDepth') - .map((call) => call.arguments), - [1, 0], - ); - }); - testWidgets('open modal barrier follows live theme changes', (tester) async { const accent = Color(0xFF3584E4); final lightTheme = buildBusyMarkTheme( @@ -603,12 +373,9 @@ void _delayedModalFocusRegressions() { 'disposed host', 'ordinary return', ]) { - testWidgets('deferred modal focus respects $scenario', (tester) async { + testWidgets('modal focus respects $scenario', (tester) async { enableDesktopFocusLifecycle(tester); - final barrier = _GatedFocusBarrierService(); - addTearDown(barrier.dispose); addTearDown(() { - if (!barrier.release.isCompleted) barrier.release.complete(); tester.binding.handleAppLifecycleStateChanged( AppLifecycleState.resumed, ); @@ -641,7 +408,6 @@ void _delayedModalFocusRegressions() { await tester.pumpAndSettle(); final dialog = showBusyMarkModalDialog( host, - headerBarService: barrier, builder: (_) => const AlertDialog(content: Text('Dismiss focus race')), ); await tester.pumpAndSettle(); @@ -651,7 +417,6 @@ void _delayedModalFocusRegressions() { FocusManager.instance.applyFocusChangesIfNeeded(); } await tester.pumpAndSettle(); - expect(barrier.releaseStarted, isTrue); if (scenario.contains('newer')) { newer.requestFocus(); await tester.pumpAndSettle(); @@ -685,7 +450,6 @@ void _delayedModalFocusRegressions() { await tester.pumpWidget(const SizedBox()); } final owner = FocusManager.instance.primaryFocus; - barrier.release.complete(); await dialog; for (var frame = 0; frame < 30; frame++) { await tester.pump(const Duration(milliseconds: 16)); @@ -716,33 +480,3 @@ void _delayedModalFocusRegressions() { }, variant: TargetPlatformVariant.only(TargetPlatform.linux)); } } - -class _GatedFocusBarrierService extends LinuxHeaderBarService { - _GatedFocusBarrierService() - : super(channel: const MethodChannel('com.busymark.test/deferred-focus')); - - final release = Completer(); - bool releaseStarted = false; - - @override - Future setModalBarrierDepth(int depth) async { - if (depth == 0) { - releaseStarted = true; - await release.future; - } - } -} - -class _FailingModalBarrierService extends LinuxHeaderBarService { - final transitions = []; - var _failNextShow = true; - - @override - Future setModalBarrierDepth(int value) async { - transitions.add(value); - if (value > 0 && _failNextShow) { - _failNextShow = false; - throw StateError('simulated native modal-barrier failure'); - } - } -} diff --git a/test/src/busymark_document_test.dart b/test/src/busymark_document_test.dart index a12c06ae..faa5ad3b 100644 --- a/test/src/busymark_document_test.dart +++ b/test/src/busymark_document_test.dart @@ -1,8 +1,10 @@ -import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:ui' show CheckedState; +import '../support/controlled_image_http_client.dart'; +import '../support/document_history_harness.dart'; + import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/l10n/generated/app_localizations_de.dart'; import 'package:busymark/l10n/generated/app_localizations_en.dart'; @@ -17,6 +19,7 @@ import 'package:busymark/src/editor/document_layout.dart'; import 'package:busymark/src/editor/document_list_marker.dart'; import 'package:busymark/src/editor/document_text_geometry.dart'; import 'package:busymark/src/editor/markdown_image_view.dart'; +import 'package:busymark/src/editor/markdown_image_permission_scope.dart'; import 'package:busymark/src/editor/wysiwyg/wysiwyg_block_widgets.dart'; import 'package:busymark/src/editor/wysiwyg/wysiwyg_commands.dart'; import 'package:busymark/src/editor/wysiwyg/wysiwyg_document_controller.dart'; @@ -30,7 +33,6 @@ import 'package:busymark/src/markdown/document_outline.dart'; import 'package:busymark/src/markdown/markdown_model.dart'; import 'package:busymark/src/markdown/markdown_parser.dart'; import 'package:busymark/src/markdown/preview_model.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -1493,6 +1495,8 @@ void main() {} ) async { final parsed = parser.parse(filePath: 'topic.md', source: 'Original\n'); var markdown = parsed.source; + final history = await DocumentHistoryHarness.create(source: markdown); + addTearDown(history.dispose); await tester.pumpWidget( MaterialApp( @@ -1504,7 +1508,25 @@ void main() {} height: 640, child: BusyMarkWysiwygEditor( document: parsed.busyDocument, - onSourceChanged: (filePath, value) => markdown = value, + readEditBase: history.readBase, + readSessionState: () => history.buffer.editorState.wysiwygState, + onUndo: () { + history.controller.undoActiveBuffer(); + markdown = history.buffer.text; + }, + onRedo: () { + history.controller.redoActiveBuffer(); + markdown = history.buffer.text; + }, + onSessionChanged: (_, value) => + history.controller.updateDocumentEditorState( + history.buffer.id, + history.buffer.editorState.copyWith(wysiwygState: value), + ), + onSourceChanged: (filePath, value) { + history.controller.updateActiveText(value); + markdown = value; + }, ), ), ), @@ -1512,6 +1534,14 @@ void main() {} ); await tester.pump(); + await tester.tap(find.byType(TextField).first); + tester + .widget(find.byType(TextField).first) + .controller! + .selection = const TextSelection.collapsed( + offset: 2, + ); + await tester.pump(); await tester.enterText(find.byType(TextField).first, 'Changed'); await tester.pump(); @@ -1567,9 +1597,19 @@ void main() {} filePath: 'second.md', source: 'Second original\n', ); + final firstHistory = await DocumentHistoryHarness.create( + source: first.source, + ); + final secondHistory = await DocumentHistoryHarness.create( + source: second.source, + ); + addTearDown(firstHistory.dispose); + addTearDown(secondHistory.dispose); + var activeHistory = firstHistory; var activeDocument = first.busyDocument; Widget buildEditor() { + final history = activeHistory; return MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, @@ -1579,7 +1619,18 @@ void main() {} height: 640, child: BusyMarkWysiwygEditor( document: activeDocument, - onSourceChanged: (_, _) {}, + documentId: history.buffer.id, + readEditBase: history.readBase, + readSessionState: () => history.buffer.editorState.wysiwygState, + onUndo: history.controller.undoActiveBuffer, + onRedo: history.controller.redoActiveBuffer, + onSessionChanged: (_, value) => + history.controller.updateDocumentEditorState( + history.buffer.id, + history.buffer.editorState.copyWith(wysiwygState: value), + ), + onSourceChanged: (_, value) => + history.controller.updateActiveText(value), ), ), ), @@ -1598,6 +1649,7 @@ void main() {} ); activeDocument = second.busyDocument; + activeHistory = secondHistory; await tester.pumpWidget(buildEditor()); await tester.pump(); @@ -1616,6 +1668,9 @@ void main() {} tester.widget(find.byType(TextField).first).controller?.text, 'Second original', ); + expect(firstHistory.buffer.text, 'Unsaved first tab\n'); + expect(firstHistory.buffer.editorState.undoState.undo, hasLength(1)); + expect(secondHistory.buffer.editorState.undoState.undo, isEmpty); }); testWidgets('WYSIWYG editor applies heading keyboard shortcuts', ( @@ -4108,66 +4163,6 @@ void main() {} expect(find.text(l10n.editHtml), findsOneWidget); }); - testWidgets('WYSIWYG dialogs activate the native headerbar barrier', ( - tester, - ) async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel('com.busymark.test/wysiwyg-modal-barrier'); - final calls = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call); - return call.method == 'initialize' ? true : null; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - final headerBarService = LinuxHeaderBarService(channel: channel); - await headerBarService.initialize(); - final l10n = AppLocalizationsEn(); - final parsed = parser.parse(filePath: 'topic.md', source: 'Start\n'); - - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: SizedBox( - width: 900, - height: 640, - child: BusyMarkWysiwygEditor( - document: parsed.busyDocument, - toolbarPlacement: EditorToolbarPlacement.bottomLeft, - headerBarService: headerBarService, - onSourceChanged: (_, _) {}, - ), - ), - ), - ), - ); - await tester.pumpAndSettle(); - - await tester.tap(find.byType(TextField).first); - await tester.tap(find.byTooltip(l10n.htmlBlock)); - await tester.pumpAndSettle(); - - expect( - calls.where((call) => call.method == 'setModalBarrierDepth').last, - isA().having((call) => call.arguments, 'arguments', 1), - ); - - await tester.tap(find.text(l10n.cancel)); - await tester.pumpAndSettle(); - - expect( - calls.where((call) => call.method == 'setModalBarrierDepth').last, - isA().having((call) => call.arguments, 'arguments', 0), - ); - }); - testWidgets('WYSIWYG typing preserves existing inline formatting', ( tester, ) async { @@ -5347,49 +5342,74 @@ void main() {} } }); - testWidgets('WYSIWYG editor renders linked remote image blocks', ( - tester, - ) async { - const imageUrl = 'https://example.com/remote.png'; - final previousHttpClientProvider = debugNetworkImageHttpClientProvider; - final parsed = parser.parse( - filePath: 'README.md', - source: '[![busymark]($imageUrl)](https://snapcraft.io/busymark)\n', - ); + testWidgets( + 'WYSIWYG linked remote images request permission before rendering', + (tester) async { + const imageUrl = 'https://example.com/remote.png'; + final previousHttpClientProvider = debugNetworkImageHttpClientProvider; + final parsed = parser.parse( + filePath: 'README.md', + source: '[![busymark]($imageUrl)](https://snapcraft.io/busymark)\n', + ); - try { - debugNetworkImageHttpClientProvider = () => _FakeImageHttpClient(); - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold( - body: SizedBox( - width: 900, - height: 640, - child: BusyMarkWysiwygEditor( - document: parsed.busyDocument, - allowRemoteImages: true, - onSourceChanged: (_, _) {}, + try { + debugNetworkImageHttpClientProvider = () => ControlledImageHttpClient(); + var requests = 0; + Future render({required bool allow}) => tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 900, + height: 640, + child: MarkdownImagePermissionScope( + resolve: (_, _, _) => MarkdownImageActions( + allowed: allow, + openMenu: (_, _, _) async { + requests++; + }, + ), + child: BusyMarkWysiwygEditor( + document: parsed.busyDocument, + allowRemoteImages: allow, + onSourceChanged: (_, _) {}, + ), + ), ), ), ), - ), - ); - await tester.pump(); + ); + await render(allow: false); + await tester.pump(); + final denied = find.text( + AppLocalizations.of( + tester.element(find.byType(MarkdownImageView)), + ).remoteImageBlocked, + ); + expect(denied, findsOneWidget); + expect(find.byType(Image), findsNothing); + await tester.tap(denied); + await tester.pump(); + expect(requests, 1); + expect(denied, findsOneWidget); - final imageView = tester.widget( - find.byType(MarkdownImageView), - ); - expect(imageView.source, imageUrl); - expect(imageView.alt, 'busymark'); - expect(find.byType(Image), findsOneWidget); - expect(find.text(imageUrl), findsNothing); - expect(find.byType(TextField), findsNothing); - } finally { - debugNetworkImageHttpClientProvider = previousHttpClientProvider; - } - }); + await render(allow: true); + await tester.pump(); + expect(denied, findsNothing); + final imageView = tester.widget( + find.byType(MarkdownImageView), + ); + expect(imageView.source, imageUrl); + expect(imageView.alt, 'busymark'); + expect(find.byType(Image), findsOneWidget); + expect(find.text(imageUrl), findsNothing); + expect(find.byType(TextField), findsNothing); + } finally { + debugNetworkImageHttpClientProvider = previousHttpClientProvider; + } + }, + ); for (final mode in MarkdownMode.values) { test('WYSIWYG Enter recognizes a pasted bare URL in ${mode.name}', () { @@ -6506,6 +6526,10 @@ void main() {} (tester) async { final parsed = parser.parse(filePath: 'topic.md', source: 'Alpha Beta\n'); var markdown = parsed.source; + final history = await DocumentHistoryHarness.create( + source: parsed.source, + ); + addTearDown(history.dispose); await tester.pumpWidget( MaterialApp( @@ -6517,7 +6541,25 @@ void main() {} height: 640, child: BusyMarkWysiwygEditor( document: parsed.busyDocument, - onSourceChanged: (filePath, value) => markdown = value, + readEditBase: history.readBase, + readSessionState: () => history.buffer.editorState.wysiwygState, + onUndo: () { + history.controller.undoActiveBuffer(); + markdown = history.buffer.text; + }, + onRedo: () { + history.controller.redoActiveBuffer(); + markdown = history.buffer.text; + }, + onSessionChanged: (_, value) => + history.controller.updateDocumentEditorState( + history.buffer.id, + history.buffer.editorState.copyWith(wysiwygState: value), + ), + onSourceChanged: (_, value) { + history.controller.updateActiveText(value); + markdown = value; + }, ), ), ), @@ -7825,65 +7867,3 @@ Future _pressControlShortcut( class _TestTabIntent extends Intent { const _TestTabIntent(); } - -class _FakeImageHttpClient implements HttpClient { - @override - Future getUrl(Uri url) async => _FakeImageRequest(); - - @override - dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); -} - -class _FakeImageRequest implements HttpClientRequest { - @override - HttpHeaders get headers => _FakeImageHeaders(); - - @override - Future close() async => _FakeImageResponse(); - - @override - dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); -} - -class _FakeImageHeaders implements HttpHeaders { - @override - void add(String name, Object value, {bool preserveHeaderCase = false}) {} - - @override - dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); -} - -class _FakeImageResponse extends Stream> - implements HttpClientResponse { - static final _bytes = base64Decode( - 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l8Kz3wAAAABJRU5ErkJggg==', - ); - - @override - int get statusCode => HttpStatus.ok; - - @override - int get contentLength => _bytes.length; - - @override - HttpClientResponseCompressionState get compressionState => - HttpClientResponseCompressionState.notCompressed; - - @override - StreamSubscription> listen( - void Function(List event)? onData, { - Function? onError, - void Function()? onDone, - bool? cancelOnError, - }) { - return Stream>.fromIterable([_bytes]).listen( - onData, - onError: onError, - onDone: onDone, - cancelOnError: cancelOnError, - ); - } - - @override - dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); -} diff --git a/test/src/clipboard_history_panel_test.dart b/test/src/clipboard_history_panel_test.dart index f759a528..6fb361b3 100644 --- a/test/src/clipboard_history_panel_test.dart +++ b/test/src/clipboard_history_panel_test.dart @@ -199,8 +199,9 @@ void main() { .map((entry) => entry.id) .toList(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyEvent(LogicalKeyboardKey.f10); - expect(_menus.isOpen, isFalse, reason: 'GTK opens after modifier release'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.f10); + expect(_menus.isOpen, isTrue, reason: 'GTK opens on keydown'); + await tester.sendKeyUpEvent(LogicalKeyboardKey.f10); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); await tester.pump(); expect(_menus.contains('Paste'), isTrue); diff --git a/test/src/clipboard_layout_table_test.dart b/test/src/clipboard_layout_table_test.dart index cb48bc14..5f5fc5bc 100644 --- a/test/src/clipboard_layout_table_test.dart +++ b/test/src/clipboard_layout_table_test.dart @@ -80,20 +80,23 @@ void main() { '', mode: MarkdownMode.gfm, )!; - expect(decoded.documentBlocks.map((block) => block.plainText), [ + final layout = decoded.documentBlocks.single; + final paragraphs = [ + for (final child in layout.children) + child.kind == BusyBlockKind.htmlBlock ? child.children.single : child, + ]; + expect(paragraphs.map((block) => block.plainText), [ 'Caption', 'First', 'Second', ]); - expect(decoded.documentBlocks.map((block) => block.attributes['dir']), [ + expect(paragraphs.map((block) => block.attributes['dir']), [ 'rtl', 'rtl', 'ltr', ]); expect( - decoded.documentBlocks.every( - (block) => block.kind == BusyBlockKind.paragraph, - ), + paragraphs.every((block) => block.kind == BusyBlockKind.paragraph), isTrue, ); }, @@ -119,7 +122,9 @@ void main() { hasLength(1), ); expect( - blocks.where((block) => block.kind == BusyBlockKind.unorderedListItem), + blocks + .expand((block) => block.children) + .where((block) => block.kind == BusyBlockKind.unorderedListItem), hasLength(3), ); diff --git a/test/src/clipboard_paste_resolver_test.dart b/test/src/clipboard_paste_resolver_test.dart index 6d6c65b5..8119fd52 100644 --- a/test/src/clipboard_paste_resolver_test.dart +++ b/test/src/clipboard_paste_resolver_test.dart @@ -157,7 +157,7 @@ void main() { const expectedKinds = [ BusyBlockKind.heading, BusyBlockKind.paragraph, - BusyBlockKind.unorderedListItem, + BusyBlockKind.writersideRawXml, BusyBlockKind.paragraph, BusyBlockKind.table, BusyBlockKind.paragraph, diff --git a/test/src/deferred_creation_focus_test.dart b/test/src/deferred_creation_focus_test.dart new file mode 100644 index 00000000..c02226de --- /dev/null +++ b/test/src/deferred_creation_focus_test.dart @@ -0,0 +1,83 @@ +import 'package:busymark/src/app/busymark_deferred_editor_focus.dart'; +import 'package:busymark/src/app/busymark_dialogs.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + for (final interruption in ['another field', 'a modal', 'app deactivation']) { + testWidgets('a creation focus request expires after $interruption', ( + tester, + ) async { + BusyMarkDeferredEditorFocus? pending; + bool? consumed; + addTearDown(() => pending?.cancel()); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => Column( + children: [ + const TextField( + decoration: InputDecoration(labelText: 'First field'), + ), + const TextField( + decoration: InputDecoration(labelText: 'Other field'), + ), + TextButton( + onPressed: () => pending = BusyMarkDeferredEditorFocus(), + child: const Text('Capture creation'), + ), + TextButton( + onPressed: () => consumed = pending!.consume(context), + child: const Text('Claim creation'), + ), + TextButton( + onPressed: () => showBusyMarkModalDialog( + context, + builder: (context) => AlertDialog( + content: TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Close intervening dialog'), + ), + ), + ), + child: const Text('Open intervening dialog'), + ), + ], + ), + ), + ), + ), + ); + await tester.tap(find.widgetWithText(TextField, 'First field')); + await tester.pump(); + // Capture from the button callback without asking the new editor to focus. + tester + .widget( + find.widgetWithText(TextButton, 'Capture creation'), + ) + .onPressed!(); + if (interruption == 'another field') { + await tester.tap(find.widgetWithText(TextField, 'Other field')); + await tester.pump(); + } else if (interruption == 'a modal') { + await tester.tap(find.text('Open intervening dialog')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Close intervening dialog')); + await tester.pumpAndSettle(); + } else { + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.inactive, + ); + tester.binding.handleAppLifecycleStateChanged( + AppLifecycleState.resumed, + ); + await tester.pump(); + } + tester + .widget(find.widgetWithText(TextButton, 'Claim creation')) + .onPressed!(); + expect(consumed, isFalse); + }); + } +} diff --git a/test/src/external_clipboard_normalization_test.dart b/test/src/external_clipboard_normalization_test.dart new file mode 100644 index 00000000..44dc7f41 --- /dev/null +++ b/test/src/external_clipboard_normalization_test.dart @@ -0,0 +1,318 @@ +import 'dart:io'; + +import 'package:busymark/src/clipboard/clipboard_insertion.dart'; +import 'package:busymark/src/editor/clipboard_paste_resolver.dart'; +import 'package:busymark/src/editor/source/source_paste_engine.dart'; +import 'package:busymark/src/editor/wysiwyg/wysiwyg_clipboard_fragment.dart'; +import 'package:busymark/src/editor/wysiwyg/wysiwyg_document_controller.dart'; +import 'package:busymark/src/markdown/busymark_document.dart'; +import 'package:busymark/src/markdown/markdown_model.dart'; +import 'package:busymark/src/markdown/markdown_parser.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:html/parser.dart' as html; +import 'package:markdown/markdown.dart' as md; + +BusyMarkPastePlan _resolve( + String html, { + String? native, + BusyMarkPasteDestination destination = + BusyMarkPasteDestination.markdownSource, + BusyMarkPasteMode mode = BusyMarkPasteMode.normal, +}) => const BusyMarkClipboardPasteResolver().resolve( + snapshot: BusyMarkClipboardSnapshot( + text: 'Interoperable plain text', + html: html, + richFragment: native, + external: native == null, + sessionOwned: native != null, + fromSystemClipboard: true, + ), + mode: mode, + destination: destination, + markdownMode: MarkdownMode.gfm, +); + +String _paste(BusyMarkPastePlan plan) { + final fragment = + (plan.candidates.first as BusyMarkStructuredPasteCandidate).fragment; + final result = + const SourcePasteEngine().prepareStructured( + target: const SourcePasteDocumentSnapshot( + expectedSource: '', + selection: TextSelection.collapsed(offset: 0), + format: SourceDocumentFormat.markdown, + markdownMode: MarkdownMode.gfm, + filePath: '/project/new.md', + ), + fragment: fragment, + ) + as SourcePasteReady; + return result.edit.replacement; +} + +void main() { + test( + 'synthetic browser selection preserves headings, prose and destinations', + () { + final source = File( + 'test/fixtures/clipboard/synthetic_browser_job.html', + ).readAsStringSync(); + final markdown = _paste(_resolve(source)); + expect( + markdown, + '## Example Developer\n\n' + '**About the role**\n\n' + 'Build tools with the team. \nOffice hours vary.\n\n' + '[Application details](https://example.test/apply?source=listing&tracking=abc)\n\n' + '*Keep this selected interface text.*\n\n' + '```dart\nvoid main() {}\n```\n', + ); + final rendered = html.parseFragment(md.markdownToHtml(markdown)); + expect(rendered.querySelector('h2')!.text, 'Example Developer'); + expect(rendered.querySelectorAll('p'), hasLength(4)); + expect(rendered.querySelectorAll('p br'), hasLength(1)); + expect( + rendered.querySelector('p em')!.text, + 'Keep this selected interface text.', + ); + expect(rendered.querySelectorAll('a'), hasLength(1)); + expect( + rendered.querySelector('a')!.attributes['href'], + 'https://example.test/apply?source=listing&tracking=abc', + ); + expect( + rendered.querySelector('pre code')!.classes, + contains('language-dart'), + ); + + final plain = _resolve(source, mode: BusyMarkPasteMode.plainText); + expect( + (plain.candidates.single as BusyMarkPlainTextPasteCandidate).text, + 'Interoperable plain text', + ); + }, + ); + + for (final destination in [ + BusyMarkPasteDestination.markdownSource, + BusyMarkPasteDestination.editor, + ]) { + test('browser table preserves consecutive breaks in ${destination.name}', () { + for (final (imported, header, body) in [ + ( + '
H
A

B
', + 'H', + 'A

B', + ), + ( + '' + '

H

I

A

B

', + '**H**

I', + 'A

*B*', + ), + ]) { + final plan = _resolve(imported, destination: destination); + final fragment = + (plan.candidates.first as BusyMarkStructuredPasteCandidate) + .fragment; + final table = fragment.documentBlocks.single; + expect(table.kind, BusyBlockKind.table); + for (final cell in table.children.expand((row) => row.children)) { + if (cell.plainText == 'H') continue; + expect( + cell.inlines.where( + (inline) => inline.kind == BusyInlineKind.hardBreak, + ), + hasLength(2), + ); + } + final String output; + if (destination == BusyMarkPasteDestination.markdownSource) { + output = _paste(plan); + } else { + final document = const MarkdownParser() + .parse( + source: 'Target', + filePath: '/project/new.md', + mode: MarkdownMode.gfm, + ) + .busyDocument; + final editor = BusyMarkWysiwygDocumentController(document: document); + addTearDown(editor.dispose); + expect( + editor.insertStyledBlocksAtSelection( + blockId: document.blocks.single.id, + selectionStart: 0, + selectionEnd: 6, + blocks: fragment.blocks, + ), + isNotNull, + ); + output = editor.markdown; + } + expect(output.trim(), '| $header |\n| --- |\n| $body |'); + final rendered = html.parseFragment( + md.markdownToHtml( + output, + extensionSet: md.ExtensionSet.gitHubFlavored, + ), + ); + expect(rendered.querySelector('td')!.text, 'AB'); + expect(rendered.querySelectorAll('td br'), hasLength(2)); + if (header != 'H') { + expect(rendered.querySelectorAll('th br'), hasLength(2)); + expect(rendered.querySelector('th strong')!.text, 'H'); + expect(rendered.querySelector('td em')!.text, 'B'); + } + } + }); + } + + test( + 'a line break between linked words and an image-only link remain linked', + () { + final markdown = _paste( + _resolve( + '

Read
this guide

' + '

', + ), + ); + expect( + markdown, + '[Read \nthis guide](guide.md#install)\n\n' + '[![](https://example.test/small)](https://example.test/big)', + ); + final rendered = html.parseFragment(md.markdownToHtml(markdown)); + expect(rendered.querySelector('a br'), isNotNull); + expect( + rendered.querySelector('a[href="guide.md#install"]')!.text, + contains('this guide'), + ); + expect( + rendered + .querySelector('a[href="https://example.test/big"] img')! + .attributes['src'], + 'https://example.test/small', + ); + }, + ); + + test( + 'DOM ownership retains tight, loose, nested, task and restarted lists', + () { + final source = File( + 'test/fixtures/clipboard/browser_list_ownership.html', + ).readAsStringSync(); + final markdown = _paste(_resolve(source)); + expect( + markdown, + '- Design\n - Outline\n - Review\n- Test\n\n' + '+ [x] Ship\n+ [ ] Document\n\n' + '3. Third\n4. Fourth\n\n' + '3) Restart\n4) Continue\n\n' + '- First paragraph\n\n Second paragraph\n\n- Last item\n', + ); + final rendered = html.parseFragment( + md.markdownToHtml( + markdown, + extensionSet: md.ExtensionSet.gitHubFlavored, + ), + ); + final lists = rendered.children; + expect(lists.map((list) => list.localName), [ + 'ul', + 'ul', + 'ol', + 'ol', + 'ul', + ]); + expect( + lists.first.querySelectorAll('li ul li').map((node) => node.text), + ['Outline', 'Review'], + ); + expect(lists.first.querySelector('li p'), isNull); + expect(lists[1].querySelectorAll('input'), hasLength(2)); + expect(lists[1].querySelectorAll('input[checked]'), hasLength(1)); + expect(lists[2].attributes['start'], '3'); + expect(lists[3].attributes['start'], '3'); + expect( + lists[4].children.first.querySelectorAll('p').map((node) => node.text), + ['First paragraph', 'Second paragraph'], + ); + }, + ); + + test('HTML-only list markers survive when Markdown cannot encode them', () { + const list = + '
  1. Fifth
  2. ' + '
  3. Second
  4. First
'; + final markdown = _paste(_resolve(list)); + expect(markdown, '$list\n'); + final rendered = html.parseFragment(md.markdownToHtml(markdown)); + expect( + rendered.querySelector('ol[reversed][type="A"][start="5"]'), + isNotNull, + ); + expect(rendered.querySelector('ol li[value="2"]')!.text, 'Second'); + }); + + test('direction with an HTML heading and a linked video retains meaning', () { + final markup = _paste( + _resolve( + '

عنوان

' + '

' + '

', + ), + ); + expect( + markup, + '

عنوان

\n\n' + '[Watch](https://example.test/movie)\n', + ); + final rendered = html.parseFragment(md.markdownToHtml(markup)); + expect(rendered.querySelector('h2[dir="rtl"]')!.text, 'عنوان'); + expect( + rendered.querySelector('a')!.attributes['href'], + 'https://example.test/movie', + ); + }); + + test('native rich fragment priority retains authored metadata', () { + final heading = BusyBlock( + id: 'heading', + kind: BusyBlockKind.heading, + attributes: const { + 'level': '2', + 'class': 'authored', + 'id': 'guide', + 'generatedId': 'false', + }, + inlines: const [ + BusyInline(kind: BusyInlineKind.text, text: 'Native heading'), + ], + ); + final native = WysiwygClipboardFragment( + mode: MarkdownMode.writersideMarkdown, + blocks: [ + BusyWysiwygStyledBlock( + kind: heading.kind, + ranges: const [], + text: heading.plainText, + completeBlock: heading, + ), + ], + ); + final plan = _resolve( + '

Alternative

', + native: native.encode(), + ); + final candidate = plan.candidates.first as BusyMarkStructuredPasteCandidate; + expect(candidate.source, BusyMarkStructuredClipboardSource.richFragment); + expect( + candidate.fragment.documentBlocks.single.attributes['class'], + 'authored', + ); + expect(_paste(plan), '## Native heading {id="guide" class="authored"}\n'); + }); +} diff --git a/test/src/git/git_cli_gateway_integration_test.dart b/test/src/git/git_cli_gateway_integration_test.dart index bcf4fe87..64d9b1f6 100644 --- a/test/src/git/git_cli_gateway_integration_test.dart +++ b/test/src/git/git_cli_gateway_integration_test.dart @@ -1,199 +1,15 @@ import 'dart:io'; -import 'package:busymark/src/git/data/git_cli_gateway.dart'; +import 'package:busymark/src/git/data/git_shared_gateway.dart'; import 'package:busymark/src/git/domain/git_models.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; void main() { - test( - 'merged rename history keeps actual revision and first-parent paths', - () async { - final root = await _createRepository('busymark-git-merged-history-'); - final original = await File(p.join(root.path, 'README.md')).readAsBytes(); - final initialBranch = await _gitOutput(root.path, [ - 'branch', - '--show-current', - ]); - await _git(root.path, ['branch', 'feature']); - await File( - p.join(root.path, 'chapter.md'), - ).writeAsString('Main chapter\r\n'); - await _git(root.path, ['add', 'chapter.md']); - await _git(root.path, ['commit', '-m', 'Main chapter']); - await _git(root.path, ['switch', 'feature']); - await Directory(p.join(root.path, 'docs')).create(); - const renamed = 'docs/日本語-review.md'; - await _git(root.path, ['mv', 'README.md', renamed]); - await _git(root.path, ['commit', '-m', 'Rename chapter']); - final renameOid = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - await _git(root.path, ['switch', initialBranch]); - await _git(root.path, [ - 'merge', - '--no-ff', - '-m', - 'Merge renamed chapter', - 'feature', - ]); - const gateway = GitCliGateway(); - final repository = (await gateway.detectRepository(root.path))!; - final history = await gateway.fileHistory(repository, renamed); - expect(history.first.commit.parentHashes, hasLength(2)); - expect(history.first.status, GitDiffFileStatus.renamed); - expect(history.first.pathAtCommit, renamed); - expect(history.first.oldPath, 'README.md'); - expect(history.first.newPath, renamed); - final rename = history.singleWhere( - (entry) => entry.commit.fullHash == renameOid, - ); - expect(rename.status, GitDiffFileStatus.renamed); - expect(rename.pathAtCommit, renamed); - expect(rename.oldPath, 'README.md'); - expect(await File(p.join(root.path, renamed)).readAsBytes(), original); - expect(await _gitOutput(root.path, ['status', '--porcelain']), isEmpty); - }, - ); - test('process-backed Git gateway requires workspace trust', () { expect(const GitCliGateway().requiresWorkspaceTrust, isTrue); }); - test( - 'configures a repository author identity without terminal setup', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await Directory.systemTemp.createTemp( - 'busymark-git-identity-', - ); - addTearDown(() async { - if (await root.exists()) { - await root.delete(recursive: true); - } - }); - await _git(root.path, ['init']); - const gateway = GitCliGateway(); - final info = await gateway.detectRepository(root.path); - - await gateway.configureAuthorIdentity( - info!, - name: 'BusyMark User', - email: 'busymark@example.com', - globally: false, - ); - - expect( - await _gitOutput(root.path, ['config', '--local', 'user.name']), - 'BusyMark User', - ); - expect( - await _gitOutput(root.path, ['config', '--local', 'user.email']), - 'busymark@example.com', - ); - }, - ); - - test('runs core workflow in a temporary Git repository', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await Directory.systemTemp.createTemp('busymark-git-real-'); - addTearDown(() async { - if (await root.exists()) { - await root.delete(recursive: true); - } - }); - await _git(root.path, ['init']); - await _git(root.path, ['config', 'user.name', 'BusyMark Test']); - await _git(root.path, ['config', 'user.email', 'busymark@example.com']); - final readme = File(p.join(root.path, 'README.md')); - await readme.writeAsString('# Docs\n'); - await _git(root.path, ['add', 'README.md']); - await _git(root.path, ['commit', '-m', 'Initial docs']); - - const gateway = GitCliGateway(); - final info = await gateway.detectRepository(root.path); - expect(info, isNotNull); - final initialBranch = info!.currentBranch!; - expect((await gateway.status(info)).clean, isTrue); - - await readme.writeAsString('# Docs\n\nChanged.\n'); - final guide = File(p.join(root.path, 'guide.md')); - await guide.writeAsString('# Guide\n'); - final modified = await gateway.status(info); - expect(modified.unstagedFiles.single.repoRelativePath, 'README.md'); - expect( - (await gateway.diffFile(info, 'README.md', staged: false)).rawPatch, - contains('Changed.'), - ); - - await gateway.stage(info, ['README.md', 'guide.md']); - expect( - (await gateway.status( - info, - )).stagedFiles.map((file) => file.repoRelativePath), - containsAll(['README.md', 'guide.md']), - ); - await gateway.commit(info, 'Update docs\n\nMultiline body.'); - final latestCommit = (await gateway.history(info)).first; - expect(latestCommit.subject, 'Update docs'); - final fullDetails = await gateway.commitDetails( - info, - latestCommit.fullHash, - ); - expect( - fullDetails.changedFiles.map((file) => file.newPath ?? file.oldPath), - containsAll(['README.md', 'guide.md']), - ); - expect(fullDetails.fileSnapshots['README.md'], contains('Changed.')); - expect(fullDetails.fileSnapshots['guide.md'], contains('# Guide')); - final readmeDetails = await gateway.commitDetails( - info, - latestCommit.fullHash, - repoRelativePath: 'README.md', - ); - expect( - readmeDetails.changedFiles.map((file) => file.newPath ?? file.oldPath), - ['README.md'], - ); - expect(readmeDetails.fileSnapshots['README.md'], contains('Changed.')); - - await gateway.createBranch(info, 'feature/docs'); - expect( - (await gateway.detectRepository(root.path))?.currentBranch, - 'feature/docs', - ); - final branchesAfterCreate = await gateway.branches(info); - expect( - branchesAfterCreate.map((branch) => branch.name), - containsAll([initialBranch, 'feature/docs']), - ); - expect( - branchesAfterCreate.every((branch) => branch.name.isNotEmpty), - isTrue, - ); - await gateway.switchBranch(info, initialBranch); - expect( - (await gateway.detectRepository(root.path))?.currentBranch, - initialBranch, - ); - - await readme.writeAsString('# Docs\n\nDiscard me.\n'); - expect((await gateway.status(info)).unstagedFiles, isNotEmpty); - await gateway.rollbackTracked(info, ['README.md']); - expect(await readme.readAsString(), contains('Changed.')); - - final draft = File(p.join(root.path, 'draft.md')); - await draft.writeAsString('# Draft\n'); - final withUntracked = await gateway.status(info); - expect(withUntracked.untrackedFiles.single.repoRelativePath, 'draft.md'); - await gateway.discardUntracked(info, ['draft.md'], withUntracked); - expect(await draft.exists(), isFalse); - }); - test('status lists every non-ignored hidden untracked file', () async { if (!await _gitAvailable()) { markTestSkipped('Git executable is unavailable.'); @@ -224,678 +40,6 @@ void main() { expect(paths, isNot(contains('.idea/workspace.xml'))); }); - test('resets the current branch with each explicit Git reset mode', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - const gateway = GitCliGateway(); - for (final mode in GitResetMode.values) { - final root = await _createRepository('busymark-git-reset-${mode.name}-'); - final initialHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - final readme = File(p.join(root.path, 'README.md')); - await readme.writeAsString('# Later\n'); - await _git(root.path, ['add', 'README.md']); - await _git(root.path, ['commit', '-m', 'Later docs']); - final info = (await gateway.detectRepository(root.path))!; - - await gateway.resetCurrentBranch(info, initialHash, mode); - - expect( - await _gitOutput(root.path, ['rev-parse', 'HEAD']), - initialHash, - reason: '$mode must move the current branch', - ); - final status = await gateway.status(info); - switch (mode) { - case GitResetMode.soft: - expect(status.stagedFiles, hasLength(1)); - expect(status.unstagedFiles, isEmpty); - expect(await readme.readAsString(), '# Later\n'); - case GitResetMode.mixed: - expect(status.stagedFiles, isEmpty); - expect(status.unstagedFiles, hasLength(1)); - expect(await readme.readAsString(), '# Later\n'); - case GitResetMode.hard || GitResetMode.keep: - expect(status.clean, isTrue); - expect(await readme.readAsString(), '# Docs\n'); - } - } - }); - - test('refuses to reset while HEAD is detached', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-reset-detached-'); - final initialHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - await _git(root.path, ['checkout', '--detach', initialHash]); - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - - await expectLater( - gateway.resetCurrentBranch(info, initialHash, GitResetMode.hard), - throwsA( - isA().having( - (failure) => failure.code, - 'code', - GitFailureCode.detachedHead, - ), - ), - ); - - expect(await _gitOutput(root.path, ['rev-parse', 'HEAD']), initialHash); - }); - - test('keeps staged and unstaged comparisons separate', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-split-diff-'); - final readme = File(p.join(root.path, 'README.md')); - await readme.writeAsString('# Docs\n\nStaged version.\n'); - await _git(root.path, ['add', 'README.md']); - await readme.writeAsString('# Docs\n\nWorking-tree version.\n'); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final status = await gateway.status(info); - expect(status.stagedFiles.single.repoRelativePath, 'README.md'); - expect(status.unstagedFiles.single.repoRelativePath, 'README.md'); - - final staged = await gateway.diffFile(info, 'README.md', staged: true); - final unstaged = await gateway.diffFile(info, 'README.md', staged: false); - - expect(staged.rawPatch, contains('Staged version.')); - expect(staged.rawPatch, isNot(contains('Working-tree version.'))); - expect(staged.fileSnapshots['README.md'], contains('Staged version.')); - expect(unstaged.rawPatch, contains('-Staged version.')); - expect(unstaged.rawPatch, contains('+Working-tree version.')); - expect(unstaged.rawPatch, isNot(contains('+Staged version.'))); - expect( - unstaged.fileSnapshots['README.md'], - contains('Working-tree version.'), - ); - }); - - test('staged rename diff and unstage preserve both paths', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-staged-rename-'); - await _git(root.path, ['mv', 'README.md', 'renamed.md']); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final before = await gateway.status(info); - final rename = before.stagedFiles.single; - expect(rename.originalRepoRelativePath, 'README.md'); - expect(rename.repoRelativePath, 'renamed.md'); - - final diff = await gateway.diffFile( - info, - rename.repoRelativePath, - staged: true, - originalRepoRelativePath: rename.originalRepoRelativePath, - ); - expect(diff.files.single.status, GitDiffFileStatus.renamed); - expect(diff.files.single.oldPath, 'README.md'); - expect(diff.files.single.newPath, 'renamed.md'); - - await gateway.unstage(info, [ - rename.originalRepoRelativePath!, - rename.repoRelativePath, - ]); - - expect((await gateway.status(info)).stagedFiles, isEmpty); - final cachedDiff = await Process.run('git', [ - '-C', - root.path, - 'diff', - '--cached', - '--quiet', - '--exit-code', - ], runInShell: false); - expect(cachedDiff.exitCode, 0, reason: '${cachedDiff.stderr}'); - }); - - test('rollback restores both sides of a staged rename to HEAD', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-rollback-rename-'); - final original = File(p.join(root.path, 'README.md')); - final renamed = File(p.join(root.path, 'renamed.md')); - await _git(root.path, ['mv', 'README.md', 'renamed.md']); - await renamed.writeAsString('# Changed after rename\n'); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final before = await gateway.status(info); - final rename = before.stagedFiles.single; - expect(rename.originalRepoRelativePath, 'README.md'); - expect(rename.repoRelativePath, 'renamed.md'); - expect(before.unstagedFiles.single.repoRelativePath, 'renamed.md'); - - await gateway.rollbackTracked(info, [ - rename.originalRepoRelativePath!, - rename.repoRelativePath, - ]); - - expect((await gateway.status(info)).clean, isTrue); - expect(await original.readAsString(), '# Docs\n'); - expect(await renamed.exists(), isFalse); - final cachedDiff = await Process.run('git', [ - '-C', - root.path, - 'diff', - '--cached', - '--quiet', - '--exit-code', - ], runInShell: false); - expect(cachedDiff.exitCode, 0, reason: '${cachedDiff.stderr}'); - }); - - test( - 'staged addition deleted from the working tree keeps separate diffs', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-added-deleted-'); - final draft = File(p.join(root.path, 'draft.md')); - await draft.writeAsString('# Draft\n\nStaged content.\n'); - await _git(root.path, ['add', 'draft.md']); - await draft.delete(); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final status = await gateway.status(info); - final file = status.files.singleWhere( - (candidate) => candidate.repoRelativePath == 'draft.md', - ); - - expect(file.indexStatus, GitFileChangeStatus.added); - expect(file.workTreeStatus, GitFileChangeStatus.deleted); - expect(status.stagedFiles, contains(file)); - expect(status.unstagedFiles, contains(file)); - expect(file.hasWorkingTreeFile, isFalse); - - final staged = await gateway.diffFile(info, 'draft.md', staged: true); - final unstaged = await gateway.diffFile(info, 'draft.md', staged: false); - - expect(staged.files.single.status, GitDiffFileStatus.added); - expect(staged.fileSnapshots['draft.md'], contains('Staged content.')); - expect(unstaged.files.single.status, GitDiffFileStatus.deleted); - expect(unstaged.fileSnapshots['draft.md'], contains('Staged content.')); - - await gateway.rollbackTracked(info, ['draft.md']); - - expect((await gateway.status(info)).clean, isTrue); - expect(await draft.exists(), isFalse); - }, - ); - - test( - 'preserves complete deleted content and restores a deleted version', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-deleted-file-'); - final readme = File(p.join(root.path, 'README.md')); - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - - await readme.delete(); - final unstaged = await gateway.diffFile(info, 'README.md', staged: false); - expect(unstaged.files.single.status, GitDiffFileStatus.deleted); - expect(unstaged.fileSnapshots['README.md'], '# Docs\n'); - - await _git(root.path, ['restore', 'README.md']); - await _git(root.path, ['rm', 'README.md']); - final staged = await gateway.diffFile(info, 'README.md', staged: true); - expect(staged.files.single.status, GitDiffFileStatus.deleted); - expect(staged.fileSnapshots['README.md'], '# Docs\n'); - await _git(root.path, ['commit', '-m', 'Delete docs']); - final deletionHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - - final commitChange = await gateway.compareFileWithParent( - info, - deletionHash, - oldPath: 'README.md', - newPath: null, - ); - expect(commitChange.oldContent, '# Docs\n'); - expect(commitChange.newContent, ''); - expect(commitChange.diff.files.single.status, GitDiffFileStatus.deleted); - expect(commitChange.diff.fileSnapshots['README.md'], '# Docs\n'); - - await readme.writeAsString('# Recreated\n'); - await _git(root.path, ['add', 'README.md']); - await _git(root.path, ['commit', '-m', 'Recreate docs']); - await gateway.restoreFileFromCommit( - info, - deletionHash, - historicalPath: 'README.md', - currentPath: 'README.md', - ); - - expect(await readme.exists(), isFalse); - final restoredStatus = await gateway.status(info); - expect(restoredStatus.unstagedFiles.single.repoRelativePath, 'README.md'); - expect(restoredStatus.unstagedFiles.single.deleted, isTrue); - expect(restoredStatus.stagedFiles, isEmpty); - }, - ); - - test('failed historical blob read cannot delete the working file', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-missing-blob-'); - final readme = File(p.join(root.path, 'README.md')); - const workingContent = '# Keep this working file\n'; - await readme.writeAsString(workingContent); - final commitHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - final blobId = await _gitOutput(root.path, ['rev-parse', 'HEAD:README.md']); - final objectFile = File( - p.join( - root.path, - '.git', - 'objects', - blobId.substring(0, 2), - blobId.substring(2), - ), - ); - final backup = File('${objectFile.path}.busymark-test-backup'); - expect(await objectFile.exists(), isTrue); - await objectFile.rename(backup.path); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - try { - await expectLater( - gateway.restoreFileFromCommit( - info, - commitHash, - historicalPath: 'README.md', - currentPath: 'README.md', - ), - throwsA( - isA().having( - (failure) => failure.code, - 'code', - GitFailureCode.commandFailed, - ), - ), - ); - expect(await readme.exists(), isTrue); - expect(await readme.readAsString(), workingContent); - } finally { - if (await backup.exists()) { - await backup.rename(objectFile.path); - } - } - }); - - test( - 'constructs complete text and binary comparisons for untracked files', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-untracked-diff-'); - final text = File(p.join(root.path, 'draft.md')); - await text.writeAsString('# Draft\n\nComplete document.\n'); - final binary = File(p.join(root.path, 'image.bin')); - await binary.writeAsBytes([0, 1, 2, 3, 255]); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final textDiff = await gateway.diffUntrackedFile(info, 'draft.md'); - final binaryDiff = await gateway.diffUntrackedFile(info, 'image.bin'); - - expect(textDiff.files.single.status, GitDiffFileStatus.added); - expect(textDiff.files.single.deletions, 0); - expect(textDiff.files.single.additions, 3); - expect(textDiff.fileSnapshots['draft.md'], await text.readAsString()); - expect( - textDiff.files.single.hunks.single.lines.every( - (line) => line.kind == GitDiffLineKind.added, - ), - isTrue, - ); - expect(binaryDiff.hasBinaryFiles, isTrue); - expect(binaryDiff.files.single.binarySize, 5); - expect(binaryDiff.fileSnapshots, isEmpty); - }, - ); - - test( - 'direct working-tree operations reject intermediate symlink escapes', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-symlink-escape-'); - final outside = await Directory.systemTemp.createTemp( - 'busymark-git-symlink-outside-', - ); - addTearDown(() async { - if (await outside.exists()) { - await outside.delete(recursive: true); - } - }); - final outsideFile = File(p.join(outside.path, 'outside.md')); - await outsideFile.writeAsString('# Outside\n'); - await Link(p.join(root.path, 'linked')).create(outside.path); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final commitHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - final unsafePathFailure = isA().having( - (failure) => failure.code, - 'code', - GitFailureCode.invalidPath, - ); - - await expectLater( - gateway.diffUntrackedFile(info, 'linked/outside.md'), - throwsA(unsafePathFailure), - ); - await expectLater( - gateway.compareFileWithWorkingTree( - info, - commitHash, - historicalPath: 'README.md', - currentPath: 'linked/outside.md', - ), - throwsA(unsafePathFailure), - ); - await expectLater( - gateway.restoreFileFromCommit( - info, - commitHash, - historicalPath: 'README.md', - currentPath: 'linked/outside.md', - ), - throwsA(unsafePathFailure), - ); - expect(await outsideFile.readAsString(), '# Outside\n'); - }, - skip: Platform.isWindows ? 'POSIX symlink behavior only.' : false, - ); - - test('fetch updates remote-tracking status without changing files', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-fetch-'); - final remote = await Directory.systemTemp.createTemp( - 'busymark-git-fetch-remote-', - ); - final contributor = await Directory.systemTemp.createTemp( - 'busymark-git-fetch-contributor-', - ); - await contributor.delete(); - addTearDown(() async { - if (await remote.exists()) { - await remote.delete(recursive: true); - } - if (await contributor.exists()) { - await contributor.delete(recursive: true); - } - }); - await _git(remote.path, ['init', '--bare']); - await _git(root.path, ['remote', 'add', 'origin', remote.path]); - final branch = (await const GitCliGateway().detectRepository( - root.path, - ))!.currentBranch!; - await _git(root.path, ['push', '--set-upstream', 'origin', branch]); - final clone = await Process.run('git', [ - 'clone', - remote.path, - contributor.path, - ], runInShell: false); - expect(clone.exitCode, 0, reason: '${clone.stderr}'); - await _git(contributor.path, ['config', 'user.name', 'Contributor']); - await _git(contributor.path, [ - 'config', - 'user.email', - 'contributor@example.com', - ]); - await File( - p.join(contributor.path, 'README.md'), - ).writeAsString('# Remote update\n'); - await _git(contributor.path, ['commit', '-am', 'Remote update']); - await _git(contributor.path, ['push']); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - expect((await gateway.status(info)).repositoryInfo.behindCount, 0); - await gateway.fetch(info); - final fetched = await gateway.status(info); - - expect(fetched.repositoryInfo.behindCount, 1); - expect( - await File(p.join(root.path, 'README.md')).readAsString(), - '# Docs\n', - ); - }); - - test( - 'follows renames, compares complete versions, and restores one file', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-file-history-'); - final oldFile = File(p.join(root.path, 'old.md')); - await oldFile.writeAsString('# Version one\n'); - await _git(root.path, ['add', 'old.md']); - await _git(root.path, ['commit', '-m', 'Add old document']); - await oldFile.writeAsString('# Version two\n'); - await _git(root.path, ['commit', '-am', 'Update old document']); - final versionTwoHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - await _git(root.path, ['mv', 'old.md', 'new.md']); - await _git(root.path, ['commit', '-m', 'Rename document']); - final renameHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - final newFile = File(p.join(root.path, 'new.md')); - await newFile.writeAsString('# Version three\n'); - await _git(root.path, ['commit', '-am', 'Update renamed document']); - await newFile.writeAsString('# Working version\n'); - - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final firstPage = await gateway.fileHistory(info, 'new.md', limit: 2); - final secondPage = await gateway.fileHistory( - info, - 'new.md', - limit: 2, - skip: 2, - ); - final history = [...firstPage, ...secondPage]; - - expect(firstPage, hasLength(2)); - expect(secondPage, isNotEmpty); - expect(history.map((entry) => entry.pathAtCommit), contains('old.md')); - final rename = history.singleWhere( - (entry) => entry.commit.fullHash == renameHash, - ); - expect(rename.oldPath, 'old.md'); - expect(rename.newPath, 'new.md'); - expect(rename.status, GitDiffFileStatus.renamed); - - final commitChange = await gateway.compareFileWithParent( - info, - renameHash, - oldPath: rename.oldPath, - newPath: rename.newPath, - ); - expect(commitChange.oldPath, 'old.md'); - expect(commitChange.newPath, 'new.md'); - expect(commitChange.oldContent, '# Version two\n'); - expect(commitChange.newContent, '# Version two\n'); - expect(commitChange.diff.files.single.status, GitDiffFileStatus.renamed); - - final versusCurrent = await gateway.compareFileWithWorkingTree( - info, - versionTwoHash, - historicalPath: 'old.md', - currentPath: 'new.md', - ); - expect(versusCurrent.oldContent, '# Version two\n'); - expect(versusCurrent.newContent, '# Working version\n'); - expect(versusCurrent.diff.rawPatch, contains('Working version')); - - await gateway.restoreFileFromCommit( - info, - versionTwoHash, - historicalPath: 'old.md', - currentPath: 'new.md', - ); - expect(await newFile.readAsString(), '# Version two\n'); - final restoredStatus = await gateway.status(info); - expect(restoredStatus.unstagedFiles.single.repoRelativePath, 'new.md'); - expect(restoredStatus.stagedFiles, isEmpty); - expect(await oldFile.exists(), isFalse); - }, - ); - - test('compares a merge commit with its first parent', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-merge-parent-'); - final readme = File(p.join(root.path, 'README.md')); - const gateway = GitCliGateway(); - final info = (await gateway.detectRepository(root.path))!; - final mainBranch = info.currentBranch!; - - await _git(root.path, ['switch', '-c', 'side']); - await readme.writeAsString('# Side version\n'); - await _git(root.path, ['commit', '-am', 'Side docs']); - await _git(root.path, ['switch', mainBranch]); - await File(p.join(root.path, 'main.txt')).writeAsString('main\n'); - await _git(root.path, ['add', 'main.txt']); - await _git(root.path, ['commit', '-m', 'Main work']); - await _git(root.path, ['merge', '--no-ff', 'side', '-m', 'Merge side']); - final mergeHash = await _gitOutput(root.path, ['rev-parse', 'HEAD']); - - final comparison = await gateway.compareFileWithParent( - info, - mergeHash, - oldPath: 'README.md', - newPath: 'README.md', - ); - - expect(comparison.oldContent, '# Docs\n'); - expect(comparison.newContent, '# Side version\n'); - expect(comparison.diff.rawPatch, contains('-# Docs')); - expect(comparison.diff.rawPatch, contains('+# Side version')); - final details = await gateway.commitDetails(info, mergeHash); - expect(details.changedFiles.single.displayPath, 'README.md'); - }); - - test('switch treats an option-like branch name as an operand', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-switch-option-'); - await _git(root.path, ['update-ref', 'refs/heads/--detach', 'HEAD']); - const gateway = GitCliGateway(); - final info = await gateway.detectRepository(root.path); - expect(info, isNotNull); - - await gateway.switchBranch(info!, '--detach'); - - final switched = await gateway.detectRepository(root.path); - expect(switched?.currentBranch, '--detach'); - expect(switched?.detachedHeadCommit, isNull); - }); - - test('diff and commit details preserve C-quoted UTF-8 paths', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-quoted-path-'); - await _git(root.path, ['config', 'core.quotePath', 'true']); - const repoRelativePath = 'docs/Über "guide".md'; - final document = File(p.join(root.path, repoRelativePath)); - await document.create(recursive: true); - await document.writeAsString('Initial.\n'); - await _git(root.path, ['add', '--', repoRelativePath]); - await _git(root.path, ['commit', '-m', 'Add quoted path']); - await document.writeAsString('Changed.\n'); - - const gateway = GitCliGateway(); - final info = await gateway.detectRepository(root.path); - expect(info, isNotNull); - - final workingTreeDiff = await gateway.diffAll(info!, staged: false); - expect(workingTreeDiff.files.single.oldPath, repoRelativePath); - expect(workingTreeDiff.files.single.newPath, repoRelativePath); - - await _git(root.path, ['add', '--', repoRelativePath]); - await _git(root.path, ['commit', '-m', 'Update quoted path']); - final commit = (await gateway.history(info, limit: 1)).single; - final details = await gateway.commitDetails(info, commit.fullHash); - - expect(details.changedFiles.single.oldPath, repoRelativePath); - expect(details.changedFiles.single.newPath, repoRelativePath); - expect(details.fileSnapshots[repoRelativePath], 'Changed.\n'); - }); - - test( - 'pushSetUpstream does not broaden an option-like branch to --all', - () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final root = await _createRepository('busymark-git-push-option-'); - final remote = await Directory.systemTemp.createTemp( - 'busymark-git-push-option-remote-', - ); - addTearDown(() async { - if (await remote.exists()) { - await remote.delete(recursive: true); - } - }); - await _git(remote.path, ['init', '--bare']); - await _git(root.path, ['remote', 'add', 'origin', remote.path]); - await _git(root.path, ['update-ref', 'refs/heads/--all', 'HEAD']); - await _git(root.path, ['update-ref', 'refs/heads/unrelated', 'HEAD']); - const gateway = GitCliGateway(); - final info = await gateway.detectRepository(root.path); - expect(info, isNotNull); - - await gateway.pushSetUpstream(info!, 'origin', '--all'); - - expect(await _gitRefExists(remote.path, 'refs/heads/--all'), isTrue); - expect( - await _gitRefExists(remote.path, 'refs/heads/unrelated'), - isFalse, - reason: 'The branch operand must not be interpreted as git push --all.', - ); - }, - ); - test('detects conflicted files in a temporary Git repository', () async { if (!await _gitAvailable()) { markTestSkipped('Git executable is unavailable.'); @@ -916,9 +60,10 @@ void main() { await readme.writeAsString('base\n'); await _git(root.path, ['add', 'README.md']); await _git(root.path, ['commit', '-m', 'Initial']); - final initialBranch = (await const GitCliGateway().detectRepository( - root.path, - ))!.currentBranch!; + final initialBranch = (await _git(root.path, [ + 'branch', + '--show-current', + ])).trim(); await _git(root.path, ['switch', '-c', 'side']); await readme.writeAsString('side\n'); @@ -939,7 +84,7 @@ void main() { final status = await gateway.status(info!); expect(status.conflictedFiles, isNotEmpty); - expect(status.repositoryInfo.hasConflicts, isTrue); + expect(status.source!.operation.unmerged, isTrue); expect( status.conflictedFiles.single.category, GitFileStatusCategory.conflicted, @@ -984,78 +129,6 @@ void main() { }, skip: Platform.isWindows, ); - - test('diff APIs do not run a repository-configured textconv', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final fixture = await _createTextconvFixture(); - final sentinel = File('${fixture.probe.path}.ran'); - - await _git(fixture.root.path, ['diff', '--textconv', '--', 'README.md']); - expect( - await sentinel.exists(), - isTrue, - reason: 'The textconv probe must execute without the mitigation.', - ); - await sentinel.delete(); - - final fileDiff = await fixture.gateway.diffFile( - fixture.info, - 'README.md', - staged: false, - ); - expect(fileDiff.rawPatch, contains('Working tree change.')); - expect( - await sentinel.exists(), - isFalse, - reason: 'Git diffFile must disable repository textconv commands.', - ); - - final allDiff = await fixture.gateway.diffAll(fixture.info, staged: false); - expect(allDiff.rawPatch, contains('Working tree change.')); - expect( - await sentinel.exists(), - isFalse, - reason: 'Git diffAll must disable repository textconv commands.', - ); - }, skip: Platform.isWindows); - - test('commit details do not run a repository-configured textconv', () async { - if (!await _gitAvailable()) { - markTestSkipped('Git executable is unavailable.'); - return; - } - final fixture = await _createTextconvFixture(); - final sentinel = File('${fixture.probe.path}.ran'); - - await _git(fixture.root.path, [ - 'show', - '--textconv', - '--format=', - '--patch', - fixture.commitHash, - ]); - expect( - await sentinel.exists(), - isTrue, - reason: 'The textconv probe must execute for raw Git show.', - ); - await sentinel.delete(); - - final details = await fixture.gateway.commitDetails( - fixture.info, - fixture.commitHash, - ); - - expect(details.patch, contains('Committed change.')); - expect( - await sentinel.exists(), - isFalse, - reason: 'Git show must disable repository textconv commands.', - ); - }, skip: Platform.isWindows); } Future _createRepository(String prefix) async { @@ -1075,75 +148,6 @@ Future _createRepository(String prefix) async { return root; } -Future<_TextconvFixture> _createTextconvFixture() async { - final root = await Directory.systemTemp.createTemp('busymark-git-textconv-'); - addTearDown(() async { - if (await root.exists()) { - await root.delete(recursive: true); - } - }); - await _git(root.path, ['init']); - await _git(root.path, ['config', 'user.name', 'BusyMark Test']); - await _git(root.path, ['config', 'user.email', 'busymark@example.com']); - await File( - p.join(root.path, '.gitattributes'), - ).writeAsString('*.md diff=busymarktest\n'); - final readme = File(p.join(root.path, 'README.md')); - await readme.writeAsString('# Original\n'); - await _git(root.path, ['add', '.gitattributes', 'README.md']); - await _git(root.path, ['commit', '-m', 'Initial docs']); - await readme.writeAsString('# Committed change.\n'); - await _git(root.path, ['add', 'README.md']); - await _git(root.path, ['commit', '-m', 'Update docs']); - - const gateway = GitCliGateway(); - final info = await gateway.detectRepository(root.path); - expect(info, isNotNull); - final commitHash = (await gateway.history(info!, limit: 1)).single.fullHash; - final probe = await _writeExecutableProbe( - root, - 'textconv-probe.sh', - output: 'exec cat "\$1"', - ); - await _git(root.path, ['config', 'diff.busymarktest.textconv', probe.path]); - await readme.writeAsString('# Working tree change.\n'); - return _TextconvFixture( - root: root, - gateway: gateway, - info: info, - commitHash: commitHash, - probe: probe, - ); -} - -Future _writeExecutableProbe( - Directory root, - String name, { - required String output, -}) async { - final probe = File(p.join(root.path, name)); - await probe.writeAsString('#!/bin/sh\n: > "\$0.ran"\n$output\n'); - final chmod = await Process.run('chmod', ['700', probe.path]); - expect(chmod.exitCode, 0, reason: '${chmod.stderr}'); - return probe; -} - -class _TextconvFixture { - const _TextconvFixture({ - required this.root, - required this.gateway, - required this.info, - required this.commitHash, - required this.probe, - }); - - final Directory root; - final GitCliGateway gateway; - final GitRepositoryInfo info; - final String commitHash; - final File probe; -} - Future _gitAvailable() async { try { final result = await Process.run('git', ['--version'], runInShell: false); @@ -1153,7 +157,7 @@ Future _gitAvailable() async { } } -Future _git(String root, List args) async { +Future _git(String root, List args) async { final result = await Process.run('git', [ '-C', root, @@ -1167,33 +171,17 @@ Future _git(String root, List args) async { result.exitCode, ); } + return result.stdout as String; } -Future _gitOutput(String root, List args) async { - final result = await Process.run('git', [ - '-C', - root, - ...args, - ], runInShell: false); - if (result.exitCode != 0) { - throw ProcessException( - 'git', - ['-C', root, ...args], - '${result.stdout}\n${result.stderr}', - result.exitCode, - ); - } - return '${result.stdout}'.trim(); -} - -Future _gitRefExists(String root, String refName) async { - final result = await Process.run('git', [ - '-C', - root, - 'show-ref', - '--verify', - '--quiet', - refName, - ], runInShell: false); - return result.exitCode == 0; +Future _writeExecutableProbe( + Directory root, + String name, { + required String output, +}) async { + final probe = File(p.join(root.path, name)); + await probe.writeAsString('#!/bin/sh\n: > "\$0.ran"\n$output\n'); + final chmod = await Process.run('chmod', ['700', probe.path]); + expect(chmod.exitCode, 0, reason: '${chmod.stderr}'); + return probe; } diff --git a/test/src/git/git_controller_test.dart b/test/src/git/git_controller_test.dart index 67320b57..c4cf3c5a 100644 --- a/test/src/git/git_controller_test.dart +++ b/test/src/git/git_controller_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'package:busymark/src/app/app_settings.dart'; @@ -6,8 +7,8 @@ import 'package:busymark/src/git/application/git_controller.dart'; import 'package:busymark/src/git/application/git_gateway.dart'; import 'package:busymark/src/git/application/git_workspace_eligibility.dart'; import 'package:busymark/src/git/domain/git_models.dart'; +import 'package:busymark/src/git/data/git_shared_gateway.dart'; import 'package:busymark/src/local_history/local_history_controller.dart'; -import 'package:busymark/src/local_history/local_history_models.dart'; import 'package:busymark/src/local_history/local_history_store.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; @@ -15,8 +16,84 @@ import 'package:busymark/src/workspace/workspace_service.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:busystack_git/busystack_git.dart' as shared; +import '../../../../busystack_git/test/support/repository_fixture.dart'; void main() { + for (final linked in [false, true]) { + test( + 'Files-only status watches external staging without editor scans, linked=$linked', + () async { + final fixture = await RepositoryFixture.create(); + addTearDown(fixture.close); + await fixture.commit('a.md', utf8.encode('initial\n'), 'initial'); + var root = fixture.root.path; + if (linked) { + root = '${fixture.directory.path}/linked'; + await fixture.git(['worktree', 'add', '-b', 'linked', root]); + } + final gateway = _CountingSharedGitGateway(fixture.engine); + await File('$root/a.md').writeAsString('external change\n'); + final container = _container(gateway); + await container + .read(appSettingsControllerProvider.notifier) + .waitUntilLoaded(); + await container + .read(appSettingsControllerProvider.notifier) + .trustGitWorkspace(root); + final controller = container.read(gitControllerProvider.notifier); + final workspace = _workspace(id: root, rootPath: root); + controller.attachWorkspace(workspace); + await controller.refresh(); + // Reconcile the status-to-watch installation gap before measuring + // editor-only attachments. This event belongs to watcher startup. + final readyUntil = DateTime.now().add(const Duration(seconds: 10)); + while ((gateway.watchEvents == 0 || + gateway.refreshedWatchEvents != gateway.watchEvents || + container.read(gitControllerProvider).isRefreshing) && + DateTime.now().isBefore(readyUntil)) { + await Future.delayed(const Duration(milliseconds: 50)); + } + expect(gateway.watchEvents, greaterThan(0)); + expect(gateway.refreshedWatchEvents, gateway.watchEvents); + expect(container.read(gitControllerProvider).isRefreshing, isFalse); + final scans = gateway.statusCalls; + for (var i = 0; i < 10; i++) { + controller.attachWorkspace( + workspace.copyWith(activeFilePath: '$root/doc$i.md'), + ); + } + await Future.delayed(const Duration(milliseconds: 500)); + expect(gateway.statusCalls, scans); + await fixture.git(['add', '--', 'a.md'], cwd: root); + final timeout = DateTime.now().add(const Duration(seconds: 10)); + while (container + .read(gitControllerProvider) + .statusSnapshot! + .stagedFiles + .isEmpty && + DateTime.now().isBefore(timeout)) { + await Future.delayed(const Duration(milliseconds: 50)); + } + expect(gateway.statusCalls, greaterThan(scans)); + expect( + container.read(gitControllerProvider).repositoryInfo!.rootPath, + root, + ); + expect( + container.read(gitControllerProvider).statusSnapshot!.stagedFiles, + hasLength(1), + ); + await container + .read(appSettingsControllerProvider.notifier) + .revokeGitWorkspaceTrust(root); + final afterRevocation = gateway.statusCalls; + await fixture.git(['reset', '--', 'a.md'], cwd: root); + await Future.delayed(const Duration(milliseconds: 700)); + expect(gateway.statusCalls, afterRevocation); + }, + ); + } + test( 'shared status serves authoring refresh without another repository scan', () async { @@ -38,17 +115,15 @@ void main() { final workspace = _workspace(id: root, rootPath: root); controller.attachWorkspace(workspace); await controller.associateSharedRepository(workspace, repository); - GitStatusSnapshot snapshot(String branch) => GitStatusSnapshot( + GitStatusSnapshot snapshot() => GitStatusSnapshot( repositoryInfo: GitRepositoryInfo( rootPath: root, gitDirPath: '$root/.git', identityKey: repository.key, - currentBranch: branch, - hasRemote: true, ), files: const [], ); - var latest = snapshot('main'), refreshes = 0, projections = 0; + var latest = snapshot(), refreshes = 0, projections = 0; expect( controller.bindSharedStatusSource( workspace, @@ -69,17 +144,13 @@ void main() { expect(refreshes, 1); expect(gateway.detectCalls, 0); expect(gateway.statusCalls, 0); - expect( - container.read(gitControllerProvider).repositoryInfo!.hasRemote, - isTrue, - ); expect( container.read(gitControllerProvider).requiresWorkspaceTrust, isTrue, reason: 'Sharing passive data does not grant executable repository trust.', ); - latest = snapshot('topic'); + latest = snapshot(); await controller.refreshFromSharedSnapshot(); expect(projections, 1); expect( @@ -88,8 +159,8 @@ void main() { reason: 'A reconciled operation already has its snapshot.', ); expect( - container.read(gitControllerProvider).repositoryInfo!.currentBranch, - 'topic', + container.read(gitControllerProvider).statusSnapshot, + same(latest), ); expect(gateway.detectCalls, 0); expect(gateway.statusCalls, 0); @@ -121,6 +192,81 @@ void main() { }, ); + test( + 'releasing the exact session resumes Files refresh and invalidates retired callbacks', + () async { + final directory = await Directory.systemTemp.createTemp( + 'git-status-release-', + ); + addTearDown(() => directory.delete(recursive: true)); + final root = await directory.resolveSymbolicLinks(); + final repository = shared.RepositoryId( + root: root, + gitDir: '$root/.git', + commonDir: '$root/.git', + objectFormat: 'sha1', + filesystemToken: 'shared', + ); + final gateway = _AssociatedGitGateway(repository); + final container = _container(gateway); + await container + .read(appSettingsControllerProvider.notifier) + .waitUntilLoaded(); + await container + .read(appSettingsControllerProvider.notifier) + .trustGitWorkspace(root); + final controller = container.read(gitControllerProvider.notifier); + final workspace = _workspace(id: root, rootPath: root); + controller.attachWorkspace(workspace); + await controller.associateSharedRepository(workspace, repository); + final old = Object(), current = Object(); + final pending = Completer(); + final status = GitStatusSnapshot( + repositoryInfo: GitRepositoryInfo( + rootPath: root, + gitDirPath: '$root/.git', + identityKey: repository.key, + ), + files: const [], + ); + controller.bindSharedStatusSource( + workspace, + repository, + owner: old, + refresh: () => pending.future, + current: () async => status, + stage: (_, _) async {}, + ); + final retiredRefresh = controller.refresh(); + var refreshes = 0; + controller.bindSharedStatusSource( + workspace, + repository, + owner: current, + refresh: () async { + refreshes++; + return status; + }, + current: () async => status, + stage: (_, _) async {}, + ); + controller.releaseSharedStatusSource(old); + await controller.refresh(); + expect(refreshes, 1); + controller.releaseSharedStatusSource(current); + await controller.refresh(); + expect(gateway.statusCalls, greaterThan(0)); + final fallback = container.read(gitControllerProvider).statusSnapshot; + pending.complete(status); + await retiredRefresh; + expect( + container.read(gitControllerProvider).statusSnapshot, + same(fallback), + ); + expect(refreshes, 1); + }, + ); + test( 'late shared status cannot target a different authoring workspace', () async { @@ -261,53 +407,6 @@ void main() { ); }, ); - test('diff open target follows the current working-tree context', () { - const repository = GitRepositoryInfo( - rootPath: '/repo', - gitDirPath: '/repo/.git', - ); - const addedThenDeleted = GitFileStatus( - repoRelativePath: 'draft.md', - absolutePath: '/repo/draft.md', - indexStatus: GitFileChangeStatus.added, - workTreeStatus: GitFileChangeStatus.deleted, - category: GitFileStatusCategory.deleted, - staged: true, - unstaged: true, - untracked: false, - deleted: true, - renamed: false, - copied: false, - conflicted: false, - ignored: false, - ); - const changesState = GitState( - repositoryInfo: repository, - statusSnapshot: GitStatusSnapshot( - repositoryInfo: repository, - files: [addedThenDeleted], - ), - selectedChange: GitChangeSelection( - path: 'draft.md', - comparison: GitComparisonType.staged, - ), - ); - - expect(changesState.selectedDiffOpenFilePath, isNull); - expect( - const GitState( - selectedView: GitView.fileHistory, - fileHistory: GitFileHistoryState(currentPath: 'current.md'), - ).selectedDiffOpenFilePath, - 'current.md', - ); - expect( - const GitState( - selectedView: GitView.projectHistory, - ).selectedDiffOpenFilePath, - isNull, - ); - }); test('refreshes after workspace attach', () async { final gateway = _FakeGitGateway(); @@ -481,8 +580,6 @@ void main() { await controller.refresh(); expect(gateway.lastDetectedWorkspacePath, trusted.path); - await controller.initializeRepository(); - expect(gateway.lastInitializeRootPath, trusted.path); final trustedDetectCalls = gateway.detectCalls; await workspaceLink.delete(); await workspaceLink.create(replacement.path); @@ -541,7 +638,6 @@ void main() { rootPath: root, gitDirPath: repository.gitDir, identityKey: repository.key, - currentBranch: 'main', ), files: [gateway._file(staged: staged, unstaged: !staged)], ); @@ -557,12 +653,6 @@ void main() { }, ); await controller.refreshFromSharedSnapshot(); - await controller.selectChange( - const GitChangeSelection( - path: 'README.md', - comparison: GitComparisonType.unstaged, - ), - ); final scansBeforeStaging = gateway.statusCalls; await controller.stageFiles(['README.md']); expect( @@ -574,13 +664,6 @@ void main() { .repoRelativePath, 'README.md', ); - expect( - container.read(gitControllerProvider).selectedChange, - const GitChangeSelection( - path: 'README.md', - comparison: GitComparisonType.staged, - ), - ); await controller.unstageFiles(['README.md']); expect( container @@ -597,133 +680,6 @@ void main() { }, ); - test('routes untracked selections to the untracked comparison', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.selectChange( - const GitChangeSelection( - path: 'draft.md', - comparison: GitComparisonType.untracked, - ), - ); - - expect(gateway.untrackedDiffRequests, ['draft.md']); - expect(gateway.diffRequests, isEmpty); - }); - - test('staged rename comparison preserves the original path', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.selectChange( - const GitChangeSelection( - path: 'new.md', - comparison: GitComparisonType.staged, - originalRepoRelativePath: 'old.md', - ), - ); - - expect(gateway.diffRequests, [('new.md', true)]); - expect(gateway.diffOriginalPaths, ['old.md']); - }); - - test('rollback forwards every validated rename path', () async { - final gateway = _FakeGitGateway(staged: true); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.rollbackFiles(['old.md', 'new.md']); - - expect(gateway.rollbackPathSets, const [ - ['old.md', 'new.md'], - ]); - }); - - test('reactivates an open change comparison tab', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - await controller.selectChange( - const GitChangeSelection( - path: 'README.md', - comparison: GitComparisonType.unstaged, - ), - ); - controller.deactivateDiffFile(); - - expect( - container.read(gitControllerProvider).selectedDiffForDisplay, - isNull, - ); - await controller.activateDiffFile('README.md'); - - final state = container.read(gitControllerProvider); - expect(state.selectedCommitFilePath, 'README.md'); - expect(state.selectedDiffForDisplay, isNotNull); - }); - - test('commit blocks empty message', () async { - final gateway = _FakeGitGateway(staged: true); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.commit(' '); - - expect( - container.read(gitControllerProvider).lastError?.code, - GitFailureCode.invalidCommitMessage, - ); - expect(gateway.commitCalls, 0); - }); - - test('commit blocks when no files are staged', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.commit('Docs'); - - expect( - container.read(gitControllerProvider).lastError?.code, - GitFailureCode.noStagedFiles, - ); - expect(gateway.commitCalls, 0); - }); - - test('configures author identity through the active repository', () async { - final gateway = _FakeGitGateway(staged: true); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - final configured = await controller.configureAuthorIdentity( - name: 'Example Author', - email: 'author@example.com', - globally: true, - ); - - expect(configured, isTrue); - expect(gateway.authorName, 'Example Author'); - expect(gateway.authorEmail, 'author@example.com'); - expect(gateway.authorIdentityGlobal, isTrue); - }); - test('AI staged-diff fingerprint rejects obsolete commit context', () async { final gateway = _FakeGitGateway(staged: true) ..stagedRawPatch = 'diff --git a/a.md b/a.md\n+first\n'; @@ -743,191 +699,6 @@ void main() { expect(await controller.stagedDiffMatches(snapshot.fingerprint), isFalse); }); - test('branch switch requires clean BusyMark editor state', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - await container - .read(workspaceControllerProvider.notifier) - .createMarkdownFile(); - container - .read(workspaceControllerProvider.notifier) - .updateActiveText('# Dirty\n'); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.switchBranch('feature'); - - expect( - container.read(gitControllerProvider).lastError?.code, - GitFailureCode.dirtyWorkspace, - ); - expect(gateway.switchCalls, 0); - }); - - test( - 'restore is blocked while the active editor has unsaved content', - () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - await container - .read(workspaceControllerProvider.notifier) - .createMarkdownFile(); - container - .read(workspaceControllerProvider.notifier) - .updateActiveText('# Unsaved\n'); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - await controller.loadFileHistory('/repo/README.md'); - await controller.selectFileHistoryCommit('1234567890abcdef'); - - final restored = await controller.restoreSelectedFileVersion(); - - expect(restored, isFalse); - expect(gateway.restoreCalls, 0); - expect( - container.read(gitControllerProvider).lastError?.code, - GitFailureCode.dirtyWorkspace, - ); - }, - ); - - test('restore is blocked while the current file is staged', () async { - final gateway = _FakeGitGateway(staged: true); - final originalIndex = gateway.indexContent; - final originalWorkingTree = gateway.workingTreeContent; - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - await controller.loadFileHistory('/repo/README.md'); - await controller.selectFileHistoryCommit('1234567890abcdef'); - - final restored = await controller.restoreSelectedFileVersion(); - - expect(restored, isFalse); - expect(gateway.restoreCalls, 0); - expect(gateway.staged, isTrue); - expect(gateway.indexContent, originalIndex); - expect(gateway.workingTreeContent, originalWorkingTree); - expect( - container.read(gitControllerProvider).lastError?.code, - GitFailureCode.stagedChanges, - ); - }); - - test( - 'restore protects a repository-relative file against the repository root', - () async { - final repository = await Directory.systemTemp.createTemp( - 'busymark-git-restore-root-', - ); - addTearDown(() async { - if (await repository.exists()) await repository.delete(recursive: true); - }); - final path = '${repository.path}/README.md'; - await File(path).writeAsString('# Working tree before restore\n'); - final store = MemoryLocalHistoryStore(); - final gateway = _RootedGitGateway(repository.path); - final container = _container(gateway, historyStore: store); - final workspaceController = container.read( - workspaceControllerProvider.notifier, - ); - await workspaceController.openPath(repository.path); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace( - container.read(workspaceControllerProvider).workspace!, - ); - await controller.refresh(); - await controller.loadFileHistory(path); - await controller.selectFileHistoryCommit('1234567890abcdef'); - - expect(await controller.restoreSelectedFileVersion(), isTrue); - expect(gateway.restoreCalls, 1); - final snapshot = await store.load(); - final protected = []; - for (final summary in snapshot.revisions.where( - (revision) => - revision.reason == LocalHistoryCaptureReason.beforeDiscard, - )) { - protected.add((await store.readRevision(summary.id))!); - } - expect(protected.map((revision) => revision.source), [ - '# Working tree before restore\n', - ]); - expect( - snapshot.documents.singleWhere( - (document) => document.currentPath == path, - ), - isNotNull, - ); - }, - ); - - test('project history reset uses the selected commit and mode', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - await controller.loadProjectHistory(); - await controller.selectProjectCommit('1234567890abcdef'); - - final reset = await controller.resetCurrentBranchToSelectedCommit( - GitResetMode.mixed, - ); - - expect(reset, isTrue); - expect(gateway.resetCalls, 1); - expect(gateway.resetHash, '1234567890abcdef'); - expect(gateway.resetMode, GitResetMode.mixed); - expect( - container.read(gitControllerProvider).selectedView, - GitView.projectHistory, - ); - }); - - test('project history reset is blocked by unsaved editor content', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - await container - .read(workspaceControllerProvider.notifier) - .createMarkdownFile(); - container - .read(workspaceControllerProvider.notifier) - .updateActiveText('# Unsaved\n'); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - await controller.loadProjectHistory(); - await controller.selectProjectCommit('1234567890abcdef'); - - final reset = await controller.resetCurrentBranchToSelectedCommit( - GitResetMode.hard, - ); - - expect(reset, isFalse); - expect(gateway.resetCalls, 0); - final failure = container.read(gitControllerProvider).lastError; - expect(failure?.code, GitFailureCode.dirtyWorkspace); - expect(failure?.commandName, 'reset'); - }); - - test('fetch refreshes repository status', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - final statusCallsBefore = gateway.statusCalls; - - await controller.fetch(); - - expect(gateway.fetchCalls, 1); - expect(gateway.statusCalls, greaterThan(statusCallsBefore)); - }); - test('reports Git unavailable state', () async { final container = _container(const UnavailableGitRepositoryGateway()); final controller = container.read(gitControllerProvider.notifier); @@ -942,8 +713,8 @@ void main() { expect(container.read(gitControllerProvider).repositoryInfo, isNull); }); - test('stores operation failure state', () async { - final gateway = _FakeGitGateway(failStage: true); + test('reports disconnected Files staging', () async { + final gateway = _FakeGitGateway(); final container = _container(gateway); final controller = container.read(gitControllerProvider.notifier); controller.attachWorkspace(_workspace()); @@ -969,10 +740,6 @@ void main() { container.read(gitControllerProvider).statusSnapshot?.conflictedFiles, isNotEmpty, ); - expect( - container.read(gitControllerProvider).repositoryInfo?.hasConflicts, - isTrue, - ); }); test('clears previous workspace Git state immediately on attach', () async { @@ -981,8 +748,6 @@ void main() { final controller = container.read(gitControllerProvider.notifier); controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); await controller.refresh(); - await controller.loadProjectHistory(); - await controller.loadCommitDetails('1234567890abcdef'); await controller.stageFiles(['../outside.md']); controller.attachWorkspace(_workspace(id: '/other', rootPath: '/other')); @@ -991,17 +756,7 @@ void main() { expect(state.attachedWorkspace?.id, '/other'); expect(state.repositoryInfo, isNull); expect(state.statusSnapshot, isNull); - expect(state.selectedFilePath, isNull); - expect(state.selectedCommitHash, isNull); - expect(state.selectedCommitFilePath, isNull); - expect(state.openDiffFilePaths, isEmpty); - expect(state.selectedDiff, isNull); - expect(state.history, isEmpty); - expect(state.historyFilePath, isNull); - expect(state.branches, isEmpty); expect(state.lastError, isNull); - expect(state.lastOperationMessage, isNull); - expect(state.scopedFilePath, isNull); }); test('ignores stale refresh results after workspace switch', () async { @@ -1029,355 +784,7 @@ void main() { expect(state.repositoryInfo?.rootPath, '/other'); expect(state.statusSnapshot?.repositoryInfo.rootPath, '/other'); }); - - test( - 'cancels set-upstream push when the workspace changes during remote lookup', - () async { - final gateway = _DeferredSetUpstreamPushGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - - controller.attachWorkspace(_workspace()); - await controller.refresh(); - expect( - container.read(gitControllerProvider).repositoryInfo?.rootPath, - '/repo', - ); - - final push = controller.push(allowSetUpstream: true); - await gateway.remotesStarted.future; - expect(gateway.remotesRepository?.rootPath, '/repo'); - - controller.attachWorkspace(_workspace(id: '/other', rootPath: '/other')); - await controller.refresh(); - expect( - container.read(gitControllerProvider).repositoryInfo?.rootPath, - '/other', - ); - - gateway.remotesResult.complete(const ['origin']); - await push; - - expect(gateway.setUpstreamPushes, isEmpty); - expect( - container.read(gitControllerProvider).repositoryInfo?.rootPath, - '/other', - ); - }, - ); - - test('ignores stale history after a workspace switch', () async { - final gateway = _DeferredHistoryGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - - controller.attachWorkspace(_workspace()); - await controller.refresh(); - final history = controller.loadProjectHistory(); - await gateway.historyStarted.future; - - controller.attachWorkspace(_workspace(id: '/other', rootPath: '/other')); - await controller.refresh(); - gateway.historyResult.complete([ - _commitSummary('aaaaaaaaaaaaaaaa', 'History from the old repository'), - ]); - await history; - - final state = container.read(gitControllerProvider); - expect(state.repositoryInfo?.rootPath, '/other'); - expect(state.history, isEmpty); - expect(state.selectedView, GitView.changes); - }); - - test('history tab reloads project history after workspace switch', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - await controller.selectView(GitView.projectHistory); - expect(container.read(gitControllerProvider).history, isNotEmpty); - - controller.attachWorkspace(_workspace(id: '/other', rootPath: '/other')); - await controller.refresh(); - expect(container.read(gitControllerProvider).selectedView, GitView.changes); - expect(container.read(gitControllerProvider).history, isEmpty); - - await controller.selectView(GitView.projectHistory); - - final state = container.read(gitControllerProvider); - expect(state.selectedView, GitView.projectHistory); - expect(state.history, isNotEmpty); - expect(gateway.lastHistoryPath, isNull); - }); - - test( - 'current file history scopes selected commit details to the file', - () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - - await controller.loadFileHistory('/repo/README.md'); - await controller.loadCommitDetails('1234567890abcdef'); - - expect(gateway.lastHistoryPath, 'README.md'); - expect(gateway.lastCommitDetailsPath, isNull); - expect( - container.read(gitControllerProvider).selectedView, - GitView.fileHistory, - ); - expect( - container.read(gitControllerProvider).selectedCommitHash, - isNotNull, - ); - }, - ); - - test( - 'file history switches between commit and working-tree comparisons', - () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - await controller.loadFileHistory('/repo/README.md'); - - await controller.selectFileHistoryCommit('1234567890abcdef'); - - var history = container.read(gitControllerProvider).fileHistory; - expect(history.comparisonType, GitComparisonType.commitChange); - expect(history.comparison?.oldContent, '# Before\n'); - expect(history.comparison?.newContent, '# Full revision text\n'); - - await controller.compareFileHistoryWithCurrent(); - - history = container.read(gitControllerProvider).fileHistory; - expect(history.comparisonType, GitComparisonType.commitVersusCurrent); - expect(history.comparison?.oldContent, '# Full revision text\n'); - expect(history.comparison?.newContent, '# Working tree\n'); - - await controller.selectFileHistoryCommit('1234567890abcdef'); - - history = container.read(gitControllerProvider).fileHistory; - expect(history.comparisonType, GitComparisonType.commitChange); - expect(history.comparison?.newContent, '# Full revision text\n'); - }, - ); - - test( - 'project history loads selected commit details without a file scope', - () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - - await controller.loadFileHistory('/repo/README.md'); - await controller.loadProjectHistory(); - await controller.loadCommitDetails('1234567890abcdef'); - - expect(gateway.lastHistoryPath, isNull); - expect(gateway.lastCommitDetailsPath, isNull); - }, - ); - - test( - 'project commit details display the first changed file by default', - () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - - await controller.loadProjectHistory(); - await controller.loadCommitDetails('1234567890abcdef'); - - final state = container.read(gitControllerProvider); - expect( - state.projectHistory.details?.changedFiles.map( - (file) => file.displayPath, - ), - ['README.md', 'guide.md'], - ); - expect(state.selectedDiff?.files.single.displayPath, 'README.md'); - expect(state.selectedCommitFilePath, 'README.md'); - expect(state.openDiffFilePaths, ['README.md']); - expect( - state.selectedDiffForDisplay?.files.single.displayPath, - 'README.md', - ); - }, - ); - - test('selected commit file opens a project commit diff tab', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.loadProjectHistory(); - await controller.loadCommitDetails('1234567890abcdef'); - await controller.selectCommitFile('guide.md'); - - final state = container.read(gitControllerProvider); - expect(state.selectedCommitFilePath, 'guide.md'); - expect(state.openDiffFilePaths, ['README.md', 'guide.md']); - expect(state.projectHistory.details?.changedFiles, hasLength(2)); - expect(state.selectedDiff?.files, hasLength(1)); - expect(state.selectedDiffForDisplay?.files.single.displayPath, 'guide.md'); - expect( - state.selectedDiffForDisplay?.fileSnapshots['guide.md'], - contains('Full revision text'), - ); - }); - - test( - 'closing a commit diff file tab activates the neighboring tab', - () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.loadProjectHistory(); - await controller.loadCommitDetails('1234567890abcdef'); - await controller.selectCommitFile('guide.md'); - controller.closeDiffFile('guide.md'); - await Future.delayed(Duration.zero); - - final state = container.read(gitControllerProvider); - expect(state.selectedCommitFilePath, 'README.md'); - expect(state.openDiffFilePaths, ['README.md']); - expect( - state.selectedDiffForDisplay?.files.single.displayPath, - 'README.md', - ); - }, - ); - - test('deactivating a diff file keeps open diff tabs', () async { - final gateway = _FakeGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace()); - await controller.refresh(); - - await controller.loadProjectHistory(); - await controller.loadCommitDetails('1234567890abcdef'); - await controller.selectCommitFile('guide.md'); - controller.deactivateDiffFile(); - - final state = container.read(gitControllerProvider); - expect(state.selectedCommitFilePath, isNull); - expect(state.openDiffFilePaths, ['README.md', 'guide.md']); - expect(state.selectedDiffForDisplay, isNull); - }); - - test( - 'file and project history paginate and retain separate selections', - () async { - final gateway = _PagedHistoryGitGateway(); - final container = _container(gateway); - final controller = container.read(gitControllerProvider.notifier); - controller.attachWorkspace(_workspace(activeFilePath: '/repo/README.md')); - await controller.refresh(); - - await controller.loadFileHistory('/repo/README.md'); - expect( - container.read(gitControllerProvider).fileHistory.entries, - hasLength(50), - ); - expect(container.read(gitControllerProvider).fileHistory.hasMore, isTrue); - await controller.loadMoreFileHistory(); - expect( - container.read(gitControllerProvider).fileHistory.entries, - hasLength(55), - ); - expect( - container.read(gitControllerProvider).fileHistory.hasMore, - isFalse, - ); - final fileHash = container - .read(gitControllerProvider) - .fileHistory - .entries - .first - .commit - .fullHash; - await controller.selectFileHistoryCommit(fileHash); - - await controller.loadProjectHistory(); - expect( - container.read(gitControllerProvider).projectHistory.commits, - hasLength(50), - ); - await controller.loadMoreProjectHistory(); - expect( - container.read(gitControllerProvider).projectHistory.commits, - hasLength(60), - ); - final projectHash = container - .read(gitControllerProvider) - .projectHistory - .commits - .first - .fullHash; - await controller.selectProjectCommit(projectHash); - await controller.selectView(GitView.fileHistory); - - final state = container.read(gitControllerProvider); - expect(state.fileHistory.selectedCommitHash, fileHash); - expect(state.projectHistory.selectedCommitHash, projectHash); - expect(state.selectedCommitHash, fileHash); - }, - ); -} - -class _PagedHistoryGitGateway extends _FakeGitGateway { - final _projectCommits = List.generate( - 60, - (index) => _commitSummary( - index.toRadixString(16).padLeft(16, '0'), - 'Project commit $index', - ), - ); - late final List _fileEntries = [ - for (var index = 0; index < 55; index++) - GitFileHistoryEntry( - commit: _commitSummary( - (index + 1000).toRadixString(16).padLeft(16, '0'), - 'File commit $index', - ), - pathAtCommit: 'README.md', - pathInParent: 'README.md', - status: GitDiffFileStatus.modified, - ), - ]; - - @override - Future> history( - GitRepositoryInfo repository, { - String? repoRelativePath, - int limit = 200, - int skip = 0, - }) async => _projectCommits.skip(skip).take(limit).toList(); - - @override - Future> fileHistory( - GitRepositoryInfo repository, - String repoRelativePath, { - int limit = 200, - int skip = 0, - }) async => _fileEntries.skip(skip).take(limit).toList(); -} +} ProviderContainer _container( GitRepositoryGateway gateway, { @@ -1414,48 +821,54 @@ Workspace _workspace({ ); } +class _CountingSharedGitGateway extends GitCliGateway { + _CountingSharedGitGateway(shared.GitEngine engine) : super(engine: engine); + var statusCalls = 0; + var watchEvents = 0, refreshedWatchEvents = 0; + + @override + Stream watch(GitRepositoryInfo repository) async* { + await for (final _ in super.watch(repository)) { + watchEvents++; + yield null; + } + } + + @override + Future status(GitRepositoryInfo repository) async { + statusCalls++; + final events = watchEvents; + final snapshot = await super.status(repository); + refreshedWatchEvents = events; + return snapshot; + } +} + class _FakeGitGateway implements GitRepositoryGateway { _FakeGitGateway({ bool staged = false, this.conflicted = false, - this.failStage = false, this.failStatus = false, }) : _staged = staged; final bool conflicted; - final bool failStage; final bool failStatus; - var _staged = false; + final bool _staged; var detectCalls = 0; var statusCalls = 0; - var commitCalls = 0; - String? authorName; - String? authorEmail; - bool? authorIdentityGlobal; - var switchCalls = 0; - var fetchCalls = 0; - var restoreCalls = 0; - var resetCalls = 0; - String? resetHash; - GitResetMode? resetMode; - final diffRequests = <(String, bool)>[]; - final diffOriginalPaths = []; - final untrackedDiffRequests = []; - final rollbackPathSets = >[]; - var indexContent = '# Indexed\n'; - var workingTreeContent = '# Working tree\n'; var stagedRawPatch = 'diff --git a/README.md b/README.md\n+staged\n'; String? lastDetectedWorkspacePath; - String? lastInitializeRootPath; - String? lastHistoryPath; - String? lastCommitDetailsPath; bool get staged => _staged; + @override + Stream watch(GitRepositoryInfo repository) => const Stream.empty(); + @override + Future stagedPatch(GitRepositoryInfo repository) async => + stagedRawPatch; static const repo = GitRepositoryInfo( rootPath: '/repo', gitDirPath: '/repo/.git', - currentBranch: 'main', ); @override @@ -1498,345 +911,7 @@ class _FakeGitGateway implements GitRepositoryGateway { ), ] : [_file(staged: _staged, unstaged: !_staged)]; - return GitStatusSnapshot( - repositoryInfo: repo.copyWith(hasConflicts: conflicted), - files: files, - ); - } - - @override - Future stage( - GitRepositoryInfo repository, - List repoRelativePaths, - ) async { - if (failStage) { - throw const GitFailure( - code: GitFailureCode.commandFailed, - userMessageKey: 'gitErrorCommandFailed', - rawMessage: 'failed', - commandName: 'add', - ); - } - _staged = true; - return _result(); - } - - @override - Future unstage( - GitRepositoryInfo repository, - List repoRelativePaths, - ) async { - _staged = false; - return _result(); - } - - @override - Future commit( - GitRepositoryInfo repository, - String message, - ) async { - commitCalls++; - _staged = false; - return _result(); - } - - @override - Future configureAuthorIdentity( - GitRepositoryInfo repository, { - required String name, - required String email, - required bool globally, - }) async { - authorName = name; - authorEmail = email; - authorIdentityGlobal = globally; - return _result(); - } - - @override - Future switchBranch( - GitRepositoryInfo repository, - String branchName, - ) async { - switchCalls++; - return _result(); - } - - @override - Future> history( - GitRepositoryInfo repository, { - String? repoRelativePath, - int limit = 200, - int skip = 0, - }) async { - lastHistoryPath = repoRelativePath; - return [ - GitCommitSummary( - fullHash: '1234567890abcdef', - shortHash: '1234567', - authorName: 'BusyMark Test', - authorEmail: 'busymark@example.com', - authorDate: DateTime(2026), - subject: 'Update docs', - parentHashes: [], - ), - ]; - } - - @override - Future> fileHistory( - GitRepositoryInfo repository, - String repoRelativePath, { - int limit = 200, - int skip = 0, - }) async { - lastHistoryPath = repoRelativePath; - if (skip > 0) { - return const []; - } - return [ - GitFileHistoryEntry( - commit: _commitSummary('1234567890abcdef', 'Update docs'), - pathAtCommit: repoRelativePath, - pathInParent: repoRelativePath, - status: GitDiffFileStatus.modified, - ), - ]; - } - - @override - Future diffFile( - GitRepositoryInfo repository, - String repoRelativePath, { - required bool staged, - String? originalRepoRelativePath, - }) async { - diffRequests.add((repoRelativePath, staged)); - diffOriginalPaths.add(originalRepoRelativePath); - return const GitDiff( - title: 'README.md', - files: [], - rawPatch: '', - hasBinaryFiles: false, - ); - } - - @override - Future diffUntrackedFile( - GitRepositoryInfo repository, - String repoRelativePath, - ) async { - untrackedDiffRequests.add(repoRelativePath); - return GitDiff( - title: repoRelativePath, - files: [_diffFile(repoRelativePath)], - rawPatch: '', - hasBinaryFiles: false, - fileSnapshots: {repoRelativePath: '# Untracked\n'}, - ); - } - - @override - Future diffAll( - GitRepositoryInfo repository, { - required bool staged, - }) async { - return GitDiff( - title: 'All', - files: const [], - rawPatch: staged ? stagedRawPatch : '', - hasBinaryFiles: false, - ); - } - - @override - Future commitDetails( - GitRepositoryInfo repository, - String hash, { - String? repoRelativePath, - }) async { - lastCommitDetailsPath = repoRelativePath; - final changedFiles = repoRelativePath == null - ? [_diffFile('README.md'), _diffFile('guide.md')] - : [_diffFile(repoRelativePath)]; - return GitCommitDetails( - summary: GitCommitSummary( - fullHash: hash, - shortHash: hash.substring(0, 7), - authorName: 'BusyMark Test', - authorEmail: 'busymark@example.com', - authorDate: DateTime(2026), - subject: 'Update docs', - parentHashes: const [], - ), - changedFiles: changedFiles, - patch: '', - fileSnapshots: { - for (final file in changedFiles) - file.displayPath: '# ${file.displayPath}\n\nFull revision text.\n', - }, - ); - } - - @override - Future readFileAtCommit( - GitRepositoryInfo repository, - String hash, - String repoRelativePath, - ) async => '# $repoRelativePath\n'; - - @override - Future compareFileWithParent( - GitRepositoryInfo repository, - String hash, { - String? oldPath, - String? newPath, - }) async { - final path = newPath ?? oldPath!; - final file = GitDiffFile( - oldPath: oldPath, - newPath: newPath, - status: newPath == null - ? GitDiffFileStatus.deleted - : oldPath == null - ? GitDiffFileStatus.added - : oldPath != newPath - ? GitDiffFileStatus.renamed - : GitDiffFileStatus.modified, - hunks: const [], - binary: false, - additions: 1, - deletions: 1, - ); - final diff = GitDiff( - title: path, - files: [file], - rawPatch: '', - hasBinaryFiles: false, - fileSnapshots: {path: '# Full revision text\n'}, - ); - return GitHistoricalFileComparison( - oldPath: oldPath, - newPath: newPath, - oldContent: oldPath == null ? '' : '# Before\n', - newContent: newPath == null ? '' : '# Full revision text\n', - diff: diff, - ); - } - - @override - Future compareFileWithWorkingTree( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }) async { - final file = _diffFile(currentPath); - final diff = GitDiff( - title: currentPath, - files: [file], - rawPatch: 'working-tree comparison', - hasBinaryFiles: false, - fileSnapshots: {currentPath: workingTreeContent}, - ); - return GitHistoricalFileComparison( - oldPath: historicalPath, - newPath: currentPath, - oldContent: '# Full revision text\n', - newContent: workingTreeContent, - diff: diff, - ); - } - - @override - Future restoreFileFromCommit( - GitRepositoryInfo repository, - String hash, { - required String historicalPath, - required String currentPath, - }) async { - restoreCalls += 1; - workingTreeContent = '# Restored\n'; - return _result(); - } - - @override - Future resetCurrentBranch( - GitRepositoryInfo repository, - String hash, - GitResetMode mode, - ) async { - resetCalls += 1; - resetHash = hash; - resetMode = mode; - return _result(); - } - - @override - Future> branches(GitRepositoryInfo repository) async { - return const [GitBranch(name: 'main', current: true)]; - } - - @override - Future> remotes(GitRepositoryInfo repository) async => const []; - - @override - Future rollbackTracked( - GitRepositoryInfo repository, - List repoRelativePaths, - ) async { - rollbackPathSets.add(List.unmodifiable(repoRelativePaths)); - return _result(); - } - - @override - Future discardUntracked( - GitRepositoryInfo repository, - List repoRelativePaths, - GitStatusSnapshot snapshot, - ) async => _result(); - - @override - Future pullFastForwardOnly( - GitRepositoryInfo repository, - ) async => _result(); - - @override - Future fetch(GitRepositoryInfo repository) async { - fetchCalls += 1; - return _result(); - } - - @override - Future push(GitRepositoryInfo repository) async => - _result(); - - @override - Future pushSetUpstream( - GitRepositoryInfo repository, - String remote, - String branch, - ) async => _result(); - - @override - Future createBranch( - GitRepositoryInfo repository, - String branchName, - ) async => _result(); - - @override - Future initializeRepository(String rootPath) async { - lastInitializeRootPath = rootPath; - return _result(); - } - - GitOperationResult _result() { - return const GitOperationResult( - success: true, - message: 'ok', - stdout: '', - stderr: '', - ); + return GitStatusSnapshot(repositoryInfo: repo, files: files); } GitFileStatus _file({ @@ -1885,7 +960,6 @@ class _AssociatedGitGateway extends _TrustRequiredFakeGitGateway { rootPath: repository.root, gitDirPath: repository.gitDir, identityKey: repository.key, - currentBranch: 'main', ); } @@ -1894,56 +968,6 @@ class _AssociatedGitGateway extends _TrustRequiredFakeGitGateway { final value = await super.status(repository); return GitStatusSnapshot(repositoryInfo: repository, files: value.files); } - - @override - Future stage( - GitRepositoryInfo repository, - List paths, - ) async { - stageCalls++; - return super.stage(repository, paths); - } -} - -class _RootedGitGateway extends _FakeGitGateway { - _RootedGitGateway(this.rootPath); - - final String rootPath; - - GitRepositoryInfo get repository => GitRepositoryInfo( - rootPath: rootPath, - gitDirPath: '$rootPath/.git', - currentBranch: 'main', - ); - - @override - Future detectRepository(String workspacePath) async { - detectCalls++; - return repository; - } - - @override - Future status(GitRepositoryInfo repository) async => - GitStatusSnapshot( - repositoryInfo: repository, - files: [ - GitFileStatus( - repoRelativePath: 'README.md', - absolutePath: '$rootPath/README.md', - indexStatus: GitFileChangeStatus.unmodified, - workTreeStatus: GitFileChangeStatus.modified, - category: GitFileStatusCategory.modified, - staged: false, - unstaged: true, - untracked: false, - deleted: false, - renamed: false, - copied: false, - conflicted: false, - ignored: false, - ), - ], - ); } class _DeferredDetectGitGateway extends _FakeGitGateway { @@ -1996,107 +1020,6 @@ class _DeferredDetectGitGateway extends _FakeGitGateway { } } -class _DeferredHistoryGitGateway extends _FakeGitGateway { - final historyStarted = Completer(); - final historyResult = Completer>(); - - @override - Future detectRepository(String workspacePath) async { - return GitRepositoryInfo( - rootPath: workspacePath, - gitDirPath: '$workspacePath/.git', - ); - } - - @override - Future status(GitRepositoryInfo repository) async { - return GitStatusSnapshot(repositoryInfo: repository, files: const []); - } - - @override - Future> history( - GitRepositoryInfo repository, { - String? repoRelativePath, - int limit = 200, - int skip = 0, - }) { - if (!historyStarted.isCompleted) { - historyStarted.complete(); - } - return historyResult.future; - } -} - -class _DeferredSetUpstreamPushGitGateway extends _FakeGitGateway { - final remotesStarted = Completer(); - final remotesResult = Completer>(); - final setUpstreamPushes = - <({String rootPath, String remote, String branch})>[]; - GitRepositoryInfo? remotesRepository; - - @override - Future detectRepository(String workspacePath) async { - return GitRepositoryInfo( - rootPath: workspacePath, - gitDirPath: '$workspacePath/.git', - currentBranch: workspacePath == '/repo' ? 'branch-a' : 'branch-b', - hasRemote: true, - ); - } - - @override - Future status(GitRepositoryInfo repository) async { - return GitStatusSnapshot(repositoryInfo: repository, files: const []); - } - - @override - Future> remotes(GitRepositoryInfo repository) { - remotesRepository = repository; - if (!remotesStarted.isCompleted) { - remotesStarted.complete(); - } - return remotesResult.future; - } - - @override - Future pushSetUpstream( - GitRepositoryInfo repository, - String remote, - String branch, - ) async { - setUpstreamPushes.add(( - rootPath: repository.rootPath, - remote: remote, - branch: branch, - )); - return _result(); - } -} - -GitCommitSummary _commitSummary(String hash, String subject) { - return GitCommitSummary( - fullHash: hash, - shortHash: hash.substring(0, 7), - authorName: 'BusyMark Test', - authorEmail: 'busymark@example.com', - authorDate: DateTime(2026), - subject: subject, - parentHashes: const [], - ); -} - -GitDiffFile _diffFile(String path) { - return GitDiffFile( - oldPath: path, - newPath: path, - status: GitDiffFileStatus.modified, - hunks: const [], - binary: false, - additions: 1, - deletions: 0, - ); -} - class _MemorySettingsStore implements LocalSettingsStore { @override Future> load() async => {}; diff --git a/test/src/git/git_diff_parser_test.dart b/test/src/git/git_diff_parser_test.dart deleted file mode 100644 index 0a779770..00000000 --- a/test/src/git/git_diff_parser_test.dart +++ /dev/null @@ -1,165 +0,0 @@ -import 'package:busymark/src/git/domain/git_diff_parser.dart'; -import 'package:busymark/src/git/domain/git_models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - const parser = GitDiffParser(); - - test('parses added file', () { - final diff = parser.parse(''' -diff --git a/new.md b/new.md -new file mode 100644 ---- /dev/null -+++ b/new.md -@@ -0,0 +1,2 @@ -+# New -+Body -'''); - - expect(diff.files.single.status, GitDiffFileStatus.added); - expect(diff.files.single.additions, 2); - }); - - test('parses deleted file', () { - final diff = parser.parse(''' -diff --git a/old.md b/old.md -deleted file mode 100644 ---- a/old.md -+++ /dev/null -@@ -1,2 +0,0 @@ --# Old --Body -'''); - - expect(diff.files.single.status, GitDiffFileStatus.deleted); - expect(diff.files.single.deletions, 2); - }); - - test('parses modified file with line numbers', () { - final diff = parser.parse(''' -diff --git a/readme.md b/readme.md ---- a/readme.md -+++ b/readme.md -@@ -1,2 +1,2 @@ heading - # Title --Old -+New -'''); - - final hunk = diff.files.single.hunks.single; - expect(hunk.heading, 'heading'); - expect(hunk.lines.map((line) => line.kind), [ - GitDiffLineKind.context, - GitDiffLineKind.removed, - GitDiffLineKind.added, - ]); - expect(hunk.lines.last.newLineNumber, 2); - }); - - test('parses renamed file', () { - final diff = parser.parse(''' -diff --git a/old.md b/new.md -similarity index 90% -rename from old.md -rename to new.md ---- a/old.md -+++ b/new.md -@@ -1 +1 @@ --Old -+New -'''); - - final file = diff.files.single; - expect(file.status, GitDiffFileStatus.renamed); - expect(file.oldPath, 'old.md'); - expect(file.newPath, 'new.md'); - }); - - test('decodes C-quoted UTF-8 paths emitted by Git', () { - final diff = parser.parse(r''' -diff --git "a/docs/\303\234ber \"guide\".md" "b/docs/\303\234ber \"guide\".md" ---- "a/docs/\303\234ber \"guide\".md" -+++ "b/docs/\303\234ber \"guide\".md" -@@ -1 +1 @@ --Old -+New -'''); - - final file = diff.files.single; - expect(file.oldPath, 'docs/Über "guide".md'); - expect(file.newPath, 'docs/Über "guide".md'); - }); - - test('decodes C-quoted rename metadata emitted by Git', () { - final diff = parser.parse(r''' -diff --git "a/docs/\303\204lter Name.md" "b/docs/\303\204lterer \"Name\".md" -similarity index 100% -rename from "docs/\303\204lter Name.md" -rename to "docs/\303\204lterer \"Name\".md" -'''); - - final file = diff.files.single; - expect(file.status, GitDiffFileStatus.renamed); - expect(file.oldPath, 'docs/Älter Name.md'); - expect(file.newPath, 'docs/Älterer "Name".md'); - }); - - test('parses binary file marker', () { - final diff = parser.parse(''' -diff --git a/image.png b/image.png -Binary files a/image.png and b/image.png differ -'''); - - expect(diff.hasBinaryFiles, isTrue); - expect(diff.files.single.binary, isTrue); - }); - - test('parses multiple hunks', () { - final diff = parser.parse(''' -diff --git a/readme.md b/readme.md ---- a/readme.md -+++ b/readme.md -@@ -1 +1 @@ --A -+B -@@ -10 +10 @@ --C -+D -'''); - - expect(diff.files.single.hunks, hasLength(2)); - }); - - test('keeps no newline marker as header line', () { - final diff = parser.parse(r''' -diff --git a/readme.md b/readme.md ---- a/readme.md -+++ b/readme.md -@@ -1 +1 @@ --A -+B -\ No newline at end of file -'''); - - expect( - diff.files.single.hunks.single.lines.last.kind, - GitDiffLineKind.header, - ); - }); - - test('tolerates unknown diff header lines', () { - final diff = parser.parse(''' -diff --git a/readme.md b/readme.md -unknown header line ---- a/readme.md -+++ b/readme.md -@@ -1 +1 @@ -unknown hunk line -'''); - - expect( - diff.files.single.hunks.single.lines.single.kind, - GitDiffLineKind.header, - ); - }); -} diff --git a/test/src/git/git_log_parser_test.dart b/test/src/git/git_log_parser_test.dart deleted file mode 100644 index eae2a0c3..00000000 --- a/test/src/git/git_log_parser_test.dart +++ /dev/null @@ -1,65 +0,0 @@ -import 'package:busymark/src/git/domain/git_log_parser.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - const parser = GitLogParser(); - - test('parses multiple commits', () { - final commits = parser.parse( - '${gitLogRecordSeparator}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' - '${gitLogUnitSeparator}aaaaaaa' - '${gitLogUnitSeparator}Ada Lovelace' - '${gitLogUnitSeparator}ada@example.com' - '${gitLogUnitSeparator}2026-01-02T03:04:05+00:00' - '${gitLogUnitSeparator}Initial docs' - '$gitLogUnitSeparator' - '${gitLogRecordSeparator}bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' - '${gitLogUnitSeparator}bbbbbbb' - '${gitLogUnitSeparator}Grace Hopper' - '${gitLogUnitSeparator}grace@example.com' - '${gitLogUnitSeparator}2026-01-03T03:04:05+00:00' - '${gitLogUnitSeparator}Update docs' - '${gitLogUnitSeparator}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - ); - - expect(commits, hasLength(2)); - expect(commits.first.subject, 'Initial docs'); - expect(commits.last.parentHashes, [ - 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', - ]); - }); - - test('parses merge commit with multiple parents', () { - final commits = parser.parse( - '${gitLogRecordSeparator}cccccccccccccccccccccccccccccccccccccccc' - '${gitLogUnitSeparator}ccccccc' - '${gitLogUnitSeparator}Maintainer' - '${gitLogUnitSeparator}maintainer@example.com' - '${gitLogUnitSeparator}2026-01-04T03:04:05+00:00' - '${gitLogUnitSeparator}Merge branch docs' - '${gitLogUnitSeparator}aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', - ); - - expect(commits.single.parentHashes, hasLength(2)); - }); - - test('preserves author punctuation and separator-like subject text', () { - final commits = parser.parse( - '${gitLogRecordSeparator}dddddddddddddddddddddddddddddddddddddddd' - '${gitLogUnitSeparator}ddddddd' - '${gitLogUnitSeparator}Docs, Inc. (Team)' - '${gitLogUnitSeparator}docs@example.com' - '${gitLogUnitSeparator}2026-01-05T03:04:05+00:00' - '${gitLogUnitSeparator}Subject mentions %x1e and %x1f literally' - '$gitLogUnitSeparator', - ); - - expect(commits.single.authorName, 'Docs, Inc. (Team)'); - expect(commits.single.subject, contains('%x1e')); - expect(commits.single.subject, contains('%x1f')); - }); - - test('parses empty history', () { - expect(parser.parse(''), isEmpty); - }); -} diff --git a/test/src/git/git_navigation_visual_contract_test.dart b/test/src/git/git_navigation_visual_contract_test.dart index 8a1a799a..cb9bbf52 100644 --- a/test/src/git/git_navigation_visual_contract_test.dart +++ b/test/src/git/git_navigation_visual_contract_test.dart @@ -202,8 +202,11 @@ void main() { ).readAsStringSync(); final header = source.substring( source.indexOf('class _SidebarHeader extends'), - source.indexOf('class _SidebarHeaderRow extends'), + source.indexOf('typedef _SidebarHeaderSecondaryTapHandler'), ); + final sidebar = File( + 'lib/src/workspace/presentation/workspace_sidebar.dart', + ).readAsStringSync(); for (final dependency in [ 'GitRepositoryInfo', 'GitView', @@ -212,7 +215,7 @@ void main() { 'gitControllerProvider', ]) { expect( - header, + '$header\n$sidebar', isNot(contains(dependency)), reason: 'The ordinary workspace header cannot own Git data or a second workflow selector.', diff --git a/test/src/git/git_process_runner_test.dart b/test/src/git/git_process_runner_test.dart deleted file mode 100644 index dfc7cc9d..00000000 --- a/test/src/git/git_process_runner_test.dart +++ /dev/null @@ -1,400 +0,0 @@ -import 'dart:io'; -import 'package:busystack_git/busystack_git.dart' as shared; - -import 'package:busymark/src/git/data/git_cli_gateway.dart'; -import 'package:busymark/src/git/data/git_executable_locator.dart'; -import 'package:busymark/src/git/data/git_process_runner.dart'; -import 'package:busymark/src/git/domain/git_models.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - test( - 'runner closes child stdin so commands waiting for EOF can finish', - () async { - final result = await const DartGitCommandRunner().run( - '/bin/sh', - const ['-c', 'IFS= read -r ignored; printf stdin-closed'], - timeout: const Duration(seconds: 1), - commandName: 'sh', - ); - - expect(result.exitCode, 0); - expect(result.stdoutText, 'stdin-closed'); - }, - skip: Platform.isWindows, - ); - - test( - 'runner terminates commands that exceed the combined output limit', - () async { - const runner = DartGitCommandRunner(maxOutputBytes: 128); - - await expectLater( - runner.run( - '/bin/sh', - const ['-c', 'printf %080d 0; printf %080d 0 >&2; sleep 10'], - timeout: const Duration(seconds: 5), - commandName: 'noisy-command', - ), - throwsA( - isA() - .having( - (failure) => failure.commandName, - 'commandName', - 'noisy-command', - ) - .having( - (failure) => failure.rawMessage, - 'rawMessage', - contains('128-byte'), - ), - ), - ); - }, - skip: Platform.isWindows, - ); - - test('normal gateway commands always receive a finite timeout', () async { - final directory = await Directory.systemTemp.createTemp( - 'busymark-shared-timeouts-', - ); - addTearDown(() => directory.delete(recursive: true)); - final runner = _RecordingCoreRunner(directory.path); - await runner.run( - ['init', '-b', 'main'], - cwd: directory.path, - deadline: const Duration(seconds: 10), - ); - final gateway = GitCliGateway( - engine: shared.GitEngine(runner: runner, authorize: (_) => true), - ); - final repository = (await gateway.detectRepository(directory.path))!; - await gateway.status(repository); - expect(runner.timeouts, isNotEmpty); - expect(runner.timeouts, everyElement(greaterThan(Duration.zero))); - }); - - test('gateway classifies a missing commit author identity', () async { - final directory = await Directory.systemTemp.createTemp( - 'busymark-shared-identity-', - ); - addTearDown(() => directory.delete(recursive: true)); - final runner = _RecordingCoreRunner(directory.path); - await runner.run( - ['init', '-b', 'main'], - cwd: directory.path, - deadline: const Duration(seconds: 10), - ); - // Git can infer a usable identity from the OS account on some machines. - // This fixture specifically exercises missing configured author identity. - await runner.run( - ['config', '--local', 'user.useConfigOnly', 'true'], - cwd: directory.path, - deadline: const Duration(seconds: 10), - ); - await File( - '${directory.path}/draft.md', - ).writeAsString('Preserve this staged draft.'); - await runner.run( - ['add', '.'], - cwd: directory.path, - deadline: const Duration(seconds: 10), - ); - final gateway = GitCliGateway( - engine: shared.GitEngine(runner: runner, authorize: (_) => true), - ); - final repository = (await gateway.detectRepository(directory.path))!; - await expectLater( - gateway.commit(repository, 'Document the release'), - throwsA( - isA() - .having( - (failure) => failure.code, - 'code', - GitFailureCode.authorIdentity, - ) - .having( - (failure) => failure.userMessageKey, - 'userMessageKey', - 'gitErrorAuthorIdentity', - ), - ), - ); - final index = await runner.run( - ['show', ':draft.md'], - cwd: directory.path, - deadline: const Duration(seconds: 10), - ); - expect(index.text, 'Preserve this staged draft.'); - }); - - test('snap packages the Linux process-group launcher', () { - final snapcraft = File('snap/snapcraft.yaml').readAsStringSync(); - - expect(snapcraft, contains(RegExp(r'^\s*- util-linux$', multiLine: true))); - }); - - test('snap Git uses bundled helpers, templates, and SSH', () { - expect(gitEnvironmentForSnap('/snap/busymark/x1'), { - 'GIT_EXEC_PATH': '/snap/busymark/x1/usr/lib/git-core', - 'GIT_TEMPLATE_DIR': '/snap/busymark/x1/usr/share/git-core/templates', - 'GIT_SSH': '/snap/busymark/x1/usr/bin/ssh', - }); - expect(gitEnvironmentForSnap(''), isEmpty); - }); - - test('snap launcher never falls back to the confined host setsid', () async { - final snapRoot = await Directory.systemTemp.createTemp( - 'busymark-snap-launcher-', - ); - addTearDown(() => snapRoot.delete(recursive: true)); - final launcher = GitProcessGroupLauncher(snapRootOverride: snapRoot.path); - - final direct = launcher.resolve('/snap/busymark/usr/bin/git', const [ - '--version', - ]); - expect(direct.executable, '/snap/busymark/usr/bin/git'); - expect(direct.arguments, const ['--version']); - expect(direct.processGroup, isFalse); - - final bundledSetsid = File('${snapRoot.path}/usr/bin/setsid'); - await bundledSetsid.create(recursive: true); - final wrapped = launcher.resolve('/snap/busymark/usr/bin/git', const [ - '--version', - ]); - expect(wrapped.executable, bundledSetsid.path); - expect(wrapped.arguments, const [ - '--wait', - '--', - '/snap/busymark/usr/bin/git', - '--version', - ]); - expect(wrapped.processGroup, isTrue); - }, skip: !Platform.isLinux); - - test('Git locator preserves process launcher failures', () async { - final availability = await const GitExecutableLocator( - runner: _PermissionDeniedGitRunner(), - candidatePaths: ['/snap/busymark/current/usr/bin/git'], - ).locate(); - - expect(availability.available, isFalse); - expect( - availability.unavailableReason, - allOf( - contains('/snap/busymark/current/usr/bin/git'), - contains('setsid'), - contains('Permission denied'), - ), - ); - }); - - test('Git locator preserves a failed version probe result', () async { - final availability = await const GitExecutableLocator( - runner: _FailedVersionGitRunner(), - candidatePaths: ['/snap/busymark/current/usr/bin/git'], - ).locate(); - - expect(availability.available, isFalse); - expect(availability.unavailableReason, contains('exited with code 126')); - expect(availability.unavailableReason, contains('loader failure')); - }); - - test( - 'Git locator reports not found for a genuinely missing command', - () async { - final availability = await const GitExecutableLocator( - runner: _MissingGitRunner(), - candidatePaths: ['git'], - ).locate(); - - expect(availability.available, isFalse); - expect(availability.unavailableReason, 'Git executable was not found.'); - }, - ); - - test( - 'runner terminates descendant processes when a command times out', - () async { - final temp = await Directory.systemTemp.createTemp( - 'busymark-git-runner-timeout-', - ); - addTearDown(() async { - if (await temp.exists()) { - await temp.delete(recursive: true); - } - }); - final sentinel = File('${temp.path}/descendant-survived'); - final started = File('${temp.path}/descendant-started'); - - await expectLater( - const DartGitCommandRunner().run( - '/bin/sh', - [ - '-c', - '(trap "" TERM; sleep 1; printf survived > "\$1") & ' - 'printf started > "\$2"; wait', - 'sh', - sentinel.path, - started.path, - ], - timeout: const Duration(milliseconds: 200), - commandName: 'sh', - ), - throwsA( - isA().having( - (failure) => failure.userMessageKey, - 'userMessageKey', - 'gitErrorCommandFailed', - ), - ), - ); - expect(await started.exists(), isTrue); - - await Future.delayed(const Duration(milliseconds: 1100)); - expect( - await sentinel.exists(), - isFalse, - reason: 'A timed-out Git command must not leave descendants running.', - ); - }, - skip: !Platform.isLinux, - ); - - test( - 'timeout covers descendants that outlive the direct child and hold stdio', - () async { - final temp = await Directory.systemTemp.createTemp( - 'busymark-git-runner-stdio-timeout-', - ); - addTearDown(() async { - if (await temp.exists()) { - await temp.delete(recursive: true); - } - }); - final sentinel = File('${temp.path}/descendant-survived'); - - await expectLater( - const DartGitCommandRunner().run( - '/bin/sh', - [ - '-c', - '(trap "" TERM; sleep 1; printf survived > "\$1") &', - 'sh', - sentinel.path, - ], - timeout: const Duration(milliseconds: 200), - commandName: 'sh', - ), - throwsA( - isA() - .having( - (failure) => failure.userMessageKey, - 'userMessageKey', - 'gitErrorCommandFailed', - ) - .having((failure) => failure.commandName, 'commandName', 'sh'), - ), - ); - - await Future.delayed(const Duration(milliseconds: 1100)); - expect(await sentinel.exists(), isFalse); - }, - skip: !Platform.isLinux, - ); -} - -class _PermissionDeniedGitRunner implements GitCommandRunner { - const _PermissionDeniedGitRunner(); - - @override - Future run( - String executable, - List arguments, { - String? workingDirectory, - required Duration timeout, - required String commandName, - Map environment = const {}, - }) async { - throw ProcessException('setsid', const [], 'Permission denied', 13); - } -} - -class _FailedVersionGitRunner implements GitCommandRunner { - const _FailedVersionGitRunner(); - - @override - Future run( - String executable, - List arguments, { - String? workingDirectory, - required Duration timeout, - required String commandName, - Map environment = const {}, - }) async { - return GitProcessResult( - executable: executable, - arguments: arguments, - exitCode: 126, - stdoutBytes: const [], - stderrBytes: 'loader failure'.codeUnits, - ); - } -} - -class _MissingGitRunner implements GitCommandRunner { - const _MissingGitRunner(); - - @override - Future run( - String executable, - List arguments, { - String? workingDirectory, - required Duration timeout, - required String commandName, - Map environment = const {}, - }) async { - throw ProcessException('git', const [], 'No such file or directory', 2); - } -} - -class _RecordingCoreRunner implements shared.GitRunner { - _RecordingCoreRunner(this.home); - final String home; - final timeouts = []; - final process = shared.ProcessGitRunner(); - @override - Future run( - List arguments, { - required String cwd, - List? input, - shared.GitCancellation? cancellation, - Duration? deadline, - void Function(List)? onStdout, - void Function(String)? onProgress, - String Function(String)? redactDiagnostic, - Map environment = const {}, - Map> byteArguments = const {}, - int? maximumBytes, - }) { - if (deadline != null) timeouts.add(deadline); - return process.run( - arguments, - cwd: cwd, - input: input, - cancellation: cancellation, - deadline: deadline, - onStdout: onStdout, - onProgress: onProgress, - redactDiagnostic: redactDiagnostic, - byteArguments: byteArguments, - maximumBytes: maximumBytes, - environment: { - 'HOME': home, - 'GIT_CONFIG_GLOBAL': '/dev/null', - 'GIT_CONFIG_NOSYSTEM': '1', - ...environment, - }, - ); - } -} diff --git a/test/src/git/git_status_parser_test.dart b/test/src/git/git_status_parser_test.dart deleted file mode 100644 index b93b53b7..00000000 --- a/test/src/git/git_status_parser_test.dart +++ /dev/null @@ -1,153 +0,0 @@ -import 'package:busymark/src/git/domain/git_models.dart'; -import 'package:busymark/src/git/domain/git_status_parser.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - const parser = GitStatusParser(); - - test('parses clean repository status', () { - final snapshot = parser.parsePorcelainV1Z( - output: '## main\x00', - repositoryInfo: _repo(), - ); - - expect(snapshot.clean, isTrue); - expect(snapshot.repositoryInfo.currentBranch, 'main'); - }); - - test('parses modified tracked file', () { - final file = _parse(' M README.md\x00').files.single; - - expect(file.repoRelativePath, 'README.md'); - expect(file.category, GitFileStatusCategory.modified); - expect(file.unstaged, isTrue); - expect(file.staged, isFalse); - }); - - test('parses staged modification', () { - final file = _parse('M README.md\x00').files.single; - - expect(file.indexStatus, GitFileChangeStatus.modified); - expect(file.staged, isTrue); - expect(file.unstaged, isFalse); - }); - - test('parses unstaged modification', () { - final file = _parse(' M README.md\x00').files.single; - - expect(file.workTreeStatus, GitFileChangeStatus.modified); - expect(file.unstaged, isTrue); - }); - - test('parses staged and unstaged same file', () { - final file = _parse('MM README.md\x00').files.single; - - expect(file.staged, isTrue); - expect(file.unstaged, isTrue); - }); - - test('keeps staged addition and working-tree deletion separate', () { - final file = _parse('AD draft.md\x00').files.single; - - expect(file.indexStatus, GitFileChangeStatus.added); - expect(file.workTreeStatus, GitFileChangeStatus.deleted); - expect(file.staged, isTrue); - expect(file.unstaged, isTrue); - expect(file.hasWorkingTreeFile, isFalse); - }); - - test('tracks rename state independently in each status column', () { - final staged = _parse('R new.md\x00old.md\x00').files.single; - final unstaged = _parse(' R new.md\x00old.md\x00').files.single; - - expect(staged.hasStagedRename, isTrue); - expect(staged.hasUnstagedRename, isFalse); - expect(unstaged.hasStagedRename, isFalse); - expect(unstaged.hasUnstagedRename, isTrue); - }); - - test('parses untracked file', () { - final file = _parse('?? draft.md\x00').files.single; - - expect(file.category, GitFileStatusCategory.untracked); - expect(file.untracked, isTrue); - }); - - test('parses deleted file', () { - final file = _parse(' D old.md\x00').files.single; - - expect(file.category, GitFileStatusCategory.deleted); - expect(file.deleted, isTrue); - }); - - test('parses renamed file', () { - final file = _parse('R new name.md\x00old name.md\x00').files.single; - - expect(file.category, GitFileStatusCategory.renamed); - expect(file.repoRelativePath, 'new name.md'); - expect(file.originalRepoRelativePath, 'old name.md'); - }); - - test('parses copied file', () { - final file = _parse('C copy.md\x00source.md\x00').files.single; - - expect(file.category, GitFileStatusCategory.copied); - expect(file.copied, isTrue); - expect(file.originalRepoRelativePath, 'source.md'); - }); - - test('parses conflicted files', () { - final snapshot = _parse('UU conflict.md\x00'); - final file = snapshot.files.single; - - expect(file.category, GitFileStatusCategory.conflicted); - expect(file.conflicted, isTrue); - expect(snapshot.conflictedFiles, [file]); - expect(snapshot.repositoryInfo.hasConflicts, isTrue); - }); - - test('parses branch header and ahead behind counts', () { - final snapshot = _parse('## main...origin/main [ahead 2, behind 3]\x00'); - - expect(snapshot.repositoryInfo.currentBranch, 'main'); - expect(snapshot.repositoryInfo.upstreamBranch, 'origin/main'); - expect(snapshot.repositoryInfo.aheadCount, 2); - expect(snapshot.repositoryInfo.behindCount, 3); - }); - - test('parses detached head header', () { - final snapshot = _parse('## HEAD (no branch)\x00'); - - expect(snapshot.repositoryInfo.currentBranch, isNull); - }); - - test('preserves spaces, unicode, quotes, and newlines in filenames', () { - final snapshot = _parse( - ' M dir/file with spaces.md\x00' - ' M unicode/привет.md\x00' - ' M quotes/"quoted".md\x00' - ' M lines/a\nb.md\x00', - ); - - expect( - snapshot.files.map((file) => file.repoRelativePath), - containsAll([ - 'dir/file with spaces.md', - 'unicode/привет.md', - 'quotes/"quoted".md', - 'lines/a\nb.md', - ]), - ); - }); -} - -GitStatusSnapshot _parse(String output) { - return const GitStatusParser().parsePorcelainV1Z( - output: output, - repositoryInfo: _repo(), - ); -} - -GitRepositoryInfo _repo() { - return const GitRepositoryInfo(rootPath: '/repo', gitDirPath: '/repo/.git'); -} diff --git a/test/src/git/shared_gateway_identity_test.dart b/test/src/git/shared_gateway_identity_test.dart index 91610c3f..4019ca52 100644 --- a/test/src/git/shared_gateway_identity_test.dart +++ b/test/src/git/shared_gateway_identity_test.dart @@ -8,11 +8,52 @@ import 'package:flutter_test/flutter_test.dart'; // The source-complete sibling layout supplies the same isolated Git fixture // used by the engine; application tests never inherit the user's Git config. import '../../../../busystack_git/test/support/repository_fixture.dart'; +import '../../../../busystack_git/test/support/isolated_runner.dart'; void main() { late RepositoryFixture f; setUp(() async => f = await RepositoryFixture.create()); tearDown(() async => f.close()); + test( + 'AI requests only the staged patch without viewer content or remotes', + () async { + await f.commit('a.md', utf8.encode('original\n'), 'initial'); + final file = File('${f.root.path}/a.md'); + await file.writeAsString('staged\n'); + await f.git(['add', '--', 'a.md']); + await file.writeAsString('unstaged\n'); + final commands = >[]; + final gateway = GitCliGateway( + engine: shared.GitEngine( + authorize: (_) => true, + runner: IsolatedGitRunner( + f.home, + beforeRun: (args, _) async { + commands.add(List.of(args)); + }, + ), + ), + ); + final repository = (await gateway.detectRepository(f.root.path))!; + expect( + commands.any((args) => args.contains('status')), + isFalse, + reason: 'Discovery needs repository identity, not another status scan.', + ); + commands.clear(); + final patch = await gateway.stagedPatch(repository); + expect(patch, contains('-original\n+staged\n')); + expect(patch, isNot(contains('+unstaged'))); + expect(commands.any((args) => args.contains('diff')), isTrue); + for (final command in ['ls-tree', 'show', 'cat-file', 'remote']) { + expect( + commands.any((args) => args.contains(command)), + isFalse, + reason: 'AI patch access does not need $command.', + ); + } + }, + ); test( 'authoring status never turns an escaped byte filename into a mutation path', () async { @@ -29,7 +70,7 @@ void main() { expect((await f.engine.status(f.repository)).changes, hasLength(2)); expect(status.files.single.repoRelativePath, path.display); expect(status.unrepresentedPathCount, 1); - await gateway.stage(repository, [status.files.single.repoRelativePath]); + await f.git(['add', '--', status.files.single.repoRelativePath]); expect(await f.git(['ls-files', '-z']), '${path.display}\u0000'); expect(await raw.readAsBytes(), [1, 2, 3]); await literal.delete(); @@ -52,7 +93,7 @@ void main() { ).rename('${f.directory.path}/saved-git'); await f.git(['init', '-b', 'replacement']); await expectLater( - gateway.stage(reviewed, ['a.md']), + gateway.stagedPatch(reviewed), throwsA(isA()), ); expect(await f.git(['ls-files']), isEmpty); diff --git a/test/src/git/shared_git_decorations_test.dart b/test/src/git/shared_git_decorations_test.dart index 9dc925a6..f4361238 100644 --- a/test/src/git/shared_git_decorations_test.dart +++ b/test/src/git/shared_git_decorations_test.dart @@ -11,7 +11,6 @@ void main() { const repo = authoring.GitRepositoryInfo( rootPath: '/repo', gitDirPath: '/repo/.git', - currentBranch: 'main', ); authoring.GitFileStatus file(String relative, String absolute) => authoring.GitFileStatus( diff --git a/test/src/gtk_header_icon_service_test.dart b/test/src/gtk_header_icon_service_test.dart index 34fdc921..8fdfabad 100644 --- a/test/src/gtk_header_icon_service_test.dart +++ b/test/src/gtk_header_icon_service_test.dart @@ -9,6 +9,8 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('semantic catalog uses the exact native GTK icon names', () { + expect(BusyMarkLinuxHeaderIcon.home.gtkNames, const ['go-home-symbolic']); + expect(BusyMarkLinuxHeaderIcon.home.directionSensitive, isFalse); expect(BusyMarkLinuxHeaderIcon.back.gtkNames, const [ 'go-previous-symbolic', ]); diff --git a/test/src/header_bar_configuration_test.dart b/test/src/header_bar_configuration_test.dart deleted file mode 100644 index e4c15702..00000000 --- a/test/src/header_bar_configuration_test.dart +++ /dev/null @@ -1,549 +0,0 @@ -import 'dart:async'; -import 'dart:io'; - -import 'package:busymark/src/platform/linux_header_bar_service.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - test( - 'rapid navigation applies only monotonic complete configurations', - () async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel( - 'com.busymark.test/headerbar-atomic-navigation', - ); - final atomicCalls = >[]; - Map? initializePayload; - final firstApplyStarted = Completer(); - final releaseFirstApply = Completer(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - if (call.method == 'initialize') { - initializePayload = Map.from( - call.arguments! as Map, - ); - return true; - } - if (call.method != 'applyConfiguration') { - fail('Unexpected legacy call: ${call.method}'); - } - final payload = Map.from( - call.arguments! as Map, - ); - atomicCalls.add(payload); - if (atomicCalls.length == 1) { - firstApplyStarted.complete(); - await releaseFirstApply.future; - } - return payload['revision']; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService( - channel: channel, - sessionId: 'navigation-session', - ); - await service.initialize(); - final workspace = _configuration( - title: 'Workspace', - documentControlsVisible: true, - searchVisible: true, - sidebarVisible: true, - sidebarToggleVisible: true, - backVisible: true, - ); - final settings = _configuration(title: 'Settings', backVisible: true); - - final workspaceApplied = service.configurationSynchronizer - .setConfiguration(workspace); - await firstApplyStarted.future; - final settingsApplied = service.configurationSynchronizer - .setConfiguration(settings); - final duplicateSettingsApplied = service.configurationSynchronizer - .setConfiguration(settings); - releaseFirstApply.complete(); - await Future.wait([ - workspaceApplied, - settingsApplied, - duplicateSettingsApplied, - ]); - - expect(atomicCalls, hasLength(2)); - expect(initializePayload, {'sessionId': 'navigation-session'}); - expect(atomicCalls.map((payload) => payload['sessionId']).toSet(), { - 'navigation-session', - }); - expect(atomicCalls.map((payload) => payload['revision']), [1, 2]); - expect(atomicCalls.map((payload) => payload['title']), [ - 'Workspace', - 'Settings', - ]); - expect(atomicCalls.last, { - 'sessionId': 'navigation-session', - 'revision': 2, - 'title': 'Settings', - 'viewMode': 'editor', - 'searchQuery': '', - 'textDirection': 'ltr', - 'canRefresh': false, - 'canExportPdf': false, - 'canExportHtml': false, - 'documentControlsVisible': false, - 'searchActive': false, - 'searchVisible': false, - 'sidebarVisible': false, - 'sidebarToggleVisible': false, - 'backVisible': true, - 'fullScreen': false, - 'modalBarrierVisible': false, - 'modalBarrierDepth': 0, - 'sidebarWidth': 300.0, - 'labels': _labels.toMap(), - 'theme': _theme.toMap(), - }); - expect( - service.configurationSynchronizer.appliedConfiguration?.title, - 'Settings', - ); - }, - ); - - test('a new Dart session can restart native revisions from one', () async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel( - 'com.busymark.test/headerbar-hot-restart-session', - ); - var activeSession = 'previous-session'; - var nativeRevision = 42; - final calls = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call); - final payload = Map.from( - call.arguments! as Map, - ); - final sessionId = payload['sessionId']! as String; - if (call.method == 'initialize') { - if (sessionId != activeSession) { - activeSession = sessionId; - nativeRevision = -1; - } - return true; - } - expect(call.method, 'applyConfiguration'); - expect(sessionId, activeSession); - final revision = payload['revision']! as int; - if (revision > nativeRevision) { - nativeRevision = revision; - } - return nativeRevision; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService( - channel: channel, - sessionId: 'restarted-session', - ); - - expect( - await service.configurationSynchronizer.setConfiguration( - _configuration(title: 'Welcome'), - ), - true, - ); - expect(service.isAvailable, true); - expect(activeSession, 'restarted-session'); - expect(nativeRevision, 1); - expect(calls.map((call) => call.method), [ - 'initialize', - 'applyConfiguration', - ]); - }); - - test('modal depth is an atomic overlay on the latest page state', () async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel('com.busymark.test/headerbar-atomic-modal'); - final atomicCalls = >[]; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - if (call.method == 'initialize') { - return true; - } - expect(call.method, 'applyConfiguration'); - final payload = Map.from( - call.arguments! as Map, - ); - atomicCalls.add(payload); - return payload['revision']; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService(channel: channel); - await service.initialize(); - await service.configurationSynchronizer.setConfiguration( - _configuration(title: 'Settings', backVisible: true), - ); - await service.setModalBarrierDepth(1); - await service.setModalBarrierDepth(2); - await service.setModalBarrierDepth(1); - await service.setModalBarrierDepth(0); - - expect(atomicCalls, hasLength(5)); - expect(atomicCalls.map((payload) => payload['revision']), [1, 2, 3, 4, 5]); - expect(atomicCalls.map((payload) => payload['modalBarrierVisible']), [ - false, - true, - true, - true, - false, - ]); - expect(atomicCalls.map((payload) => payload['modalBarrierDepth']), [ - 0, - 1, - 2, - 1, - 0, - ]); - expect( - atomicCalls.every((payload) => payload['title'] == 'Settings'), - true, - ); - }); - - test('modal barrier is retained before the first page publishes', () async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel( - 'com.busymark.test/headerbar-atomic-early-modal', - ); - final calls = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call); - if (call.method == 'initialize') { - return true; - } - if (call.method == 'applyConfiguration') { - final payload = Map.from( - call.arguments! as Map, - ); - return payload['revision']; - } - return null; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService(channel: channel); - await service.initialize(); - await service.setModalBarrierDepth(1); - await service.configurationSynchronizer.setConfiguration( - _configuration(title: 'Welcome'), - ); - - expect( - calls - .where((call) => call.method == 'setModalBarrierDepth') - .single - .arguments, - 1, - ); - final atomicPayload = - calls - .where((call) => call.method == 'applyConfiguration') - .single - .arguments - as Map; - expect(atomicPayload['modalBarrierVisible'], true); - expect(atomicPayload['modalBarrierDepth'], 1); - }); - - test('older runners fall back once to the ordered legacy protocol', () async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel( - 'com.busymark.test/headerbar-atomic-fallback', - ); - final calls = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call.method); - if (call.method == 'initialize') { - return true; - } - if (call.method == 'applyConfiguration') { - throw MissingPluginException(); - } - return null; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService(channel: channel); - await service.initialize(); - await service.configurationSynchronizer.setConfiguration( - _configuration(title: 'Welcome'), - ); - await service.configurationSynchronizer.setConfiguration( - _configuration(title: 'Settings', backVisible: true), - ); - - expect( - calls.where((method) => method == 'applyConfiguration'), - hasLength(1), - ); - expect(calls.where((method) => method == 'setTitleRange'), hasLength(2)); - expect(calls.last, 'setModalBarrierVisible'); - expect(service.isAvailable, true); - }); - - test( - 'failed atomic apply keeps the last success and retries the same desired state', - () async { - if (!Platform.isLinux) { - return; - } - const channel = MethodChannel('com.busymark.test/headerbar-atomic-retry'); - final atomicCalls = >[]; - var initializeCalls = 0; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - if (call.method == 'initialize') { - initializeCalls++; - return true; - } - expect(call.method, 'applyConfiguration'); - final payload = Map.from( - call.arguments! as Map, - ); - atomicCalls.add(payload); - if (atomicCalls.length == 2) { - throw PlatformException(code: 'native_update_failed'); - } - return payload['revision']; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService(channel: channel); - final availabilityChanges = []; - service.addListener( - () => availabilityChanges.add(service.usesNativeHeaderBar), - ); - await service.initialize(); - final workspace = _configuration(title: 'Workspace'); - final settings = _configuration(title: 'Settings', backVisible: true); - - expect( - await service.configurationSynchronizer.setConfiguration(workspace), - true, - ); - expect( - await service.configurationSynchronizer.setConfiguration(settings), - false, - ); - - expect(service.usesNativeHeaderBar, false); - expect( - service.configurationSynchronizer.appliedConfiguration?.title, - 'Workspace', - ); - expect( - service.configurationSynchronizer.desiredConfiguration?.title, - 'Settings', - ); - - expect( - await service.configurationSynchronizer.setConfiguration(settings), - true, - ); - expect(service.usesNativeHeaderBar, true); - expect( - service.configurationSynchronizer.appliedConfiguration?.title, - 'Settings', - ); - expect(initializeCalls, 2); - expect(availabilityChanges, [true, false, true]); - expect(atomicCalls.map((payload) => payload['revision']), [1, 2, 2]); - expect(atomicCalls.map((payload) => payload['title']), [ - 'Workspace', - 'Settings', - 'Settings', - ]); - }, - ); - - test('theme map contains the native semantic visual roles', () { - expect(_theme.toMap().keys, { - 'preferDark', - 'backgroundColor', - 'sidebarBackgroundColor', - 'foregroundColor', - 'sidebarBorderColor', - 'modalBarrierColor', - 'tooltip', - }); - expect( - _theme.toMap(), - containsPair('sidebarBorderColor', 'rgba(1,2,3,0.067)'), - ); - expect( - _theme.toMap(), - containsPair('foregroundColor', 'rgba(32,32,32,1.000)'), - ); - expect(_theme.toMap(), containsPair('tooltip', _tooltipTheme.toMap())); - expect( - _tooltipTheme.toMap(), - containsPair('backgroundColor', 'rgba(0,0,0,0.800)'), - ); - expect(_tooltipTheme.toMap(), containsPair('borderRadius', 8.0)); - expect(_tooltipTheme.toMap(), containsPair('fontSize', 14.0)); - expect(_tooltipTheme.toMap(), containsPair('horizontalPadding', 10.0)); - expect(_tooltipTheme.toMap(), containsPair('verticalPadding', 6.0)); - expect(_tooltipTheme.toMap(), containsPair('minimumHeight', 30.0)); - }); - - test('native header labels expose only application-menu commands', () { - expect( - _labels.toMap(), - containsPair('syntaxReference', 'Syntax Reference'), - ); - expect(_labels.toMap(), containsPair('syntaxReferenceShortcut', 'F1')); - expect( - _labels.toMap(), - containsPair('syntaxReferenceGtkAccelerator', 'F1'), - ); - expect(_labels.toMap(), containsPair('export', 'Export')); - expect(_labels.toMap(), containsPair('exportShortcut', 'Ctrl+Shift+E')); - expect( - _labels.toMap(), - containsPair('exportGtkAccelerator', 'e'), - ); - expect(_labels.toMap(), isNot(contains('markdownAndHtml'))); - for (final removedLabel in { - 'keyboardShortcuts', - 'keyboardShortcutsShortcut', - 'keyboardShortcutsGtkAccelerator', - 'clipboardHistory', - 'localHistory', - 'findLocalHistory', - }) { - expect(_labels.toMap(), isNot(contains(removedLabel))); - } - }); -} - -HeaderBarConfiguration _configuration({ - required String title, - bool documentControlsVisible = false, - bool searchVisible = false, - bool sidebarVisible = false, - bool sidebarToggleVisible = false, - bool backVisible = false, - bool fullScreen = false, -}) { - return HeaderBarConfiguration( - title: title, - viewMode: AppViewMode.editor, - searchQuery: '', - textDirection: TextDirection.ltr, - canRefresh: false, - documentControlsVisible: documentControlsVisible, - searchActive: false, - searchVisible: searchVisible, - sidebarVisible: sidebarVisible, - sidebarToggleVisible: sidebarToggleVisible, - backVisible: backVisible, - fullScreen: fullScreen, - modalBarrierDepth: 0, - sidebarWidth: 300, - labels: _labels, - theme: _theme, - ); -} - -const _labels = HeaderBarLabels( - editor: 'Editor', - source: 'Source', - preview: 'Preview', - split: 'Dual', - viewMode: 'View mode', - editorShortcut: 'Ctrl+1', - editorGtkAccelerator: '1', - sourceShortcut: 'Ctrl+2', - sourceGtkAccelerator: '2', - previewShortcut: 'Ctrl+3', - previewGtkAccelerator: '3', - splitShortcut: 'Ctrl+4', - splitGtkAccelerator: '4', - search: 'Search', - searchShortcut: 'Ctrl+F', - refresh: 'Refresh', - menu: 'Menu', - sidebar: 'Sidebar', - sidebarShortcut: 'F9', - back: 'Back', - backShortcut: 'Alt+Left', - save: 'Save', - export: 'Export', - exportShortcut: 'Ctrl+Shift+E', - exportGtkAccelerator: 'e', - fullScreen: 'Full Screen', - fullScreenShortcut: 'F11', - fullScreenGtkAccelerator: 'F11', - settings: 'Settings', - settingsShortcut: 'Ctrl+,', - settingsGtkAccelerator: 'comma', - syntaxReference: 'Syntax Reference', - syntaxReferenceShortcut: 'F1', - syntaxReferenceGtkAccelerator: 'F1', - reportIssue: 'Report Issue', - aboutBusyMark: 'About BusyMark', -); - -const _theme = HeaderBarTheme( - preferDark: false, - backgroundColor: Color(0xFFFFFFFF), - sidebarBackgroundColor: Color(0xFFF6F6F6), - foregroundColor: Color(0xFF202020), - sidebarBorderColor: Color(0x11010203), - modalBarrierColor: Color(0x55000000), - tooltip: _tooltipTheme, -); - -const _tooltipTheme = HeaderBarTooltipTheme( - backgroundColor: Color.fromRGBO(0, 0, 0, 0.8), - foregroundColor: Color(0xFFFFFFFF), - borderColor: Color.fromRGBO(255, 255, 255, 0.1), - borderRadius: 8, - fontSize: 14, - horizontalPadding: 10, - verticalPadding: 6, - minimumHeight: 30, -); diff --git a/test/src/html_export_test.dart b/test/src/html_export_test.dart index 1584a0cf..9a701ce7 100644 --- a/test/src/html_export_test.dart +++ b/test/src/html_export_test.dart @@ -2,6 +2,7 @@ import 'dart:io'; import 'package:busymark/src/core/local_image_resolver.dart'; import 'package:busymark/src/export/html_export_models.dart'; import 'package:busymark/src/export/html_export_service.dart'; +import 'package:busymark/src/export/html_export_publisher.dart'; import 'package:busymark/src/export/html_export_assets.dart'; import 'package:busymark/src/markdown/markdown_model.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -436,6 +437,51 @@ css: https://evil.invalid/style.css expect(await File(result.entryPointPath).readAsString(), index); }); + test( + 'site validation failure preserves displaced and newer directories through service cleanup', + () async { + final source = p.absolute('test/fixtures/writerside/conformance_project'); + final destination = p.join(root.path, 'site'); + await service.exportWriterside( + projectRoot: source, + moduleRoot: source, + instanceId: 'conformance', + destinationPath: destination, + ); + String? displaced; + final racing = HtmlExportService( + stylesheetLoader: () => File('assets/export/html.css').readAsString(), + publisher: HtmlExportPublisher( + beforeSiteExchange: (target, _) async { + await File(p.join(target, 'external-A.txt')).writeAsString('A'); + }, + afterSiteExchange: (target, stage) async { + displaced = stage; + await File(p.join(target, 'external-B.txt')).writeAsString('B'); + }, + ), + ); + await expectLater( + racing.exportWriterside( + projectRoot: source, + moduleRoot: source, + instanceId: 'conformance', + destinationPath: destination, + overwrite: true, + ), + throwsA(isA()), + ); + expect( + await File(p.join(destination, 'external-B.txt')).readAsString(), + 'B', + ); + expect( + await File(p.join(displaced!, 'external-A.txt')).readAsString(), + 'A', + ); + }, + ); + test('official conformance fixture exports as individual pages', () async { final source = p.absolute('test/fixtures/writerside/conformance_project'); final cfg = await File(p.join(source, 'conformance.tree')).exists(); diff --git a/test/src/html_export_ui_test.dart b/test/src/html_export_ui_test.dart index 804261bb..9a70aea9 100644 --- a/test/src/html_export_ui_test.dart +++ b/test/src/html_export_ui_test.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:io'; +import 'package:busymark/src/core/save_destination.dart'; import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/src/app/app_settings.dart'; import 'package:busymark/src/app/app_theme.dart'; @@ -8,7 +9,6 @@ import 'package:busymark/src/app/command_registry.dart'; import 'package:busymark/src/export/html_export_models.dart'; import 'package:busymark/src/export/html_export_service.dart'; import 'package:busymark/src/export/html_export_ui.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/writerside/writerside_project.dart'; import 'package:flutter/material.dart'; @@ -76,13 +76,13 @@ void main() { final root = Directory.systemTemp.createTempSync('html-ui-'); addTearDown(() => root.deleteSync(recursive: true)); final service = _RecordingExporter(); - final picker = Completer(); - const channel = MethodChannel('plugins.flutter.io/file_selector'); - String? suggestion; + final picker = Completer?>(); + const channel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( call, ) async { - suggestion = (call.arguments as Map)['suggestedName'] as String?; + expect(call.method, 'save'); + expect((call.arguments as Map)['suggestedName'], endsWith('.html')); return picker.future; }); addTearDown( @@ -107,11 +107,12 @@ void main() { await tester.pumpAndSettle(); await tester.tap(find.byKey(const ValueKey('export-options-submit'))); await tester.pumpAndSettle(); - expect(suggestion, endsWith('.html')); ref .read(workspaceControllerProvider.notifier) .updateActiveText('# Later edit'); - picker.complete(p.join(root.path, 'untitled.html')); + picker.complete( + SaveDestination.inspect('${root.path}/export.html').chooserReview, + ); for (var i = 0; i < 15; i++) { await tester.runAsync( () => Future.delayed(const Duration(milliseconds: 50)), @@ -213,11 +214,6 @@ Widget _harness(HtmlExportService service, void Function(WidgetRef) ready) => overrides: [ htmlExportServiceProvider.overrideWithValue(service), localSettingsStoreProvider.overrideWithValue(_Settings()), - linuxHeaderBarServiceProvider.overrideWithValue( - LinuxHeaderBarService( - channel: const MethodChannel('html-test-header'), - ), - ), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, @@ -280,6 +276,8 @@ class _RecordingExporter extends HtmlExportService { required String instanceId, required String destinationPath, bool overwrite = false, + SaveDestination? authorization, + String? expectedSiteOwnership, HtmlExportOptions options = const HtmlExportOptions(), WritersideProject? capturedProject, HtmlExportCancellationToken? cancellationToken, diff --git a/test/src/html_publication_test.dart b/test/src/html_publication_test.dart index c0a14d71..530235a2 100644 --- a/test/src/html_publication_test.dart +++ b/test/src/html_publication_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:io'; import 'dart:convert'; +import 'package:busymark/src/core/save_destination.dart'; import 'package:busymark/src/core/atomic_file_writer.dart'; import 'package:busymark/src/export/html_export_models.dart'; import 'package:busymark/src/export/html_export_publisher.dart'; @@ -514,7 +515,9 @@ class _FailHtmlWrite extends AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { if (targetPath.endsWith('.html')) { @@ -525,6 +528,7 @@ class _FailHtmlWrite extends AtomicFileWriter { bytes, overwrite: overwrite, beforePublish: beforePublish, + checkBeforeCommit: checkBeforeCommit, acceptReplaced: acceptReplaced, ); } diff --git a/test/src/linux_accent_provider_test.dart b/test/src/linux_accent_provider_test.dart index f5d1bd43..7ff30bfd 100644 --- a/test/src/linux_accent_provider_test.dart +++ b/test/src/linux_accent_provider_test.dart @@ -4,7 +4,6 @@ import 'package:busymark/src/app/app_router.dart'; import 'package:busymark/src/app/app_settings.dart'; import 'package:busymark/src/app/busymark_app.dart'; import 'package:busymark/src/app/system_accent.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:dbus/dbus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -268,9 +267,6 @@ void main() { await tester.pump(); expect(ready, isTrue); await initialized; - final header = LinuxHeaderBarService( - channel: const MethodChannel('test.busymark/headerbar'), - ); final router = GoRouter( routes: [ GoRoute( @@ -289,7 +285,6 @@ void main() { }), initialSystemAccentColorProvider.overrideWithValue(coordinator.color), localSettingsStoreProvider.overrideWithValue(_MemorySettings()), - linuxHeaderBarServiceProvider.overrideWithValue(header), appRouterProvider.overrideWithValue(router), ], ); @@ -349,7 +344,6 @@ void main() { expect(gtk.cancels, 1); expect(io.closes, 1); router.dispose(); - header.dispose(); await gtk.events.close(); await io.signals.close(); }); diff --git a/test/src/linux_header_bar_service_test.dart b/test/src/linux_header_bar_service_test.dart deleted file mode 100644 index 387c2678..00000000 --- a/test/src/linux_header_bar_service_test.dart +++ /dev/null @@ -1,198 +0,0 @@ -import 'dart:io'; - -import 'package:busymark/src/platform/linux_header_bar_service.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - test( - 'headerbar update retries native channel initialization after early miss', - () async { - if (!Platform.isLinux) { - return; - } - TestWidgetsFlutterBinding.ensureInitialized(); - const channel = MethodChannel('com.busymark.test/headerbar-retry'); - final calls = []; - var initializeAttempts = 0; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call.method); - if (call.method == 'initialize') { - initializeAttempts++; - if (initializeAttempts == 1) { - throw MissingPluginException(); - } - return true; - } - return null; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService(channel: channel); - - await service.initialize(); - await service.setSidebarVisible(false); - - expect(calls, ['initialize', 'initialize', 'setSidebarVisible']); - }, - ); - - test('headerbar forwards text direction updates', () async { - if (!Platform.isLinux) { - return; - } - TestWidgetsFlutterBinding.ensureInitialized(); - const channel = MethodChannel('com.busymark.test/headerbar-direction'); - final calls = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call); - if (call.method == 'initialize') { - return true; - } - return null; - }); - addTearDown(() { - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - }); - - final service = LinuxHeaderBarService(channel: channel); - - await service.setTextDirection(TextDirection.rtl); - - expect(calls.map((call) => call.method), [ - 'initialize', - 'setTextDirection', - ]); - expect(calls.last.arguments, 'rtl'); - }); - - test('headerbar action events preserve repeated identical clicks', () async { - if (!Platform.isLinux) { - return; - } - TestWidgetsFlutterBinding.ensureInitialized(); - const channelName = 'com.busymark.test/headerbar-events'; - const channel = MethodChannel(channelName); - const codec = StandardMethodCodec(); - final service = LinuxHeaderBarService(channel: channel); - final events = []; - final subscription = service.actionEvents.listen(events.add); - - addTearDown(() async { - await subscription.cancel(); - channel.setMethodCallHandler(null); - }); - - Future sendNativeAction(String method) { - return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - channelName, - codec.encodeMethodCall(MethodCall(method)), - (_) {}, - ); - } - - await sendNativeAction('save'); - await sendNativeAction('save'); - await sendNativeAction('export'); - await sendNativeAction('fullScreen'); - await sendNativeAction('reportIssue'); - await sendNativeAction('sidebarFiles'); - await sendNativeAction('sidebarToc'); - await sendNativeAction('sidebarOutline'); - await sendNativeAction('sidebarGit'); - await sendNativeAction('sidebarLocalHistory'); - await sendNativeAction('sidebarClipboardHistory'); - - expect(events.map((event) => event.action), [ - HeaderBarAction.save, - HeaderBarAction.save, - HeaderBarAction.export, - HeaderBarAction.fullScreen, - HeaderBarAction.reportIssue, - HeaderBarAction.sidebarFiles, - HeaderBarAction.sidebarToc, - HeaderBarAction.sidebarOutline, - HeaderBarAction.sidebarGit, - HeaderBarAction.sidebarLocalHistory, - HeaderBarAction.sidebarClipboardHistory, - ]); - expect(events.map((event) => event.sequence), [ - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - ]); - expect(events.first, isNot(events.last)); - }); - - test( - 'native search events and focus request keep semantic meaning', - () async { - if (!Platform.isLinux) { - return; - } - TestWidgetsFlutterBinding.ensureInitialized(); - const channelName = 'com.busymark.test/headerbar-search-events'; - const channel = MethodChannel(channelName); - const codec = StandardMethodCodec(); - final calls = []; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, (call) async { - calls.add(call); - return switch (call.method) { - 'initialize' || 'focusSearch' => true, - _ => null, - }; - }); - final service = LinuxHeaderBarService(channel: channel); - final events = []; - final subscription = service.searchEvents.listen(events.add); - - addTearDown(() async { - await subscription.cancel(); - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(channel, null); - channel.setMethodCallHandler(null); - }); - - Future sendNativeEvent(String method, [Object? arguments]) { - return TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .handlePlatformMessage( - channelName, - codec.encodeMethodCall(MethodCall(method, arguments)), - (_) {}, - ); - } - - expect(await service.focusSearch(), isTrue); - expect(calls.map((call) => call.method), ['initialize', 'focusSearch']); - - await sendNativeEvent('searchQueryChanged', 'draft'); - await sendNativeEvent('searchSubmitted', 'draft'); - await sendNativeEvent('searchFocusChanged', true); - await sendNativeEvent('searchCleared'); - await sendNativeEvent('searchEscapePressed'); - - expect(events, hasLength(5)); - expect((events[0] as HeaderBarSearchQueryChanged).query, 'draft'); - expect((events[1] as HeaderBarSearchSubmitted).query, 'draft'); - expect((events[2] as HeaderBarSearchFocusChanged).focused, isTrue); - expect(events[3], isA()); - expect(events[4], isA()); - }, - ); -} diff --git a/test/src/local_history_controller_test.dart b/test/src/local_history_controller_test.dart index 65adb7da..5e56c98a 100644 --- a/test/src/local_history_controller_test.dart +++ b/test/src/local_history_controller_test.dart @@ -2052,10 +2052,9 @@ void main() { contains('authentication'), ); - controller.browseDocuments(); final contents = await controller.findRetained(query: 'authentication'); var state = container.read(localHistoryControllerProvider); - expect(state.browsingDocuments, isTrue); + expect(contents!.matches.map((m) => m.document.id).toSet(), { state.snapshot.documents.single.id, }); @@ -2097,7 +2096,6 @@ void main() { .read(localHistoryControllerProvider) .selectedDocumentId; - controller.browseDocuments(); final matches = await controller.findRetained(query: 'Unique retained'); var state = container.read(localHistoryControllerProvider); final deleted = state.snapshot.documents.singleWhere( @@ -2116,7 +2114,7 @@ void main() { await controller.selectDocumentForBuffer(current); state = container.read(localHistoryControllerProvider); expect(state.inspectingRetainedDocument, isFalse); - expect(state.browsingDocuments, isFalse); + expect(state.selectedDocumentId, currentId); expect(state.selectedRevisions, isNotEmpty); }, @@ -2164,7 +2162,7 @@ void main() { await tester.runAsync(() => workspace.openPath(currentPath)); final history = container.read(localHistoryControllerProvider.notifier); await tester.runAsync(history.refresh); - history.browseDocuments(); + expect( (await tester.runAsync( () => history.findRetained(query: 'Unique retained'), diff --git a/test/src/local_history_workspace_test.dart b/test/src/local_history_workspace_test.dart index 04db6ebe..74445f3e 100644 --- a/test/src/local_history_workspace_test.dart +++ b/test/src/local_history_workspace_test.dart @@ -2,6 +2,7 @@ import 'dart:io'; import 'dart:async'; import 'dart:convert'; +import 'package:busymark/src/core/save_destination.dart'; import 'package:busymark/src/app/app_settings.dart'; import 'package:busymark/src/app/app_theme.dart'; import 'package:busymark/l10n/generated/app_localizations.dart'; @@ -21,9 +22,12 @@ import 'package:busymark/src/workspace/workspace_model.dart'; import 'package:busymark/src/workspace/workspace_service.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; +import '../support/widget_async.dart'; + void main() { late Directory root; @@ -895,7 +899,11 @@ void main() { test( 'pre-traversal recovery survives branch and reopen (autosave=$autoSave)', () async { - final path = p.join(root.path, 'traversal.md'); + // The History store is app data, outside the watched document folder. + final documents = await Directory( + p.join(root.path, 'documents'), + ).create(); + final path = p.join(documents.path, 'traversal.md'); await File(path).writeAsString('baseline'); final store = FileLocalHistoryStore( rootDirectory: () async => Directory(p.join(root.path, 'history')), @@ -920,10 +928,25 @@ void main() { h.controller.updateActiveText('new branch'); expect(h.controller.redoActiveBuffer(), isFalse); if (autoSave) { - await _waitFor( - () => !h.state.activeBuffer!.isDirty, - operation: 'autosave after branch', - ); + final saved = Completer(); + final subscription = h.container.listen(workspaceControllerProvider, ( + _, + next, + ) { + final buffer = next.bufferForPath(path); + if (buffer != null && + !buffer.isDirty && + buffer.lastSavedText == 'new branch' && + !saved.isCompleted) { + saved.complete(); + } + }, fireImmediately: true); + try { + await saved.future; + } finally { + subscription.close(); + } + expect(await File(path).readAsString(), 'new branch'); } expect(await history.flushAll(h.state.documentBuffers), isTrue); expect( @@ -7464,6 +7487,111 @@ void main() { }); } + for (final direct in [true, false]) { + testWidgets( + 'missing revision uses final destination consent (direct=$direct)', + (tester) async { + final original = p.join(root.path, 'original.md'); + final copy = p.join(root.path, 'copy.md'); + final anchor = p.join(root.path, 'anchor.md'); + File(anchor).writeAsStringSync('Unchanged anchor'); + const channel = MethodChannel('busymark/save_chooser'); + final messenger = tester.binding.defaultBinaryMessenger; + var chooserUses = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'save'); + chooserUses++; + return chooserUses == 1 + ? null + : SaveDestination.inspect(copy).chooserReview; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final h = (await tester.runAsync(() async { + final store = MemoryLocalHistoryStore(); + final captured = await _capture( + store, + original, + 'Historical revision', + ); + final h = await _harness( + store, + fileMonitor: _ControlledFileMonitor(), + comparisonComputer: (old, current) async => + compareSource(old, current), + ); + await h.controller.openPath(anchor); + final history = h.container.read( + localHistoryControllerProvider.notifier, + ); + await history.refresh(); + history.inspectRetainedDocument(captured.document.id); + await history.selectRevision(captured.revision!.id); + return h; + }))!; + await tester.pumpWidget( + UncontrolledProviderScope( + container: h.container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const Scaffold(body: LocalHistoryComparisonView()), + ), + ), + ); + final app = AppLocalizations.of( + tester.element(find.byType(LocalHistoryComparisonView)), + ); + final action = find.text( + direct + ? app.localHistoryRestoreOriginalLocation + : app.localHistoryRestoreNewLocation, + ); + await pumpUntil( + tester, + () => action.evaluate().isNotEmpty, + operation: 'Show restore route', + ); + + // The destination appeared after the comparison still showed a missing file. + final replacement = File(direct ? original : copy) + ..writeAsStringSync('Arrived later'); + Future showConfirmation() async { + await tester.tap(action); + if (!direct) { + await tester.pump(); + expect(find.text(app.overwrite), findsNothing); + return; + } + final overwrite = find.text(app.overwrite); + await pumpUntil( + tester, + () => overwrite.evaluate().isNotEmpty, + operation: 'Show one final overwrite confirmation', + ); + await tester.pump(const Duration(milliseconds: 300)); + expect(overwrite, findsOneWidget); + } + + await showConfirmation(); + if (direct) await tester.tap(find.text(app.cancel)); + await tester.pumpAndSettle(); + expect(replacement.readAsStringSync(), 'Arrived later'); + expect(h.state.activeText, 'Unchanged anchor'); + await showConfirmation(); + if (direct) await tester.tap(find.text(app.overwrite)); + await pumpUntil( + tester, + () => h.state.activeText == 'Historical revision', + operation: 'Restore revision into the approved buffer', + ); + expect(h.state.activeBuffer!.filePath, replacement.path); + expect(replacement.readAsStringSync(), 'Arrived later'); + expect(chooserUses, direct ? 0 : 2); + await tester.pumpWidget(const SizedBox()); + }, + ); + } + testWidgets( 'comparison renders styled intraline spans without framework errors', (tester) async { @@ -8491,12 +8619,28 @@ class _RecordingRestoreWorkspaceService extends WorkspaceService { return super.saveText(path, text); } + @override + Future saveTextIfUnchanged( + String path, + String text, { + required WorkspaceFileSnapshot expectedSnapshot, + }) async { + writes.add(text); + return super.saveTextIfUnchanged( + path, + text, + expectedSnapshot: expectedSnapshot, + ); + } + @override Future saveNewFormattedText( String path, String text, { TextFormatMetadata? format, LineEndingNormalization? mixedNormalization, + SaveDestination? authorization, + bool Function()? stillCurrent, Future Function()? onPublished, }) async { writes.add(text); diff --git a/test/src/markdown_pdf_export_test.dart b/test/src/markdown_pdf_export_test.dart index ab6d1fdb..6e734cea 100644 --- a/test/src/markdown_pdf_export_test.dart +++ b/test/src/markdown_pdf_export_test.dart @@ -11,11 +11,9 @@ import 'package:busymark/src/export/markdown_pdf_models.dart'; import 'package:busymark/src/export/typst_compiler.dart'; import 'package:busymark/src/export/writerside_pdf_export_ui.dart'; import 'package:busymark/src/markdown/markdown_parser.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; import 'package:busymark/src/writerside/writerside_module_service.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; @@ -40,12 +38,8 @@ void main() { ), ), ); - final headerBar = LinuxHeaderBarService( - channel: const MethodChannel('markdown-pdf-error-test'), - ); final dialog = showMarkdownPdfExportError( context, - headerBar, const MarkdownPdfExportException( MarkdownPdfFailureCode.compilerFailed, detail: 'Typst could not load the bundled template.', diff --git a/test/src/markdown_visualization_export_test.dart b/test/src/markdown_visualization_export_test.dart index c0291255..7275f493 100644 --- a/test/src/markdown_visualization_export_test.dart +++ b/test/src/markdown_visualization_export_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; @@ -21,7 +22,7 @@ import 'package:path/path.dart' as p; void main() { late Directory temporaryDirectory; late Directory exportRoot; - late VisualizationCoordinator coordinator; + late _TrackingCoordinator coordinator; setUp(() async { temporaryDirectory = await Directory.systemTemp.createTemp( @@ -30,7 +31,7 @@ void main() { exportRoot = await Directory( p.join(temporaryDirectory.path, 'export'), ).create(); - coordinator = VisualizationCoordinator( + coordinator = _TrackingCoordinator( renderers: [_ExportRenderer()], cache: VisualizationCache( diskRoot: Directory(p.join(temporaryDirectory.path, 'cache')), @@ -65,6 +66,11 @@ void main() { cancellationToken: MarkdownPdfCancellationToken(), ); + expect(coordinator.retired, hasLength(4)); + expect(coordinator.cleared, coordinator.retired); + for (final key in coordinator.retired) { + expect(coordinator.lastSuccessfulFor(key), isNull); + } expect(preparation.blockOverrides, hasLength(3)); expect(preparation.warnings, hasLength(1)); expect( @@ -112,6 +118,54 @@ void main() { }, ); + test( + 'cancellation retires every export key and clears retained results', + () async { + final parsed = const MarkdownParser().parse( + filePath: p.join(temporaryDirectory.path, 'guide.md'), + source: _allVisualizations, + validateLocalReferences: false, + ); + final blocked = _BlockedExportRenderer(); + coordinator.dispose(); + coordinator = _TrackingCoordinator( + renderers: [blocked], + cache: VisualizationCache(), + ); + final cancellation = MarkdownPdfCancellationToken(); + final operation = + MarkdownVisualizationExportRenderer(coordinator: coordinator).prepare( + document: parsed.busyDocument, + exportRoot: exportRoot, + documentPath: parsed.filePath, + workspaceRoot: temporaryDirectory.path, + cancellationToken: cancellation, + ); + final failure = expectLater( + operation, + throwsA( + anyOf( + isA().having( + (e) => e.code, + 'code', + MarkdownPdfFailureCode.cancelled, + ), + isA(), + ), + ), + ); + await blocked.started.future; + cancellation.cancel(); + blocked.release.complete(); + await failure; + expect(coordinator.retired, hasLength(4)); + expect(coordinator.cleared, coordinator.retired); + for (final key in coordinator.retired) { + expect(coordinator.lastSuccessfulFor(key), isNull); + } + }, + ); + test( 'enforces the export block count without failing the document', () async { @@ -468,3 +522,32 @@ class _RecordingExportRenderer extends _ExportRenderer { return super.render(request, cancellationToken); } } + +class _TrackingCoordinator extends VisualizationCoordinator { + _TrackingCoordinator({required super.renderers, required super.cache}); + final retired = {}, cleared = {}; + @override + void cancel(String blockKey) { + retired.add(blockKey); + super.cancel(blockKey); + } + + @override + void clearLastSuccessful(String blockKey) { + cleared.add(blockKey); + super.clearLastSuccessful(blockKey); + } +} + +class _BlockedExportRenderer extends _ExportRenderer { + final started = Completer(), release = Completer(); + @override + Future render( + VisualizationRenderRequest request, + VisualizationCancellationToken token, + ) async { + if (!started.isCompleted) started.complete(); + await release.future; + return super.render(request, token); + } +} diff --git a/test/src/modal_barrier_test.dart b/test/src/modal_barrier_test.dart index 2c54531b..fc195a99 100644 --- a/test/src/modal_barrier_test.dart +++ b/test/src/modal_barrier_test.dart @@ -1,7 +1,6 @@ import 'package:busymark/src/app/app_theme.dart'; import 'package:busymark/src/app/busymark_design.dart'; import 'package:busymark/src/app/busymark_dialogs.dart'; -import 'package:busymark/src/platform/header_bar_configuration.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -18,7 +17,6 @@ void main() { accentColor: const Color(0xFF3584E4), ); late Color flutterBarrier; - late Color nativeBarrier; await tester.pumpWidget( MaterialApp( @@ -26,9 +24,6 @@ void main() { home: Builder( builder: (context) { flutterBarrier = busyMarkModalBarrierColor(context); - nativeBarrier = HeaderBarTheme.fromContext( - context, - ).modalBarrierColor; return const SizedBox.shrink(); }, ), @@ -37,7 +32,6 @@ void main() { final shade = theme.extension()!.shade; expect(flutterBarrier, shade); - expect(nativeBarrier, shade); expect(flutterBarrier.a, closeTo(expectedAlpha, 0.0001)); }); } diff --git a/test/src/native_headerbar_audit_test.dart b/test/src/native_headerbar_audit_test.dart index 87bc4b1b..f0f03872 100644 --- a/test/src/native_headerbar_audit_test.dart +++ b/test/src/native_headerbar_audit_test.dart @@ -423,7 +423,9 @@ void main() { expect(nativeMenu, contains('GTK_IS_MENU(session->menu)')); expect(nativeMenu, contains('gtk_menu_attach_to_widget(')); expect(nativeMenu, contains('gtk_widget_translate_coordinates(')); - expect(nativeMenu, contains('native_menu_capture_trigger_event')); + expect(nativeMenu, contains('native_menu_view_event')); + expect(nativeMenu, contains('native_menu_route_key_event')); + expect(nativeMenu, contains('deliver_menu_event_to_view(data, event)')); expect(nativeMenu, contains('gdk_event_copy(event)')); expect(nativeMenu, contains('gtk_menu_popup_at_rect(')); expect(nativeMenu, contains('rect_window, &window_anchor')); diff --git a/test/src/nextcloud_notes/notes_disconnect_sync_test.dart b/test/src/nextcloud_notes/notes_disconnect_sync_test.dart new file mode 100644 index 00000000..e92491d5 --- /dev/null +++ b/test/src/nextcloud_notes/notes_disconnect_sync_test.dart @@ -0,0 +1,284 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:busymark/src/app/app_settings.dart'; +import 'package:busymark/src/nextcloud_notes/application/nextcloud_connection.dart'; +import 'package:busymark/src/nextcloud_notes/application/notes_repository.dart'; +import 'package:busymark/src/nextcloud_notes/application/notes_sync_coordinator.dart'; +import 'package:busymark/src/nextcloud_notes/data/notes_secret_store.dart'; +import 'package:busymark/src/nextcloud_notes/data/notes_store.dart'; +import 'package:busymark/src/nextcloud_notes/domain/notes_models.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:sqlite3/sqlite3.dart'; + +import 'notes_api_test.dart' show testAccount; + +void main() { + final account = testAccount(); + late Directory root; + late String path; + late NotesStore owner; + late _Secrets secrets; + late int revocations; + late int revokeStatus; + + setUp(() async { + root = await Directory.systemTemp.createTemp('notes-disconnect-'); + path = '${root.path}/notes.sqlite'; + owner = await NotesStore.open(path: path); + await owner.saveAccount(account); + secrets = _Secrets(); + revocations = 0; + revokeStatus = 200; + }); + + tearDown(() async { + await owner.close(); + await root.delete(recursive: true); + }); + + Future connection() async { + final container = ProviderContainer( + overrides: [ + nextcloudNotesDatabasePathProvider.overrideWith((_) async => path), + nextcloudSecretStoreProvider.overrideWithValue(secrets), + nextcloudHttpClientProvider.overrideWithValue( + MockClient((request) async { + expect(request.method, 'DELETE'); + expect(request.url.path, endsWith('/core/apppassword')); + revocations++; + return http.Response('', revokeStatus); + }), + ), + localSettingsStoreProvider.overrideWithValue(_Settings()), + ], + ); + final repository = await container.read( + nextcloudNotesRepositoryProvider.future, + ); + final controller = container.read(nextcloudConnectionProvider.notifier); + await controller.reload(); + addTearDown(() async { + container.dispose(); + await repository.dispose(); + }); + return controller; + } + + test('stale disconnect leaves both credentials untouched', () async { + final controller = await connection(); + await owner.saveAccount(account.copyWith(appVersion: '6.2.0')); + expect(await controller.disconnect(), isFalse); + expect(revocations, 0); + expect(secrets.deletions, 0); + expect(secrets.password, 'fixture'); + expect((await owner.accounts()).single.disconnectPending, isFalse); + expect(controller.state.failure, isA()); + }); + + test( + 'foreign ownership excludes disconnect and a later retry succeeds', + () async { + final controller = await connection(); + final acquired = Completer(), release = Completer(); + final held = owner.withRequestOwnership(account.id, () async { + acquired.complete(); + await release.future; + }); + await acquired.future; + try { + expect(await controller.disconnect(), isFalse); + expect(revocations, 0); + expect(secrets.deletions, 0); + } finally { + release.complete(); + await held; + } + expect(await controller.disconnect(), isTrue); + expect(revocations, 1); + expect(secrets.password, isNull); + expect(await owner.accounts(), isEmpty); + expect(controller.state.account, isNull); + }, + ); + + test( + 'failed credential deletion leaves durable disconnect state and retry', + () async { + final controller = await connection(); + secrets.failDeletion = true; + expect(await controller.disconnect(), isFalse); + expect(revocations, 1); + expect(secrets.password, 'fixture'); + expect((await owner.accounts()).single.disconnectPending, isTrue); + expect( + controller.state.phase, + NextcloudConnectionPhase.disconnectPending, + ); + final reopened = await connection(); + expect(reopened.state.phase, NextcloudConnectionPhase.disconnectPending); + expect(await reopened.reconnect(), isFalse); + secrets.failDeletion = false; + expect(await reopened.disconnect(), isTrue); + expect(secrets.password, isNull); + expect(await owner.accounts(), isEmpty); + }, + ); + + test( + 'database removal failure after revocation stays disconnected on retry', + () async { + final controller = await connection(); + final db = sqlite3.open(path); + addTearDown(db.close); + db.execute(''' + CREATE TRIGGER block_disconnect BEFORE DELETE ON accounts + BEGIN SELECT RAISE(ABORT, 'test failure'); END + '''); + expect(await controller.disconnect(), isFalse); + expect(revocations, 1); + expect(secrets.password, isNull); + expect( + controller.state.phase, + NextcloudConnectionPhase.disconnectPending, + ); + final reopened = await connection(); + expect(reopened.state.phase, NextcloudConnectionPhase.disconnectPending); + db.execute('DROP TRIGGER block_disconnect'); + expect(await reopened.disconnect(), isTrue); + expect(revocations, 1); + expect(await owner.accounts(), isEmpty); + }, + ); + + test( + 'failed remote revocation removes local state with the existing warning', + () async { + final controller = await connection(); + revokeStatus = 503; + expect(await controller.disconnect(), isTrue); + expect(controller.state.removedWithWarning, isTrue); + expect(controller.state.account, isNull); + expect(secrets.password, isNull); + expect(await owner.accounts(), isEmpty); + }, + ); + + test( + 'manual Sync reports a foreign owner and a stale cache as account errors', + () async { + var requests = 0; + final repository = NotesRepository( + store: await NotesStore.open(path: path), + clientForAccount: (_) async { + requests++; + throw StateError('Unexpected network access'); + }, + ); + await repository.initialize(); + addTearDown(repository.dispose); + final coordinator = NotesSyncCoordinator(repository) + ..setActiveAccount(account.id); + addTearDown(coordinator.dispose); + await owner.withRequestOwnership(account.id, () async { + await coordinator.request(NotesSyncTrigger.manual); + expect( + repository.accountError(account.id)?.code, + NotesFailureCode.conflict, + ); + }); + await owner.saveAccount(account.copyWith(appVersion: '6.2.0')); + await coordinator.request(NotesSyncTrigger.manual); + expect( + repository.accountError(account.id)?.code, + NotesFailureCode.conflict, + ); + expect(requests, 0); + }, + ); + + test( + 'unexpected acquisition failure propagates and disposal still closes', + () async { + final store = await NotesStore.open(path: path); + final repository = NotesRepository( + store: store, + clientForAccount: (_) async => + throw StateError('Unexpected network access'), + ); + await repository.initialize(); + await store.close(); + await expectLater(repository.synchronize(account.id), throwsStateError); + final disposal = repository.dispose(); + await disposal; + expect(repository.dispose(), same(disposal)); + await expectLater(repository.changes, emitsDone); + }, + ); + + test( + 'failed pending synchronization releases ownership and disposal closes resources', + () async { + final entered = Completer(), fail = Completer(); + final store = await NotesStore.open(path: path); + final repository = NotesRepository( + store: store, + clientForAccount: (_) async { + entered.complete(); + await fail.future; + throw StateError('injected synchronization failure'); + }, + ); + await repository.initialize(); + final ended = expectLater( + repository.changes, + emitsInOrder([mayEmit(null), emitsDone]), + ); + final sync = repository.synchronize(account.id); + final rejected = expectLater(sync, throwsStateError); + await entered.future; + final disposal = repository.dispose(); + final disposedWithError = expectLater(disposal, throwsStateError); + expect(repository.dispose(), same(disposal)); + fail.complete(); + await rejected; + await disposedWithError; + await ended; + await expectLater(store.accounts(), throwsStateError); + await owner.withRequestOwnership(account.id, () async {}); + }, + ); +} + +class _Secrets implements NextcloudSecretStore { + String? password = 'fixture'; + int deletions = 0; + bool failDeletion = false; + + @override + Future read(String accountId) async => password; + + @override + Future write(String accountId, String secret) async { + password = secret; + } + + @override + Future delete(String accountId) async { + deletions++; + if (failDeletion) { + throw const NextcloudCredentialException('injected failure'); + } + password = null; + } +} + +class _Settings implements LocalSettingsStore { + @override + Future> load() async => {}; + @override + Future save(Map json) async {} +} diff --git a/test/src/nextcloud_notes/notes_process_ownership_test.dart b/test/src/nextcloud_notes/notes_process_ownership_test.dart new file mode 100644 index 00000000..39f0e11c --- /dev/null +++ b/test/src/nextcloud_notes/notes_process_ownership_test.dart @@ -0,0 +1,271 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; +import 'package:busymark/src/nextcloud_notes/application/notes_repository.dart'; +import 'package:busymark/src/nextcloud_notes/data/notes_store.dart'; +import 'package:busymark/src/nextcloud_notes/domain/notes_models.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'notes_api_test.dart' show testAccount, testNote; + +void main() { + late Directory root; + late String path; + setUp(() async { + root = await Directory.systemTemp.createTemp('notes-process-cas-'); + path = p.join(root.path, 'notes.db'); + final store = await NotesStore.open(path: path); + await store.saveAccount(testAccount()); + await store.saveNote(testNote(serverId: null)); + await store.close(); + }); + tearDown(() => root.delete(recursive: true)); + final conflict = throwsA( + isA().having( + (e) => e.code, + 'code', + NotesFailureCode.conflict, + ), + ); + + Future repository() async { + final r = NotesRepository( + store: await NotesStore.open(path: path), + clientForAccount: (_) async => + throw StateError('No network in local save test'), + ); + await r.initialize(); + addTearDown(r.dispose); + return r; + } + + test( + 'independent repository caches reject stale content and retain the editor proposal', + () async { + final a = await repository(), b = await repository(); + final original = b.notes.single; + await a.save(original.localId, content: 'A'); + await expectLater(b.save(original.localId, content: 'B'), conflict); + await expectLater( + b.save(original.localId, content: original.content), + conflict, + ); + expect(a.notes.single.content, 'A'); + expect( + b.notes.single.content, + original.content, + reason: 'Failed durability never advances the cache', + ); + expect((await b.store.notes()).single.content, 'A'); + // Even a fresh observational read cannot authorize the stale cached edit. + await expectLater(b.save(original.localId, content: 'B'), conflict); + }, + ); + + test( + 'deleted cached identities block remote requests before any network operation', + () async { + final r = await repository(); + final external = await NotesStore.open(path: path); + addTearDown(external.close); + await external.commit(removeNotes: [r.notes.single.localId]); + await expectLater(r.delete(r.notes.single.localId), conflict); + expect(await external.notes(), isEmpty); + }, + ); + + test( + 'independent processes reject stale edits and acknowledgments without revision changes', + () async { + final a = await _Peer.open(path), b = await _Peer.open(path); + addTearDown(a.stop); + addTearDown(b.stop); + expect(await a.call({'action': 'ack'}), {'ok': true}); + expect(await b.call({'action': 'save', 'content': 'B'}), { + 'conflict': true, + }); + // The acknowledgment changed durable state without incrementing revision. + expect(await b.call({'action': 'ack'}), {'conflict': true}); + final current = (await a.call({'action': 'read'}))['note'] as Map; + expect(current['content'], 'body'); + expect(current['ackRevision'], current['revision']); + }, + ); + + test( + 'startup leaves a live request alone; process death permits crash recovery', + () async { + final owner = await _Peer.open(path); + addTearDown(owner.stop); + expect(await owner.call({'action': 'hold'}), {'ok': true}); + final observer = await NotesStore.open(path: path); + expect((await observer.notes()).single.syncState, NoteSyncState.syncing); + await expectLater( + observer.withRequestOwnership(testAccount().id, () async {}), + conflict, + ); + await expectLater( + observer.saveNote(testNote(serverId: null, content: 'foreign')), + conflict, + ); + await observer.close(); + owner.process.kill(ProcessSignal.sigkill); + await owner.process.exitCode; + final recovered = await NotesStore.open(path: path); + addTearDown(recovered.close); + expect( + (await recovered.notes()).single.syncState, + NoteSyncState.creationUncertain, + ); + expect((await recovered.notes()).single.content, 'body'); + }, + ); + + test( + 'a queued overlapping request retains ownership after the first request ends', + () async { + final owner = await NotesStore.open(path: path); + final observer = await NotesStore.open(path: path); + addTearDown(owner.close); + addTearDown(observer.close); + final entered = Completer(), release = Completer(); + late Future overlapping; + await owner.withRequestOwnership(testAccount().id, () async { + overlapping = owner.withRequestOwnership(testAccount().id, () async { + entered.complete(); + await release.future; + }); + // End while the second begin is queued, before its reply reaches Dart. + }); + await entered.future; + await expectLater( + observer.withRequestOwnership(testAccount().id, () async {}), + conflict, + ); + release.complete(); + await overlapping; + await observer.withRequestOwnership(testAccount().id, () async {}); + }, + ); + + test( + 'closing a store drains active requests before releasing their claim', + () async { + final owner = await NotesStore.open(path: path); + final observer = await NotesStore.open(path: path); + addTearDown(observer.close); + final entered = Completer(), release = Completer(); + final request = owner.withRequestOwnership(testAccount().id, () async { + entered.complete(); + await release.future; + }); + await entered.future; + var closed = false; + final closing = owner.close().then((_) { + closed = true; + }); + await Future.delayed(Duration.zero); + expect(closed, isFalse); + await expectLater( + observer.withRequestOwnership(testAccount().id, () async {}), + conflict, + ); + release.complete(); + await request; + await closing; + await observer.withRequestOwnership(testAccount().id, () async {}); + }, + ); + + test( + 'attachment metadata and bytes plus removals share the persisted fence', + () async { + final a = await NotesStore.open(path: path); + final note = (await a.notes()).single; + final attachment = NotesAttachment( + id: 'attachment', + noteId: note.localId, + filename: 'a.bin', + reference: 'busymark-attachment:fixture', + ); + await a.saveAttachment(attachment, Uint8List.fromList([1, 2])); + final b = await NotesStore.open(path: path); + addTearDown(a.close); + addTearDown(b.close); + final old = (await b.attachments()).single; + await a.updateAttachment( + NotesAttachment( + id: old.id, + noteId: old.noteId, + filename: old.filename, + reference: old.reference, + state: 'uploading', + ), + ); + await a.saveNote(note.copyWith(syncState: NoteSyncState.syncing)); + await expectLater(b.updateAttachment(old), conflict); + await expectLater(b.removeAccount(note.accountId), conflict); + expect(await b.attachmentBytes(old.id), [1, 2]); + expect((await b.attachments()).single.state, 'uploading'); + await expectLater( + b.createWithAttachments( + note.copyWith(content: 'stale'), + [], + additionalNotes: [note], + ), + conflict, + ); + expect((await b.notes()).single.content, 'body'); + }, + ); +} + +class _Peer { + _Peer(this.process, this.messages); + final Process process; + final StreamIterator messages; + bool _stopped = false; + static Future<_Peer> open(String path) async { + final dart = p.join( + Platform.environment['FLUTTER_ROOT']!, + 'bin', + 'cache', + 'dart-sdk', + 'bin', + 'dart', + ); + final process = await Process.start(dart, [ + 'run', + 'test/support/notes_store_process.dart', + path, + ]); + final errors = []; + process.stderr.transform(utf8.decoder).listen(errors.add); + final messages = StreamIterator( + process.stdout.transform(utf8.decoder).transform(const LineSplitter()), + ); + if (!await messages.moveNext().timeout(const Duration(seconds: 90))) { + throw StateError('Notes peer failed: ${errors.join()}'); + } + expect(jsonDecode(messages.current)['ready'], isTrue); + return _Peer(process, messages); + } + + Future> call(Map command) async { + process.stdin.writeln(jsonEncode(command)); + await process.stdin.flush(); + if (!await messages.moveNext().timeout(const Duration(seconds: 30))) { + throw StateError('Notes peer exited'); + } + return jsonDecode(messages.current) as Map; + } + + Future stop() async { + if (_stopped) return; + _stopped = true; + process.kill(); + await process.exitCode; + await messages.cancel(); + } +} diff --git a/test/src/nextcloud_notes/notes_repository_regression_test.dart b/test/src/nextcloud_notes/notes_repository_regression_test.dart index 76c3b66d..41925b90 100644 --- a/test/src/nextcloud_notes/notes_repository_regression_test.dart +++ b/test/src/nextcloud_notes/notes_repository_regression_test.dart @@ -902,9 +902,9 @@ void main() { }, ); - for (final schema in [2, 3, 4, 5]) { + for (final schema in [2, 3, 4, 5, 6, 7]) { test( - 'v$schema migration retains exact outbox and bytes; failed recovery rolls back fence; v7 rejected', + 'v$schema migration retains exact pending notes and bytes, drops mirror transactionally; v9 rejected', () async { final r = await open(MockClient((_) async => http.Response('[]', 200))); final draft = await r.create(testAccount().id, content: 'retained'); @@ -926,7 +926,11 @@ void main() { db.execute('DROP TABLE IF EXISTS $table'); } db.execute('PRAGMA user_version=$schema'); - final outbox = db.select('SELECT data FROM outbox').single['data']; + db.execute( + 'CREATE TABLE outbox (note_id TEXT PRIMARY KEY, data TEXT NOT NULL)', + ); + final pending = db.select('SELECT data FROM notes').single['data']; + db.execute('INSERT INTO outbox VALUES(?,?)', [draft.localId, pending]); db.close(); final migrated = await open( MockClient((_) async => http.Response('[]', 200)), @@ -938,8 +942,24 @@ void main() { expect(await migrated.store.attachmentBytes(attachment.id), [1, 2]); await restart(migrated); db = sqlite3.open('${directory.path}/notes.sqlite3'); - expect(db.select('PRAGMA user_version').single.values.single, 6); - expect(db.select('SELECT data FROM outbox').single['data'], outbox); + expect(db.select('PRAGMA user_version').single.values.single, 8); + expect( + db.select("SELECT name FROM sqlite_master WHERE name='outbox'"), + isEmpty, + ); + expect(db.select('SELECT data FROM notes').single['data'], pending); + db.execute('PRAGMA user_version=9'); + db.close(); + await expectLater( + NotesStore.open(path: '${directory.path}/notes.sqlite3'), + throwsStateError, + ); + db = sqlite3.open('${directory.path}/notes.sqlite3'); + expect(db.select('PRAGMA user_version').single.values.single, 9); + db.execute( + 'CREATE TABLE outbox (note_id TEXT PRIMARY KEY, data TEXT NOT NULL)', + ); + db.execute('INSERT INTO outbox VALUES(?,?)', [draft.localId, pending]); db.execute('DROP TRIGGER IF EXISTS notes_search_delete'); for (final table in [ 'note_search', @@ -965,12 +985,8 @@ void main() { ), isEmpty, ); - db.execute('PRAGMA user_version=7'); + expect(db.select('SELECT data FROM outbox').single['data'], pending); db.close(); - await expectLater( - NotesStore.open(path: '${directory.path}/notes.sqlite3'), - throwsStateError, - ); }, ); } diff --git a/test/src/nextcloud_notes/notes_repository_test.dart b/test/src/nextcloud_notes/notes_repository_test.dart index 48422867..974c6e7a 100644 --- a/test/src/nextcloud_notes/notes_repository_test.dart +++ b/test/src/nextcloud_notes/notes_repository_test.dart @@ -765,8 +765,12 @@ void main() { ); expect((await store.notes()).single.content, 'body'); final db = sqlite3.open(path); - expect(db.select('PRAGMA user_version').single.values.single, 6); - expect(db.select('SELECT COUNT(*) AS n FROM outbox').single['n'], 1); + expect(db.select('PRAGMA user_version').single.values.single, 8); + expect( + db.select("SELECT name FROM sqlite_master WHERE name='outbox'"), + isEmpty, + ); + expect((await store.notes()).single.hasPendingChanges, isTrue); db.close(); if (Platform.isLinux) { expect((await File(path).stat()).mode & 0x1ff, 0x180); diff --git a/test/src/nextcloud_notes/notes_settings_test.dart b/test/src/nextcloud_notes/notes_settings_test.dart index ff10f9a8..cc56c4bb 100644 --- a/test/src/nextcloud_notes/notes_settings_test.dart +++ b/test/src/nextcloud_notes/notes_settings_test.dart @@ -298,7 +298,9 @@ void main() { container .read(appRouterProvider) .go('/settings?returnTo=welcome&page=nextcloudNotes'); - await tester.pumpAndSettle(); + // Build the route once, then let real repository initialization make + // progress before waiting for a visually idle page. + await tester.pump(); await tester.runAsync(() async { await container.read(nextcloudNotesRepositoryProvider.future); await container.read(nextcloudConnectionProvider.notifier).reload(); @@ -611,12 +613,19 @@ void main() { await tester.runAsync(() async { await container.read(nextcloudConnectionProvider.notifier).reload(); }); - await tester.pumpAndSettle(); - await tester.runAsync(() async { - await container - .read(notesSettingsProvider.notifier) - .load(testAccount().id); - }); + // The page loads settings automatically. Allow its real SQLite replies + // to complete before advancing the fake clock to visual quiescence. + for ( + var i = 0; + i < 100 && container.read(notesSettingsProvider).original == null; + i++ + ) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(const Duration(milliseconds: 50)); + } + expect(container.read(notesSettingsProvider).original, isNotNull); await tester.pumpAndSettle(); expect(find.text('Server Notes settings'), findsOneWidget); final suffix = find.descendant( diff --git a/test/src/nextcloud_notes/notes_store_open_lifecycle_test.dart b/test/src/nextcloud_notes/notes_store_open_lifecycle_test.dart index 6cff0fc6..ec838d92 100644 --- a/test/src/nextcloud_notes/notes_store_open_lifecycle_test.dart +++ b/test/src/nextcloud_notes/notes_store_open_lifecycle_test.dart @@ -5,7 +5,54 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:sqlite3/sqlite3.dart'; void main() { - for (final schema in [3, 7]) { + test('invalid generation metadata fails open and permits repair', () async { + final directory = await Directory.systemTemp.createTemp( + 'notes-generation-open-', + ); + addTearDown(() => directory.delete(recursive: true)); + final path = '${directory.path}/notes.sqlite3'; + final store = await NotesStore.open(path: path); + await store.close(); + final fixture = sqlite3.open(path); + try { + fixture.execute( + "INSERT INTO store_versions VALUES ('notes', 'retired', 'invalid')", + ); + fixture.execute('CREATE TABLE outbox (id TEXT PRIMARY KEY, data TEXT)'); + fixture.execute("INSERT INTO outbox VALUES ('pending', 'retain')"); + fixture.execute('PRAGMA user_version=6'); + } finally { + fixture.close(); + } + for (var cycle = 0; cycle < 3; cycle++) { + await expectLater( + NotesStore.open(path: path).timeout(const Duration(seconds: 5)), + throwsStateError, + ); + final inspection = sqlite3.open(path); + try { + expect( + inspection.select('PRAGMA user_version').single.values.single, + 6, + ); + expect( + inspection.select('SELECT data FROM outbox').single['data'], + 'retain', + ); + expect(inspection.select('SELECT * FROM store_sessions'), isEmpty); + inspection.execute('BEGIN IMMEDIATE'); + if (cycle == 2) inspection.execute('DELETE FROM store_versions'); + inspection.execute('COMMIT'); + } finally { + inspection.close(); + } + } + final repaired = await NotesStore.open(path: path); + expect(await repaired.notes(), isEmpty); + await repaired.close(); + }); + + for (final schema in [3, 8]) { test('failed v$schema open releases SQLite before reporting failure', () async { final directory = await Directory.systemTemp.createTemp( 'notes-failed-open-', diff --git a/test/src/nextcloud_notes/notes_workspace_workflows_test.dart b/test/src/nextcloud_notes/notes_workspace_workflows_test.dart index 77ef4fd2..c9188efb 100644 --- a/test/src/nextcloud_notes/notes_workspace_workflows_test.dart +++ b/test/src/nextcloud_notes/notes_workspace_workflows_test.dart @@ -24,6 +24,7 @@ import 'package:path/path.dart' as p; import 'package:sqlite3/sqlite3.dart'; import 'notes_api_test.dart' show testAccount, serverNote; +import '../../support/widget_async.dart'; class _Fixture { bool closed = false; @@ -223,94 +224,128 @@ void main() { }); final note = f.repository.notes.single; final offline = NotesOfflineController(f.repository, testAccount().id); - await tester.runAsync(() async { - await offline.initialize(); - if (mode == 'retry') { - f.failMedia = true; - await offline.setRequirement('note', note.localId); - f.failMedia = false; - } else if (mode == 'resume') { - await offline.setRequirement('note', note.localId, paused: true); - } - }); - offline.failures['another-note:held-failure'] = - 'Retain this separate failure'; - final before = f.downloads; - f.mediaGate = Completer(); - await tester.pumpWidget( - ProviderScope( - overrides: [ - notesOfflineProvider( - testAccount().id, - ).overrideWith((ref) async => offline), - ], - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold(body: NotesOfflineDialog(note: note)), + try { + await tester.runAsync(() async { + await offline.initialize(); + if (mode == 'retry') { + f.failMedia = true; + await offline.setRequirement('note', note.localId); + f.failMedia = false; + } else if (mode == 'resume') { + await offline.setRequirement('note', note.localId, paused: true); + } + }); + offline.failures['another-note:held-failure'] = + 'Retain this separate failure'; + final before = f.downloads; + f.mediaGate = Completer(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + notesOfflineProvider( + testAccount().id, + ).overrideWith((ref) async => offline), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: NotesOfflineDialog(note: note)), + ), ), - ), - ); - Future settle() async { - for (var i = 0; i < 20; i++) { - await tester.runAsync( - () => Future.delayed(const Duration(milliseconds: 10)), - ); - await tester.pump(const Duration(milliseconds: 30)); - } - } - - await settle(); - if (mode == 'keep') { - await tester.tap(find.byType(BusyMarkSwitchRow)); - } else { - await tester.tap( - find.widgetWithText( + ); + await pumpUntil(tester, () { + if (!tester + .widget(find.byType(BusyMarkSwitchRow)) + .enabled) { + return false; + } + if (mode == 'keep') return true; + final action = find.widgetWithText( BusyMarkDialogButton, mode == 'retry' ? 'Retry' : 'Resume Downloads', - ), + ); + return action.evaluate().isNotEmpty && + tester.widget(action).onPressed != null; + }, operation: 'offline dialog ready'); + if (mode == 'keep') { + await tester.tap(find.byType(BusyMarkSwitchRow)); + } else { + await tester.tap( + find.widgetWithText( + BusyMarkDialogButton, + mode == 'retry' ? 'Retry' : 'Resume Downloads', + ), + ); + } + await pumpUntil( + tester, + () => + f.downloads == before + 1 && + find + .widgetWithText(BusyMarkDialogButton, 'Pause Downloads') + .evaluate() + .isNotEmpty, + operation: 'held offline download starts', ); + expect(f.downloads, before + 1); + expect(f.mediaGate!.isCompleted, isFalse); + final pause = find.widgetWithText( + BusyMarkDialogButton, + 'Pause Downloads', + ); + expect( + tester.widget(pause).onPressed, + isNotNull, + ); + await tester.tap(pause); + await pumpUntil( + tester, + () => find.text('Downloads paused').evaluate().isNotEmpty, + operation: 'offline pause is published', + ); + expect( + (await tester.runAsync(() => offline.inspect(note)))!.paused, + isTrue, + ); + expect(find.text('Downloads paused'), findsOneWidget); + expect(f.mediaGate!.isCompleted, isFalse); + expect(f.downloads, before + 1); + expect( + offline.failures['another-note:held-failure'], + 'Retain this separate failure', + ); + final available = await tester.runAsync( + () => f.repository.attachmentAvailability(note.localId), + ); + expect(available!.available, contains('.attachments.1/cached.png')); + f.mediaGate!.complete(); + var reconciled = false; + unawaited(offline.reconcile().then((_) => reconciled = true)); + await pumpUntil( + tester, + () => reconciled, + operation: 'paused reconciliation drains', + ); + expect(f.downloads, before + 1); + } finally { + if (f.mediaGate?.isCompleted == false) f.mediaGate!.complete(); + await tester.pumpWidget(const SizedBox.shrink()); + var offlineClosed = false; + unawaited(offline.dispose().then((_) => offlineClosed = true)); + await pumpUntil( + tester, + () => offlineClosed, + operation: 'offline controller closes', + ); + expect(offlineClosed, isTrue); + unawaited(f.repository.dispose().then((_) => f.closed = true)); + await pumpUntil( + tester, + () => f.closed, + operation: 'offline repository closes', + ); + expect(f.closed, isTrue); } - await settle(); - expect(f.downloads, before + 1); - expect(f.mediaGate!.isCompleted, isFalse); - final pause = find.widgetWithText( - BusyMarkDialogButton, - 'Pause Downloads', - ); - expect(tester.widget(pause).onPressed, isNotNull); - await tester.tap(pause); - await settle(); - expect( - (await tester.runAsync(() => offline.inspect(note)))!.paused, - isTrue, - ); - expect(find.text('Downloads paused'), findsOneWidget); - expect(f.mediaGate!.isCompleted, isFalse); - expect(f.downloads, before + 1); - expect( - offline.failures['another-note:held-failure'], - 'Retain this separate failure', - ); - final available = await tester.runAsync( - () => f.repository.attachmentAvailability(note.localId), - ); - expect(available!.available, contains('.attachments.1/cached.png')); - f.mediaGate!.complete(); - await settle(); - expect(f.downloads, before + 1); - await tester.pumpWidget(const SizedBox.shrink()); - var offlineClosed = false; - unawaited(offline.dispose().then((_) => offlineClosed = true)); - for (var i = 0; i < 100 && !offlineClosed; i++) { - await settle(); - } - expect(offlineClosed, isTrue); - unawaited(f.repository.dispose().then((_) => f.closed = true)); - for (var i = 0; i < 100 && !f.closed; i++) { - await settle(); - } - expect(f.closed, isTrue); }, ); } @@ -961,7 +996,6 @@ void main() { for (final table in [ 'accounts', 'notes', - 'outbox', 'attachments', 'import_items', 'offline_requirements', @@ -986,7 +1020,7 @@ void main() { 6, ]); db = sqlite3.open(f.repository.store.path); - expect(db.select('PRAGMA user_version').single.values.single, 6); + expect(db.select('PRAGMA user_version').single.values.single, 8); for (final entry in before.entries) { expect( db diff --git a/test/src/nextcloud_notes_interaction_test.dart b/test/src/nextcloud_notes_interaction_test.dart index c2036d05..3afbfcc7 100644 --- a/test/src/nextcloud_notes_interaction_test.dart +++ b/test/src/nextcloud_notes_interaction_test.dart @@ -567,7 +567,12 @@ void main() { ), ), ); - await _settle(tester); + // The result is rendered only after the SQLite and filesystem work has + // finished. Wait for the dialog to leave its progress state. + await _settle( + tester, + until: () => find.byType(LinearProgressIndicator).evaluate().isEmpty, + ); expect( find.textContaining('The source changed after review'), findsOneWidget, diff --git a/test/src/nextcloud_notes_ui_test.dart b/test/src/nextcloud_notes_ui_test.dart index 860d2f60..5629c56d 100644 --- a/test/src/nextcloud_notes_ui_test.dart +++ b/test/src/nextcloud_notes_ui_test.dart @@ -1,3 +1,4 @@ +import '../support/widget_async.dart'; import '../support/native_menu_probe.dart'; import 'dart:async'; import 'package:busymark/src/search/search_session.dart'; @@ -13,6 +14,7 @@ import 'package:busymark/src/nextcloud_notes/data/notes_api_client.dart'; import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/src/app/app_settings.dart'; +import 'package:busymark/src/editor/source/source_editor.dart'; import 'package:busymark/src/app/busymark_design.dart'; import 'package:busymark/src/nextcloud_notes/domain/notes_conflict.dart'; import 'package:busymark/src/app/app_router.dart'; @@ -21,7 +23,9 @@ import 'package:busymark/src/app/system_accent.dart'; import 'package:busymark/src/app/window_control_service.dart'; import 'package:busymark/src/nextcloud_notes/application/notes_settings_controller.dart'; import 'package:window_manager/window_manager.dart'; +import 'package:busymark/src/local_history/local_history_comparison_view.dart'; import 'package:busymark/src/local_history/local_history_controller.dart'; +import 'package:busymark/src/local_history/local_history_models.dart'; import 'package:busymark/src/local_history/local_history_store.dart'; import 'package:busymark/src/nextcloud_notes/application/nextcloud_connection.dart'; import 'package:busymark/src/nextcloud_notes/application/notes_navigation.dart'; @@ -31,8 +35,10 @@ import 'package:busymark/src/nextcloud_notes/domain/notes_models.dart'; import 'package:busymark/src/nextcloud_notes/presentation/notes_sidebar.dart'; import 'package:busymark/src/nextcloud_notes/presentation/notes_workspace_ui.dart'; import 'package:busymark/src/workspace/presentation/settings_screen.dart'; +import 'package:busymark/src/workspace/document_origin.dart'; import 'package:busymark/src/workspace/recovery_persistence.dart'; import 'package:busymark/src/workspace/session_persistence.dart'; +import 'package:busymark/src/workspace/text_format_metadata.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; import 'package:busymark/src/workspace/workspace_message.dart'; @@ -43,7 +49,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; -Future settleStorage(WidgetTester tester) async { +Future settleStorage( + WidgetTester tester, { + bool Function()? until, +}) async { // Give real history/attachment I/O a real async turn before settling frames. // Animating an indeterminate loader in fake time cannot complete that I/O. final deadline = DateTime.now().add(const Duration(seconds: 10)); @@ -62,7 +71,8 @@ Future settleStorage(WidgetTester tester) async { ); await tester.pump(const Duration(milliseconds: 30)); rounds++; - } while ((rounds < 10 || loading()) && DateTime.now().isBefore(deadline)); + } while ((rounds < 10 || loading() || until?.call() == false) && + DateTime.now().isBefore(deadline)); await tester.pumpAndSettle(); } @@ -399,6 +409,7 @@ void main() { Future Function()? repositoryLoader, NativeWindowController? nativeWindow, NotesSettingsController? serverSettings, + Duration? persistenceDelay, }) async { tester.view.physicalSize = const Size(1100, 1000); tester.view.devicePixelRatio = 1; @@ -406,6 +417,8 @@ void main() { addTearDown(tester.view.resetDevicePixelRatio); final container = ProviderContainer( overrides: [ + if (persistenceDelay != null) + documentPersistenceDelayProvider.overrideWithValue(persistenceDelay), if (nativeWindow != null) nativeWindowControllerProvider.overrideWithValue(nativeWindow), if (serverSettings != null) @@ -457,6 +470,54 @@ void main() { fixtureClosed = true; } + testWidgets('New from Settings honors its unsaved server settings guard', ( + tester, + ) async { + final menus = NativeMenuProbe(tester); + final container = await pumpWelcome( + tester, + serverSettings: _WindowDraftSettings(), + ); + final router = container.read(appRouterProvider); + router.go('/settings?returnTo=welcome&page=nextcloudNotes'); + await settleStorage(tester); + expect(container.read(notesSettingsProvider).dirty, isTrue); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.keyN); + await tester.pumpAndSettle(); + expect(menus.contains('New Markdown File'), isTrue); + expect(menus.packets.last['focusFirst'], isTrue); + await tester.sendKeyUpEvent(LogicalKeyboardKey.keyN); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + menus.select('New Markdown File'); + await settleStorage(tester); + final dialog = find.byType(BusyMarkDialogShell); + await tester.tap( + find.descendant(of: dialog, matching: find.text('Cancel')), + ); + await settleStorage(tester); + expect(router.routeInformationProvider.value.uri.path, '/settings'); + expect(container.read(notesSettingsProvider).dirty, isTrue); + expect(container.read(workspaceControllerProvider).workspace, isNull); + + await tester.tap(find.byKey(const ValueKey('header-new-menu'))); + await tester.pumpAndSettle(); + menus.select('New Markdown File'); + await settleStorage(tester); + await tester.tap( + find.descendant(of: dialog, matching: find.text('Discard')), + ); + await settleStorage(tester); + expect(router.routeInformationProvider.value.uri.path, '/workspace'); + expect( + container.read(workspaceControllerProvider).activeBuffer?.isUntitled, + isTrue, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }); + testWidgets('native close protects a dirty or saving server settings draft', ( tester, ) async { @@ -679,6 +740,513 @@ void main() { ); } + testWidgets( + 'New Markdown from Notes guards dirty work and focuses local Source', + (tester) async { + final menus = NativeMenuProbe(tester); + final settings = _RecentReopenSettings( + failSave: false, + value: AppSettings.defaults() + .copyWith( + autoSave: false, + automaticSpelling: false, + documentViewMode: DocumentViewModePreference.source, + ) + .toJson(), + ); + final connection = _ConnectingWelcomeAccount(repository.accounts.first) + ..connected = true; + final container = await pumpWelcome( + tester, + settings: settings, + persistenceDelay: const Duration(hours: 1), + connection: connection, + ); + try { + final controller = container.read(workspaceControllerProvider.notifier); + final before = repository.notes.length; + await tester.tap(find.byKey(const ValueKey('header-open-menu'))); + await tester.pumpAndSettle(); + menus.select('Browse Nextcloud Notes'); + await settleStorage(tester); + expect( + container + .read(workspaceControllerProvider) + .workspace + ?.nextcloudAccountId, + accountId, + ); + + controller.updateActiveEditorMode(DocumentViewModePreference.source); + await container + .read(appSettingsControllerProvider.notifier) + .setDocumentViewMode(DocumentViewModePreference.source); + await settleStorage(tester); + final priorBufferId = container + .read(workspaceControllerProvider) + .activeBufferId; + await tester.tap(find.byKey(const ValueKey('header-new-menu'))); + await tester.pumpAndSettle(); + menus.select('New Nextcloud Note'); + await settleStorage( + tester, + until: () => + repository.notes.length == before + 1 && + container.read(workspaceControllerProvider).activeBufferId != + priorBufferId, + ); + expect(repository.notes.length, before + 1); + final active = container + .read(workspaceControllerProvider) + .activeBuffer!; + expect(active.remoteNote?.accountId, accountId); + expect(active.editorState.mode, DocumentViewModePreference.source); + final source = find.descendant( + of: find.byType(BusyMarkSourceEditor), + matching: find.byType(EditableText), + ); + expect( + tester.widget(source).focusNode.hasPrimaryFocus, + isTrue, + ); + controller.updateActiveText('Unsaved note draft'); + await settleStorage(tester); + + for (final choice in ['Cancel', 'Discard']) { + await tester.tap(find.byKey(const ValueKey('header-new-menu'))); + await tester.pumpAndSettle(); + menus.select('New Markdown File'); + await tester.pumpAndSettle(); + expect(find.text('Discard'), findsOneWidget); + await tester.tap(find.text(choice)); + await settleStorage( + tester, + until: choice == 'Discard' + ? () => + container + .read(workspaceControllerProvider) + .workspace + ?.kind == + WorkspaceKind.untitledMarkdown + : null, + ); + if (choice == 'Cancel') { + expect( + container.read(workspaceControllerProvider).activeText, + 'Unsaved note draft', + ); + expect( + container.read(workspaceControllerProvider).activeBuffer?.id, + active.id, + ); + } + } + + final state = container.read(workspaceControllerProvider); + expect(state.workspace?.kind, WorkspaceKind.untitledMarkdown); + expect(state.documentBuffers.single.isRemote, isFalse); + expect(repository.notes.length, before + 1); + expect( + repository.noteById(active.remoteNote!.localId)?.content, + active.text, + ); + + final field = tester.widget(source); + expect(field.focusNode.hasPrimaryFocus, isTrue); + expect( + field.controller.selection, + const TextSelection.collapsed(offset: 0), + ); + tester.testTextInput.enterText('First local keystrokes'); + await tester.pump(); + expect( + container.read(workspaceControllerProvider).activeText, + 'First local keystrokes', + ); + expect(tester.takeException(), isNull); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + container.dispose(); + await closeFixture(tester); + } + }, + ); + + testWidgets('Recent opens a Writerside-owned document from Notes and back', ( + tester, + ) async { + final menus = NativeMenuProbe(tester); + final project = Directory('test/fixtures/writerside/toc_ui').absolute; + final topic = p.join(project.path, 'topics', 'home.md'); + final missing = p.join(project.path, 'topics', 'missing.md'); + const localId = '223e4567-e89b-42d3-a456-426614174000'; + final settings = _RecentReopenSettings( + failSave: false, + value: AppSettings.defaults() + .copyWith( + autoSave: false, + automaticSpelling: false, + recentWorkspaces: [ + RecentResource( + path: topic, + ownerRoot: project.path, + kind: 'writersideModule', + document: true, + title: 'Writerside recent topic', + lastOpenedAt: DateTime.utc(2026, 10, 20), + ), + RecentResource( + path: missing, + ownerRoot: project.path, + kind: 'writersideModule', + document: true, + title: 'Missing recent topic', + lastOpenedAt: DateTime.utc(2026, 10, 20), + ), + RecentResource( + path: '', + accountId: 'removed', + localId: localId, + kind: 'nextcloudNote', + document: true, + title: 'Removed account entry', + lastOpenedAt: DateTime.utc(2026, 10, 20), + ), + RecentResource( + path: '', + accountId: accountId, + localId: '423e4567-e89b-42d3-a456-426614174000', + kind: 'nextcloudNote', + document: true, + title: 'Unavailable note entry', + lastOpenedAt: DateTime.utc(2026, 10, 20), + ), + RecentResource( + path: '', + accountId: accountId, + localId: localId, + kind: 'nextcloudNote', + document: true, + title: 'Recent cached note', + lastOpenedAt: DateTime.utc(2026, 10, 20), + ), + ], + ) + .toJson(), + ); + final container = await pumpWelcome( + tester, + settings: settings, + persistenceDelay: const Duration(hours: 1), + ); + try { + final router = container.read(appRouterProvider); + final controller = container.read(workspaceControllerProvider.notifier); + WorkspaceState state() => container.read(workspaceControllerProvider); + + Future showRecent(String initialView) async { + await tester.tap( + find.byKey(const ValueKey('workspace-sidebar-view-menu')), + ); + await tester.pumpAndSettle(); + expect( + menus.entries.singleWhere((row) => row['selected'] == true)['label'], + initialView, + ); + menus.select('Recent'); + await settleStorage(tester); + } + + await tester.tap(find.text('Recent cached note')); + await settleStorage(tester); + expect(state().workspace?.nextcloudAccountId, accountId); + expect(state().activeBuffer?.remoteNote?.localId, localId); + await showRecent('Nextcloud Notes'); + controller.updateActiveText('Keep my remote edits'); + await settleStorage(tester); + final unavailable = container + .read(appSettingsControllerProvider) + .recentWorkspaces + .where( + (resource) => + resource.path == missing || + resource.localId == '423e4567-e89b-42d3-a456-426614174000' || + resource.accountId == 'removed', + ) + .toList(); + expect(unavailable, hasLength(3)); + for (final resource in unavailable) { + await tester.tap( + find.byKey(ValueKey(RecentSearchResult(resource).identity)), + ); + await settleStorage(tester); + expect(state().activeText, 'Keep my remote edits'); + expect(state().workspace?.nextcloudAccountId, accountId); + } + + final item = tester.widget( + find.ancestor( + of: find.text('Writerside recent topic'), + matching: find.byWidgetPredicate( + (widget) => widget is BusyMarkSidebarRecordRow, + ), + ), + ); + item.onTap!(); + item.onTap!(); + await settleStorage(tester); + expect(find.text('Discard'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await settleStorage(tester); + expect(state().activeText, 'Keep my remote edits'); + expect(router.routeInformationProvider.value.uri.path, '/workspace'); + + Future openWriterside({String? choice}) async { + final settled = Completer.sync(); + final subscription = container.listen(workspaceControllerProvider, ( + before, + after, + ) { + if (before?.isLoading == true && + !after.isLoading && + !settled.isCompleted) { + settled.complete(); + } + }); + try { + await tester.runAsync( + () => tester.tap(find.text('Writerside recent topic')), + ); + if (choice != null) { + final action = find.text(choice).hitTestable(); + await pumpUntil( + tester, + () => action.evaluate().isNotEmpty, + operation: 'confirm departure from the dirty note', + ); + await tester.runAsync(() => tester.tap(action)); + } + await pumpUntil( + tester, + () => state().isLoading || settled.isCompleted, + operation: 'start opening the recorded Writerside document', + ); + // The opening uses real file scans and model workers. The published + // state signals completion, even if the ancillary Recent write is + // still waiting on a widget-clock callback. + await tester.runAsync(() => settled.future); + } finally { + subscription.close(); + } + await tester.pumpAndSettle(); + expect(state().isLoading, isFalse); + expect(state().workspace?.kind, WorkspaceKind.writersideModule); + expect(state().activeBuffer?.filePath, topic); + expect(find.text('Discard'), findsNothing); + } + + await openWriterside(choice: 'Discard'); + expect(repository.noteById(localId)?.content, 'private search text'); + await showRecent('Files'); + final sameWorkspace = state().workspace!.id; + final sameBuffer = state().activeBuffer!.id; + final topicRecent = state().activeBuffer!.displayName; + final topicRecord = container + .read(appSettingsControllerProvider) + .recentWorkspaces + .firstWhere( + (resource) => + resource.path == topic && resource.ownerRoot == project.path, + ); + await tester.tap( + find.byKey(ValueKey(RecentSearchResult(topicRecord).identity)), + ); + await settleStorage(tester); + expect(state().workspace!.id, sameWorkspace, reason: topicRecent); + expect(state().documentBuffers.single.id, sameBuffer); + + Future returnToNote() async { + final noteRecord = container + .read(appSettingsControllerProvider) + .recentWorkspaces + .firstWhere((resource) => resource.localId == localId); + await tester.tap( + find.byKey(ValueKey(RecentSearchResult(noteRecord).identity)), + ); + await pumpUntil( + tester, + () => + state().workspace?.nextcloudAccountId == accountId && + state().activeBuffer?.remoteNote?.localId == localId && + !state().isLoading, + operation: 'reopen the recorded Nextcloud note', + ); + expect(state().isDirty, isFalse); + } + + await returnToNote(); + await showRecent('Nextcloud Notes'); + await openWriterside(); + await showRecent('Files'); + await returnToNote(); + await showRecent('Nextcloud Notes'); + controller.updateActiveText('Save this note before leaving'); + await tester.pump(); + await openWriterside(choice: 'Save'); + expect( + (await tester.runAsync( + repository.store.notes, + ))!.singleWhere((note) => note.localId == localId).content, + 'Save this note before leaving', + ); + expect(tester.takeException(), isNull); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + container.dispose(); + await closeFixture(tester); + } + }); + + for (final choice in ['Cancel', 'Discard', 'Save']) { + testWidgets( + 'retained Notes history reviews a dirty local document: $choice', + (tester) async { + const localId = '223e4567-e89b-42d3-a456-426614174000'; + const reference = NextcloudNoteReference( + accountId: accountId, + localId: localId, + ); + const retainedSource = 'Retained Notes revision'; + const localDraft = 'Unsaved local draft'; + final localRoot = Directory(p.join(root.path, 'authoring')) + ..createSync(); + final local = File(p.join(localRoot.path, 'local.md')) + ..writeAsStringSync('Local disk source'); + final settings = _RecentReopenSettings( + failSave: false, + value: AppSettings.defaults() + .copyWith(autoSave: false, automaticSpelling: false) + .toJson(), + ); + final container = await pumpWelcome( + tester, + settings: settings, + persistenceDelay: const Duration(hours: 1), + ); + try { + final controller = container.read( + workspaceControllerProvider.notifier, + ); + WorkspaceState state() => container.read(workspaceControllerProvider); + final store = container.read(localHistoryStoreProvider); + final history = container.read( + localHistoryControllerProvider.notifier, + ); + final recovery = + container.read(documentRecoveryStoreProvider) + as MemoryDocumentRecoveryStore; + await tester.runAsync(() => controller.openPath(local.path)); + expect(state().activeBuffer?.filePath, local.path); + container.read(appRouterProvider).go('/workspace'); + await tester.pumpAndSettle(); + controller.updateActiveText(localDraft); + await controller.flushPersistence(); + expect(recovery.value.entries.single.text, localDraft); + final captured = await store.capture( + LocalHistoryCaptureRequest( + remoteNote: reference, + displayName: 'Personal note', + source: retainedSource, + format: TextFormatMetadata.utf8Lf, + capturedAt: DateTime.now().toUtc(), + reason: LocalHistoryCaptureReason.saved, + ), + const LocalHistoryPolicy(), + ); + await history.refresh(); + history.inspectRetainedDocument(captured.document.id); + await history.selectRevision(captured.revision!.id); + await tester.pump(); + final comparison = find.byType(LocalHistoryComparisonView); + expect(comparison, findsOneWidget); + final l10n = AppLocalizations.of(tester.element(comparison)); + final restore = find.byWidgetPredicate( + (widget) => + widget is IconButton && + widget.tooltip == l10n.localHistoryRestoreRevision && + widget.onPressed != null, + ); + await pumpUntil( + tester, + () => restore.evaluate().isNotEmpty, + operation: 'show the retained note restore action', + ); + final confirm = find.text(switch (choice) { + 'Cancel' => l10n.cancel, + 'Discard' => l10n.discard, + _ => l10n.save, + }).hitTestable(); + await tester.tap(restore); + await pumpUntil( + tester, + () => confirm.evaluate().isNotEmpty, + operation: 'review the dirty local document before restoring', + ); + await tester.tap(confirm); + if (choice == 'Cancel') { + await pumpUntil( + tester, + () => restore.evaluate().isNotEmpty, + operation: 'finish cancelling the retained restore', + ); + expect(state().activeBuffer?.filePath, local.path); + expect(state().activeText, localDraft); + expect(state().isDirty, isTrue); + expect( + repository.noteById(localId)?.content, + 'private search text', + ); + expect(recovery.value.entries.single.text, localDraft); + } else { + await pumpUntil( + tester, + () => + repository.noteById(localId)?.content == retainedSource && + state().activeBuffer?.remoteNote == reference && + !state().isDirty, + operation: 'durably restore the selected Notes revision', + ); + expect(state().activeText, retainedSource); + await controller.flushPersistence(); + expect(recovery.value.entries, isEmpty); + final snapshot = await store.load(); + final sources = await Future.wait([ + for (final revision in snapshot.revisions) + store.readRevision(revision.id), + ]); + expect( + sources.map((revision) => revision?.source), + containsAll([localDraft, 'private search text', retainedSource]), + ); + } + expect( + local.readAsStringSync(), + choice == 'Save' ? localDraft : 'Local disk source', + ); + expect( + (await store.readRevision(captured.revision!.id))?.source, + retainedSource, + ); + expect(tester.takeException(), isNull); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + container.dispose(); + await closeFixture(tester); + } + }, + ); + } + testWidgets( 'Welcome retains a remote revocation warning without a phantom connected account', (tester) async { diff --git a/test/src/nextcloud_workspace_test.dart b/test/src/nextcloud_workspace_test.dart index fc063357..55b99fca 100644 --- a/test/src/nextcloud_workspace_test.dart +++ b/test/src/nextcloud_workspace_test.dart @@ -11,11 +11,13 @@ import 'package:busymark/src/nextcloud_notes/application/notes_repository.dart'; import 'package:busymark/src/nextcloud_notes/data/notes_api_client.dart'; import 'package:busymark/src/nextcloud_notes/data/notes_store.dart'; import 'package:busymark/src/nextcloud_notes/domain/notes_models.dart'; +import 'package:busymark/src/workspace/document_buffer.dart'; import 'package:busymark/src/workspace/recovery_persistence.dart'; import 'package:busymark/src/workspace/session_persistence.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/workspace/workspace_file_monitor.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; +import 'package:busymark/src/workspace/workspace_service.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; @@ -140,58 +142,268 @@ void main() { } for (final dirty in [false, true]) { - test( - 'remote history restore navigates accounts safely from local workspace ' - '(dirty=$dirty)', - () async { - final h = await _Harness.create(); - addTearDown(h.dispose); - await h.controller.openNextcloudWorkspace(_accountId); - final buffer = h.state.activeBuffer!; - final store = h.container.read(localHistoryStoreProvider); - final captured = await store.capture( - LocalHistoryCaptureRequest( - remoteNote: buffer.remoteNote, - displayName: buffer.displayName, - source: 'retained remote source\n', - format: buffer.format, - capturedAt: DateTime.now().toUtc(), - reason: LocalHistoryCaptureReason.saved, + test('remote history restore navigates accounts safely from local workspace ' + '(dirty=$dirty)', () async { + final service = _GatedLocalOpenService(); + final (:h, :server, :openingSync) = await _openNotesWithHeldSync(service); + final buffer = h.state.activeBuffer!; + final openedBase = buffer.remoteEditBase!; + expect(openedBase.state, isNotNull); + final store = h.container.read(localHistoryStoreProvider); + final captured = await store.capture( + LocalHistoryCaptureRequest( + remoteNote: buffer.remoteNote, + displayName: buffer.displayName, + source: 'retained remote source\n', + format: buffer.format, + capturedAt: DateTime.now().toUtc(), + reason: LocalHistoryCaptureReason.saved, + ), + const LocalHistoryPolicy(), + ); + final revision = (await store.readRevision(captured.revision!.id))!; + final local = File(p.join(h.root.path, 'local.md')); + await local.writeAsString('local source'); + + final opening = h.controller.openPath(local.path); + try { + await service.started.future; + final before = h.state.activeBuffer!; + final base = before.remoteEditBase!; + final note = h.repository.noteById(before.remoteNote!.localId)!; + expect(base.state, same(openedBase.state)); + expect(base.generation, openedBase.generation); + expect(base.state, same(note.base)); + + // Opening Sync remains blocked at the collection read. Updating + // account metadata emits a real Notes change without touching the note. + const refreshedVersion = '6.1.1'; + final after = await _observeBufferChange( + h, + () => + h.repository.accountById(_accountId)?.appVersion == + refreshedVersion, + () => h.repository.upsertAccount( + h.repository + .accountById(_accountId)! + .copyWith(appVersion: refreshedVersion), ), - const LocalHistoryPolicy(), ); - final revision = (await store.readRevision(captured.revision!.id))!; - final localPath = p.join(h.root.path, 'local.md'); - await File(localPath).writeAsString('local source'); - await h.controller.openPath(localPath); - if (dirty) h.controller.updateActiveText('unsaved local source'); - final current = await h.controller.localHistoryCurrentSource( - captured.document, - revision, + expect(h.repository.isSynchronizing(_accountId), isTrue); + expect(h.repository.noteById(note.localId), same(note)); + expect(after, isNot(same(before))); + expect(after.remoteEditBase, isNot(same(base))); + expect(after.remoteEditBase!.state, same(base.state)); + expect(after.remoteEditBase!.generation, base.generation); + expect(after.id, before.id); + expect(after.remoteNote, before.remoteNote); + expect(after.text, before.text); + expect(after.revision, before.revision); + expect(after.readonly, before.readonly); + expect(after.isDirty, isFalse); + expect(h.state.workspace!.nextcloudAccountId, _accountId); + expect(h.state.isLoading, isTrue); + } finally { + service.release.complete(); + await opening; + server.release(); + await openingSync; + } + expect(h.state.activeBuffer?.filePath, local.path); + expect(h.state.activeText, 'local source'); + expect(h.state.isLoading, isFalse); + + Future restore() => h.controller.restoreLocalHistoryRevision( + document: captured.document, + revision: revision, + ); + + if (dirty) { + h.controller.updateActiveText('unsaved local source'); + await h.controller.flushPersistence(); + } + final current = await h.controller.localHistoryCurrentSource( + captured.document, + revision, + ); + expect(current.canRestore, isTrue); + if (dirty) { + expect(await restore(), isFalse); + expect(h.state.activeBuffer!.filePath, local.path); + expect(h.state.activeText, 'unsaved local source'); + expect(h.state.isDirty, isTrue); + expect(h.recovery.value.entries.single.text, 'unsaved local source'); + expect( + h.repository.noteById(buffer.remoteNote!.localId)!.content, + buffer.text, ); - expect(current.canRestore, isTrue); + expect(await local.readAsString(), 'local source'); + expect(await h.controller.saveActive(), isTrue); + } + expect(await restore(), isTrue); + expect(h.state.workspace!.nextcloudAccountId, _accountId); + expect(h.state.activeBuffer!.remoteNote, buffer.remoteNote); + expect(h.state.activeText, revision.source); + expect( + h.repository.noteById(buffer.remoteNote!.localId)!.content, + revision.source, + ); + expect( + (await store.readRevision(revision.summary.id))!.source, + revision.source, + ); + await h.controller.flushPersistence(); + expect(h.recovery.value.entries, isEmpty); + expect( + await local.readAsString(), + dirty ? 'unsaved local source' : 'local source', + ); + }); + } + + for (final (change, remotePatch) in [ + ('server snapshot', {'favorite': true}), + ('server generation', {'etag': 'new-server-version'}), + ('permission', {'error': true}), + ]) { + test('pending local open rejects a changed Notes $change', () async { + final service = _GatedLocalOpenService(); + final (:h, :server, :openingSync) = await _openNotesWithHeldSync(service); + final local = File(p.join(h.root.path, 'local.md')); + await local.writeAsString('local source'); + var published = false; + final opening = h.controller.openPath( + local.path, + acceptNavigation: () => true, + onOpened: () => published = true, + ); + final DocumentBuffer updated; + try { + await service.started.future; + final original = h.state.activeBuffer!; + final base = original.remoteEditBase!; + updated = await _observeBufferChange( + h, + () { + final note = h.repository.noteById(original.remoteNote!.localId)!; + return switch (change) { + 'server snapshot' => note.favorite, + 'server generation' => note.etag == 'new-server-version', + _ => note.readonly, + }; + }, + () async { + server.note.addAll(remotePatch); + server.release(); + await openingSync; + }, + ); + expect(updated.id, original.id); + expect(updated.text, original.text); + expect(updated.revision, original.revision); + expect(updated.isDirty, isFalse); + expect(updated.readonly, change == 'permission'); expect( - await h.controller.restoreLocalHistoryRevision( - document: captured.document, - revision: revision, - ), - !dirty, + updated.remoteEditBase!.state, + change == 'permission' ? same(base.state) : isNot(same(base.state)), ); - if (dirty) { - expect(h.state.activeBuffer!.filePath, localPath); - expect(h.state.activeText, 'unsaved local source'); - } else { - expect(h.state.workspace!.nextcloudAccountId, _accountId); - expect(h.state.activeBuffer!.remoteNote, buffer.remoteNote); - expect(h.state.activeText, revision.source); + expect( + updated.remoteEditBase!.generation, + base.generation + (change == 'server generation' ? 1 : 0), + ); + } finally { + service.release.complete(); + await opening; + } + expect(published, isFalse); + expect(h.state.activeBuffer!.remoteNote, updated.remoteNote); + expect(h.state.activeText, updated.text); + expect(h.state.activeBuffer!.readonly, updated.readonly); + expect(h.state.isLoading, isFalse); + expect(await local.readAsString(), 'local source'); + }); + } + + for (final change in [ + 'dirty edit', + 'revision', + 'note', + 'new open', + 'disposal', + ]) { + test('pending local open rejects Notes $change', () async { + final service = _GatedLocalOpenService(); + final (:h, :server, :openingSync) = await _openNotesWithHeldSync(service); + final controller = h.controller; + final local = File(p.join(h.root.path, 'local.md')); + await local.writeAsString('local source'); + final before = h.state.activeBuffer!; + var published = false; + final opening = controller.openPath( + local.path, + onOpened: () => published = true, + ); + int? readsBeforeRelease; + DocumentBuffer? kept; + try { + await service.started.future; + switch (change) { + case 'dirty edit': + controller.updateActiveText('Keep this draft'); + expect(h.state.isDirty, isTrue); + case 'revision': + controller.updateActiveText( + 'Edit before returning to saved source', + ); + expect(controller.undoActiveBuffer(), isTrue); + expect(h.state.isDirty, isFalse); + expect(h.state.activeText, before.text); + expect( + h.state.activeBuffer!.revision, + greaterThan(before.revision), + ); + case 'note': + final other = h.repository.notes.singleWhere( + (note) => note.serverId == 2, + ); + expect(await controller.openNextcloudNote(other.localId), isTrue); + expect(h.state.activeBuffer!.remoteNote!.localId, other.localId); + case 'new open': + final newer = File(p.join(h.root.path, 'newer.md')); + await newer.writeAsString('New destination'); + await controller.openPath(newer.path); + expect(h.state.activeBuffer!.filePath, newer.path); + case 'disposal': + server.release(); + await openingSync; + await h.dispose(); + } + readsBeforeRelease = service.reads; + if (change != 'disposal') kept = h.state.activeBuffer!; + } finally { + service.release.complete(); + await opening; + } + expect(published, isFalse); + if (change == 'disposal' || change == 'new open') { + expect(service.reads, readsBeforeRelease); + } + if (kept != null) { + expect(await local.readAsString(), 'local source'); + expect(h.state.activeBuffer!.id, kept.id); + expect(h.state.activeText, kept.text); + expect(h.state.isLoading, isFalse); + if (change == 'dirty edit') { + expect(h.state.activeText, 'Keep this draft'); + expect(h.state.activeBuffer!.id, before.id); + await controller.flushPersistence(); expect( - h.repository.noteById(buffer.remoteNote!.localId)!.content, - revision.source, + h.repository.noteById(before.remoteNote!.localId)!.content, + 'Keep this draft', ); } - expect(await File(localPath).readAsString(), 'local source'); - }, - ); + } + }); } test( @@ -761,6 +973,7 @@ class _Harness { bool deferPersistence = false, Duration? persistenceDelay, LocalHistoryStore? historyStore, + WorkspaceService? workspaceService, }) async { final directory = root ?? @@ -814,6 +1027,8 @@ class _Harness { nextcloudNotesRepositoryProvider.overrideWith( (ref) async => repository, ), + if (workspaceService != null) + workspaceServiceProvider.overrideWithValue(workspaceService), workspaceFileMonitorProvider.overrideWithValue(monitor), documentSessionStoreProvider.overrideWithValue(sessionStore), documentRecoveryStoreProvider.overrideWithValue(recoveryStore), @@ -833,7 +1048,11 @@ class _Harness { ); } - Future dispose() async { + Future? _disposal; + + Future dispose() => _disposal ??= _dispose(); + + Future _dispose() async { await controller.flushPersistence(); await controller.refreshNextcloudNotes(); container.dispose(); @@ -843,6 +1062,107 @@ class _Harness { } } +Future<({_Harness h, _GatedNotesCollection server, Future openingSync})> +_openNotesWithHeldSync(_GatedLocalOpenService service) async { + final server = _GatedNotesCollection(); + final h = await _Harness.create( + seedLocal: false, + deferPersistence: true, + client: MockClient(server.respond), + workspaceService: service, + ); + addTearDown(h.dispose); + addTearDown(server.release); + await h.container + .read(appSettingsControllerProvider.notifier) + .setAutoSave(false); + await h.repository.synchronize(_accountId, allowWrites: false); + server.holdNextRead = true; + expect(await h.controller.openNextcloudWorkspace(_accountId), isTrue); + await server.started.future; + expect(h.repository.isSynchronizing(_accountId), isTrue); + final openingSync = h.repository.synchronize(_accountId); + return (h: h, server: server, openingSync: openingSync); +} + +Future _observeBufferChange( + _Harness h, + bool Function() expectedNotification, + Future Function() causeChange, +) async { + final observed = Completer(); + final subscription = h.container.listen(workspaceControllerProvider, ( + _, + next, + ) { + if (!observed.isCompleted && expectedNotification()) { + observed.complete(next.activeBuffer!); + } + }); + try { + await causeChange(); + return await observed.future; + } finally { + subscription.close(); + } +} + +class _GatedNotesCollection { + final note = serverNote(1, content: 'current server source', etag: 'base'); + final _otherNote = serverNote(2, content: 'Other source'); + final started = Completer(); + final _released = Completer(); + var holdNextRead = false; + + void release() { + if (!_released.isCompleted) _released.complete(); + } + + Future respond(http.Request request) async { + if (request.method == 'PUT') { + note['content'] = (jsonDecode(request.body) as Map)['content']; + note['etag'] = 'acknowledged'; + return http.Response(jsonEncode(note), 200); + } + expect(request.method, 'GET'); + if (request.url.path.endsWith('/notes')) { + if (holdNextRead) { + holdNextRead = false; + started.complete(); + await _released.future; + } + return http.Response(jsonEncode([note, _otherNote]), 200); + } + expect(request.url.path, matches(RegExp(r'/notes/[12]$'))); + return http.Response( + jsonEncode(request.url.path.endsWith('/1') ? note : _otherNote), + 200, + ); + } +} + +class _GatedLocalOpenService extends WorkspaceService { + final started = Completer(); + final release = Completer(); + var reads = 0; + + @override + Future loadTextWithSnapshot(String path) { + reads++; + return super.loadTextWithSnapshot(path); + } + + @override + Future openPath(String path) async { + final loaded = await super.openPath(path); + if (!started.isCompleted) { + started.complete(); + await release.future; + } + return loaded; + } +} + class _BlockingRestoreHistoryStore extends MemoryLocalHistoryStore { final started = Completer(); final release = Completer(); diff --git a/test/src/pdf_title_page_ui_test.dart b/test/src/pdf_title_page_ui_test.dart index df308c8b..4b5af217 100644 --- a/test/src/pdf_title_page_ui_test.dart +++ b/test/src/pdf_title_page_ui_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:io'; +import 'package:busymark/src/core/save_destination.dart'; import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/src/app/app_settings.dart'; import 'package:busymark/src/app/app_theme.dart'; @@ -13,7 +14,6 @@ import 'package:busymark/src/export/workspace_export_ui.dart'; import 'package:busymark/src/export/writerside_pdf_export_service.dart'; import 'package:busymark/src/export/writerside_pdf_export_ui.dart'; import 'package:busymark/src/export/writerside_pdf_models.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/writerside/writerside_model.dart'; import 'package:flutter/material.dart'; @@ -221,11 +221,18 @@ void main() { addTearDown(() => root.deleteSync(recursive: true)); final markdown = _MarkdownExporter(); final instance = _WritersideExporter(); - final picker = Completer(); - const channel = MethodChannel('plugins.flutter.io/file_selector'); + final picker = Completer?>(); + const channel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( channel, - (_) => picker.future, + (call) { + expect(call.method, 'save'); + expect( + (call.arguments as Map)['suggestedName'], + endsWith('.pdf'), + ); + return picker.future; + }, ); addTearDown( () => tester.binding.defaultBinaryMessenger @@ -283,7 +290,11 @@ void main() { } await tester.tap(find.byKey(const ValueKey('export-options-submit'))); await _settle(tester); - picker.complete(p.join(root.path, 'export.pdf')); + picker.complete( + SaveDestination.inspect( + p.join(root.path, 'export.pdf'), + ).chooserReview, + ); for (var i = 0; i < 20; i++) { await _settle(tester); if (markdown.request != null || instance.request != null) break; @@ -291,6 +302,12 @@ void main() { final titlePage = writerside ? instance.request!.titlePage! : markdown.request!.titlePage!; + expect( + writerside + ? instance.request!.destinationPath + : markdown.request!.destinationPath, + p.join(root.path, 'export.pdf'), + ); expect(titlePage.subtitle, 'Only this request'); expect(titlePage.author, ''); if (writerside) { @@ -359,11 +376,6 @@ Widget _harness( }) => ProviderScope( overrides: [ localSettingsStoreProvider.overrideWithValue(settings), - linuxHeaderBarServiceProvider.overrideWithValue( - LinuxHeaderBarService( - channel: const MethodChannel('pdf-title-test-header'), - ), - ), if (markdown != null) markdownPdfExportServiceProvider.overrideWithValue(markdown), if (writerside != null) diff --git a/test/src/references/reference_controller_test.dart b/test/src/references/reference_controller_test.dart index 64be8d68..6590cc26 100644 --- a/test/src/references/reference_controller_test.dart +++ b/test/src/references/reference_controller_test.dart @@ -8,6 +8,7 @@ import 'package:busymark/src/workspace/workspace_service.dart'; import 'package:busymark/src/workspace/document_buffer.dart'; import 'package:busymark/src/nextcloud_notes/application/nextcloud_connection.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class IndexedWorkspace extends WorkspaceController { @@ -19,6 +20,88 @@ class IndexedWorkspace extends WorkspaceController { } void main() { + test('editor state leaves the reference corpus untouched', () async { + final root = await Directory.systemTemp.createTemp('reference-inputs-'); + addTearDown(() => root.delete(recursive: true)); + final source = File('${root.path}/source.md'); + final target = File('${root.path}/target.md'); + await source.writeAsString('[target](target.md#old)'); + await target.writeAsString('# Old'); + final workspace = await const WorkspaceService().openPath(root.path); + final buffer = DocumentBuffer( + id: 'open', + filePath: source.path, + text: await source.readAsString(), + lastSavedText: await source.readAsString(), + dirty: false, + ); + final controller = IndexedWorkspace( + WorkspaceState( + workspace: workspace, + documentBuffers: [buffer], + activeBufferId: buffer.id, + ), + ); + final container = ProviderContainer( + overrides: [ + workspaceControllerProvider.overrideWith(() => controller), + nextcloudNotesRepositoryProvider.overrideWith( + (_) async => throw StateError('Local fixture'), + ), + ], + ); + addTearDown(container.dispose); + final subscription = container.listen(referenceIndexProvider, (_, _) {}); + addTearDown(subscription.close); + Future settle(bool Function(ReferenceIndex) ready) async { + final deadline = DateTime.now().add(const Duration(seconds: 10)); + while (DateTime.now().isBefore(deadline)) { + final index = container.read(referenceIndexProvider).value; + if (index != null && ready(index)) return index; + await Future.delayed(const Duration(milliseconds: 20)); + } + throw StateError('Reference index did not settle.'); + } + + final initial = await settle((index) => index.documents.length == 2); + controller.publish( + container + .read(workspaceControllerProvider) + .copyWith( + documentBuffers: [ + buffer.copyWith( + editorState: buffer.editorState.copyWith( + selection: const TextSelection.collapsed(offset: 2), + scrollOffset: 42, + foldedRegionKeys: const {'heading'}, + ), + ), + ], + ), + ); + await Future.delayed(const Duration(milliseconds: 500)); + expect(container.read(referenceIndexProvider).value, same(initial)); + + controller.publish( + container + .read(workspaceControllerProvider) + .copyWith( + documentBuffers: [buffer.edited('[target](target.md#new)')], + ), + ); + await settle( + (index) => index.references.single.authored.destination.endsWith('#new'), + ); + final monitor = container.read(workspaceFileMonitorProvider); + await monitor.start(rootPath: root.path, openFilePaths: [source.path]); + await target.writeAsString('# New'); + final external = await settle( + (index) => + index.references.single.resolution == ReferenceResolution.resolved, + ); + expect(external.references.single.target!.anchor, 'new'); + }); + test( 'edits during initial indexing reuse accepted batches and reject obsolete results', () async { @@ -175,10 +258,10 @@ void main() { i.references.singleOrNull?.authored.destination == 'target.md#new', ); expect(await source.readAsString(), '[old](target.md#old)'); + await container + .read(workspaceFileMonitorProvider) + .start(rootPath: root.path, openFilePaths: [source.path]); await target.writeAsString('# New'); - controller.publish( - container.read(workspaceControllerProvider).copyWith(), - ); await settle( (i) => i.references.singleOrNull?.resolution == diff --git a/test/src/remote_image_permissions_test.dart b/test/src/remote_image_permissions_test.dart new file mode 100644 index 00000000..04f62e8f --- /dev/null +++ b/test/src/remote_image_permissions_test.dart @@ -0,0 +1,291 @@ +import 'package:busymark/src/core/source_span.dart'; +import 'package:busymark/src/markdown/busymark_document.dart'; +import 'package:busymark/src/markdown/markdown_model.dart'; +import 'package:busymark/src/markdown/markdown_parser.dart'; +import 'package:busymark/src/workspace/document_buffer.dart'; +import 'package:busymark/src/workspace/remote_image_permissions.dart'; +import 'package:busymark/src/workspace/workspace_model.dart'; +import 'package:busymark/src/workspace/workspace_service.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const url = 'https://example.com/identity.png'; + const image = '![Image]($url)'; + + final workspace = const WorkspaceService().createUntitledMarkdown(); + WorkspaceState state(DocumentBuffer buffer) => WorkspaceState( + workspace: workspace, + documentBuffers: [buffer], + activeBufferId: buffer.id, + ); + SourceSpan span(String text, {bool last = false}) { + final start = last ? text.lastIndexOf(image) : text.indexOf(image); + return SourceSpan.fromOffsets( + filePath: '', + source: text, + startOffset: start, + endOffset: start + image.length, + ); + } + + test( + 'identical markup cannot inherit a grant through an ambiguous deletion', + () { + final permissions = RemoteImagePermissions(); + addTearDown(permissions.dispose); + final before = DocumentBuffer.untitled( + id: 'draft', + name: 'Draft', + text: '$image\n\n$image\n', + ); + final target = permissions.capture( + state(before), + before, + before.text, + span(before.text, last: true), + url, + null, + )!; + expect( + permissions.apply(target, RemoteImagePermission.image, state(before)), + isTrue, + ); + final after = before.edited('$image\n'); + permissions.update(state(before), state(after)); + expect( + permissions.allows(after, after.text, span(after.text), url), + isFalse, + ); + }, + ); + + test( + 'source changing out of and back into image syntax invalidates a pending grant', + () { + final permissions = RemoteImagePermissions(); + addTearDown(permissions.dispose); + final before = DocumentBuffer.untitled( + id: 'draft', + name: 'Draft', + text: 'Text\n\n$image\n', + ); + final target = permissions.capture( + state(before), + before, + before.text, + span(before.text), + url, + null, + )!; + final asCode = before.edited('Text\n\n```md\n$image\n'); + final restored = asCode.edited(before.text); + permissions.update(state(before), state(asCode)); + permissions.update(state(asCode), state(restored)); + expect( + permissions.apply( + target, + RemoteImagePermission.document, + state(restored), + ), + isFalse, + ); + expect( + permissions.allows(restored, restored.text, span(restored.text), url), + isFalse, + ); + }, + ); + + test( + 'a pending grant stays with its opening even when another tab is active', + () { + final permissions = RemoteImagePermissions(); + addTearDown(permissions.dispose); + final origin = DocumentBuffer.untitled( + id: 'draft', + name: 'Draft', + text: '$image\n', + ); + final other = DocumentBuffer.untitled( + id: 'other', + name: 'Other', + text: origin.text, + ); + final range = span(origin.text); + final target = permissions.capture( + state(origin), + origin, + origin.text, + range, + url, + null, + )!; + final switched = WorkspaceState( + workspace: workspace, + documentBuffers: [origin, other], + activeBufferId: other.id, + ); + permissions.update(state(origin), switched); + expect( + permissions.apply(target, RemoteImagePermission.document, switched), + isTrue, + ); + expect(permissions.allows(origin, origin.text, range, url), isTrue); + expect(permissions.allows(other, other.text, range, url), isFalse); + + final pending = permissions.capture( + switched, + origin, + origin.text, + range, + url, + null, + )!; + final replacement = DocumentBuffer.untitled( + id: origin.id, + name: origin.displayName, + text: origin.text, + ); + permissions.update(switched, state(replacement)); + expect( + permissions.apply( + pending, + RemoteImagePermission.global, + state(replacement), + ), + isFalse, + ); + expect( + permissions.capture( + state(replacement), + origin, + origin.text, + range, + url, + null, + ), + isNull, + ); + }, + ); + + test( + 'remote image spans cover brackets, whitespace destinations and references', + () { + const source = ''' +Before [![Link](https://example.com/linked.png)](https://example.org/) after. + +![Spaces](https://example.com/two words.png) + +![Reference][ref] + +[ref]: https://example.com/reference.png +'''; + final parsed = const MarkdownParser().parse(filePath: '', source: source); + final all = parsed.busyDocument.blocks.expand((b) => b.inlines); + final images = [ + for (final inline in all) ...[inline, ...inline.children], + ].where((inline) => inline.imageSpan != null); + expect( + images.map((inline) { + final span = inline.imageSpan!; + return source.substring(span.startOffset, span.endOffset); + }), + [ + '![Link](https://example.com/linked.png)', + '![Spaces](https://example.com/two words.png)', + '![Reference][ref]', + ], + ); + }, + ); + for (final (mode, source, markup) in [ + ( + MarkdownMode.commonMark, + '> ![Real](https://example.com/real.png)\n>\n> ![Example](https://example.com/example.png)\n', + '![Real](https://example.com/real.png)', + ), + ( + MarkdownMode.commonMark, + '> ![Real](https://example.com/real.png)\n>\n> ![Real](https://example.com/real.png)\n', + '![Real](https://example.com/real.png)', + ), + ( + MarkdownMode.commonMark, + '> - `![Example](https://example.com/example.png)` and [![Real][ref]](https://example.com/)\n>\n> ```md\n> ![Example](https://example.com/example.png)\n> ```\n\n[ref]: https://example.com/real.png\n', + '![Real][ref]', + ), + ( + MarkdownMode.writersideMarkdown, + '# Topic\n\n\nReal\n\n', + 'Real', + ), + ]) { + test( + 'binds only authored images in ${mode.name}: ${source.split('\n').first}', + () { + final document = const MarkdownParser() + .parse(filePath: 'draft.md', source: source, mode: mode) + .busyDocument; + Iterable images(Iterable inlines) sync* { + for (final inline in inlines) { + if (inline.kind == BusyInlineKind.image) yield inline; + yield* images(inline.children); + } + } + + Iterable blockImages(Iterable blocks) sync* { + for (final block in blocks) { + yield* images(block.inlines); + yield* blockImages(block.children); + } + } + + final occurrence = blockImages(document.blocks).single; + final range = occurrence.imageSpan!; + const real = 'https://example.com/real.png'; + expect(occurrence.destination, real); + expect(source.substring(range.startOffset, range.endOffset), markup); + expect(range.startOffset, source.lastIndexOf(markup)); + final permissions = RemoteImagePermissions(); + addTearDown(permissions.dispose); + final buffer = DocumentBuffer.untitled( + id: 'draft', + name: 'Draft', + text: source, + ); + final target = permissions.capture( + state(buffer), + buffer, + source, + range, + real, + null, + )!; + expect(target.hasOccurrence, isTrue); + expect( + permissions.apply(target, RemoteImagePermission.image, state(buffer)), + isTrue, + ); + expect(permissions.allows(buffer, source, range, real), isTrue); + expect( + permissions.allows( + buffer, + source, + range, + 'https://example.com/example.png', + ), + isFalse, + ); + expect( + permissions.apply( + target, + RemoteImagePermission.global, + state(buffer), + ), + isFalse, + ); + }, + ); + } +} diff --git a/test/src/save_alert_interaction_test.dart b/test/src/save_alert_interaction_test.dart new file mode 100644 index 00000000..4134d99d --- /dev/null +++ b/test/src/save_alert_interaction_test.dart @@ -0,0 +1,148 @@ +import 'dart:ui'; + +import 'package:busymark/l10n/generated/app_localizations.dart'; +import 'package:busymark/src/app/app_theme.dart'; +import 'package:busymark/src/app/busymark_dialogs.dart'; +import 'package:busymark/src/app/busymark_native_controls.dart'; +import 'package:busymark/src/app/busymark_toast.dart'; +import 'package:busymark/src/app/localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + for (final theme in Brightness.values) { + testWidgets('alert keyboard traversal and cancellation in ${theme.name}', ( + tester, + ) async { + bool? response; + await tester.pumpWidget( + MaterialApp( + locale: const Locale('es'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: buildBusyMarkTheme( + brightness: theme, + accentColor: Colors.green, + ), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(1.65)), + child: child!, + ), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + response = await showBusyMarkModalDialog( + context, + builder: (context) => BusyMarkAlert( + heading: context.l10n.fileChangedOnDisk, + responses: [ + BusyMarkAlertResponse( + label: context.l10n.cancel, + onPressed: () => Navigator.pop(context, false), + ), + BusyMarkAlertResponse( + label: context.l10n.overwrite, + destructive: true, + onPressed: () => Navigator.pop(context, true), + ), + const BusyMarkAlertResponse( + label: 'Disabled', + onPressed: null, + ), + ], + children: [Text(context.l10n.fileChangedOnDiskMessage)], + ), + ); + }, + child: const Text('Start'), + ), + ), + ), + ), + ); + + Future show() async { + await tester.tap(find.text('Start')); + await tester.pumpAndSettle(); + expect(find.byType(BusyMarkAlert), findsOneWidget); + expect(tester.takeException(), isNull); + } + + await show(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(response, isNull); + expect(find.byType(BusyMarkAlert), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + expect(FocusManager.instance.primaryFocus?.debugLabel, 'BusyMark action'); + await tester.sendKeyEvent(LogicalKeyboardKey.space); + await tester.pumpAndSettle(); + expect(response, isFalse); + + await show(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(response, isNull); + expect(find.byType(BusyMarkAlert), findsNothing); + }); + } + + testWidgets('toast keyboard action activates once and advances the queue', ( + tester, + ) async { + var actions = 0; + await tester.pumpWidget( + MaterialApp( + home: BusyMarkToastOverlay( + child: Scaffold( + body: Builder( + builder: (context) => ElevatedButton( + onPressed: () { + BusyMarkToastOverlay.show( + context, + message: 'PDF exported', + actionLabel: 'Open', + onAction: () => actions++, + duration: Duration.zero, + ); + BusyMarkToastOverlay.show( + context, + message: 'Queued notification', + duration: Duration.zero, + ); + }, + child: const Text('Show notifications'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('Show notifications')); + await tester.pumpAndSettle(); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: tester.getCenter(find.text('Open'))); + await tester.pump(); + for (var step = 0; step < 3; step++) { + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + if (FocusManager.instance.primaryFocus?.debugLabel == 'BusyMark action') { + break; + } + } + expect(FocusManager.instance.primaryFocus?.debugLabel, 'BusyMark action'); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(actions, 1); + await tester.pump(const Duration(milliseconds: 400)); + await tester.pumpAndSettle(); + expect(find.text('Open'), findsNothing); + expect(find.text('Queued notification'), findsOneWidget); + await mouse.removePointer(); + }); +} diff --git a/test/src/save_destination_test.dart b/test/src/save_destination_test.dart new file mode 100644 index 00000000..f27c6246 --- /dev/null +++ b/test/src/save_destination_test.dart @@ -0,0 +1,183 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:busymark/src/core/atomic_file_writer.dart'; +import 'package:busymark/src/core/save_destination.dart'; +import 'package:busymark/src/workspace/workspace_service.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + late Directory root; + + setUp(() { + root = Directory.systemTemp.createTempSync('busymark-save-destination-'); + }); + tearDown(() => root.deleteSync(recursive: true)); + + test( + 'suffix finalization handles correct, missing, different and uppercase', + () { + for (final (name, expected) in [ + ('export.pdf', 'export.pdf'), + ('export', 'export.pdf'), + ('export.txt', 'export.txt.pdf'), + ('export.PDF', 'export.PDF'), + ]) { + expect(SaveDestination.withSuffix(name, '.pdf'), expected); + } + expect( + SaveDestination.withSuffix('topic.xml', '.md', onlyWhenMissing: true), + 'topic.xml', + ); + expect(SaveDestination.withSuffix('site', null), 'site'); + }, + ); + + test('chooser reviews bind consent to the entry observed before Replace', () { + final path = p.join(root.path, 'export.PDF'); + SaveDestination accept(Map review) => + SaveDestination.fromChooserReview( + review, + kind: SaveDestinationKind.file, + ); + final missing = SaveDestination.inspect(path).chooserReview; + expect(accept(missing).replacesExisting, isFalse); + final file = File(path)..writeAsStringSync('First version'); + expect(() => accept(missing), throwsA(isA())); + final offer = SaveDestination.inspect(path).chooserReview; + expect(accept(offer).replacesExisting, isTrue); + file.writeAsStringSync('Modified while Replace was open'); + expect(() => accept(offer), throwsA(isA())); + expect(file.readAsStringSync(), 'Modified while Replace was open'); + }); + + test( + 'a new final path refuses a file appearing while bytes are staged', + () async { + final file = File(p.join(root.path, 'diagram.png')); + final newFile = SaveDestination.inspect(file.path); + await expectLater( + const AtomicFileWriter().writeBytes( + file.path, + [1, 2, 3], + overwrite: false, + authorization: newFile, + beforePublish: () => file.writeAsStringSync('late entrant'), + ), + throwsA(isA()), + ); + expect(file.readAsStringSync(), 'late entrant'); + expect(root.listSync().map((entry) => entry.path), [file.path]); + }, + ); + + test( + 'authorization binds the entry and never crosses a suffix change', + () async { + final chosen = File(p.join(root.path, 'diagram')) + ..writeAsStringSync('first'); + final finalFile = File(SaveDestination.withSuffix(chosen.path, '.svg')) + ..writeAsStringSync('protected'); + final approval = SaveDestination.inspect(chosen.path); + await expectLater( + const AtomicFileWriter().writeBytes( + finalFile.path, + utf8.encode(''), + overwrite: true, + authorization: approval, + ), + throwsA(isA()), + ); + expect(finalFile.readAsStringSync(), 'protected'); + expect(chosen.readAsStringSync(), 'first'); + }, + ); + + test( + 'diagram bytes publish to a new or explicitly reviewed final file', + () async { + final file = File(p.join(root.path, 'diagram.png')); + for (final bytes in [ + [1, 2, 3], + [4, 5, 6], + ]) { + final authorization = SaveDestination.inspect(file.path); + await const AtomicFileWriter().writeBytes( + file.path, + bytes, + overwrite: authorization.replacesExisting, + authorization: authorization, + ); + expect(file.readAsBytesSync(), bytes); + } + expect(root.listSync().map((entry) => entry.path), [file.path]); + }, + ); + + test( + 'an identical-looking replacement inode still invalidates consent', + () async { + final file = File(p.join(root.path, 'same.md')) + ..writeAsStringSync('same'); + final authorization = SaveDestination.inspect(file.path); + final other = File(p.join(root.path, 'other')) + ..writeAsStringSync('same') + ..setLastModifiedSync(file.lastModifiedSync()); + final service = WorkspaceService( + beforeNewFilePublish: (_) async { + other.renameSync(file.path); + }, + ); + final expected = await service.fileSnapshot(file.path); + await expectLater( + service.saveFormattedTextReplacingPath( + file.path, + 'new', + expectedSnapshot: expected, + authorization: authorization, + ), + throwsA(isA()), + ); + expect(file.readAsStringSync(), 'same'); + }, + ); + + test( + 'file and directory workflows preserve their symlink policies', + () async { + final file = File(p.join(root.path, 'target.md')) + ..writeAsStringSync('old'); + final link = Link(p.join(root.path, 'alias.md'))..createSync('target.md'); + expect( + () => SaveDestination.inspect(link.path), + throwsA(isA()), + ); + expect( + () => SaveDestination.inspect(root.path), + throwsA(isA()), + ); + expect( + SaveDestination.inspect( + root.path, + kind: SaveDestinationKind.directory, + ).replacesExisting, + isTrue, + ); + final authorization = SaveDestination.inspect( + link.path, + kind: SaveDestinationKind.fileOrSymbolicLink, + ); + final service = const WorkspaceService(); + await service.saveFormattedTextReplacingPath( + link.path, + 'new copy', + expectedSnapshot: await service.fileSnapshot(link.path), + authorization: authorization, + ); + expect(File(link.path).readAsStringSync(), 'new copy'); + expect(file.readAsStringSync(), 'old'); + expect(link.existsSync(), isFalse); + }, + ); +} diff --git a/test/src/sidebar_native_contract_test.dart b/test/src/sidebar_native_contract_test.dart index c446188c..219c32ce 100644 --- a/test/src/sidebar_native_contract_test.dart +++ b/test/src/sidebar_native_contract_test.dart @@ -121,12 +121,9 @@ void main() { expect(primary, 0); expect(menus, 1); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); - await tester.sendKeyEvent(LogicalKeyboardKey.f10); - expect( - menus, - 1, - reason: 'The native grab waits for trigger release', - ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.f10); + expect(menus, 2, reason: 'The native menu opens on keydown'); + await tester.sendKeyUpEvent(LogicalKeyboardKey.f10); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); await tester.pump(); expect(menus, 2); diff --git a/test/src/sidebar_search_session_test.dart b/test/src/sidebar_search_session_test.dart index e0994339..22bd2fd5 100644 --- a/test/src/sidebar_search_session_test.dart +++ b/test/src/sidebar_search_session_test.dart @@ -1588,7 +1588,7 @@ void main() { initial.copyWith( documentBuffers: [ ...initial.documentBuffers, - const DocumentBuffer( + DocumentBuffer( id: 'outside', text: 'needle outside', lastSavedText: '', diff --git a/test/src/source_audit_test.dart b/test/src/source_audit_test.dart index 206dc8a7..1d6f5be6 100644 --- a/test/src/source_audit_test.dart +++ b/test/src/source_audit_test.dart @@ -414,6 +414,9 @@ void main() { final welcome = File( 'lib/src/workspace/presentation/welcome_screen.dart', ).readAsStringSync(); + final sharedSidebar = File( + 'lib/src/workspace/presentation/workspace_sidebar.dart', + ).readAsStringSync(); final sidebarSurface = RegExp( r'class BusyMarkSidebarSurface[\s\S]*?class BusyMarkGroupedList', ).firstMatch(design)!.group(0)!; @@ -422,8 +425,9 @@ void main() { expect(sidebarSurface, contains('BorderDirectional(')); expect(sidebarSurface, contains('end: BorderSide(')); expect(sidebarSurface, contains('color: colors.sidebarBorder')); - expect(workspace, contains('return BusyMarkSidebarSurface(')); - expect(welcome, contains('BusyMarkSidebarSurface(')); + expect(workspace, contains('WorkspaceSidebar<_SidebarTab>')); + expect(welcome, contains('WorkspaceSidebar')); + expect(sharedSidebar, contains('return BusyMarkSidebarSurface(')); expect( workspace, isNot(contains('decoration: BoxDecoration(color: colors.sidebar)')), @@ -482,37 +486,42 @@ void main() { }, ); - test('native search action toggles workspace search UI', () { - final workspace = File( - 'lib/src/workspace/presentation/workspace_screen.dart', - ).readAsStringSync(); + test( + 'workspace search uses the mounted command and shared search controls', + () { + final workspace = File( + 'lib/src/workspace/presentation/workspace_screen.dart', + ).readAsStringSync(); - expect( - workspace, - contains('case HeaderBarAction.search:\n _toggleSearch(ref);'), - ); - expect(workspace, contains('backVisible: !searchState.active')); - final sidebar = File( - 'lib/src/search/search_sidebar.dart', - ).readAsStringSync(); - final session = File( - 'lib/src/search/search_session.dart', - ).readAsStringSync(); - final matcher = File( - 'lib/src/search/workspace_text_search.dart', - ).readAsStringSync(); - expect(workspace, contains('searchSessionProvider')); - expect(sidebar, contains('class SearchHeaderField')); - expect(sidebar, contains('child: BusyMarkSearchField(')); - expect(sidebar, isNot(contains('TextField('))); - expect(sidebar, isNot(contains('OutlineInputBorder('))); - expect(sidebar, contains('onEscape: controller.close')); - expect(sidebar, contains('class SearchSidebar')); - expect(session, contains('loadWorkspaceTextMatches')); - expect(matcher, contains('await loadText(file.absolutePath)')); - expect(workspace, isNot(contains('readAsStringSync()'))); - expect(workspace, contains('_searchNavigationTargetProvider')); - }); + expect(workspace, contains('const SearchHeaderField()')); + expect(workspace, contains("ValueKey('workspace-home')")); + final sidebar = File( + 'lib/src/search/search_sidebar.dart', + ).readAsStringSync(); + final session = File( + 'lib/src/search/search_session.dart', + ).readAsStringSync(); + final matcher = File( + 'lib/src/search/workspace_text_search.dart', + ).readAsStringSync(); + expect(workspace, contains('searchSessionProvider')); + expect( + session, + contains('BusyMarkCommandIds.search: SearchCategory.file'), + ); + expect(sidebar, contains('searchCommandForCategory(')); + expect(sidebar, contains('class SearchHeaderField')); + expect(sidebar, contains('child: BusyMarkSearchField(')); + expect(sidebar, isNot(contains('TextField('))); + expect(sidebar, isNot(contains('OutlineInputBorder('))); + expect(sidebar, contains('onEscape: controller.close')); + expect(sidebar, contains('class SearchSidebar')); + expect(session, contains('loadWorkspaceTextMatches')); + expect(matcher, contains('await loadText(file.absolutePath)')); + expect(workspace, isNot(contains('readAsStringSync()'))); + expect(workspace, contains('_searchNavigationTargetProvider')); + }, + ); test('preview links are actionable instead of styled-only text', () { final workspace = File( @@ -752,14 +761,10 @@ void main() { singleMarkdownClause.indexOf('_SidebarTab.localHistory'), lessThan(singleMarkdownClause.indexOf('_SidebarTab.clipboard')), ); - expect(workspace, contains('showTabMenu: tabs.length > 1')); - expect( - workspace, - contains(RegExp(r'if \(!widget\.searchState\.active\)\s+_SidebarHeader')), - ); - expect(workspace, contains('_preferredSidebarTabIndex')); - expect(workspace, contains('_shouldShowOutlineForOpenFile')); - expect(workspace, contains('tabs.indexOf(_SidebarTab.outline)')); + expect(workspace, contains('WorkspaceSidebar<_SidebarTab>')); + expect(workspace, contains('late _SidebarTab _tab')); + expect(workspace, contains('_initialSidebarTab')); + expect(singleMarkdownClause, contains('_SidebarTab.recent')); expect( workspace, contains('widget.workspace.activeFilePath != _activeFilePath'), @@ -772,10 +777,7 @@ void main() { activeFileUpdateClause, contains('_activeFilePath = widget.workspace.activeFilePath;'), ); - expect( - activeFileUpdateClause, - isNot(contains('_tab = _preferredSidebarTabIndex')), - ); + expect(activeFileUpdateClause, isNot(contains('_tab ='))); expect(folderClause, contains('_SidebarTab.files')); expect(folderClause, contains('_SidebarTab.outline')); expect(folderClause, contains('_SidebarTab.git')); @@ -838,7 +840,11 @@ void main() { settings, contains('BusyMarkPopupSelector('), ); - expect(workspace, contains('BusyMarkHeaderPopupMenuButton<_SidebarTab>')); + final sidebar = File( + 'lib/src/workspace/presentation/workspace_sidebar.dart', + ).readAsStringSync(); + expect(workspace, contains('WorkspaceSidebar<_SidebarTab>')); + expect(sidebar, contains('BusyMarkHeaderPopupMenuButton.native')); expect(workspace, isNot(contains('class _SidebarSegmentLabel'))); expect(workspace, contains('softWrap: false')); expect( @@ -868,18 +874,22 @@ void main() { 'lib/src/workspace/presentation/workspace_screen.dart', ).readAsStringSync(); - expect(workspace, contains('BusyMarkHeaderPopupMenuButton<_SidebarTab>')); + final sidebar = File( + 'lib/src/workspace/presentation/workspace_sidebar.dart', + ).readAsStringSync(); + expect(workspace, contains('WorkspaceSidebar<_SidebarTab>')); + expect(sidebar, contains('BusyMarkHeaderPopupMenuButton.native')); expect(workspace, contains('BusyMarkPopupMenuItem(')); - expect(workspace, contains('tooltip: context.l10n.sidebarViewMenu')); - expect(workspace, contains('icon: BusyMarkGlyphs.sidebarViews')); + expect(sidebar, contains('tooltip: context.l10n.sidebarViewMenu')); + expect(sidebar, contains('icon: BusyMarkGlyphs.sidebarViews')); expect( File('lib/src/app/busymark_glyphs.dart').readAsStringSync(), contains('sidebarViews = YaruIcons.display_layout'), ); expect(workspace, isNot(contains('icon: selectedTabMenuItem.icon'))); - expect(workspace, contains('transparent: true')); + expect(sidebar, contains('transparent: true')); expect( - workspace, + sidebar, contains('borderRadius: BusyMarkRadius.nativeHeaderButton'), ); expect( @@ -916,7 +926,7 @@ void main() { '_SidebarTab.localHistory => BusyMarkGlyphs.sidebarLocalHistory', ), ); - expect(workspace, contains('itemBuilder: (context) => tabMenuItems')); + expect(sidebar, contains('itemBuilder: (_) => items')); expect(workspace, isNot(contains('_SidebarTab.gitFileHistory'))); expect(workspace, isNot(contains('_SidebarTab.gitProjectHistory'))); expect(workspace, contains('checked: tab == selectedTab')); @@ -972,7 +982,8 @@ void main() { r'class BusyMarkHeaderIconButton[\s\S]*?class ' r'BusyMarkCompactIconButton', ).firstMatch(design)!.group(0)!; - expect(headerIcon, contains('final button = YaruIconButton(')); + expect(headerIcon, contains('extends YaruIconButton')); + expect(headerIcon, contains('style!.merge(super.defaultStyleOf(context))')); expect(headerIcon, contains('style: style')); expect(headerIcon, contains('isSelected: selected')); expect(headerIcon, contains('padding: EdgeInsets.zero')); @@ -1012,11 +1023,15 @@ void main() { ).firstMatch(workspace)!.group(0)!; final outlineHeader = RegExp( r'class _SidebarHeader extends ConsumerWidget[\s\S]*?' - r'class _SidebarHeaderRow', + r'typedef _SidebarHeaderSecondaryTapHandler', ).firstMatch(workspace)!.group(0)!; final outlineActions = '$outlineMenu\n$outlineHeader'; - expect(workspace, contains('BusyMarkHeaderPopupMenuButton<_SidebarTab>')); + final sidebar = File( + 'lib/src/workspace/presentation/workspace_sidebar.dart', + ).readAsStringSync(); + expect(workspace, contains('WorkspaceSidebar<_SidebarTab>')); + expect(sidebar, contains('BusyMarkHeaderPopupMenuButton.native')); for (final retired in [ 'BusyMarkHeaderPopupMenuButton<_GitMenuAction>', '_loadWorkspaceGitMenuItems', @@ -1047,9 +1062,9 @@ void main() { expect(workspace, isNot(contains('_showSidebarBranchMenu'))); expect(workspace, isNot(contains('_sidebarMenuLeft'))); expect(workspace, isNot(contains('_BoldDownArrowIcon'))); - expect(workspace, contains("ValueKey('workspace-sidebar-primary-row')")); - expect(workspace, contains('class _SidebarHeaderRow')); - expect(workspace, contains('minHeight: BusyMarkSizes.iconButton')); + expect(sidebar, contains("ValueKey('workspace-sidebar-primary-row')")); + expect(sidebar, contains('class WorkspaceSidebarHeaderRow')); + expect(sidebar, contains('minHeight: BusyMarkSizes.iconButton')); expect( RegExp( r"ValueKey\('workspace-sidebar-first-content'\)", @@ -1321,8 +1336,11 @@ void main() { test('data-entry dialogs use native grouped modal editors', () { final design = File('lib/src/app/busymark_design.dart').readAsStringSync(); - final welcome = File( - 'lib/src/workspace/presentation/welcome_screen.dart', + final operations = File( + 'lib/src/workspace/workspace_resource_actions.dart', + ).readAsStringSync(); + final projectDialog = File( + 'lib/src/workspace/presentation/create_writerside_project_dialog.dart', ).readAsStringSync(); final workspace = File( 'lib/src/workspace/presentation/workspace_screen.dart', @@ -1352,18 +1370,21 @@ void main() { expect(entries, isNot(contains('MouseRegion('))); expect(entries, isNot(contains('GestureDetector('))); expect(entries, isNot(contains('busyMarkSurfaceDecoration('))); - expect(welcome, contains('showBusyMarkModalEditorDialog(')); - expect(welcome, contains('BusyMarkModalEditorScaffold(')); - expect(RegExp(r'BusyMarkGroupedTextEntry\(').allMatches(welcome).length, 5); + expect(operations, contains('showBusyMarkModalEditorDialog(')); + expect(projectDialog, contains('BusyMarkModalEditorScaffold(')); + expect( + RegExp(r'BusyMarkGroupedTextEntry\(').allMatches(projectDialog).length, + 5, + ); expect(workspace, contains('showBusyMarkModalEditorDialog(')); expect(workspace, contains('showBusyMarkModalDialog(')); expect(editor, contains('showBusyMarkModalEditorDialog(')); - expect(welcome, isNot(contains('BusyMarkFloatingTextEntry'))); + expect(projectDialog, isNot(contains('BusyMarkFloatingTextEntry'))); expect(workspace, isNot(contains('BusyMarkFloatingTextEntry'))); expect(editor, isNot(contains('BusyMarkFloatingTextEntry'))); - expect(welcome, isNot(contains('autofocus: true'))); + expect(projectDialog, isNot(contains('autofocus: true'))); expect( - welcome, + projectDialog, isNot(contains('hintText: context.l10n.defaultProjectName')), ); }); @@ -1526,7 +1547,7 @@ void main() { ).readAsStringSync(); final stagingAdapter = gitController.substring( gitController.indexOf('Future stageFiles('), - gitController.indexOf('Future rollbackFiles('), + gitController.indexOf('Future stagedDiffForAi('), ); expect( stagingAdapter, @@ -1631,8 +1652,8 @@ void main() { }); test('recent workspaces expose one native menu action model', () { - final welcome = File( - 'lib/src/workspace/presentation/welcome_screen.dart', + final recentPanel = File( + 'lib/src/workspace/presentation/workspace_sidebar.dart', ).readAsStringSync(); final design = File('lib/src/app/busymark_design.dart').readAsStringSync(); final settings = File('lib/src/app/app_settings.dart').readAsStringSync(); @@ -1640,7 +1661,7 @@ void main() { final sidebar = File( 'lib/src/search/search_sidebar.dart', ).readAsStringSync(); - expect(welcome, contains('SearchResultList(')); + expect(recentPanel, contains('SearchResultList(')); final navigation = File( 'lib/src/workspace/recent_navigation.dart', ).readAsStringSync(); @@ -1893,7 +1914,7 @@ void main() { ); expect(toolbar, isNot(contains('busyMarkContainedControlBackground('))); expect(toolbar, isNot(contains('foregroundColor: colors.foreground'))); - expect(RegExp(r'elevated: true').allMatches(toolbar), hasLength(3)); + expect(toolbar, isNot(contains('elevated: true'))); expect(toolbar, isNot(contains('accented: true'))); expect(toolbar, contains('clipBehavior: Clip.hardEdge')); expect(toolbar, contains('hitTestBehavior: HitTestBehavior.deferToChild')); @@ -1906,7 +1927,7 @@ void main() { final floatingToolbar = RegExp( r'class _FloatingWysiwygToolbar[\s\S]*?class _EditorToolbarMenuAction', ).firstMatch(editor)!.group(0)!; - expect(floatingToolbar, contains('elevated: true')); + expect(floatingToolbar, isNot(contains('elevated: true'))); expect(floatingToolbar, contains('accented: true')); expect( floatingToolbar, @@ -1974,9 +1995,12 @@ void main() { dotAll: true, ).firstMatch(editor)!.group(0)!; - expect(imageView, isNot(contains('color: colors.panel'))); + final imageRendering = imageView + .split('class _RemoteImageBlockedPlaceholder') + .first; + expect(imageRendering, isNot(contains('color: colors.panel'))); expect( - imageView, + imageRendering, isNot(contains('Border.all(color: colors.subtleBorder)')), ); expect(prefix, isNot(contains('BusyBlockKind.image => Icon'))); diff --git a/test/src/source_document_test.dart b/test/src/source_document_test.dart index d5789408..1cefbfab 100644 --- a/test/src/source_document_test.dart +++ b/test/src/source_document_test.dart @@ -29,6 +29,48 @@ void main() { expect(document.visibleRangeToFullRange(4, 7).range.end, 7); }); + test( + 'unfolded edits share the full index, fold transitions keep distinct coordinates', + () { + const text = 'one\ntwo\nthree\n'; + final full = SourceDocument(fullText: text); + expect(full.visibleLineIndex, same(full.lineIndex)); + final folded = SourceDocument( + fullText: text, + hiddenRanges: SourceHiddenRanges( + ranges: [SourceHiddenRange(start: 4, end: 8)], + textLength: text.length, + ), + ); + expect(folded.visibleLineIndex, isNot(same(folded.lineIndex))); + final editedText = folded.applyVisibleEdit('ONE\nthree\n'); + final edited = SourceDocument.afterVisibleEdit( + previous: folded, + fullText: editedText, + hiddenRanges: SourceHiddenRanges( + ranges: const [], + textLength: editedText.length, + ), + edit: folded.describeVisibleEdit('ONE\nthree\n'), + ); + expect(edited.visibleLineIndex, same(edited.lineIndex)); + expect(edited.visibleLineIndex.lineCount, 4); + expect(edited.lineIndex.lineAt(2).startOffset, 4); + final nextText = edited.applyVisibleEdit('ONE\nTWO\nthree\n'); + final next = SourceDocument.afterVisibleEdit( + previous: edited, + fullText: nextText, + hiddenRanges: SourceHiddenRanges( + ranges: const [], + textLength: nextText.length, + ), + edit: edited.describeVisibleEdit('ONE\nTWO\nthree\n'), + ); + expect(next.visibleLineIndex, same(next.lineIndex)); + expect(next.lineIndex.lineAt(3).startOffset, 8); + }, + ); + test('single fold projects visible text and maps offsets', () { const source = '# Title\nIntro.\nMore.\n# Next\n'; final region = sourceFoldRegions( diff --git a/test/src/source_highlighter_test.dart b/test/src/source_highlighter_test.dart index b57dfc07..aecc9d27 100644 --- a/test/src/source_highlighter_test.dart +++ b/test/src/source_highlighter_test.dart @@ -528,98 +528,6 @@ void main() { expect(foldedHeight, lessThan(unfoldedHeight - 20)); }); - testWidgets( - 'visual markdown editor keeps syntax markers visible while styling content', - (tester) async { - const source = - '# **Title**\n' - 'Paragraph with [link](target.md) and `code`.\n'; - late TextSpan root; - late List spans; - - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - theme: buildBusyMarkTheme( - brightness: Brightness.dark, - accentColor: BusyMarkLinuxPalette.blueAccent, - ), - home: Builder( - builder: (context) { - final controller = BusyMarkSourceEditingController( - text: source, - language: SourceSyntaxLanguage.markdown, - )..visualMarkdown = true; - root = controller.buildTextSpan( - context: context, - style: const TextStyle(fontSize: 14), - withComposing: false, - ); - spans = _flattenTextSpans(root); - return const SizedBox.shrink(); - }, - ), - ), - ); - - expect(root.toPlainText(), source); - expect(_spanStyle(spans, '# ')?.color, isNot(Colors.transparent)); - expect(_spanStyle(spans, '**')?.color, isNot(Colors.transparent)); - expect(_spanStyle(spans, 'Title')?.fontWeight, FontWeight.w700); - expect(_spanStyle(spans, '[')?.color, isNot(Colors.transparent)); - expect( - _spanStyle(spans, '](target.md)')?.color, - isNot(Colors.transparent), - ); - expect(_spanStyle(spans, 'link')?.decoration, TextDecoration.underline); - }, - ); - - testWidgets('visual markdown tracks dynamic fence delimiters', ( - tester, - ) async { - const source = - '````dart\n' - 'final value = 1;\n' - '```\n' - '# Still code\n' - '`````\n' - '# Heading\n'; - late List spans; - - await tester.pumpWidget( - MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - theme: buildBusyMarkTheme( - brightness: Brightness.dark, - accentColor: BusyMarkLinuxPalette.blueAccent, - ), - home: Builder( - builder: (context) { - final controller = BusyMarkSourceEditingController( - text: source, - language: SourceSyntaxLanguage.markdown, - )..visualMarkdown = true; - spans = _flattenTextSpans( - controller.buildTextSpan( - context: context, - style: const TextStyle(fontSize: 14), - withComposing: false, - ), - ); - return const SizedBox.shrink(); - }, - ), - ), - ); - - expect(_spanStyle(spans, '```')?.fontFamily, 'Ubuntu Mono'); - expect(_spanStyle(spans, '# Still code')?.fontFamily, 'Ubuntu Mono'); - expect(_spanStyle(spans, 'Heading')?.fontSize, greaterThan(14)); - }); - testWidgets('markdown highlighter merges nested emphasis inside links', ( tester, ) async { diff --git a/test/src/source_search_test.dart b/test/src/source_search_test.dart index cc1e0e0c..9a8b7ab7 100644 --- a/test/src/source_search_test.dart +++ b/test/src/source_search_test.dart @@ -196,23 +196,6 @@ void main() { ); }); - test('workspace search groups authoring content by file', () { - final results = searchWorkspaceSources( - files: const { - 'topics/intro.md': '# Intro\nInstall BusyMark.', - 'topics/install.topic': 'Install', - 'images/install.png': 'Install', - }, - options: const SourceSearchOptions(query: 'install'), - ); - - expect(results.map((result) => result.filePath), [ - 'topics/install.topic', - 'topics/intro.md', - ]); - expect(results.expand((result) => result.matches), hasLength(2)); - }); - test('source search worker cancels stale requests', () async { final worker = SourceSearchWorker(); addTearDown(worker.dispose); diff --git a/test/src/spellcheck_projection_test.dart b/test/src/spellcheck_projection_test.dart index ffb27e52..2f0ca44a 100644 --- a/test/src/spellcheck_projection_test.dart +++ b/test/src/spellcheck_projection_test.dart @@ -324,14 +324,20 @@ void main() { final reloaded = const MarkdownParser() .parse(filePath: '/pasted.md', source: source, mode: MarkdownMode.gfm) .busyDocument; - List prose(BusyDocument document) => [ - for (final block in document.blocks) - if (block.plainText.trim().isNotEmpty) - block.plainText.trim().replaceAll(RegExp(r'\s+'), ' '), - ]; + Iterable prose(Iterable blocks) sync* { + for (final block in blocks) { + if (block.plainText.trim().isNotEmpty) { + yield block.plainText.trim().replaceAll(RegExp(r'\s+'), ' '); + } + if (block.attributes['busymark-list-form'] == 'markdown') { + yield* prose(block.children); + } + } + } + expect( - prose(reloaded), - prose(live), + prose(reloaded.blocks), + prose(live.blocks), reason: 'Formatting must not reload as literal Markdown markers.', ); final projection = const WysiwygSpellingProjector().project( @@ -341,6 +347,18 @@ void main() { documentGeneration: 1, ); expect(projection.complete, isTrue, reason: projection.message); + final item = projection.runs.singleWhere( + (run) => run.text == 'Design accessible interfaces.', + ); + expect(item.hasValidMapping, isTrue); + final listPlan = const SpellingReplacementPlanner().build( + occurrence: _rejected(item, 'accessible'), + suggestion: 'usable', + ); + expect( + listPlan.applyToSource(source), + source.replaceFirst('accessible interfaces', 'usable interfaces'), + ); final team = projection.runs.singleWhere( (run) => run.text.contains('Team responsibilities'), ); diff --git a/test/src/spelling_editor_integration_test.dart b/test/src/spelling_editor_integration_test.dart index 60769147..2051d24d 100644 --- a/test/src/spelling_editor_integration_test.dart +++ b/test/src/spelling_editor_integration_test.dart @@ -1,3 +1,4 @@ +import '../support/document_history_harness.dart'; import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/src/core/diagnostic.dart'; import 'package:busymark/src/editor/source/source_editor.dart'; @@ -185,7 +186,6 @@ void main() { document: document, documentId: 'formatted-buffer', contentRevision: 3, - useExternalUndoHistory: true, spellingAnnotations: [_annotation(occurrence)], onDocumentChanged: (value) => updatedDocument = value, onSourceChanged: (_, _) {}, @@ -248,17 +248,63 @@ void main() { ); final key = GlobalKey(); final sources = []; + var fixtureHistory0Document = document; + final fixtureHistory0 = await DocumentHistoryHarness.create( + source: fixtureHistory0Document.source ?? '', + ); + addTearDown(fixtureHistory0.dispose); await tester.pumpWidget( _testApp( BusyMarkWysiwygEditor( + readEditBase: fixtureHistory0.readBase, + readSessionState: () => + fixtureHistory0.buffer.editorState.wysiwygState, + onUndo: () { + if (fixtureHistory0.controller.undoActiveBuffer()) { + ((_, text) => sources.add(text))( + fixtureHistory0Document.filePath, + fixtureHistory0.buffer.text, + ); + } + }, + onRedo: () { + if (fixtureHistory0.controller.redoActiveBuffer()) { + ((_, text) => sources.add(text))( + fixtureHistory0Document.filePath, + fixtureHistory0.buffer.text, + ); + } + }, + onSessionChanged: (id, value) { + fixtureHistory0.controller.updateDocumentEditorState( + fixtureHistory0.buffer.id, + fixtureHistory0.buffer.editorState.copyWith(wysiwygState: value), + ); + }, key: key, - document: document, + document: fixtureHistory0Document, documentId: snapshot.bufferId, contentRevision: snapshot.contentRevision, spellingAnnotations: [_annotation(occurrence)], - onDocumentChanged: (_) {}, - onSourceChanged: (_, text) => sources.add(text), - onSpellingSourceChanged: (_, text, _, _) => sources.add(text), + onDocumentChanged: (value) { + fixtureHistory0Document = value; + }, + onSourceChanged: (path, text) { + fixtureHistory0.controller.updateActiveWysiwygText( + text, + document: fixtureHistory0Document, + ); + ((_, text) => sources.add(text))(path, text); + }, + onSpellingSourceChanged: (path, text, before, after) { + fixtureHistory0.controller.updateActiveWysiwygText( + text, + document: fixtureHistory0Document, + previousWysiwygState: before, + wysiwygState: after, + ); + ((_, text, _, _) => sources.add(text))(path, text, before, after); + }, ), ), ); @@ -288,7 +334,7 @@ void main() { ); await tester.pump(); expect(sources, ['Before ![hello `world`](image.png) after\n']); - expect(editor.debugUndoSnapshotCount, 1); + expect(fixtureHistory0.buffer.editorState.undoState.undo.length, 1); final editable = find.byType(EditableText).first; await tester.tap(editable); @@ -356,18 +402,67 @@ void main() { expect(occurrence.sourceStart, source.indexOf('wrld')); final key = GlobalKey(); final sources = []; + var fixtureHistory1Document = document; + final fixtureHistory1 = await DocumentHistoryHarness.create( + source: fixtureHistory1Document.source ?? '', + ); + addTearDown(fixtureHistory1.dispose); await tester.pumpWidget( ProviderScope( child: _testApp( BusyMarkWysiwygEditor( + readEditBase: fixtureHistory1.readBase, + readSessionState: () => + fixtureHistory1.buffer.editorState.wysiwygState, + onUndo: () { + if (fixtureHistory1.controller.undoActiveBuffer()) { + ((_, text) => sources.add(text))( + fixtureHistory1Document.filePath, + fixtureHistory1.buffer.text, + ); + } + }, + onRedo: () { + if (fixtureHistory1.controller.redoActiveBuffer()) { + ((_, text) => sources.add(text))( + fixtureHistory1Document.filePath, + fixtureHistory1.buffer.text, + ); + } + }, + onSessionChanged: (id, value) { + fixtureHistory1.controller.updateDocumentEditorState( + fixtureHistory1.buffer.id, + fixtureHistory1.buffer.editorState.copyWith( + wysiwygState: value, + ), + ); + }, key: key, - document: document, + document: fixtureHistory1Document, documentId: snapshot.bufferId, contentRevision: snapshot.contentRevision, spellingAnnotations: [_annotation(occurrence)], - onDocumentChanged: (_) {}, - onSourceChanged: (_, text) => sources.add(text), - onSpellingSourceChanged: (_, text, _, _) => sources.add(text), + onDocumentChanged: (value) { + fixtureHistory1Document = value; + }, + onSourceChanged: (path, text) { + fixtureHistory1.controller.updateActiveWysiwygText( + text, + document: fixtureHistory1Document, + ); + ((_, text) => sources.add(text))(path, text); + }, + onSpellingSourceChanged: (path, text, before, after) { + fixtureHistory1.controller.updateActiveWysiwygText( + text, + document: fixtureHistory1Document, + previousWysiwygState: before, + wysiwygState: after, + ); + ((_, text, _, _) => + sources.add(text))(path, text, before, after); + }, ), ), ), @@ -398,7 +493,7 @@ void main() { ); await tester.pump(); expect(sources, [expected]); - expect(editor.debugUndoSnapshotCount, 1); + expect(fixtureHistory1.buffer.editorState.undoState.undo.length, 1); final target = occurrence.run.target as SpellingRichBlockTarget; await tester.tap( find.byKey(ValueKey('wysiwyg-rendered-math-${target.blockId}')), @@ -576,7 +671,6 @@ void main() { isFalse, ); expect(changes, isEmpty); - expect(key.currentState!.debugUndoSnapshotCount, 0); }); testWidgets('delayed math image preparation refuses a newer revision', ( @@ -657,7 +751,6 @@ void main() { isFalse, ); expect(changes, isEmpty); - expect(key.currentState!.debugUndoSnapshotCount, 0); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(const Duration(seconds: 11)); }); @@ -704,7 +797,6 @@ void main() { document: document, documentId: snapshot.bufferId, contentRevision: snapshot.contentRevision, - useExternalUndoHistory: true, spellingAnnotations: [_annotation(occurrence)], onDocumentChanged: (_) {}, onSourceChanged: (_, _) {}, @@ -772,7 +864,6 @@ void main() { document: document, documentId: snapshot.bufferId, contentRevision: snapshot.contentRevision, - useExternalUndoHistory: true, spellingAnnotations: [_annotation(occurrence)], onDocumentChanged: (_) {}, onSourceChanged: (_, _) {}, @@ -843,7 +934,6 @@ void main() { document: document, documentId: snapshot.bufferId, contentRevision: snapshot.contentRevision, - useExternalUndoHistory: true, spellingAnnotations: [_annotation(occurrence)], onDocumentChanged: (_) {}, onSourceChanged: (_, _) {}, @@ -929,7 +1019,6 @@ void main() { document: document, documentId: 'rich-buffer', contentRevision: 11, - useExternalUndoHistory: true, spellingAnnotations: [_annotation(occurrence)], onDocumentChanged: (_) => publicationOrder.add('document'), onSourceChanged: (_, _) => genericSourceChanges++, diff --git a/test/src/spelling_service_test.dart b/test/src/spelling_service_test.dart index 6da3474d..84573107 100644 --- a/test/src/spelling_service_test.dart +++ b/test/src/spelling_service_test.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'package:busymark/src/core/save_destination.dart'; import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/l10n/generated/app_localizations_en.dart'; import 'package:busymark/src/app/app_settings.dart'; @@ -9,7 +10,6 @@ import 'package:busymark/src/app/app_router.dart'; import 'package:busymark/src/app/busymark_design.dart'; import 'package:busymark/src/app/busymark_toast.dart'; import 'package:busymark/src/core/atomic_file_writer.dart'; -import 'package:busymark/src/platform/header_bar_configuration.dart'; import 'package:busymark/src/markdown/busymark_document.dart'; import 'package:busymark/src/markdown/markdown_model.dart'; import 'package:busymark/src/markdown/markdown_parser.dart'; @@ -3275,8 +3275,7 @@ void main() { child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - builder: (context, child) => - _spellingSettingsHeaderDefaults(context, child!), + builder: (context, child) => (child!), home: const SettingsScreen( returnTarget: SettingsReturnTarget.welcome, initialPage: SettingsPage.editor, @@ -3354,8 +3353,7 @@ void main() { child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - builder: (context, child) => - _spellingSettingsHeaderDefaults(context, child!), + builder: (context, child) => (child!), home: const SettingsScreen( returnTarget: SettingsReturnTarget.welcome, initialPage: SettingsPage.editor, @@ -3479,8 +3477,7 @@ void main() { child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - builder: (context, child) => - _spellingSettingsHeaderDefaults(context, child!), + builder: (context, child) => (child!), home: const SettingsScreen( returnTarget: SettingsReturnTarget.welcome, initialPage: SettingsPage.spellingDictionaries, @@ -3539,8 +3536,7 @@ void main() { child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - builder: (context, child) => - _spellingSettingsHeaderDefaults(context, child!), + builder: (context, child) => (child!), home: const SettingsScreen( returnTarget: SettingsReturnTarget.welcome, initialPage: SettingsPage.editor, @@ -5923,68 +5919,6 @@ final class _SpellingMemorySettingsStore implements LocalSettingsStore { Future save(Map json) async {} } -Widget _spellingSettingsHeaderDefaults(BuildContext context, Widget child) => - HeaderBarConfigurationDefaults( - configuration: HeaderBarConfiguration( - title: 'Settings', - viewMode: AppViewMode.editor, - searchQuery: '', - textDirection: TextDirection.ltr, - canRefresh: false, - documentControlsVisible: false, - searchActive: false, - searchVisible: false, - sidebarVisible: false, - sidebarToggleVisible: false, - backVisible: true, - fullScreen: false, - modalBarrierDepth: 0, - sidebarWidth: 200, - labels: _spellingSettingsHeaderLabels, - theme: HeaderBarTheme.fromContext(context), - ), - child: child, - ); - -const _spellingSettingsHeaderLabels = HeaderBarLabels( - editor: 'Editor', - source: 'Source', - preview: 'Preview', - split: 'Dual', - viewMode: 'View mode', - editorShortcut: '', - editorGtkAccelerator: '', - sourceShortcut: '', - sourceGtkAccelerator: '', - previewShortcut: '', - previewGtkAccelerator: '', - splitShortcut: '', - splitGtkAccelerator: '', - search: 'Search', - searchShortcut: '', - refresh: 'Refresh', - menu: 'Menu', - sidebar: 'Sidebar', - sidebarShortcut: '', - back: 'Back', - backShortcut: '', - save: 'Save', - export: 'Export', - exportShortcut: '', - exportGtkAccelerator: '', - fullScreen: 'Full screen', - fullScreenShortcut: '', - fullScreenGtkAccelerator: '', - settings: 'Settings', - settingsShortcut: '', - settingsGtkAccelerator: '', - syntaxReference: 'Syntax reference', - syntaxReferenceShortcut: '', - syntaxReferenceGtkAccelerator: '', - reportIssue: 'Report issue', - aboutBusyMark: 'About', -); - final class _DelayedAtomicFileWriter extends AtomicFileWriter { _DelayedAtomicFileWriter(); @@ -6000,7 +5934,9 @@ final class _DelayedAtomicFileWriter extends AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { await super.writeBytes( @@ -6028,7 +5964,9 @@ final class _ToggleFailAtomicFileWriter extends AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { writeCount++; @@ -6051,6 +5989,7 @@ final class _ToggleFailAtomicFileWriter extends AtomicFileWriter { bytes, overwrite: overwrite, beforePublish: beforePublish, + checkBeforeCommit: checkBeforeCommit, acceptReplaced: acceptReplaced, ); } @@ -6072,7 +6011,9 @@ final class _GatedSpellingAtomicFileWriter extends AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { if (_hold) { @@ -6085,6 +6026,7 @@ final class _GatedSpellingAtomicFileWriter extends AtomicFileWriter { bytes, overwrite: overwrite, beforePublish: beforePublish, + checkBeforeCommit: checkBeforeCommit, acceptReplaced: acceptReplaced, ); } @@ -6103,7 +6045,9 @@ final class _PostExchangeAtomicFileWriter extends AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { await super.writeBytes( @@ -6111,6 +6055,7 @@ final class _PostExchangeAtomicFileWriter extends AtomicFileWriter { bytes, overwrite: overwrite, beforePublish: beforePublish, + checkBeforeCommit: checkBeforeCommit, acceptReplaced: acceptReplaced == null ? null : (replacedPath) async { @@ -6146,7 +6091,9 @@ final class _RejectedExchangeAtomicFileWriter extends AtomicFileWriter { String targetPath, List bytes, { required bool overwrite, + SaveDestination? authorization, FutureOr Function()? beforePublish, + void Function()? checkBeforeCommit, FutureOr Function(String replacedPath)? acceptReplaced, }) async { await super.writeBytes( diff --git a/test/src/spelling_workspace_test.dart b/test/src/spelling_workspace_test.dart index 10513541..739560d9 100644 --- a/test/src/spelling_workspace_test.dart +++ b/test/src/spelling_workspace_test.dart @@ -15,7 +15,6 @@ import 'package:busymark/src/editor/wysiwyg/wysiwyg_block_widgets.dart'; import 'package:busymark/src/editor/wysiwyg/wysiwyg_editor.dart'; import 'package:busymark/src/local_history/local_history_store.dart'; import 'package:busymark/src/local_history/local_history_controller.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/platform/native_menu_service.dart'; import 'package:busymark/src/platform/rich_clipboard_service.dart'; import 'package:busymark/src/spellcheck/spelling_dictionary_downloader.dart'; @@ -85,17 +84,8 @@ void main() { 'delayed spelling review return respects newerOwner=$newerOwner', (tester) async { enableDesktopFocusLifecycle(tester); - final barrier = _ReviewFocusBarrier(); - addTearDown(() { - if (!barrier.release.isCompleted) barrier.release.complete(); - barrier.dispose(); - }); const original = 'helo world\n'; - final harness = await _pumpWorkspace( - tester, - source: original, - headerBarService: barrier, - ); + final harness = await _pumpWorkspace(tester, source: original); await _until( tester, () => @@ -125,10 +115,7 @@ void main() { find.descendant(of: dialog, matching: find.text(l10n.close)), pointer: 1402, ); - await _until( - tester, - () => barrier.releaseStarted && dialog.evaluate().isEmpty, - ); + await _until(tester, () => dialog.evaluate().isEmpty); if (newerOwner) { entry = OverlayEntry( builder: (_) => Positioned( @@ -149,7 +136,6 @@ void main() { await tester.pumpAndSettle(); expect(FocusManager.instance.primaryFocus, same(newer)); } - barrier.release.complete(); for (var frame = 0; frame < 30; frame++) { tester.binding.scheduleFrame(); await tester.pump(const Duration(milliseconds: 16)); @@ -1745,7 +1731,6 @@ Future<_Harness> _pumpWorkspace( bool automaticSpelling = true, SpellingDictionaryFileDownload? downloadFile, SpellingCoordinatorStarter? coordinatorStarter, - LinuxHeaderBarService? headerBarService, }) async { await tester.binding.setSurfaceSize(const Size(1400, 1000)); addTearDown(() => tester.binding.setSurfaceSize(null)); @@ -1800,9 +1785,6 @@ Future<_Harness> _pumpWorkspace( documentRecoveryStoreProvider.overrideWithValue( MemoryDocumentRecoveryStore(), ), - linuxHeaderBarServiceProvider.overrideWithValue( - headerBarService ?? _HeaderBar(), - ), systemAccentColorProvider.overrideWith((ref) => const Stream.empty()), spellingSessionControllerProvider.overrideWith((ref) => spelling), ], @@ -1926,29 +1908,6 @@ class _Settings implements LocalSettingsStore { Future save(Map value) async {} } -class _HeaderBar extends LinuxHeaderBarService { - _HeaderBar() : super(channel: const MethodChannel('test.busymark/spelling')); - @override - bool get isAvailable => false; - @override - bool get usesNativeHeaderBar => false; - @override - Stream get actions => const Stream.empty(); -} - -class _ReviewFocusBarrier extends _HeaderBar { - final release = Completer(); - bool releaseStarted = false; - - @override - Future setModalBarrierDepth(int depth) async { - if (depth == 0) { - releaseStarted = true; - await release.future; - } - } -} - Future _copyDictionaryDownload({ required Uri source, required File destination, diff --git a/test/src/validation_problems_ui_test.dart b/test/src/validation_problems_ui_test.dart index ffccc388..162675dc 100644 --- a/test/src/validation_problems_ui_test.dart +++ b/test/src/validation_problems_ui_test.dart @@ -8,7 +8,6 @@ import 'package:busymark/src/app/app_router.dart'; import 'package:busymark/src/app/system_accent.dart'; import 'package:busymark/src/core/source_span.dart'; import 'package:busymark/src/editor/source/source_editor.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/workspace/document_buffer.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; @@ -224,7 +223,6 @@ Future<_Harness> _open( _Settings(mode, validateOnEdit: validateOnEdit), ), workspaceServiceProvider.overrideWithValue(service), - linuxHeaderBarServiceProvider.overrideWithValue(_HeaderBar()), ], ); harness = _Harness(root, container); @@ -295,14 +293,6 @@ class _Settings implements LocalSettingsStore { Future save(Map json) async {} } -class _HeaderBar extends LinuxHeaderBarService { - _HeaderBar() : super(channel: const MethodChannel('test.busymark/problems')); - @override - bool get isAvailable => false; - @override - bool get usesNativeHeaderBar => false; -} - class _ControlledValidationService extends WorkspaceService { bool fail = false; Completer? gate; diff --git a/test/src/view_selector_menu_test.dart b/test/src/view_selector_menu_test.dart index 0a55bf05..1d06b085 100644 --- a/test/src/view_selector_menu_test.dart +++ b/test/src/view_selector_menu_test.dart @@ -211,7 +211,7 @@ void main() { ); testWidgets( - 'native selector waits for its trigger releases with Num Lock pressed', + 'native selector opens with the triggering keys and Num Lock held', (tester) async { final probe = NativeMenuProbe(tester); final controller = BusyMarkHeaderMenuController(); @@ -250,23 +250,16 @@ void main() { await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.f9); - controller.open( - shortcuts: const [ - SingleActivator(LogicalKeyboardKey.f9, control: true, shift: true), - ], - ); - await tester.pump(); - expect(probe.isOpen, isFalse); + controller.open(); + await tester.pumpAndSettle(); + expect(probe.isOpen, isTrue); + expect(probe.packets.last['focusFirst'], isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.f9); - await tester.pump(); - expect(probe.isOpen, isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); - await tester.pump(); - expect(probe.isOpen, isFalse); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); await tester.pumpAndSettle(); expect(probe.isOpen, isTrue); - expect(probe.packets.last['focusFirst'], isTrue); + expect(probe.packets, hasLength(1)); expect({ for (final e in probe.entries) e['mnemonic']: e['label'], }, _sidebar); @@ -284,9 +277,7 @@ void main() { BusyMarkCommandIds.sidebarViewSelector, BusyMarkCommandIds.contentViewSelector, ]) { - testWidgets('$id release barrier follows the configured binding', ( - tester, - ) async { + testWidgets('$id opens with its configured binding held', (tester) async { const binding = BusyMarkKeyBinding( LogicalKeyboardKey.f8, alt: true, @@ -324,13 +315,13 @@ void main() { await tester.sendKeyDownEvent(LogicalKeyboardKey.altRight); await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftRight); await tester.sendKeyDownEvent(binding.key); - controller.open(shortcuts: commands.activators(id)); - await tester.pump(); - expect(probe.isOpen, isFalse); + controller.open(); + await tester.pumpAndSettle(); + expect(probe.isOpen, isTrue); await tester.sendKeyUpEvent(binding.key); await tester.sendKeyUpEvent(LogicalKeyboardKey.altRight); await tester.pump(); - expect(probe.isOpen, isFalse, reason: 'Right Shift is still held'); + expect(probe.isOpen, isTrue); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftRight); await tester.pumpAndSettle(); expect(probe.isOpen, isTrue, reason: 'Unrelated keys must not block'); @@ -349,7 +340,6 @@ void main() { } testWidgets('Linux context-menu keys exclude Ctrl+Shift+F10', (tester) async { - final keys = BusyMarkContextMenuKeys(); var opened = 0; const event = KeyDownEvent( physicalKey: PhysicalKeyboardKey.f10, @@ -360,7 +350,8 @@ void main() { MaterialApp( home: Focus( autofocus: true, - onKeyEvent: (_, event) => keys.handle(event, () => opened++) + onKeyEvent: (_, event) => + handleBusyMarkContextMenuKey(event, () => opened++) ? KeyEventResult.handled : KeyEventResult.ignored, child: const SizedBox(), @@ -371,9 +362,10 @@ void main() { await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(isBusyMarkContextMenuKeyEvent(event), isTrue); await tester.sendKeyDownEvent(LogicalKeyboardKey.f10); - expect(opened, 0); + expect(opened, 1, reason: 'Shift+F10 opens on keydown'); + await tester.sendKeyRepeatEvent(LogicalKeyboardKey.f10); + expect(opened, 1, reason: 'Repeats do not reopen a native menu'); await tester.sendKeyUpEvent(LogicalKeyboardKey.f10); - expect(opened, 0, reason: 'GTK must wait for Shift release'); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(opened, 1); await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); diff --git a/test/src/visualization_card_test.dart b/test/src/visualization_card_test.dart index d62accd0..6caea40c 100644 --- a/test/src/visualization_card_test.dart +++ b/test/src/visualization_card_test.dart @@ -1,6 +1,7 @@ +import 'package:busymark/src/core/save_destination.dart'; import 'package:busymark/src/app/busymark_design.dart'; import 'package:busymark/src/app/busymark_dialogs.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; +import 'package:busymark/src/app/busymark_toast.dart'; import 'package:flutter/services.dart'; import 'dart:io'; @@ -17,6 +18,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_test/flutter_test.dart'; +import '../support/widget_async.dart'; + void main() { late Directory cacheDirectory; @@ -38,14 +41,12 @@ void main() { cache: _MemoryVisualizationCache(cacheDirectory), ); addTearDown(coordinator.dispose); - final barrier = _VisualizationModalBarrier(); final previousFocus = FocusNode(); addTearDown(previousFocus.dispose); await tester.pumpWidget( ProviderScope( overrides: [ visualizationCoordinatorProvider.overrideWithValue(coordinator), - linuxHeaderBarServiceProvider.overrideWithValue(barrier), ], child: _App( child: Focus( @@ -64,7 +65,6 @@ void main() { final previewTransform = preview.transformationController!.value.clone(); await tester.tap(find.byTooltip('Full Screen')); await tester.pumpAndSettle(); - expect(barrier.depths, [1]); expect(find.byType(BusyMarkModalShortcutBoundary), findsOneWidget); expect(find.byType(BusyMarkDialogTitleBar), findsOneWidget); final viewer = tester.widget( @@ -85,7 +85,6 @@ void main() { expect(viewer.transformationController!.value.getMaxScaleOnAxis(), 2); await tester.tap(find.bySemanticsLabel('Close').last); await tester.pumpAndSettle(); - expect(barrier.depths, [1, 0]); expect(find.byType(BusyMarkDialogTitleBar), findsNothing); expect(preview.transformationController!.value, previewTransform); expect(previousFocus.hasFocus, isTrue); @@ -94,7 +93,6 @@ void main() { await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); - expect(barrier.depths, [1, 0, 1, 0]); expect(find.byType(InteractiveViewer), findsOneWidget); expect(previousFocus.hasFocus, isTrue); }, @@ -148,6 +146,71 @@ void main() { expect(find.textContaining('```MerMAID'), findsOneWidget); }); + testWidgets( + 'Save image refuses an unapproved final SVG and publishes a new one', + (tester) async { + final coordinator = VisualizationCoordinator( + renderers: const [_CardRenderer()], + cache: _MemoryVisualizationCache(cacheDirectory), + ); + addTearDown(coordinator.dispose); + const chooser = MethodChannel('busymark/save_chooser'); + final messenger = tester.binding.defaultBinaryMessenger; + Map? selection; + messenger.setMockMethodCallHandler(chooser, (call) async { + expect(call.method, 'save'); + expect((call.arguments as Map)['suffix'], '.svg'); + return selection; + }); + addTearDown(() => messenger.setMockMethodCallHandler(chooser, null)); + final protected = File('${cacheDirectory.path}/diagram.svg') + ..writeAsStringSync('existing SVG'); + await tester.pumpWidget( + ProviderScope( + overrides: [ + visualizationCoordinatorProvider.overrideWithValue(coordinator), + ], + child: const _App(child: _CardHarness(onDiagnosticSelected: _ignore)), + ), + ); + await _pumpUntilFound(tester, find.byType(SvgPicture)); + + Future choose(Map? review) async { + selection = review; + await tester.tap(find.byTooltip('Save image')); + await tester.pumpAndSettle(); + } + + final reviewed = SaveDestination.inspect(protected.path).chooserReview; + await choose({...reviewed, 'path': '${cacheDirectory.path}/diagram'}); + await choose({...reviewed, 'entry': null}); + await choose(null); + expect(protected.readAsStringSync(), 'existing SVG'); + expect(find.textContaining('Saved diagram.svg'), findsNothing); + + for (var index = 0; index < 2; index++) { + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + } + + final published = File('${cacheDirectory.path}/new-diagram.SVG'); + await choose(SaveDestination.inspect(published.path).chooserReview); + await pumpUntil( + tester, + published.existsSync, + operation: 'Publish staged SVG', + ); + expect(published.readAsStringSync(), startsWith(' find.text('Saved new-diagram.SVG').evaluate().isNotEmpty, + operation: 'Show successful SVG publication', + ); + await tester.pumpWidget(const SizedBox()); + }, + ); + testWidgets('fits a small Mermaid diagram to the preview width', ( tester, ) async { @@ -272,6 +335,8 @@ class _MemoryVisualizationCache extends VisualizationCache { } } +void _ignore(int _) {} + class _App extends StatelessWidget { const _App({required this.child}); @@ -282,7 +347,9 @@ class _App extends StatelessWidget { return MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, - home: Scaffold(body: SingleChildScrollView(child: child)), + home: BusyMarkToastOverlay( + child: Scaffold(body: SingleChildScrollView(child: child)), + ), ); } } @@ -518,9 +585,3 @@ class _OpenReferenceHost implements WebRenderHost { required VisualizationCancellationToken cancellationToken, }) => throw UnimplementedError(); } - -class _VisualizationModalBarrier extends LinuxHeaderBarService { - final depths = []; - @override - Future setModalBarrierDepth(int value) async => depths.add(value); -} diff --git a/test/src/visualization_packaging_audit_test.dart b/test/src/visualization_packaging_audit_test.dart index 88279817..2661c347 100644 --- a/test/src/visualization_packaging_audit_test.dart +++ b/test/src/visualization_packaging_audit_test.dart @@ -29,10 +29,10 @@ void main() { 'linux/io.busystack.busymark.metainfo.xml', ).readAsStringSync(); - expect(pubspec, contains(RegExp(r'^version: 0\.7\.1$', multiLine: true))); + expect(pubspec, contains(RegExp(r'^version: 0\.7\.2$', multiLine: true))); expect( snapcraft, - contains(RegExp(r'^version: "0\.7\.1"$', multiLine: true)), + contains(RegExp(r'^version: "0\.7\.2"$', multiLine: true)), ); expect(snapcraft, contains(RegExp(r'^grade: stable$', multiLine: true))); expect( @@ -59,7 +59,7 @@ void main() { ), ), ); - expect(metainfo, contains(' root.delete(recursive: true)); + final file = await File( + p.join(root.path, 'note.md'), + ).writeAsString('old'); + final monitor = _ControlledFileMonitor(); + final service = WorkspaceService( + beforeDisplacedValidation: (target, displaced) async { + monitor.emitEvent( + classifyWorkspaceFileMonitorEvent( + FileSystemMoveEvent(target, false, displaced), + openFilePaths: {target}, + workspaceRoot: true, + )!, + ); + await Future.delayed(const Duration(milliseconds: 100)); + }, + ); + final harness = await _createControllerHarness( + service: service, + fileMonitor: monitor, + ); + await harness.settingsController.setAutoSave(false); + final controller = harness.controller; + await controller.openPath(file.path); + final id = controller.state.activeBuffer!.id; + controller.updateActiveText('saved'); + expect(await controller.saveActive(), isTrue); + expect(controller.state.activeBuffer!.id, id); + expect(controller.state.activeBuffer!.filePath, file.path); + expect(controller.state.activeBuffer!.isDirty, isFalse); + expect(await file.readAsString(), 'saved'); + }, + ); + + for (final route in ['manual', 'all', 'auto']) { + test( + '$route save retains editor and both external versions on final publication race', + () async { + final root = await Directory.systemTemp.createTemp( + 'controller-save-race-', + ); + addTearDown(() => root.delete(recursive: true)); + final file = File(p.join(root.path, 'note.md'))..writeAsStringSync('E'); + String? recovery; + final service = WorkspaceService( + beforeNewFilePublish: (target) async { + await File(target).writeAsString('A'); + }, + beforeDisplacedValidation: (target, displaced) async { + recovery = displaced; + await File(target).writeAsString('B'); + }, + ); + final harness = await _createControllerHarness(service: service); + await harness.settingsController.setAutoSave(route == 'auto'); + final controller = harness.controller; + await controller.openPath(file.path); + controller.updateActiveText('S'); + if (route == 'manual') { + expect(await controller.saveActive(), isFalse); + } else if (route == 'all') { + final result = await controller.saveAll(); + expect(result.conflictBufferIds, [controller.state.activeBuffer!.id]); + expect(result.failedBufferIds, isEmpty); + } else { + expect(await controller.autoSaveActiveIfNeeded(), isFalse); + } + expect(await file.readAsString(), 'B'); + expect(await File(recovery!).readAsString(), 'A'); + expect(controller.state.activeBuffer!.text, 'S'); + expect(controller.state.activeBuffer!.isDirty, isTrue); + final error = + controller.state.message!.error as AtomicFileChangedException; + expect(error.recoveryPath, recovery); + await harness.settingsController.setAutoSave(false); + }, + ); + } + for (final operation in ['open', 'Save As']) { test('Recent failure preserves successful $operation', () async { final directory = await Directory.systemTemp.createTemp( @@ -1113,7 +1198,14 @@ void main() { sourceFilePath: bPath, ); await controller.openActiveFile(aPath); + await harness.settingsController.setValidateOnEdit(false); + final beforePreparation = controller.state; final index = (await controller.writersideEditorIndex())!; + expect( + controller.state, + same(beforePreparation), + reason: 'Reference preparation must not publish validation state', + ); final symbol = index .definitions('a.topic#anchor', moduleId: 'docs') .single; @@ -1500,7 +1592,7 @@ code expect(await controller.discardActiveChanges(), isTrue); expect(controller.state.activeText, savedText); expect(controller.state.isDirty, isFalse); - expect(controller.state.workspace?.activeFileSnapshot, isNotNull); + expect(controller.state.activeBuffer?.diskSnapshot, isNotNull); controller.dispose(); settingsController.dispose(); @@ -1541,6 +1633,204 @@ code await parent.delete(recursive: true); }); + for (final dirty in [false, true]) { + for (final outcome in [ + 'valid', + 'valid existing directory', + 'nonempty', + 'read failure', + 'read failure in existing directory', + 'cancelled', + 'superseded', + 'destination replaced', + 'published entry replaced', + ]) { + test( + 'Writerside creation from a ${dirty ? 'dirty' : 'clean'} workspace: $outcome', + () async { + final root = await Directory.systemTemp.createTemp( + 'busymark-create-transaction-', + ); + addTearDown(() => root.delete(recursive: true)); + final source = File(p.join(root.path, 'original.md')) + ..writeAsStringSync('# Original'); + final existing = Directory(p.join(root.path, 'destination')); + if (outcome.contains('existing directory') || outcome == 'nonempty') { + existing.createSync(); + } + final existingIdentity = existing.existsSync() + ? LinuxFileIdentity.read(existing.path) + : null; + if (outcome == 'nonempty') { + File( + p.join(existing.path, 'keep.txt'), + ).writeAsStringSync('Keep this'); + } + final service = _WritersideCreationService( + failRead: outcome.startsWith('read failure'), + pause: + outcome == 'superseded' || + outcome == 'published entry replaced', + ); + final harness = await _createControllerHarness(service: service); + final controller = harness._container.read( + workspaceControllerProvider.notifier, + ); + final settings = harness._container.read( + appSettingsControllerProvider.notifier, + ); + await settings.setAutoSave(false); + await settings.setValidateOnEdit(false); + WorkspaceState state() => + harness._container.read(workspaceControllerProvider); + await controller.openPath(source.path); + controller.updateActiveEditorState( + state().activeBuffer!.editorState.copyWith( + selection: const TextSelection.collapsed(offset: 2), + ), + ); + if (dirty) controller.updateActiveText('# Dirty original'); + await controller.validateActive(); + final before = state(); + expect(before.hasUnsavedChanges, dirty); + var authorized = false; + WorkspaceMessage? error; + final creation = controller.createWritersideProject( + WritersideProjectCreateRequest( + parentDirectoryPath: root.path, + projectName: 'Docs', + directoryName: 'destination', + instanceName: 'User Guide', + topicTitle: 'Getting started', + ), + authorizeReplacement: (isCurrent) async { + expect(isCurrent(), isTrue); + expect(state().workspace?.id, before.workspace?.id); + expect(state().workspace?.openedAt, before.workspace?.openedAt); + expect(state().activeBuffer, same(before.activeBuffer)); + expect( + root.listSync().any( + (entry) => p + .basename(entry.path) + .startsWith('.busymark-writerside-'), + ), + isFalse, + ); + expect(existing.existsSync(), existingIdentity != null); + authorized = true; + if (outcome == 'destination replaced') { + existing.createSync(); + File( + p.join(existing.path, 'keep.txt'), + ).writeAsStringSync('Concurrent work'); + } + return outcome != 'cancelled'; + }, + onError: (message) => error = message, + ); + if (outcome == 'superseded') { + await service.entered.future; + expect(state().activeBuffer, same(before.activeBuffer)); + await controller.createMarkdownFile(); + final replacement = state(); + service.release.complete(); + expect(await creation, isFalse); + expect(state().workspace, same(replacement.workspace)); + expect(state().activeBuffer, same(replacement.activeBuffer)); + expect(state().documentBuffers, contains(before.activeBuffer)); + expect(authorized, isTrue); + expect(error, isNull); + expect(existing.existsSync(), isFalse); + expect(root.listSync().map((entry) => entry.path), [source.path]); + return; + } + if (outcome == 'published entry replaced') { + await service.entered.future; + final replacement = File(p.join(root.path, 'replacement.xml')) + ..writeAsStringSync('Concurrent configuration'); + replacement.renameSync(p.join(existing.path, 'writerside.cfg')); + service.release.complete(); + } + final succeeded = outcome.startsWith('valid'); + expect(await creation, succeeded); + switch (outcome) { + case 'valid': + case 'valid existing directory': + expect(authorized, isTrue); + expect(state().workspace?.kind, WorkspaceKind.writersideModule); + expect(state().documentBuffers, hasLength(1)); + expect(state().activeText, contains('Getting started')); + expect(source.readAsStringSync(), '# Original'); + case 'nonempty': + case 'read failure': + case 'read failure in existing directory': + case 'destination replaced': + case 'published entry replaced': + expect(authorized, outcome != 'nonempty'); + expect( + error?.code, + WorkspaceMessageCode.createWritersideProjectFailed, + ); + if (outcome == 'nonempty') { + expect( + File(p.join(existing.path, 'keep.txt')).readAsStringSync(), + 'Keep this', + ); + } + case 'cancelled': + expect(authorized, isTrue); + expect(error, isNull); + } + if (existingIdentity != null) { + expect(LinuxFileIdentity.read(existing.path), existingIdentity); + } + if (!succeeded) { + if (outcome == 'read failure in existing directory') { + expect(existing.listSync(), isEmpty); + } else if (outcome == 'destination replaced') { + expect( + existing.listSync().map((entry) => p.basename(entry.path)), + ['keep.txt'], + ); + expect( + File(p.join(existing.path, 'keep.txt')).readAsStringSync(), + 'Concurrent work', + ); + } else if (outcome == 'published entry replaced') { + expect( + existing.listSync().map((entry) => p.basename(entry.path)), + ['writerside.cfg'], + ); + expect( + File( + p.join(existing.path, 'writerside.cfg'), + ).readAsStringSync(), + 'Concurrent configuration', + ); + } else if (outcome != 'nonempty') { + expect(existing.existsSync(), isFalse); + } + expect( + root.listSync().any( + (entry) => + p.basename(entry.path).startsWith('.busymark-writerside-'), + ), + isFalse, + ); + expect(state().workspace?.id, before.workspace?.id); + expect(state().workspace?.openedAt, before.workspace?.openedAt); + expect(state().documentBuffers, same(before.documentBuffers)); + expect( + state().activeBuffer!.editorState, + same(before.activeBuffer!.editorState), + ); + expect(state().hasUnsavedChanges, dirty); + } + }, + ); + } + } + test( 'creates a Writerside topic and opens it without changing recents', () async { @@ -2190,13 +2480,13 @@ CommonMark paragraph. await service.validationStarted.future; expect(await controller.saveActive(), isTrue); - final savedSnapshot = controller.state.workspace!.activeFileSnapshot!; + final savedSnapshot = controller.state.activeBuffer!.diskSnapshot!; expect(savedSnapshot.contentHash, '# Dirty A\n'); service.finishValidation(); await validation; - final finalSnapshot = controller.state.workspace!.activeFileSnapshot!; + final finalSnapshot = controller.state.activeBuffer!.diskSnapshot!; expect(finalSnapshot.contentHash, savedSnapshot.contentHash); expect(finalSnapshot.modifiedAt, savedSnapshot.modifiedAt); @@ -2489,7 +2779,7 @@ CommonMark paragraph. await controller.closeOpenFileTab(initialPath); expect(controller.state.workspace?.activeFilePath, isNull); - expect(controller.state.workspace?.activeFileSnapshot, isNull); + expect(controller.state.activeBuffer?.diskSnapshot, isNull); expect(controller.state.workspace?.openFilePaths, isEmpty); expect(controller.state.activeText, isEmpty); expect(controller.state.preview, isNull); @@ -2553,8 +2843,8 @@ CommonMark paragraph. await controller.closeAllOpenFileTabs(); expect(controller.state.workspace?.activeFilePath, isNull); - expect(controller.state.workspace?.activeFileModifiedAt, isNull); - expect(controller.state.workspace?.activeFileSnapshot, isNull); + expect(controller.state.activeBuffer?.diskSnapshot?.modifiedAt, isNull); + expect(controller.state.activeBuffer?.diskSnapshot, isNull); expect(controller.state.workspace?.openFilePaths, isEmpty); expect(controller.state.workspace?.markdown, isNull); expect(controller.state.workspace?.diagnostics, isEmpty); @@ -2654,20 +2944,35 @@ CommonMark paragraph. }, ); - test('failed open clears stale workspace state', () async { - final harness = await _createControllerHarness(); - final settingsController = harness.settingsController; - final controller = harness.controller; + test( + 'failed open preserves the current workspace and dirty document', + () async { + final harness = await _createControllerHarness(); + final settingsController = harness.settingsController; + final controller = harness.controller; - await controller.openPath('test/fixtures/markdown/basic.md'); - await controller.openPath('test/fixtures/markdown/does-not-exist.md'); + await controller.openPath('test/fixtures/markdown/basic.md'); + final workspaceId = controller.state.workspace!.id; + final bufferId = controller.state.activeBufferId; + await controller.openPath('test/fixtures/markdown/does-not-exist.md'); + expect(controller.state.workspace?.id, workspaceId); + expect(controller.state.activeBufferId, bufferId); + expect(controller.state.message?.code, WorkspaceMessageCode.openFailed); - expect(controller.state.workspace, isNull); - expect(controller.state.message?.code, WorkspaceMessageCode.openFailed); + await settingsController.setAutoSave(false); + controller.updateActiveText('# Unsaved work\n'); + await controller.openPath('test/fixtures/markdown/does-not-exist.md'); - controller.dispose(); - settingsController.dispose(); - }); + expect(controller.state.workspace?.id, workspaceId); + expect(controller.state.activeBufferId, bufferId); + expect(controller.state.activeText, '# Unsaved work\n'); + expect(controller.state.hasUnsavedChanges, isTrue); + expect(controller.state.isLoading, isFalse); + + controller.dispose(); + settingsController.dispose(); + }, + ); test( 'math renderer failures become source-linked runtime diagnostics', @@ -3426,7 +3731,7 @@ CommonMark paragraph. final controller = harness.controller; await controller.openPath(file.path); - final loadedSnapshot = controller.state.workspace!.activeFileSnapshot!; + final loadedSnapshot = controller.state.activeBuffer!.diskSnapshot!; await file.writeAsString('# External rewrite\n'); await file.setLastModified(loadedSnapshot.modifiedAt); controller.updateActiveText('# BusyMark\n'); @@ -5145,11 +5450,6 @@ class _AutosaveWorkspaceService extends WorkspaceService { kind: WorkspaceKind.singleMarkdown, openedAt: DateTime(2026), activeFilePath: path, - activeFileSnapshot: WorkspaceFileSnapshot( - modifiedAt: _autosaveInitialModifiedAt, - size: 11, - contentHash: 'initial', - ), files: [ DocumentFile( absolutePath: path, @@ -5327,7 +5627,6 @@ class _DelayedValidationWorkspaceService extends WorkspaceService { kind: WorkspaceKind.markdownFolder, openedAt: DateTime(2026), activeFilePath: aPath, - activeFileSnapshot: _snapshots[aPath], openFilePaths: [aPath], files: [ DocumentFile( @@ -6172,6 +6471,28 @@ void _registerResponsivenessTests() { ); } +class _WritersideCreationService extends WorkspaceService { + _WritersideCreationService({required this.failRead, required this.pause}); + + final bool failRead; + final bool pause; + final entered = Completer(); + final release = Completer(); + @override + Future loadTextWithSnapshot(String path) async { + if (p.basename(path) == 'getting-started.md') { + if (pause) { + entered.complete(); + await release.future; + } + if (failRead) { + throw FileSystemException('Injected initial-topic read failure', path); + } + } + return super.loadTextWithSnapshot(path); + } +} + class _ChangedDuringOpenService extends WorkspaceService { @override Future openPath(String path) async { diff --git a/test/src/workspace_file_monitor_test.dart b/test/src/workspace_file_monitor_test.dart index b338dca8..370ad41f 100644 --- a/test/src/workspace_file_monitor_test.dart +++ b/test/src/workspace_file_monitor_test.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:busymark/src/workspace/workspace_file_monitor.dart'; +import 'package:busymark/src/workspace/workspace_service.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as p; @@ -22,6 +23,32 @@ void main() { ) .timeout(const Duration(seconds: 5)); + test('conditional exchange keeps staging descendants private', () async { + final file = await File(p.join(root.path, 'note.md')).writeAsString('old'); + final events = []; + final subscription = monitor.events.listen(events.add); + addTearDown(subscription.cancel); + final service = WorkspaceService( + beforeNewFilePublish: (target) => + monitor.start(rootPath: root.path, openFilePaths: [target]), + ); + final published = eventFor(file.path); + await service.saveTextIfUnchanged( + file.path, + 'saved', + expectedSnapshot: await service.fileSnapshot(file.path), + ); + await published; + await Future.delayed(const Duration(milliseconds: 100)); + expect(await file.readAsString(), 'saved'); + expect(events, isNotEmpty); + for (final event in events) { + expect(event.path, file.path); + expect(event.destinationPath, isNull); + expect(event.kind, isNot(WorkspaceFileEventKind.moved)); + } + }); + test( 'nested closed files report edits, deletion and atomic replacement', () async { diff --git a/test/src/workspace_monitor_endpoints_test.dart b/test/src/workspace_monitor_endpoints_test.dart index 322dd22b..a20e65c6 100644 --- a/test/src/workspace_monitor_endpoints_test.dart +++ b/test/src/workspace_monitor_endpoints_test.dart @@ -4,6 +4,8 @@ import 'package:flutter_test/flutter_test.dart'; void main() { final names = [ + '/tmp/.busymark-save-10/contents', + '/tmp/.busymark-save-batch-10/contents', '/tmp/.guide.tree.busymark-topic-create-10-100-0', '/tmp/.guide.tree.busymark-safe-delete-10-100-0', '/tmp/.topic.md.busymark-safe-delete-quarantine-10-100-0', diff --git a/test/src/workspace_safety_test.dart b/test/src/workspace_safety_test.dart index b7ea9a7e..14c1ea9f 100644 --- a/test/src/workspace_safety_test.dart +++ b/test/src/workspace_safety_test.dart @@ -3,6 +3,10 @@ import 'package:busymark/src/git/application/shared_git_presentation.dart'; import 'dart:async'; import 'dart:io'; +import 'package:busymark/src/core/save_destination.dart'; +import 'package:busymark/src/workspace/workspace_file_monitor.dart'; +import 'package:busymark/src/workspace/text_format_metadata.dart'; + import 'package:busymark/l10n/generated/app_localizations.dart'; import 'package:busymark/l10n/generated/app_localizations_en.dart'; import 'package:busymark/src/app/app_settings.dart'; @@ -92,9 +96,6 @@ void main() { expect(find.text(l10n.unsavedChanges), findsOneWidget); expect(find.byType(BusyMarkNativeActionButton), findsNWidgets(3)); - expect(find.byIcon(BusyMarkGlyphs.clear), findsOneWidget); - expect(find.byIcon(BusyMarkGlyphs.delete), findsOneWidget); - expect(find.byIcon(BusyMarkGlyphs.save), findsOneWidget); await tester.tap(find.text(l10n.cancel)); await tester.pumpAndSettle(); @@ -493,15 +494,13 @@ void main() { ) async { final service = _IdentityWorkspaceService(); - const fileSelectorChannel = MethodChannel( - 'plugins.flutter.io/file_selector', - ); - final pickerResult = Completer(); + const fileSelectorChannel = MethodChannel('busymark/save_chooser'); + final pickerResult = Completer?>(); final pickerStarted = Completer(); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( fileSelectorChannel, (call) async { - expect(call.method, 'getSavePath'); + expect(call.method, 'save'); pickerStarted.complete(); return pickerResult.future; }, @@ -557,7 +556,7 @@ void main() { await controller.openPath(service.secondPath); controller.updateActiveText('# Edited active document\n'); - pickerResult.complete(service.saveAsPath); + pickerResult.complete({'path': service.saveAsPath}); await tester.pumpAndSettle(); expect(saved, isFalse); @@ -578,16 +577,14 @@ void main() { testWidgets( 'Save As cancel does not overwrite an existing normalized markdown path', (tester) async { - final service = _IdentityWorkspaceService(); + final service = _saveAsFixture(); - const fileSelectorChannel = MethodChannel( - 'plugins.flutter.io/file_selector', - ); + const fileSelectorChannel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( fileSelectorChannel, (call) async { - expect(call.method, 'getSavePath'); - return service.saveAsExtensionlessPath; + expect(call.method, 'save'); + return null; }, ); addTearDown(() { @@ -641,13 +638,7 @@ void main() { await tester.tap(find.text('Save document')); await tester.pumpAndSettle(); - expect(find.text(l10n.overwrite), findsOneWidget); - expect( - find.text(l10n.errorPathAlreadyExists(service.saveAsNormalizedPath)), - findsOneWidget, - ); - await tester.tap(find.text(l10n.cancel)); - await tester.pumpAndSettle(); + expect(find.text(l10n.overwrite), findsNothing); expect(saved, isFalse); expect( @@ -665,16 +656,16 @@ void main() { testWidgets( 'Save As overwrites an existing normalized markdown path only after confirmation', (tester) async { - final service = _IdentityWorkspaceService(); + final service = _saveAsFixture(); - const fileSelectorChannel = MethodChannel( - 'plugins.flutter.io/file_selector', - ); + const fileSelectorChannel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( fileSelectorChannel, (call) async { - expect(call.method, 'getSavePath'); - return service.saveAsExtensionlessPath; + expect(call.method, 'save'); + return SaveDestination.inspect( + service.saveAsNormalizedPath, + ).chooserReview; }, ); addTearDown(() { @@ -728,13 +719,7 @@ void main() { await tester.tap(find.text('Save document')); await tester.pumpAndSettle(); - expect(find.text(l10n.overwrite), findsOneWidget); - expect( - service.documents[service.saveAsNormalizedPath], - '# Existing notes\n', - ); - await tester.tap(find.text(l10n.overwrite)); - await tester.pumpAndSettle(); + expect(find.text(l10n.overwrite), findsNothing); expect(saved, isTrue); expect( @@ -751,85 +736,88 @@ void main() { }, ); - testWidgets('Save As cancels when the document changes during path lookup', ( - tester, - ) async { - final service = _IdentityWorkspaceService() - ..pendingPathExistsResult = Completer(); - const fileSelectorChannel = MethodChannel( - 'plugins.flutter.io/file_selector', - ); - tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( - fileSelectorChannel, - (call) async => service.saveAsExtensionlessPath, - ); - addTearDown(() { + testWidgets( + 'Save As cancels when the document changes while overwrite confirmation is open', + (tester) async { + final service = _saveAsFixture(); + final picker = Completer?>(); + final review = SaveDestination.inspect( + service.saveAsNormalizedPath, + ).chooserReview; + const fileSelectorChannel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( fileSelectorChannel, - null, + (call) => picker.future, ); - }); + addTearDown(() { + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + fileSelectorChannel, + null, + ); + }); - bool? saved; - late WidgetRef widgetRef; - await tester.pumpWidget( - ProviderScope( - overrides: [ - localSettingsStoreProvider.overrideWithValue(_MemorySettingsStore()), - workspaceServiceProvider.overrideWithValue(service), - ], - child: MaterialApp( - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - theme: buildBusyMarkTheme( - brightness: Brightness.light, - accentColor: Colors.green, - ), - home: Scaffold( - body: Consumer( - builder: (context, ref, child) { - widgetRef = ref; - return TextButton( - onPressed: () async { - saved = await saveActiveWithOverwriteConfirmation( - context, - ref, - ); - }, - child: const Text('Save document'), - ); - }, + bool? saved; + late WidgetRef widgetRef; + await tester.pumpWidget( + ProviderScope( + overrides: [ + localSettingsStoreProvider.overrideWithValue( + _MemorySettingsStore(), + ), + workspaceServiceProvider.overrideWithValue(service), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: buildBusyMarkTheme( + brightness: Brightness.light, + accentColor: Colors.green, + ), + home: Scaffold( + body: Consumer( + builder: (context, ref, child) { + widgetRef = ref; + return TextButton( + onPressed: () async { + saved = await saveActiveWithOverwriteConfirmation( + context, + ref, + ); + }, + child: const Text('Save document'), + ); + }, + ), ), ), ), - ), - ); + ); - final controller = widgetRef.read(workspaceControllerProvider.notifier); - await controller.createMarkdownFile(); - controller.updateActiveText('# Untitled draft\n'); + final controller = widgetRef.read(workspaceControllerProvider.notifier); + await controller.createMarkdownFile(); + controller.updateActiveText('# Untitled draft\n'); - await tester.tap(find.text('Save document')); - await tester.runAsync(() => service.pathExistsCheckStarted.future); + await tester.tap(find.text('Save document')); + await tester.pumpAndSettle(); - await controller.openPath(service.secondPath); - controller.updateActiveText('# Edited active document\n'); - service.pendingPathExistsResult!.complete(true); - await tester.pumpAndSettle(); + await controller.openPath(service.secondPath); + controller.updateActiveText('# Edited active document\n'); + picker.complete(review); + await tester.pumpAndSettle(); - expect(saved, isFalse); - expect(find.text(l10n.overwrite), findsNothing); - expect(service.pathExistsChecks, [service.saveAsNormalizedPath]); - expect(service.saves, isEmpty); - expect( - service.documents[service.saveAsNormalizedPath], - '# Existing notes\n', - ); - final state = widgetRef.read(workspaceControllerProvider); - expect(state.workspace?.activeFilePath, service.secondPath); - expect(state.activeText, '# Edited active document\n'); - expect(state.isDirty, isTrue); - }); + expect(saved, isFalse); + expect(find.text(l10n.overwrite), findsNothing); + expect(service.saves, isEmpty); + expect( + service.documents[service.saveAsNormalizedPath], + '# Existing notes\n', + ); + final state = widgetRef.read(workspaceControllerProvider); + expect(state.workspace?.activeFilePath, service.secondPath); + expect(state.activeText, '# Edited active document\n'); + expect(state.isDirty, isTrue); + }, + ); testWidgets('discard confirmation cannot discard a newly active document', ( tester, @@ -1462,6 +1450,11 @@ void main() { .toJson(), ), workspaceServiceProvider.overrideWithValue(service), + workspaceFileMonitorProvider.overrideWith((ref) { + final monitor = _SaveDialogMonitor(); + ref.onDispose(() => unawaited(monitor.dispose())); + return monitor; + }), if (createController != null) workspaceControllerProvider.overrideWith(createController), ], @@ -1706,13 +1699,17 @@ void main() { testWidgets('scoped tab close supports untitled first Save As $saveAs', ( tester, ) async { - final service = _IdentityWorkspaceService(); - const channel = MethodChannel('plugins.flutter.io/file_selector'); + final service = saveAs == 'save' + ? _saveAsFixture() + : _IdentityWorkspaceService(); + const channel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( call, ) async { - expect(call.method, 'getSavePath'); - return saveAs == 'save' ? service.saveAsPath : null; + expect(call.method, 'save'); + return saveAs == 'save' + ? SaveDestination.inspect(service.saveAsPath).chooserReview + : null; }); addTearDown( () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( @@ -1814,8 +1811,22 @@ void main() { expect(refreshed, isTrue); final before = h.ref.read(workspaceControllerProvider); targets.add(before.documentBuffers.last.id); - final git = h.ref.read(gitControllerProvider.notifier); - git.state = git.state.copyWith(openDiffFilePaths: ['comparison.md']); + final review = SharedGitReview( + shared.RepositoryId( + root: before.workspace!.rootPath, + gitDir: '${before.workspace!.rootPath}/.git', + commonDir: '${before.workspace!.rootPath}/.git', + objectFormat: 'sha1', + ), + comparison: shared.GitComparison( + shared.RepoPath.text('comparison.md'), + const shared.ContentVersion.index(), + const shared.ContentVersion.working(), + ), + ); + h.ref + .read(sharedGitReviewProvider.notifier) + .open(before.workspace!.id, review); history.state = history.state.copyWith( selectedRevisionId: 'revision-to-keep', ); @@ -1831,9 +1842,13 @@ void main() { .map((b) => b.id), before.documentBuffers.map((b) => b.id), ); - expect(h.ref.read(gitControllerProvider).openDiffFilePaths, [ - 'comparison.md', - ]); + expect( + h.ref + .read(sharedGitReviewProvider)[before.workspace!.id]! + .entries + .single, + same(review), + ); expect( h.ref.read(localHistoryControllerProvider).selectedRevisionId, 'revision-to-keep', @@ -1855,7 +1870,7 @@ void main() { h.controller.updateActiveText('# Target to save\n'); await h.controller.createMarkdownFile(); h.controller.updateActiveText('# Untitled target\n'); - const channel = MethodChannel('plugins.flutter.io/file_selector'); + const channel = MethodChannel('busymark/save_chooser'); tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( channel, (_) async => null, @@ -2086,6 +2101,27 @@ class _PendingGitGateway implements GitRepositoryGateway { throw StateError('Unexpected metadata request: ${invocation.memberName}'); } +class _SaveDialogMonitor extends WorkspaceFileMonitor { + @override + Future start({ + required String rootPath, + required Iterable openFilePaths, + }) async {} + + @override + void updateOpenFilePaths(Iterable paths) {} +} + +_IdentityWorkspaceService _saveAsFixture() { + final folder = Directory.systemTemp.createTempSync('busymark-save-as-test-'); + addTearDown(() => folder.deleteSync(recursive: true)); + final service = _IdentityWorkspaceService(rootPath: folder.path); + File( + service.saveAsNormalizedPath, + ).writeAsStringSync(service.documents[service.saveAsNormalizedPath]!); + return service; +} + class _IdentityWorkspaceService extends WorkspaceService { _IdentityWorkspaceService({this.rootPath = '/virtual/workspace'}) : firstPath = '$rootPath/a.md', @@ -2109,14 +2145,11 @@ class _IdentityWorkspaceService extends WorkspaceService { final saves = <({String path, String text})>[]; final fileChangeCheckStarted = Completer(); final firstSaveStarted = Completer(); - final pathExistsCheckStarted = Completer(); - final pathExistsChecks = []; var failSave = false; var openPathCalls = 0; var firstChangedOnDisk = false; var pauseFirstSave = false; Completer? pendingFileChangedResult; - Completer? pendingPathExistsResult; final _releaseFirstSave = Completer(); @override @@ -2129,7 +2162,6 @@ class _IdentityWorkspaceService extends WorkspaceService { kind: WorkspaceKind.markdownFolder, openedAt: DateTime(2026), activeFilePath: firstPath, - activeFileSnapshot: _snapshot('# Original A\n'), openFilePaths: [firstPath, secondPath], files: [_file(firstPath), _file(secondPath)], diagnostics: const [], @@ -2141,7 +2173,6 @@ class _IdentityWorkspaceService extends WorkspaceService { kind: WorkspaceKind.singleMarkdown, openedAt: DateTime(2026), activeFilePath: path, - activeFileSnapshot: _snapshot(documents[path] ?? ''), files: [_file(path)], diagnostics: const [], ); @@ -2172,17 +2203,7 @@ class _IdentityWorkspaceService extends WorkspaceService { } @override - Future pathExists(String path) async { - pathExistsChecks.add(path); - if (!pathExistsCheckStarted.isCompleted) { - pathExistsCheckStarted.complete(); - } - final pendingResult = pendingPathExistsResult; - if (pendingResult != null) { - return pendingResult.future; - } - return documents.containsKey(path); - } + Future pathExists(String path) async => documents.containsKey(path); @override Future saveText(String path, String text) async { @@ -2209,6 +2230,21 @@ class _IdentityWorkspaceService extends WorkspaceService { } } + @override + Future saveNewFormattedText( + String path, + String text, { + TextFormatMetadata? format, + LineEndingNormalization? mixedNormalization, + SaveDestination? authorization, + bool Function()? stillCurrent, + Future Function()? onPublished, + }) { + authorization?.requireCurrent(path); + expect(stillCurrent?.call(), isNot(false)); + return saveNewText(path, text, onPublished: onPublished); + } + @override Future saveNewText( String path, @@ -2231,6 +2267,22 @@ class _IdentityWorkspaceService extends WorkspaceService { return result; } + @override + Future saveFormattedTextReplacingPath( + String path, + String text, { + TextFormatMetadata? format, + LineEndingNormalization? mixedNormalization, + WorkspaceFileSnapshot? expectedSnapshot, + SaveDestination? authorization, + bool Function()? stillCurrent, + Future Function()? onPublished, + }) { + authorization?.requireCurrent(path); + expect(stillCurrent?.call(), isNot(false)); + return saveTextReplacingPath(path, text, onPublished: onPublished); + } + @override Future saveTextReplacingPathIfUnchanged( String path, diff --git a/test/src/workspace_service_test.dart b/test/src/workspace_service_test.dart index e359dd1b..2bd803bc 100644 --- a/test/src/workspace_service_test.dart +++ b/test/src/workspace_service_test.dart @@ -7,6 +7,7 @@ import 'package:busymark/src/markdown/markdown_model.dart'; import 'package:busymark/src/markdown/markdown_parser.dart'; import 'package:busymark/src/markdown/preview_model.dart'; import 'package:busymark/src/workspace/document_buffer.dart'; +import 'package:busymark/src/workspace/text_format_metadata.dart'; import 'package:busymark/src/workspace/workspace_model.dart'; import 'package:busymark/src/workspace/workspace_service.dart'; import 'package:busymark/src/writerside/writerside_module_service.dart'; @@ -21,6 +22,133 @@ import 'package:xml/xml.dart'; void main() { const service = WorkspaceService(); + test( + 'normal conditional save preserves final-race content and symlink format/mode', + () async { + final root = await Directory.systemTemp.createTemp('normal-save-race-'); + addTearDown(() => root.delete(recursive: true)); + final target = File(p.join(root.path, 'target.md')); + await target.writeAsBytes([0xef, 0xbb, 0xbf, ...'old\r\n'.codeUnits]); + await Process.run('chmod', ['640', target.path]); + final link = Link(p.join(root.path, 'note.md')); + await link.create('target.md'); + final loaded = await service.loadTextWithSnapshot(link.path); + final saved = await service.saveFormattedText( + link.path, + 'new\n', + format: loaded.format, + expectedSnapshot: loaded.snapshot, + ); + expect(await link.target(), 'target.md'); + expect(await target.readAsBytes(), [ + 0xef, + 0xbb, + 0xbf, + ...'new\r\n'.codeUnits, + ]); + expect((await target.stat()).mode & 0x1ff, 0x1a0); + expect( + (await service.fileSnapshot(target.path)).differsFrom(saved), + isFalse, + ); + final racing = WorkspaceService( + beforeNewFilePublish: (path) => + File(path).writeAsString('external A').then((_) {}), + ); + await expectLater( + racing.saveTextIfUnchanged( + link.path, + 'BusyMark', + expectedSnapshot: saved, + ), + throwsA(isA()), + ); + expect(await target.readAsString(), 'external A'); + expect(await link.target(), 'target.md'); + }, + ); + + test( + 'conditional save reports retained displaced path after a second writer', + () async { + final root = await Directory.systemTemp.createTemp( + 'normal-save-recovery-', + ); + addTearDown(() => root.delete(recursive: true)); + final target = File(p.join(root.path, 'note.md')); + await target.writeAsString('E'); + final expected = await service.fileSnapshot(target.path); + final racing = WorkspaceService( + beforeNewFilePublish: (path) async { + await File(path).writeAsString('A'); + }, + beforeDisplacedValidation: (path, displaced) async { + await File(path).writeAsString('B'); + }, + ); + AtomicFileChangedException? conflict; + try { + await racing.saveTextIfUnchanged( + target.path, + 'S', + expectedSnapshot: expected, + ); + fail('Publication must conflict'); + } on AtomicFileChangedException catch (error) { + conflict = error; + } + expect(await target.readAsString(), 'B'); + expect(conflict.recoveryPath, isNotNull); + expect(await File(conflict.recoveryPath!).readAsString(), 'A'); + }, + ); + + for (final newerWriter in [false, true]) { + test( + 'batch validation I/O error recovers exchanged file, newer=$newerWriter', + () async { + final root = await Directory.systemTemp.createTemp('batch-validation-'); + addTearDown(() => root.delete(recursive: true)); + final a = File(p.join(root.path, 'a.md'))..writeAsStringSync('a'); + final b = File(p.join(root.path, 'b.md'))..writeAsStringSync('b'); + String? retained; + final writer = WorkspaceService( + beforeDisplacedValidation: (target, displaced) async { + if (target != b.path) return; + retained = displaced; + if (newerWriter) await File(target).writeAsString('external'); + throw const FileSystemException( + 'injected post-exchange read/stat failure', + ); + }, + ); + await expectLater( + writer.saveFormattedTextBatch([ + WorkspaceBatchTextWrite( + path: a.path, + text: 'A', + format: TextFormatMetadata.utf8Lf, + expectedSnapshot: await service.fileSnapshot(a.path), + ), + WorkspaceBatchTextWrite( + path: b.path, + text: 'B', + format: TextFormatMetadata.utf8Lf, + expectedSnapshot: await service.fileSnapshot(b.path), + ), + ]), + throwsA( + newerWriter + ? isA() + : isA(), + ), + ); + expect(await a.readAsString(), 'a'); + expect(await b.readAsString(), newerWriter ? 'external' : 'b'); + if (newerWriter) expect(await File(retained!).readAsString(), 'b'); + }, + ); + } test('opens a single Markdown file workspace', () async { final workspace = await service.openPath('test/fixtures/markdown/basic.md'); diff --git a/test/src/writerside_authoring_ui_test.dart b/test/src/writerside_authoring_ui_test.dart index 14fee4c8..ab019401 100644 --- a/test/src/writerside_authoring_ui_test.dart +++ b/test/src/writerside_authoring_ui_test.dart @@ -1,3 +1,7 @@ +import 'package:busymark/src/workspace/presentation/workspace_screen.dart'; +import 'package:busymark/src/workspace/workspace_controller.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../support/document_history_harness.dart'; import 'dart:async'; import 'dart:io'; @@ -14,7 +18,6 @@ import 'package:busymark/src/markdown/busymark_document.dart'; import 'package:busymark/src/markdown/markdown_model.dart'; import 'package:busymark/src/markdown/markdown_parser.dart'; import 'package:busymark/src/platform/native_menu_service.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/writerside/writerside_project.dart'; import 'package:busymark/src/writerside/writerside_effective_properties.dart'; import 'package:busymark/src/writerside/writerside_model.dart'; @@ -27,27 +30,6 @@ import 'package:flutter_test/flutter_test.dart'; import '../support/desktop_focus.dart'; -class _GatedSemanticDialogBarrier extends LinuxHeaderBarService { - _GatedSemanticDialogBarrier() - : super(channel: const MethodChannel('busymark/test/semantic-focus')); - - final release = Completer(); - bool releaseStarted = false; - bool releaseFinished = false; - - @override - bool get isAvailable => true; - - @override - Future setModalBarrierDepth(int depth) async { - if (depth == 0) { - releaseStarted = true; - await release.future; - releaseFinished = true; - } - } -} - BusyDocument _document(bool xml, {String? source}) => xml ? const WritersideEditingAdapter().parseXml( filePath: 'a.topic', @@ -445,17 +427,77 @@ void main() { tearDown(() { binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null); }); - Future mount( + Future mount( WidgetTester tester, BusyMarkWysiwygEditor editor, { bool openProperties = true, + bool workspaceHost = false, + Size size = const Size(1100, 850), + Brightness brightness = Brightness.light, + TextDirection direction = TextDirection.ltr, + double scale = 1, }) async { tester.view.resetPhysicalSize(); - tester.view.physicalSize = const Size(1100, 850); + tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); - await tester.pumpWidget(_app(editor)); + DocumentHistoryHarness? host; + if (openProperties || workspaceHost) { + final root = (await tester.runAsync( + () => Directory.systemTemp.createTemp('workspace-inspector-'), + ))!; + addTearDown(() async { + if (await root.exists()) await root.delete(recursive: true); + }); + final name = editor.document.isXmlTopic ? 'a.topic' : 'a.md'; + await tester.runAsync(() async { + await Directory('${root.path}/topics').create(); + await File( + '${root.path}/topics/$name', + ).writeAsString(editor.document.source!); + await File('${root.path}/writerside.cfg').writeAsString( + '', + ); + await File('${root.path}/main.tree').writeAsString( + '', + ); + }); + final history = (await tester.runAsync( + () => DocumentHistoryHarness.create(path: root.path), + ))!; + host = history; + addTearDown(history.dispose); + await tester.runAsync(() async { + final settings = history.container.read( + appSettingsControllerProvider.notifier, + ); + await settings.setSidebarVisible(false); + await settings.setEditorToolbarDirection(editor.toolbarDirection); + }); + final changes = history.container.listen(workspaceControllerProvider, ( + before, + after, + ) { + if (before?.activeText != after.activeText) { + editor.onSourceChanged(editor.document.filePath, after.activeText); + } + }); + addTearDown(changes.close); + await tester.pumpWidget( + UncontrolledProviderScope( + container: history.container, + child: _app( + const WorkspaceScreen(), + brightness: brightness, + direction: direction, + scale: scale, + ), + ), + ); + } else { + await tester.pumpWidget(_app(editor)); + } await tester.pumpAndSettle(); if (openProperties) { final pointer = await tester.createGesture(kind: PointerDeviceKind.mouse); @@ -473,6 +515,7 @@ void main() { await pointer.removePointer(); await tester.pumpAndSettle(); } + return host; } testWidgets( @@ -595,8 +638,6 @@ void main() { ); final body = _textField('Before Read guide and Other.'); await tester.tap(body); - // Inside the unformatted segment, then inside the bold segment: both - // selections expose the same owning link, without changing styling. for (final caret in [9, 15]) { tester .widget(_textField('Before Read guide and Other.')) @@ -747,14 +788,61 @@ void main() { var saved = original; final changes = []; final key = GlobalKey(); + var fixtureHistory102Document = document; + final fixtureHistory102 = await DocumentHistoryHarness.create( + source: fixtureHistory102Document.source ?? '', + ); + addTearDown(fixtureHistory102.dispose); await mount( tester, BusyMarkWysiwygEditor( + readEditBase: fixtureHistory102.readBase, + readSessionState: () => + fixtureHistory102.buffer.editorState.wysiwygState, + onUndo: () { + if (fixtureHistory102.controller.undoActiveBuffer()) { + ((_, source) { + saved = source; + changes.add(source); + })( + fixtureHistory102Document.filePath, + fixtureHistory102.buffer.text, + ); + } + }, + onRedo: () { + if (fixtureHistory102.controller.redoActiveBuffer()) { + ((_, source) { + saved = source; + changes.add(source); + })( + fixtureHistory102Document.filePath, + fixtureHistory102.buffer.text, + ); + } + }, + onDocumentChanged: (value) { + fixtureHistory102Document = value; + }, + onSessionChanged: (id, value) { + fixtureHistory102.controller.updateDocumentEditorState( + fixtureHistory102.buffer.id, + fixtureHistory102.buffer.editorState.copyWith( + wysiwygState: value, + ), + ); + }, key: key, - document: document, - onSourceChanged: (_, source) { - saved = source; - changes.add(source); + document: fixtureHistory102Document, + onSourceChanged: (path, text) { + fixtureHistory102.controller.updateActiveWysiwygText( + text, + document: fixtureHistory102Document, + ); + ((_, source) { + saved = source; + changes.add(source); + })(path, text); }, ), openProperties: false, @@ -867,7 +955,10 @@ void main() { expect(body.controller!.selection, selection); expect(saved, original); expect(changes, isEmpty); - expect(key.currentState!.debugUndoSnapshotCount, 0); + expect( + fixtureHistory102.buffer.editorState.undoState.undo.length, + 0, + ); if (owner == 'other trigger') return; expect(tester.testTextInput.hasAnyClients, isTrue); final text = owner == 'newer' @@ -897,12 +988,18 @@ void main() { expect(body.controller!.selection, selection); expect(saved, original); expect(changes, isEmpty); - expect(key.currentState!.debugUndoSnapshotCount, 0); + expect( + fixtureHistory102.buffer.editorState.undoState.undo.length, + 0, + ); expect(position.pixels, closeTo(pixels, 0.1)); } else { expect(saved, original.replaceFirst('Text', text)); expect(changes, hasLength(1)); - expect(key.currentState!.debugUndoSnapshotCount, 1); + expect( + fixtureHistory102.buffer.editorState.undoState.undo.length, + 1, + ); expect( tester.getTopLeft(_textField(text)).dy, inInclusiveRange(0, 850), @@ -1051,17 +1148,14 @@ void main() { '${xml ? "XML" : "Markdown"} delayed semantic cancellation $label newerOwner=$newerOwner', (tester) async { enableDesktopFocusLifecycle(tester); - final barrier = _GatedSemanticDialogBarrier(); final newer = FocusNode(debugLabel: 'Search after semantic dialog'); final search = TextEditingController(text: 'Search'); OverlayEntry? entry; addTearDown(() { - if (!barrier.release.isCompleted) barrier.release.complete(); entry?.remove(); entry?.dispose(); newer.dispose(); search.dispose(); - barrier.dispose(); }); final paragraphs = [ 'Text', @@ -1074,15 +1168,61 @@ void main() { var saved = original; final changes = []; final key = GlobalKey(); + var fixtureHistory104Document = _document(xml, source: original); + final fixtureHistory104 = await DocumentHistoryHarness.create( + source: fixtureHistory104Document.source ?? '', + ); + addTearDown(fixtureHistory104.dispose); await mount( tester, BusyMarkWysiwygEditor( + readEditBase: fixtureHistory104.readBase, + readSessionState: () => + fixtureHistory104.buffer.editorState.wysiwygState, + onUndo: () { + if (fixtureHistory104.controller.undoActiveBuffer()) { + ((_, source) { + saved = source; + changes.add(source); + })( + fixtureHistory104Document.filePath, + fixtureHistory104.buffer.text, + ); + } + }, + onRedo: () { + if (fixtureHistory104.controller.redoActiveBuffer()) { + ((_, source) { + saved = source; + changes.add(source); + })( + fixtureHistory104Document.filePath, + fixtureHistory104.buffer.text, + ); + } + }, + onDocumentChanged: (value) { + fixtureHistory104Document = value; + }, + onSessionChanged: (id, value) { + fixtureHistory104.controller.updateDocumentEditorState( + fixtureHistory104.buffer.id, + fixtureHistory104.buffer.editorState.copyWith( + wysiwygState: value, + ), + ); + }, key: key, - document: _document(xml, source: original), - headerBarService: barrier, - onSourceChanged: (_, source) { - saved = source; - changes.add(source); + document: fixtureHistory104Document, + onSourceChanged: (path, text) { + fixtureHistory104.controller.updateActiveWysiwygText( + text, + document: fixtureHistory104Document, + ); + ((_, source) { + saved = source; + changes.add(source); + })(path, text); }, ), openProperties: false, @@ -1109,7 +1249,10 @@ void main() { final readingText = reading.controller!.text; final readingTop = tester.getTopLeft(_textField(readingText)).dy; final generation = key.currentState!.spellingDocumentGeneration; - expect(key.currentState!.debugUndoSnapshotCount, 0); + expect( + fixtureHistory104.buffer.editorState.undoState.undo.length, + 0, + ); labels.add(label); await tester.tap( find.byKey(const ValueKey('wysiwyg-writerside')), @@ -1122,7 +1265,6 @@ void main() { ); await tester.tap(find.text('Cancel'), pointer: 1203); await tester.pumpAndSettle(); - expect(barrier.releaseStarted, isTrue); expect( find.byKey(const ValueKey('wysiwyg-semantic-text')), findsNothing, @@ -1148,7 +1290,6 @@ void main() { expect(FocusManager.instance.primaryFocus, same(newer)); } expect(key.currentState!.spellingDocumentGeneration, generation); - barrier.release.complete(); for (var frame = 0; frame < 30; frame++) { // A gated release can finish after the route animation has // stopped. Drive the render phase so post-frame restoration @@ -1165,7 +1306,6 @@ void main() { closeTo(readingTop, 0.1), ); } - expect(barrier.releaseFinished, isTrue); expect( FocusManager.instance.primaryFocus, same(newerOwner ? newer : body.focusNode), @@ -1173,7 +1313,10 @@ void main() { expect(body.controller!.selection, selection); expect(saved, original); expect(changes, isEmpty); - expect(key.currentState!.debugUndoSnapshotCount, 0); + expect( + fixtureHistory104.buffer.editorState.undoState.undo.length, + 0, + ); expect(tester.testTextInput.hasAnyClients, isTrue); // Use the existing IME connection; enterText would refocus and // conceal a cancellation callback that stole the newer owner. @@ -1193,12 +1336,18 @@ void main() { expect(saved, original); expect(changes, isEmpty); expect(body.controller!.selection, selection); - expect(key.currentState!.debugUndoSnapshotCount, 0); + expect( + fixtureHistory104.buffer.editorState.undoState.undo.length, + 0, + ); expect(position.pixels, closeTo(pixels, 0.1)); } else { expect(saved, original.replaceFirst('Text', 'Te!xt')); expect(changes, hasLength(1)); - expect(key.currentState!.debugUndoSnapshotCount, 1); + expect( + fixtureHistory104.buffer.editorState.undoState.undo.length, + 1, + ); expect( tester.getTopLeft(_textField('Te!xt')).dy, inInclusiveRange(0, 850), @@ -1236,11 +1385,52 @@ void main() { (tester) async { final original = _document(xml).source!; var saved = original; + var fixtureHistory105Document = _document(xml); + final fixtureHistory105 = await DocumentHistoryHarness.create( + source: fixtureHistory105Document.source ?? '', + ); + addTearDown(fixtureHistory105.dispose); await mount( tester, BusyMarkWysiwygEditor( - document: _document(xml), - onSourceChanged: (_, s) => saved = s, + readEditBase: fixtureHistory105.readBase, + readSessionState: () => + fixtureHistory105.buffer.editorState.wysiwygState, + onUndo: () { + if (fixtureHistory105.controller.undoActiveBuffer()) { + ((_, s) => saved = s)( + fixtureHistory105Document.filePath, + fixtureHistory105.buffer.text, + ); + } + }, + onRedo: () { + if (fixtureHistory105.controller.redoActiveBuffer()) { + ((_, s) => saved = s)( + fixtureHistory105Document.filePath, + fixtureHistory105.buffer.text, + ); + } + }, + onDocumentChanged: (value) { + fixtureHistory105Document = value; + }, + onSessionChanged: (id, value) { + fixtureHistory105.controller.updateDocumentEditorState( + fixtureHistory105.buffer.id, + fixtureHistory105.buffer.editorState.copyWith( + wysiwygState: value, + ), + ); + }, + document: fixtureHistory105Document, + onSourceChanged: (path, text) { + fixtureHistory105.controller.updateActiveWysiwygText( + text, + document: fixtureHistory105Document, + ); + ((_, s) => saved = s)(path, text); + }, ), openProperties: false, ); @@ -1320,11 +1510,52 @@ void main() { ? '

Before.

$style example.

After.

' : '# Title\n\nBefore.\n\n$style **example**.\n\nAfter.\n'; var source = original; + var fixtureHistory106Document = _document(xml, source: original); + final fixtureHistory106 = await DocumentHistoryHarness.create( + source: fixtureHistory106Document.source ?? '', + ); + addTearDown(fixtureHistory106.dispose); await mount( tester, BusyMarkWysiwygEditor( - document: _document(xml, source: original), - onSourceChanged: (_, value) => source = value, + readEditBase: fixtureHistory106.readBase, + readSessionState: () => + fixtureHistory106.buffer.editorState.wysiwygState, + onUndo: () { + if (fixtureHistory106.controller.undoActiveBuffer()) { + ((_, value) => source = value)( + fixtureHistory106Document.filePath, + fixtureHistory106.buffer.text, + ); + } + }, + onRedo: () { + if (fixtureHistory106.controller.redoActiveBuffer()) { + ((_, value) => source = value)( + fixtureHistory106Document.filePath, + fixtureHistory106.buffer.text, + ); + } + }, + onDocumentChanged: (value) { + fixtureHistory106Document = value; + }, + onSessionChanged: (id, value) { + fixtureHistory106.controller.updateDocumentEditorState( + fixtureHistory106.buffer.id, + fixtureHistory106.buffer.editorState.copyWith( + wysiwygState: value, + ), + ); + }, + document: fixtureHistory106Document, + onSourceChanged: (path, text) { + fixtureHistory106.controller.updateActiveWysiwygText( + text, + document: fixtureHistory106Document, + ); + ((_, value) => source = value)(path, text); + }, ), openProperties: false, ); @@ -1484,6 +1715,7 @@ void main() { writersideModuleId: project.index.modulesById.keys.single, onSourceChanged: (_, value) => saved = value, ), + openProperties: false, ); await tester.tap(_textField('Text')); labels.addAll(['Include Reusable Content', 'library.topic', 'shared']); @@ -1530,6 +1762,7 @@ void main() { writersideModuleId: 'm', onSourceChanged: (_, s) => source = s, ), + openProperties: false, ); await tester.tap(_textField('Text')); await tester.pumpAndSettle(); @@ -1650,7 +1883,9 @@ void main() { find.byType(BusyMarkWritersideProperties), ) .topicSelected, - isTrue, + xml, + reason: + 'The workspace retains a logical XML topic or its authored Markdown title target.', ); await inspectSelection(tester); expect( @@ -1667,13 +1902,12 @@ void main() { await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); await tester.pumpAndSettle(); expect(saved, original); - await tester.pumpWidget( - _app( - BusyMarkWysiwygEditor( - document: _document(xml, source: authored), - documentId: 'reopened', - onSourceChanged: (_, source) => saved = source, - ), + await mount( + tester, + BusyMarkWysiwygEditor( + document: _document(xml, source: authored), + documentId: 'reopened', + onSourceChanged: (_, source) => saved = source, ), ); await tester.pumpAndSettle(); @@ -1903,7 +2137,11 @@ void main() { ), onSourceChanged: (_, s) => saved = s, ); - await mount(tester, editor(1, source.indexOf('') + 9)); + await mount( + tester, + editor(1, source.indexOf('') + 9), + openProperties: false, + ); expect(saved, isEmpty); final field = _textField('Save Save'); expect( @@ -1978,7 +2216,7 @@ void main() { expect(props.target!.attributes['id'], 'code'); final entry = find.byKey( ValueKey( - 'writerside-property-a.topic-element-${props.target!.id}-language', + 'writerside-property-${props.document.filePath}-element-${props.target!.id}-language', ), ); final language = find.descendant( @@ -2026,12 +2264,12 @@ void main() { ), onSourceChanged: (_, _) => edits++, ); - await mount(tester, editor(first)); + final host = (await mount(tester, editor(first)))!; await tester.tap(_textField('print(1);')); await tester.pumpAndSettle(); await inspectSelection(tester); - final property = find.byKey( - const ValueKey('writerside-property-a.topic-element-xml-1-language'), + final property = find.byWidgetPredicate( + (w) => w is BusyMarkGroupedTextEntry && w.label == 'Language (lang)', ); final entry = find.descendant( of: property, @@ -2040,8 +2278,9 @@ void main() { await tester.enterText(entry, 'python'); await tester.pumpAndSettle(); expect(edits, 0); - await tester.pumpWidget(_app(editor(replaced))); + host.controller.updateActiveText(replaced); await tester.pumpAndSettle(); + final acceptedChanges = edits; expect(tester.widget(entry).controller!.text, 'python'); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pumpAndSettle(); @@ -2049,7 +2288,8 @@ void main() { find.textContaining('document or element changed'), findsOneWidget, ); - expect(edits, 0); + expect(edits, acceptedChanges); + expect(host.buffer.text, replaced); }, ); for (final direction in EditorToolbarDirection.values) { @@ -2060,17 +2300,19 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio); - await tester.pumpWidget( - _app( - BusyMarkWysiwygEditor( - document: _document(true), - toolbarDirection: direction, - onSourceChanged: (_, _) {}, - ), - brightness: Brightness.dark, - direction: TextDirection.rtl, - scale: 1.5, + await mount( + tester, + BusyMarkWysiwygEditor( + document: _document(true), + toolbarDirection: direction, + onSourceChanged: (_, _) {}, ), + openProperties: false, + workspaceHost: true, + size: const Size(620, 800), + brightness: Brightness.dark, + direction: TextDirection.rtl, + scale: 1.5, ); await tester.pumpAndSettle(); expect(find.text('Writerside'), findsNothing); diff --git a/test/src/writerside_project_creator_test.dart b/test/src/writerside_project_creator_test.dart index 4251ab6c..4f4a90d3 100644 --- a/test/src/writerside_project_creator_test.dart +++ b/test/src/writerside_project_creator_test.dart @@ -41,6 +41,11 @@ void main() { ); expect(Directory(result.rootPath).existsSync(), isTrue); + final ordinary = Directory(p.join(parent.path, 'ordinary'))..createSync(); + expect( + Directory(result.rootPath).statSync().mode & 0x1ff, + ordinary.statSync().mode & 0x1ff, + ); expect(result.configPath, p.join(result.rootPath, 'writerside.cfg')); expect(result.treePath, p.join(result.rootPath, 'user-guide.tree')); expect(File(result.configPath).existsSync(), isTrue); diff --git a/test/src/writerside_toc_regressions_test.dart b/test/src/writerside_toc_regressions_test.dart index 4b8b0a1f..a5b495a7 100644 --- a/test/src/writerside_toc_regressions_test.dart +++ b/test/src/writerside_toc_regressions_test.dart @@ -9,7 +9,6 @@ import 'package:busymark/src/app/system_accent.dart'; import 'package:busymark/src/editor/source/source_editor.dart'; import 'package:busymark/src/local_history/local_history_controller.dart'; import 'package:busymark/src/local_history/local_history_store.dart'; -import 'package:busymark/src/platform/linux_header_bar_service.dart'; import 'package:busymark/src/workspace/recovery_persistence.dart'; import 'package:busymark/src/workspace/session_persistence.dart'; import 'package:busymark/src/workspace/workspace_controller.dart'; @@ -65,7 +64,6 @@ void main() { '''); container = ProviderContainer( overrides: [ - linuxHeaderBarServiceProvider.overrideWithValue(_FallbackHeader()), systemAccentColorProvider.overrideWith( (ref) => Stream.value(busyMarkDefaultAccentColor), ), @@ -838,14 +836,3 @@ class _Settings implements LocalSettingsStore { value = json; } } - -class _FallbackHeader extends LinuxHeaderBarService { - _FallbackHeader() - : super(channel: const MethodChannel('test.busymark/toc-header')); - @override - bool get isAvailable => false; - @override - bool get usesNativeHeaderBar => false; - @override - Stream get actions => const Stream.empty(); -} diff --git a/test/src/writerside_topic_file_editor_test.dart b/test/src/writerside_topic_file_editor_test.dart index 3b37e9d9..8ca25247 100644 --- a/test/src/writerside_topic_file_editor_test.dart +++ b/test/src/writerside_topic_file_editor_test.dart @@ -1817,53 +1817,6 @@ Following-line destination: [Guide][next]. }, ); - test( - 'delete reloads newly configured instances before start-page checks', - () async { - final fixture = await _fixture( - trees: { - 'guide.tree': ''' - - - - -''', - }, - topics: {'guide.md': '# Guide\n', 'other.md': '# Other\n'}, - ); - final staleTopic = _topic(fixture.module, 'guide.md'); - File(p.join(fixture.root.path, 'admin.tree')).writeAsStringSync(''' - - - -'''); - File(p.join(fixture.root.path, 'writerside.cfg')).writeAsStringSync(''' - - - - - -'''); - - await expectLater( - editor.delete(module: fixture.module, topic: staleTopic), - throwsA( - isA().having( - (error) => error.code, - 'code', - 'writerside.topic-file.is-start-page', - ), - ), - ); - - expect(File(staleTopic.filePath).existsSync(), isTrue); - expect( - File(p.join(fixture.root.path, 'admin.tree')).readAsStringSync(), - contains('topic="guide.md"'), - ); - }, - ); - test('rename does not claim a new same-basename nested reference', () async { final fixture = await _fixture( trees: { @@ -1960,56 +1913,6 @@ Following-line destination: [Guide][next]. }, ); - test( - 'delete aborts when a concurrent topic changes basename resolution', - () async { - final fixture = await _fixture( - trees: { - 'guide.tree': ''' - - - - -''', - }, - topics: { - 'nested/guide.md': '# Nested guide\n', - 'other.md': '# Other\n', - }, - ); - final topic = _topic(fixture.module, 'nested/guide.md'); - final tree = File(p.join(fixture.root.path, 'guide.tree')); - final originalTree = tree.readAsStringSync(); - final concurrentTopic = File( - p.join(fixture.root.path, 'topics', 'guide.md'), - ); - var inserted = false; - final racingEditor = WritersideTopicFileEditor( - beforeTreePublish: (_) async { - if (!inserted) { - inserted = true; - await concurrentTopic.writeAsString('# Concurrent guide\n'); - } - }, - ); - - await expectLater( - racingEditor.delete(module: fixture.module, topic: topic), - throwsA( - isA().having( - (error) => error.code, - 'code', - 'writerside.topic-file.topic-inventory-changed', - ), - ), - ); - - expect(tree.readAsStringSync(), originalTree); - expect(File(topic.filePath).readAsStringSync(), '# Nested guide\n'); - expect(concurrentTopic.readAsStringSync(), '# Concurrent guide\n'); - }, - ); - test( 'rename retains target when an applied tree cannot be rolled back', () async { @@ -2221,109 +2124,6 @@ Following-line destination: [Guide][next]. expect((await renamed.stat()).mode & 0xfff, 0x180); }, skip: Platform.isWindows ? 'POSIX file modes only.' : false); - test( - 'delete removes every TOC entry and promotes children in place', - () async { - final fixture = await _fixture( - trees: { - 'guide.tree': ''' - - - - - - - - - -''', - 'admin.tree': ''' - - - - - - -''', - }, - topics: { - 'parent.md': '# Parent\n', - 'doomed.md': '# Doomed\n', - 'child-a.md': '# Child A\n', - 'child-b.md': '# Child B\n', - 'after.md': '# After\n', - 'other.md': '# Other\n', - }, - ); - final topic = _topic(fixture.module, 'doomed.md'); - - final result = await editor.delete(module: fixture.module, topic: topic); - - expect(File(topic.filePath).existsSync(), isFalse); - expect(result.removedTocEntries, 2); - expect(result.updatedTreePaths, hasLength(2)); - final guideTree = _tree(fixture.root, 'guide.tree'); - final parent = guideTree - .findAllElements('toc-element') - .singleWhere( - (element) => element.getAttribute('topic') == 'parent.md', - ); - expect(_directTopicReferences(parent), [ - 'child-a.md', - 'child-b.md', - 'after.md', - ]); - expect( - _directTopicReferences(_tree(fixture.root, 'admin.tree').rootElement), - ['child-b.md', 'other.md'], - ); - expect(_allTopicReferences(guideTree), isNot(contains('doomed.md'))); - }, - ); - - test('delete rejects a topic used as any instance start page', () async { - final fixture = await _fixture( - trees: { - 'guide.tree': ''' - - - - -''', - 'admin.tree': ''' - - - -''', - }, - topics: {'doomed.md': '# Doomed\n', 'other.md': '# Other\n'}, - ); - final topic = _topic(fixture.module, 'doomed.md'); - final originalTrees = { - for (final name in ['guide.tree', 'admin.tree']) - name: File(p.join(fixture.root.path, name)).readAsStringSync(), - }; - - await expectLater( - editor.delete(module: fixture.module, topic: topic), - throwsA( - isA().having( - (error) => error.code, - 'code', - 'writerside.topic-file.is-start-page', - ), - ), - ); - - expect(File(topic.filePath).existsSync(), isTrue); - for (final entry in originalTrees.entries) { - expect( - File(p.join(fixture.root.path, entry.key)).readAsStringSync(), - entry.value, - ); - } - }); - test('rename rejects unsafe path components before writing', () async { final fixture = await _fixture( trees: { @@ -2358,54 +2158,6 @@ Following-line destination: [Guide][next]. isFalse, ); }); - - test( - 'delete rejects a topic replaced by a symlink without touching its target', - () async { - final fixture = await _fixture( - trees: { - 'guide.tree': ''' - - - - -''', - }, - topics: {'guide.md': '# Guide\n', 'other.md': '# Other\n'}, - ); - final topic = _topic(fixture.module, 'guide.md'); - final outside = await Directory.systemTemp.createTemp( - 'busymark-topic-file-editor-outside-', - ); - addTearDown(() async { - if (await outside.exists()) { - await outside.delete(recursive: true); - } - }); - final target = File(p.join(outside.path, 'keep.md')) - ..writeAsStringSync('# Keep\n'); - await File(topic.filePath).delete(); - await Link(topic.filePath).create(target.path); - - await expectLater( - editor.delete(module: fixture.module, topic: topic), - throwsA( - isA().having( - (error) => error.code, - 'code', - 'writerside.topic-file.path-unsafe', - ), - ), - ); - - expect(target.readAsStringSync(), '# Keep\n'); - expect( - FileSystemEntity.typeSync(topic.filePath, followLinks: false), - FileSystemEntityType.link, - ); - }, - skip: Platform.isWindows ? 'POSIX symlink behavior only.' : false, - ); } Future<({Directory root, WritersideModule module})> _fixture({ @@ -2506,13 +2258,6 @@ List _allTopicReferences(XmlDocument document) { ]; } -List _directTopicReferences(XmlElement element) { - return [ - for (final child in element.childElements) - if (child.name.local == 'toc-element') child.getAttribute('topic')!, - ]; -} - String _instanceTree(String id, List topics) => ''' diff --git a/test/src/writerside_topic_removal_service_test.dart b/test/src/writerside_topic_removal_service_test.dart index 90db0e84..ef9b8a58 100644 --- a/test/src/writerside_topic_removal_service_test.dart +++ b/test/src/writerside_topic_removal_service_test.dart @@ -24,6 +24,94 @@ void main() { selectedNodePath: const [0], ); + test( + 'post-exchange rejection retains A and newer B and reports partial publication', + () async { + final fixture = await _homeFixture(); + final analysis = await analyzeHome(fixture); + final tree = File(p.join(fixture.root.path, 'guide.tree')); + await Process.run('chmod', ['640', tree.path]); + String? displaced; + final racing = WritersideTopicRemovalService( + beforeFileExchange: (target, _) async { + await File(target).writeAsString('A'); + }, + afterFileExchange: (target, temporary) async { + displaced = temporary; + expect((await File(target).stat()).mode & 0x1ff, 0x1a0); + await File(target).writeAsString('B'); + }, + ); + await expectLater( + racing.apply( + WritersideTopicRemovalRequest( + analysis: analysis, + homePageReplacement: analysis.homePageReplacements.first, + ), + ), + throwsA( + isA() + .having( + (e) => e.code, + 'truthful partial result', + 'writerside.topic-removal.rollback-failed', + ) + .having( + (e) => e.args['paths'], + 'recovery path', + contains('busymark-safe-delete-'), + ), + ), + ); + expect(await tree.readAsString(), 'B'); + expect(await File(displaced!).readAsString(), 'A'); + expect(File(analysis.topicPath).existsSync(), isTrue); + }, + ); + + test( + 'domain rollback preserves the recovery path from a failed earlier-file rollback', + () async { + final fixture = await _homeFixture( + referrer: '# Referrer\n\n[Old](doomed.md)\n', + ); + final analysis = await analyzeHome(fixture); + var before = 0, after = 0; + String? retained, destination; + final racing = WritersideTopicRemovalService( + beforeFileExchange: (_, _) async { + if (++before == 2) { + throw StateError('fail later file before publication'); + } + }, + afterFileExchange: (target, displaced) async { + if (++after != 2) return; + retained = displaced; + destination = target; + await File(displaced).writeAsString('rollback A'); + await File(target).writeAsString('rollback B'); + }, + ); + BusyMarkException? failure; + try { + await racing.apply( + WritersideTopicRemovalRequest( + analysis: analysis, + homePageReplacement: analysis.homePageReplacements.first, + updateUsagesAutomatically: true, + ), + ); + fail('Rollback must report the uncertain publication'); + } on BusyMarkException catch (error) { + failure = error; + } + expect(failure.code, 'writerside.topic-removal.rollback-failed'); + expect(failure.args['paths'], contains(retained)); + expect(await File(retained!).readAsString(), 'rollback A'); + expect(await File(destination!).readAsString(), 'rollback B'); + }, + ); + for (final redirect in [false, true]) { test( 'explicit Home Page replacement promotes children (redirect=$redirect)', diff --git a/test/src/writerside_video_test.dart b/test/src/writerside_video_test.dart index 17f46c43..78ab2e8e 100644 --- a/test/src/writerside_video_test.dart +++ b/test/src/writerside_video_test.dart @@ -59,6 +59,35 @@ After. expect(previewVideo.attributes['preview-src'], 'poster.png'); }); + test( + 'authored remote poster has the same source range in Editor and Preview', + () { + const tag = + '