Compare commits

..
252 Commits
Author SHA1 Message Date
Yuri Karamian 458bff3eac docs(flatpak): record live ArkHost repository and update flow 2026-11-10 22:46:07 +04:00
Yuri Karamian 882006feb7 chore(flatpak): pin stable repository package metadata 2026-11-10 19:41:10 +04:00
Yuri Karamian d5dc7147ab feat(flatpak): prepare signed ArkHost repository publishing 2026-11-10 19:40:22 +04:00
Yuri Karamian 59b171af0a chore(flatpak): pin the source for submission preparation 2026-11-10 17:53:25 +04:00
Yuri Karamian d36ac5e9fa chore(flatpak): prepare Flathub identity and store metadata 2026-11-10 16:56:41 +04:00
Yuri Karamian 4787559af5 fix(flatpak): detect external edits with preserved timestamps 2026-11-10 16:39:52 +04:00
Yuri Karamian ceb3a7d647 feat(linux): add sandboxed Flatpak packaging 2026-11-10 15:14:32 +04:00
Yuri Karamian b9074ec550 fix(android): keep font choices within narrow settings 2026-11-10 12:26:12 +04:00
Yuri Karamian c8277bb01c fix(android): wrap settings options on narrow screens 2026-11-10 12:13:22 +04:00
Yuri Karamian 17f1af4294 fix(android): simplify the note toolbar 2026-11-10 12:00:00 +04:00
Yuri Karamian fbabcf5099 fix(android): keep scaled layouts within the screen 2026-11-10 11:09:01 +04:00
Yuri Karamian 338db1e7b0 chore: prepare v1.3.7 release 2026-11-10 10:25:33 +04:00
Yuri Karamian ac4b85fd0f Merge branch 'main' into 'main'
feat: add 12 more folder/tag icons

See merge request ArkHost/HelixNotes!21
2026-11-06 21:56:19 +00:00
Blake Boone 6716fec63a feat: add 12 more folder/tag icons 2026-11-06 21:56:19 +00:00
Yuri Karamian 237bf799e3 fix: toggle selected paragraphs as one code block 2026-11-06 12:33:49 +04:00
Yuri Karamian 77164427f1 fix: keep table horizontal scrolling when notes open read-only
TipTap registers the table node view together with column resizing only when the editor starts editable. Opening a note in View mode therefore left tables without their .tableWrapper, so wide tables could not scroll horizontally until the app was restarted in Edit mode.

Keep the table view plugin installed for read-only editors; its resize handlers still ignore non-editable views.

Add a regression test that the table node view is registered when the initial editor is read-only. (Discord report)
2026-11-05 01:27:11 +04:00
Yuri Karamian 523d1a5511 fix(webdav): use Last-Modified when a server has no strong ETag
Some WebDAV servers return no usable strong ETag for a file. Sync then refused to overwrite an edited note with "server provides no strong ETag".

Request and parse getlastmodified in PROPFIND, and use If-Unmodified-Since as the conditional header for overwrites and deletes when no strong ETag is available. Keep failing safely when neither validator exists.

Refs #291.
2026-11-04 14:38:53 +04:00
Yuri Karamian 6ecde99f25 fix: keep formatting and single spacing when copying
Copied notes now use inline single spacing, so Word and email clients no longer add their own paragraph spacing. Context-menu Copy and Cut now write rich HTML with a plain-text fallback instead of text only, preserving formatting and blank lines.

Add "Copy as Plain Text" to the context menu and a "Single" line-spacing preset in Settings.

Add regression tests for clipboard HTML spacing.
2026-11-04 02:03:28 +04:00
Yuri Karamian a466df85ed fix: stop compose and dead keys from adding stray quotes around accents
Typing é with a compose key (Compose ' e) or a dead key on Linux gave
'é' instead of é, with the first quote curled by Typography. Every
accented letter was affected.

GTK shows the keys typed so far as a preedit in the editor (· then ')
and replaces it at each step. ProseMirror reports that replacement as
a quote typed over a non-empty range. WrapSelectedText only checked
that the range was non-empty, so it treated the preedit as a selection
and wrapped it in quotes. The composition then removed its own preedit
but left the added quotes behind.

Wrap only when the range is exactly the user's selection and no
composition is active. Selecting text and typing ( or " still wraps
it.

Move the logic into wrapSelection() and cover it with tests.
2026-10-30 17:28:54 +04:00
Yuri Karamian 3858f8e455 fix: let Alt+Left/Right move by word while editing (#290)
History navigation is bound to Alt+Left/Right by default, so the global
keydown handler swallowed those keys before the editor could use them.
Skip the history shortcuts while focus is in the rich editor, the source
editor, or a text input, letting the editable surface handle word
movement. History still works via the mouse buttons and outside editors.
2026-10-28 22:49:17 +04:00
Yuri Karamian 64266969f3 fix: Interface Scale on Android, and a larger default on phones (#288)
Phones used the desktop sizes with no way to enlarge the interface: the
Interface Scale setting was hidden on mobile, and setZoom does nothing on
Android. Android now has the setting (100, 115, 125 and 140%) and starts
at 115% until a scale is chosen. It is applied through the viewport
scale, so taps and menu positions keep matching. Presets that would make
the layout narrower than the mobile menus are left out on small phones.
2026-10-28 11:32:06 +04:00
Yuri Karamian a80425e084 Merge branch 'perf/parallel-listing-upstream' into 'main'
perf(sync): list WebDAV folders several at a time

See merge request ArkHost/HelixNotes!17
2026-10-28 07:06:40 +00:00
Chris Benninger 2d554c6a9d perf(sync): list WebDAV folders several at a time 2026-10-28 07:06:39 +00:00
Yuri Karamian 1676f9fbd1 fix: keep the link around an image and the size of HTML images on save
An image inside a link lost the link the first time the note was saved,
and <img width=...> lost its size. Images now keep the link around them
and are written back as HTML when they have a width or height. Only a
single plain image line is joined to the block above, as the parser
reads it, so a linked or sized image keeps the blank line before it.
2026-10-17 22:53:19 +02:00
Yuri Karamian 3c8b320892 fix: Ctrl+A in source mode selects the text, not every note
The note list's window-wide select-all skipped text fields and the rich
editor but not the source editor. It now skips any editable field.
2026-10-17 17:17:13 +02:00
Yuri Karamian b5189cf0e5 feat: paste Markdown text as formatted content in the rich editor
Plain text written in Markdown is rendered the way a note is read and
inserted: one paragraph joins the line at the cursor, several blocks
split it. Styled text from a code editor or terminal counts as plain.
Text without Markdown, pastes inside code, Ctrl+Shift+V and clipboard
HTML with its own formatting paste as before. Pasting ![](url) no longer
stays as text that saves as ![]([url](url)).
2026-10-17 17:17:13 +02:00
Yuri Karamian 3d21a74d24 fix: count words in tables and agree between rich and source mode
The rich editor ran blocks and table cells together, so a table counted
as a few words. Source mode counted table pipes, delimiter rows and list
markers as words. Blocks are now kept apart, a word needs a letter or
digit, both modes count the same, and switching to source mode recounts.
2026-10-17 16:48:30 +02:00
Yuri Karamian 3b59d34fed fix: keep links working when notes are renamed or moved
Renaming through the title field saved the new title before the file was
renamed, so the rename took the new title for the old one and [[Old]]
links were never updated. It now uses the old file name.

A rename now also updates heading and block links, other capitals,
[[Note.md]] and Markdown links to the file. Moving a note, and renaming
or moving a notebook, updates links that contain a folder, keeping each
link's form, and points the moved notes' own relative links from their
new folder. Code is left as written, and a name another note shares is
not rewritten. Open notes with unsaved edits follow the same rules,
checked on both sides against tests/fixtures/renamed-links.json.
2026-10-17 16:48:30 +02:00
Yuri Karamian c7bcb993bb fix: group images on consecutive lines into a grid, and say when there is nothing to group
Images on consecutive lines share one paragraph joined by line breaks,
which counted as text, so the image toolbar's Grid button did nothing.
Line breaks and whitespace between images no longer count. When no other
image sits right above or below, the button is disabled with a hint.
2026-10-14 09:44:02 +02:00
Yuri Karamian 4e2c87434d fix: show images glued to the empty-line marker by older versions
Before 1.3.7 an empty line before an image could be saved as
<!-- -->![](image.png) on one line, which reads as raw HTML and showed
the image as text. That line is now read as the empty line plus the
image, and the next save writes them apart.
2026-10-14 08:53:58 +02:00
Yuri Karamian 76919d6f1c fix: ask again for a web image that failed to load
A failed web image stayed blank until the note was redrawn. It is now
requested again after 1, 3 and 9 seconds, counted per address and reset
when a note opens.
2026-10-14 08:53:58 +02:00
Yuri Karamian 5e49051ecb fix: follow web image redirects to other hosts, checking every hop
The image proxy refused any redirect to a different host, so an image
behind a CDN or a bare-domain to www redirect never loaded. It now
follows up to five redirects itself and resolves, checks and pins each
hop exactly like a direct image address.
2026-10-14 08:53:58 +02:00
Yuri Karamian a6798d31e2 fix: a new ETag for unchanged remote bytes is not a sync conflict
Some WebDAV servers report a new ETag for a file nobody changed. A note
edited locally then became a conflict copy. The downloaded bytes are now
compared with the hash from the last sync; only different bytes count as
a remote change, so the local edit is uploaded with If-Match.
2026-10-14 08:53:58 +02:00
Yuri Karamian 648cf48dcc feat: offer to create the note from the [[ menu when none has that name
The menu gets a 'Create note' row when no note has the typed title. It
inserts the link, creates the note in the open note's notebook and stays
there. Aliases and #heading parts are kept; typing ]] still only links.
2026-10-14 08:53:58 +02:00
Yuri Karamian 3a9cae27c4 fix: keep one wiki-link mark per text so renaming through a link writes [[New]]
Editing a link's text renamed the note and then added a second wikiLink
mark beside the old one, because the mark only excluded normal links.
The note was saved as [[Old|[[New]]]]. The mark now also excludes itself.
2026-10-14 08:53:58 +02:00
Yuri Karamian 31d19a9faf feat: use a vault icon for Manage Vaults 2026-10-14 00:34:06 +02:00
Yuri Karamian d8e6228f13 feat: color the default notebook glyph and fold extra icons behind a More button 2026-10-14 00:34:06 +02:00
Yuri Karamian 48e39a0cbc feat: add colors to notebook icons and 16 more built-in icons 2026-10-14 00:08:24 +02:00
Yuri Karamian 2ddefc51e4 fix: run hourly backups every hour
The scheduler had no case for the 1 hour frequency offered in Settings
and fell back to 24 hours.
2026-10-13 22:42:29 +02:00
Yuri Karamian 557f625947 feat: show the note beside the notebooks and note list on wide tablets
The mobile layout showed one panel at a time at any size. From 900 px
wide (an iPad in landscape) the notebooks or the note list now stay in a
left column with the note next to them, and back returns from the note
list to the notebooks. A header button hides or shows the column, and
the choice is kept on the device. Narrower windows are unchanged.
2026-10-13 15:46:38 +02:00
Yuri Karamian 043d2bd6c4 fix: measure mermaid labels in the editor so the last line is not cut off
Labels were measured under <body> with a smaller line height than the
editor's, so boxes came out too short for their text. They are now
measured inside the diagram's container. PNG copy and save carry the
editor font and line height into the image.
2026-10-13 14:39:10 +02:00
Yuri Karamian 7100ac637c fix: keep graph hover links inside the local graph and visible when zoomed out
Hovering a neighbour of the open note in the local graph highlighted that
neighbour's links to notes the local graph does not show, so lines and
arrowheads ended in empty space. Only links in the local graph are
highlighted now. Link lines and hover arrowheads also keep their on-screen
size below 100% zoom instead of thinning out under a pixel.
2026-10-13 14:19:27 +02:00
Yuri Karamian c0058f43f4 perf: reuse the wiki title index, parsed note dates and skip grammar guessing
Opening a note rebuilt the wiki-link title lookup every time; it is now
built once per titles list and the list is replaced, not mutated, when a
title changes. Re-sorting the note list on each external file change
re-parsed every note's date; parsed dates are now kept per entry. A code
block naming a language without a grammar (mermaid, a typo) ran every
registered grammar on each keystroke; it is now left plain.
2026-10-13 14:19:27 +02:00
Yuri Karamian 6986546f20 fix: find and update aliased wiki links in table cells
In a table cell the alias separator is written \|. The graph did not
find such links and renaming a note did not update them.
2026-10-11 13:37:14 +02:00
Yuri Karamian 578bf9d253 fix: give a sync conflict copy a title that says so
The copy differed from the original only in its file name, and the
note list, search and quick open go by title, so it could not be found.
Its title and leading heading now carry the same suffix.
2026-10-11 13:37:14 +02:00
Yuri Karamian 94b477d072 fix: show the last sync result in Settings however the sync started
The result line was only filled in for a sync started with the button
in Settings, so a sync from the title bar or an automatic one left it
empty or stale.
2026-10-11 13:37:14 +02:00
Yuri Karamian 5b21e1c3a1 fix: fall back when a volume has no exclusive rename
exFAT on macOS and some FUSE mounts reject the exclusive rename, so
trash, move, rename, attachments, version history and backups failed
there. They now check that the target does not exist and then rename.
2026-10-11 09:43:25 +02:00
Yuri Karamian 630e6ea878 fix: check a vault's windows before locking when forgetting it
Asking a window for its address waits for the main thread, which could
be waiting for the settings lock held here, freezing the app.
2026-10-11 09:43:25 +02:00
Yuri Karamian 1289e865ce fix: keep angle-bracket text and comments when a note is saved
Text such as List<String> or <username> was read as an HTML tag and
deleted on the next save, and HTML comments were dropped. Anything in
angle brackets that is not an HTML element now stays text, and
comments are kept and shown. A numbered list that starts at 0 keeps
its numbering.
2026-10-11 09:43:24 +02:00
Yuri Karamian 0f946ca330 feat: replace in note
The find bar gets a second row with Replace and Replace all, opened
from the bar or with Ctrl+H (Cmd+Option+F on macOS, rebindable). It
works in the rich editor and in source mode, and replace all is one
undo step. Replacing the text of a wiki link changes what it shows,
not its target.
2026-10-11 01:39:03 +02:00
Yuri Karamian 39c56f7e13 fix: keep unsaved edits when a linked note is renamed
Renaming a note rewrites the links to it in other notes. A note that
was open with unsaved edits then failed its next save with a conflict,
and the rewritten notes had no copy of their previous state.

The rename now reports the notes it rewrote. Their previous state goes
into version history, and an open editor takes over the new links and
continues from the rewritten file.
2026-10-11 01:39:03 +02:00
Yuri Karamian 8f07a24d62 perf: only serialize the blocks that changed when saving
Saving turned the whole note into Markdown every time. Document nodes
are immutable and an edit replaces only the blocks it touches, so the
Markdown of each top-level block is now kept and reused. A repeated
save of a 1.1 MB note drops from 70 ms to 4 ms. The first save after
opening a note is unchanged.
2026-10-10 22:53:57 +02:00
Yuri Karamian 9b8602e20f fix: keep literal text literal when a note is saved
Text that reads as Markdown (asterisks around words, a line starting with
"1." or "#", an HTML tag or entity written as text) lost its escaping on
save and came back as formatting. It is now written with a backslash, but
only where the parser would otherwise read it differently, so ordinary
notes are written as before. Text that reads as a link or an image is
still left to become one, and a line the note already had unescaped keeps
its previous behavior.
2026-10-10 22:36:58 +02:00
Yuri Karamian 90795bea73 fix: keep a single title heading when a note's title changes
The heading that reads as the old title follows a title change, in the
editor and on disk, and a title heading is only added to a note that has
no top-level heading.
2026-10-10 22:04:38 +02:00
Yuri Karamian 66fe9c8344 fix: rewrite links after a rename in one step and only for the renamed note
Notes that link to a renamed note are replaced in one step instead of with
a truncating write, and an alias is only updated on links that target the
renamed note.
2026-10-10 21:08:19 +02:00
Yuri Karamian 05249a3c81 fix: leave hidden files and empty folders alone when importing
Hidden files and folders are not moved into attachments or deleted, and
folders that were already empty before the import are kept.
2026-10-10 21:08:19 +02:00
Yuri Karamian af35b4dd75 fix: keep version history inside real folders and prune only snapshots
The history folders must be real folders, and only regular files named
like snapshots are listed, read and pruned.
2026-10-10 21:08:19 +02:00
Yuri Karamian b8821dd6fb fix: read frontmatter fields independently and write new frontmatter safely
Known keys are read one by one, so a field of another shape (a scalar tag
list, yes/no, a numeric title or id) no longer discards the note's id,
title and tags. New frontmatter is written through the YAML serializer, so
any title or tag reads back as written.
2026-10-10 21:08:19 +02:00
Yuri Karamian 5185f9a040 feat: open a tag's notes from the tags under a note's title
Clicking a tag there used to open the same tag editor as the header
button. It now shows that tag's notes; editing stays on the header button,
and a note without tags keeps "+ Tags".
2026-10-10 20:24:48 +02:00
Yuri Karamian 7db8d3f9d3 fix: harden backups against empty archives, foreign vaults and sync rollback
A backup folder that contains the vault now produces complete archives and
an archive without content is not restored. Archives from another vault
are labelled. After a restore the sync baseline is reset.
2026-10-10 20:14:37 +02:00
Yuri Karamian 9f9c7e6c07 fix: make configuration saves and loading resilient
The configuration is replaced in one step, an unreadable one is kept aside
instead of being overwritten, missing or damaged entries no longer discard
the rest, and migrated global sync settings are cleared.
2026-10-10 20:14:37 +02:00
Yuri Karamian 1ad948d4f0 fix: open only document and media files with the default application
Other file types are shown in the file manager instead of being handed to
the system opener.
2026-10-10 17:19:19 +02:00
Yuri Karamian 6341fa8c9b fix: bound frontmatter parsing
Frontmatter is parsed through a YAML engine with limits on size, aliases
and nesting. Frontmatter outside those limits is read as a note without
metadata instead of being handed to the unbounded loader.
2026-10-10 16:21:23 +02:00
Yuri Karamian 21ab7ac49e fix: keep editor state consistent when a note fails to load
A note that cannot be converted for the rich editor no longer leaves the
previous note's content in place. The editor is emptied and locked, saving
is blocked, and source mode shows the real content. Programmatic document
changes no longer leave the next user edit untracked.
2026-10-10 15:28:17 +02:00
Yuri Karamian 3b25992a15 fix: validate remote paths during sync
Paths from a WebDAV listing and from the stored sync state are now checked
before they are used as local file paths, and other spellings of the app's
internal folder are never synced.
2026-10-10 14:30:10 +02:00
Yuri Karamian 33514f28c9 fix: name the operation and file in sync errors
A local file failure during WebDAV sync surfaced as a bare OS error such as
"Operation not permitted (os error 1)", with no file and no hint that it
was local. Local failures now name themselves, the operation and the file,
and requests that get no answer name the operation and remote path.

Refs #249
2026-10-10 13:34:39 +02:00
Yuri Karamian 6e2165661c fix: keep the note title readable in a narrow editor pane
The title was the only part of the header that could shrink, down to a few
characters or nothing. It now keeps a minimum width and the toolbar buttons
move to a second row when there is no room. Unchanged when there is room,
and on mobile.

Refs #246
2026-10-10 13:34:39 +02:00
Yuri Karamian e168f4e004 fix: no indented blank line after a nested list
A nested list left an indented blank line behind when saved, which showed
as an extra empty line after the list in source view.

Refs #277
2026-10-10 13:34:39 +02:00
Yuri Karamian 2014365e4a fix: reset the zoom to the font size chosen in Appearance
Ctrl+0 reset the editor font to a fixed 14 px, because zooming overwrote
the size chosen in Appearance. That choice is now kept separately and
Ctrl+0 returns to it. For existing installs the size in use at first
launch becomes the preference.

Refs #272
2026-10-10 13:34:39 +02:00
Yuri Karamian 8df5efacb8 fix: write spaces at the edges of bold and italic outside the markers
Text formatted with a trailing or leading space was saved as **bold **rest,
which Markdown does not read as bold, so it showed as literal asterisks
after reopening. Edge spaces now go outside the markers and a mark over
only spaces is not written. Formatting around an inline code span is
dropped when a letter or digit touches it, where it would not render.

Refs #240, #276
2026-10-10 13:34:38 +02:00
Yuri Karamian f87b8af238 fix: let Backspace leave and remove a collapsible section
Backspace at the start of a collapsible section's body did nothing, so the
caret could never leave it and a section on the first line of a note could
not be removed from the keyboard. It now steps back into the summary, where
further Backspaces delete the text and unwrap the section. A section with
nothing in it is removed.

Refs #278
2026-10-10 13:34:38 +02:00
Yuri Karamian f0bf0ac5e3 fix: keep bare code fences, link titles, table alignment and formatted inline code
A round-trip audit of 1590 notes showed four things lost the first time a
note was edited. A code block without a language was saved as "text".
Link titles were dropped. Table column alignment was reset. Bold or
italic around inline code was removed.

All four now survive loading, editing and saving. Formatting that covers
only part of a code run is still dropped, since it cannot be written
inside a code span.
2026-10-10 10:19:04 +02:00
Yuri Karamian 0ecacbe1dd fix: parse lines with many unclosed links in linear time, and close a stale image toolbar
A line with thousands of unclosed [label]( starts took about 1.1 s at
56 KB, because each start read to the end of the line for its closing
parenthesis. The legacy link rule now skips starts beyond the last
closing parenthesis and bounds the failed searches per block.

The image toolbar stayed open after an undo and its buttons then changed
a different image. It now closes when its image is no longer at the
remembered position.
2026-10-09 23:28:46 +02:00
Yuri Karamian 455b059fb5 fix: group images a blank line apart into a grid, and keep blank lines on ungroup
Images separated by a blank line load with an empty paragraph between
them, so the Grid button never found two neighboring image blocks and
did nothing in an existing note. Grouping now spans a single empty
paragraph between image blocks and takes the one above the first image,
which would otherwise be saved as a marker line above the grid.

Ungroup gave each image its own paragraph but no blank line, so the
images were saved directly under the preceding paragraph and became part
of it on reload. Top-level grids now ungroup into images a blank line
apart, the reverse of grouping them.

Refs #254
2026-10-09 23:06:53 +02:00
Yuri Karamian f4c6649c0a Merge branch 'feature/side-by-side-grid-masonry-layout-for-images' into 'main' 2026-10-09 22:50:50 +02:00
Yuri Karamian 6c4d1c2e93 Merge branch 'feature/image-hover-titles' into 'main' 2026-10-09 22:45:39 +02:00
Shawn Olson 32b1e091fd fix: keep formatting when pasting from the context menu on WebKitGTK
For content copied from another app, WebKitGTK's navigator.clipboard.read() often
returns nothing, or only text/plain, while Ctrl+V still receives the HTML. The
context menu then pasted plain text and lost bold, links and other formatting.

Whatever the web clipboard leaves out is now filled in from the native clipboard.
The new read_clipboard_contents command (replacing read_clipboard_text) returns
both text and HTML through arboard. The result is replayed through the same paste
handlers as Ctrl+V. That includes the WebKitGTK image fallback for an <img>-only
clipboard. The direct native image read only runs when there is no text or HTML.
2026-10-09 12:34:54 -07:00
Shawn Olson 9aa9ca7d3e test: keep the grid title assertion independent of the image title policy 2026-10-09 09:12:25 -07:00
Shawn Olson 0b94d9ff32 feat: keep image hover titles ("title") and let users edit them
Images now keep their CommonMark title as hover text through load, edit and
save: `![alt](image.png "Hover text")`. Link titles are still dropped, as
before.

Parsing:
- helix_images no longer strips `title` from images (links unchanged).
- An image whose destination and title are valid CommonMark now uses
  markdown-it's own image rule instead of the legacy-link rule. Previously
  any space before a title sent the image down the legacy path, which can't
  handle escaped quotes (`"Say \"hi\""`) or `(title)` titles and mangled
  them into the URL.
- Genuinely legacy forms (spaces in the path, `%20"title"`) still go through
  the legacy rule, which now also keeps the image's title.

Saving: `serializeImageTitle()` writes ` "title"` with CommonMark backslash
escapes (`\"`, `\\`, and `\&` only before entity-like text). The parser
undoes these exactly, so titles survive any number of saves unchanged.

UI: a "T" button on the image toolbar opens a small dialog to set or clear
the hover text.

Tests: tests/image-titles.test.mjs covers exact round trips for tricky titles
(parentheses, &, entities, quotes, backslashes, markup), no growth over
repeated saves, the written form, titles from other apps, legacy
destinations, and links still dropping titles. The upstream assertion that
images render without `title=` is updated to the new contract.
2026-10-09 09:12:11 -07:00
Shawn Olson bd86fb8a4d feat: side-by-side image grids via a portable :::img-grid block
Implements #254. Several images can now sit side by side in a grid or masonry
layout with 2 to 4 columns. The syntax is plain Markdown images inside a
`:::` container, so other renderers show the images stacked:

    :::img-grid cols=3 masonry
    ![](a.jpg)
    ![Beach|size=small](b.jpg)
    :::

Parsing is a markdown-it block rule (`helix_img_grid` in markdownParser.ts),
not a text pre-pass:
- Grid syntax inside code blocks is never converted, because code blocks
  claim those lines first.
- A block converts only if every line is exactly one image (CommonMark image
  syntax, so titles, parentheses and <angle> destinations parse as for any
  image). Unknown options, out-of-range columns, captions, linked images,
  blank lines or a missing closer leave the whole block as ordinary Markdown.
- Each grid image is an ordinary inline image token, so it gets the same
  source resolution, `|size=` handling and title policy as other images.

Saving writes the grid as a normal block through joinMarkdownBlocks, with a
blank line before it. The images serialize with the same code as images in
paragraphs, one per line. The header is written in canonical form.

Editor (src/lib/editor/extensions/imageGrid.ts):
- `imageGrid` node (`image+`) whose renderHTML includes data-img-grid, so
  copied grids paste back as grids
- header controls: cycle columns, grid/masonry toggle, ungroup
- image toolbar: "Grid" groups the image with neighboring image-only blocks;
  arrow buttons move an image left or right inside its grid
- drag-and-drop reorder within and between grids; an emptied grid is removed
- `/image-grid` slash command: multi-file picker that inserts a grid, using
  the origin-guarded asset saving
- mobile: 3-4 column grids collapse to 2. Print: compact 2-column rows,
  controls hidden

Tests (tests/image-grid.test.mjs) cover byte-identical round trips, sizes,
code-fenced examples, no partial conversion, titles and angle-bracket
destinations, repeated saves, trailing closers, nesting, reloading next to
other blocks, renderHTML/parseHTML agreement, grouping and reorder targets.
2026-10-09 09:09:02 -07:00
Shawn Olson ec479ced8e fix: make editor context-menu paste match keyboard paste on Linux
On Linux, the context-menu Paste used its own navigator.clipboard.readText()
flow. On WebKitGTK it lost text copied from other applications. When a web
image copy also carried text, it pasted the URL instead of the bitmap. It
also skipped ProseMirror's paste handling, so things like callout paste and
the pasted-HTML style cleanup never ran.

The context menu now reads the clipboard with navigator.clipboard.read(),
classifies each format, and replays the result as a paste event on the
editor DOM. That runs the same path as Ctrl/Cmd+V: ProseMirror's paste
handler, every handlePaste prop (file, callout, link), transformPastedHTML,
the clipboard parsers and TipTap's paste rules.

Only real attachments (image/*, application/pdf) become files. Other text
formats such as text/uri-list stay text, and browser/OS metadata formats are
ignored, so a copied link no longer becomes a pasted-0.uri-list attachment.
A link offered only as a URI list pastes as its first URI.

When the web clipboard is unavailable (WebKitGTK bug #218519), Paste falls
back to native arboard reads: the image first, then text through the new
read_clipboard_text command. The text is replayed through the same paste
path. Every await re-checks the editor origin, as upstream's paste code does.

The classification lives in src/lib/utils/clipboard-paste.ts and has
regression tests.

Closes #259
2026-10-09 08:53:42 -07:00
Yuri Karamian add45ad9dd fix: clear the old caret when switching notes
Switching quickly between notes in the rich editor could leave a frozen
caret from the previous note next to the real one. The outgoing native
selection is now cleared before the note content is replaced, including
for very large notes. Reproduced on Linux and gone with the change.

Refs #281
2026-10-09 09:28:27 +02:00
Yuri Karamian 076234974a fix: parse long link destinations in linear time, and polish small mobile and history details
Strip a legacy link title with a single scan instead of a regular
expression that is quadratic on a long run of spaces. Widen the done
checkbox's tap area on phones without changing its look, and say "1
unchanged line" in Version History when only one line is folded.
2026-10-08 01:04:18 +02:00
Yuri Karamian 6d9b29343f perf: build very large notes in slices so opening them does not freeze
For notes over 100,000 characters, show the first screen at once and build
the rest of the document in growing slices. Until it is complete the
document cannot be edited: a user action, saving, or switching modes
finishes the build first, and switching notes cancels it. Smaller notes load
as before.
2026-10-08 00:34:07 +02:00
Yuri Karamian 504461bfe7 fix: Overdue tasks exclude completed ones
The Overdue filter now lists only tasks that are late and still open, even
with Hide done off, and a completed task's due date no longer uses the
overdue colour. Today and the calendar are unchanged.
2026-10-08 00:34:07 +02:00
Yuri Karamian 4aa72e4c76 fix: keep list blocks, folded callouts and opened notes intact; speed up saving
Keep a second paragraph, code block or quote inside its list item when a
note is saved, indented under the item. Import attachment links that follow
a stray backtick and images indented by four spaces. Keep a folded callout
that was revealed from the Outline open while it is edited.

Stop treating the editor's first normalization of a freshly loaded note as
an edit, so opening a note no longer saves or reformats it. Join serialized
blocks in linear time, so autosaving a large note no longer freezes the page.
2026-10-07 23:42:03 +02:00
Yuri Karamian ea4a5eae26 fix: keep dollar signs, aligned images, attachment names and code spaces intact
Write a literal $ as typed unless plain dollars could create, remove or
re-pair an inline formula. Save portable image paths when a centered,
aligned or styled block is written. Percent-encode a newly stored
attachment's path before it is inserted, and keep a Windows drive letter
literal in paths outside the vault. Keep whitespace-only code spans in
simple list items, task items and table cells.

Compare Version History in bounded time with a synchronous line diff and
an edit limit. Beyond the limit, shared lines at the start and end stay
unchanged and the rest is shown as removed and added.
2026-10-07 22:25:16 +02:00
Yuri Karamian 8d3338ef89 fix: keep callouts, numbered lists, images and blank lines intact on save
Render the first soft break of a callout's opening paragraph as a newline
so the title and body split correctly again. Only turn [ ] and [x] markers
into task items in bullet lists, not numbered ones. Join serialized blocks
in markdown.ts so an empty paragraph before an image is written as a blank
line, and lists no longer gain an extra blank line, without collapsing blank
lines inside code blocks.

In Version History, compare the current note and snapshots after ignoring
leading and trailing blank lines, so unchanged last lines and a blank line
after the frontmatter no longer show as changes.
2026-10-07 22:12:20 +02:00
Yuri Karamian b2c306d69f fix: scan vaults whose own folder name starts with a dot
A vault kept in a dot-named folder such as ~/.notes was treated as hidden
by seven vault walkers, so All Notes, note titles for links, Graph View,
Tasks and rename link updates found no notes. Exempt the vault root from
the hidden-folder check, as the tag scan and search already do. Hidden
subfolders, .helixnotes and the existing hidden-name rules are unchanged.
2026-10-07 21:03:49 +02:00
Yuri KaramianandClaude Sonnet 5.5 ac2c0aef94 fix: read full frontmatter for note metadata and speed up title and graph scans
Note lists, mobile listings and tag counts read a fixed 1-2 KB prefix, so notes
with longer frontmatter lost their title and tags. Read the complete frontmatter
instead, stopping after the closing delimiter (256 KB cap if unterminated).

Scan note titles in parallel from the frontmatter only, and build graph nodes and
links in one parallel read per note without keeping note bodies in memory. The
Ctrl+K link dialog reuses the loaded wiki-link title cache.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 20:39:21 +02:00
Yuri Karamian f07241dd3a fix: harden note saves, attachment imports, and Markdown handling
- Fix new-note save conflicts and scoped external Markdown access
- Preserve attachment URIs and links across saves, imports, and moves
- Ignore unused and overridden attachment reference definitions
- Improve Markdown parsing, outline handling, and editor performance
- Optimize graph, task filtering, tags, WebDAV, and Obsidian imports
- Fix note-list metadata wrapping and add regression coverage
- Document saving and close-to-tray behavior
2026-10-06 06:09:14 +02:00
Yuri Karamian 14b2a3e8a2 feat: improve history review and note workflows
- Add draft-aware diffs, rendered snapshots and restore confirmation
- Show saved YAML frontmatter in Note Info
- Add Today/Overdue task filters and Ubuntu font families
- Honor timestamp preferences
- Improve vault labels and full-path tooltips

Refs: #234, #244, #257, #262, #265, #268
2026-10-04 00:46:43 +02:00
Yuri Karamian 505ed2b890 docs: update README downloads to v1.3.6 2026-09-30 22:13:48 +02:00
Yuri Karamian b03d7fd12c fix: simplify update download label 2026-09-30 22:09:20 +02:00
Yuri Karamian e1f1ef0b02 Harden v1.3.6 data safety and editor lifecycle
Protect file mutations, backup restoration, and WebDAV synchronization from data loss. Preserve editor drafts across concurrent saves, external changes, and window or vault transitions. Integrate toolbar customization inline and extend regression coverage.
2026-09-29 14:05:46 +02:00
Yuri Karamian 806c63aa65 Add desktop toolbar customization and fix pane toggle icons 2026-09-28 23:28:56 +02:00
Yuri Karamian 4157beddf7 Remove GitLab CI 2026-09-28 21:15:55 +02:00
Yuri Karamian 923cb9571c Improve search and show save errors
- Show search results in the right notebook or All Notes list
- Scroll to the selected note and highlight matching text
- Keep unsaved edits safe and ignore old or cancelled searches
- Show save errors with a Retry button
- Run graph and vault statistics scans in the background
- Fix folder checks when counting vault files
- Keep desktop window-close code out of mobile builds
2026-09-28 21:06:28 +02:00
Yuri Karamian 640b5e3d10 Improve editor performance and harden note saving
Replace the source editor with CodeMirror and reduce typing-time work.
Virtualize note lists, apply targeted refreshes, and batch search indexing.
Improve vault and in-note search, and bound graph layout work.
Make saves revision-safe and flush pending changes before navigation or close.
Preserve originating-vault ownership across async operations and detached windows.
Harden sync, attachment writes, and notebook/tag appearance updates.
Keep Trash previews read-only and skip restoring trashed notes.
Update AI model presets and isolate streamed responses by request.
Fix local image rendering and preserve portable image paths.
Include regression tests for the changed behavior.
2026-09-28 07:50:46 +02:00
Yuri Karamian 3607cf1b3f Merge branch 'main' into 'main'
feat: add custom tag icons and colors

See merge request ArkHost/HelixNotes!9
2026-09-21 09:08:33 +00:00
Blake Boone 245cdacb68 feat: add custom tag icons and colors 2026-09-21 09:08:33 +00:00
Yuri Karamian 2983e3db29 Merge branch 'main' into 'main'
Merge branch 'fix/sort-theme-list-alphabetically' into 'main'

Closes #250

See merge request ArkHost/HelixNotes!7
2026-09-17 12:30:52 +00:00
Shawn cc7c9e2b49 Merge branch HelixNotes:main into main 2026-09-15 16:09:56 +00:00
Shawn 2240231f61 Merge branch 'fix/sort-theme-list-alphabetically' into 'main'
fix: sort theme list alphabetically

See merge request locodarwin/HelixNotes!1
2026-09-15 15:36:44 +00:00
Yuri Karamian b2d0c7175e test: cover built-in theme preset ordering 2026-09-15 15:04:51 +02:00
Shawn Olson 1bc0026731 fix: sort theme list alphabetically 2026-09-14 14:42:06 -07:00
Yuri Karamian 41c0e4c993 fix: preserve Linux window title and configuration 2026-09-10 16:50:54 +02:00
Yuri Karamian 34a0f9efa3 fix: keep mobile navigation visible with collapsed desktop sidebar 2026-09-06 22:46:11 +02:00
Yuri Karamian 9d92489586 Merge branch 'fix/macos-escape-overlay-fullscreen' into 'main'
Prevent Escape from exiting fullscreen when closing overlays

See merge request ArkHost/HelixNotes!4
2026-09-04 13:00:47 +00:00
Vijay c45efb60ab Prevent Escape from exiting fullscreen when closing overlays 2026-09-04 13:00:46 +00:00
Yuri Karamian 0d11fd01dd fix: preserve hidden note title across editor modes 2026-09-04 14:46:30 +02:00
Yuri Karamian 0aaa05ce5c Merge branch 'fix/context-menu-paste-image' into 'main'
fix: paste images from the editor context menu

See merge request ArkHost/HelixNotes!6
2026-09-04 08:54:04 +00:00
Sridhar 77e92ef25c fix: paste images from the editor context menu 2026-09-04 08:54:04 +00:00
Yuri Karamian d7e4be7f3a Merge branch 'fix/webkitgtk-clipboard-image-paste' into 'main'
fix: paste images copied from a browser on WebKitGTK

Closes #245

See merge request ArkHost/HelixNotes!5
2026-09-03 19:07:34 +00:00
Sridhar 2aa572dcaa fix: paste images copied from a browser on WebKitGTK 2026-09-03 19:07:34 +00:00
Yuri Karamian 32f270ce9e Update v1.3.5 download documentation 2026-08-27 00:37:30 +02:00
Yuri Karamian a15b267614 Add scroll font size preference and bump v1.3.5 2026-08-26 17:16:16 +02:00
Yuri Karamian ce48d77cd8 fix: stop wiki links extending after autocomplete 2026-08-23 15:38:57 +02:00
Yuri Karamian 221625aabd fix: override vulnerable cookie dependency 2026-08-17 21:17:53 +02:00
Yuri Karamian 1bd4cd8138 chore: set Rust MSRV to 1.88 2026-08-17 21:15:11 +02:00
Yuri Karamian dd748776b2 test: add local verification command 2026-08-17 21:08:31 +02:00
Yuri Karamian 0391a60c1b fix: block private image proxy requests 2026-08-17 21:06:50 +02:00
Yuri Karamian 33d77cf2fd fix: restrict external file access 2026-08-17 21:02:05 +02:00
Yuri Karamian 81e4e26290 fix: restrict asset protocol to vaults 2026-08-17 20:14:34 +02:00
Yuri Karamian 111d819f92 fix: improve editor accessibility 2026-08-17 19:55:00 +02:00
Yuri Karamian c37818de1a fix: improve settings accessibility 2026-08-17 19:49:05 +02:00
Yuri Karamian 95dab8cf74 fix: improve note list accessibility 2026-08-17 19:46:50 +02:00
Yuri Karamian 62365f52b1 fix: mark resize handles presentational 2026-08-17 19:45:19 +02:00
Yuri Karamian 6eb1ec6eb2 fix: improve sidebar interactions 2026-08-17 19:44:35 +02:00
Yuri Karamian 527c6a7a91 fix: label storage location choices 2026-08-17 19:43:31 +02:00
Yuri Karamian 45e3c389e4 fix: handle info overlay clicks 2026-08-17 19:42:47 +02:00
Yuri Karamian 9ccbf3aff5 fix: make layout references reactive 2026-08-17 19:31:21 +02:00
Yuri Karamian 695664913a fix: make graph state reactive 2026-08-17 19:28:48 +02:00
Yuri Karamian d0fb87cf3a style: format Rust code 2026-08-17 19:27:05 +02:00
Yuri Karamian ac7c79af04 fix: resolve Rust lints 2026-08-17 19:24:32 +02:00
Yuri Karamian 1ebf2a9843 fix: resolve type errors 2026-08-17 19:04:21 +02:00
Yuri Karamian 44dcfbe24a fix: tighten app permissions 2026-08-17 18:57:56 +02:00
Yuri Karamian 00196ecedb fix: protect config files 2026-08-17 18:53:53 +02:00
Yuri Karamian c4d2d1b2d1 fix: validate version paths 2026-08-17 18:52:40 +02:00
Yuri Karamian 3a9a5129c4 fix: restrict backup paths 2026-08-17 18:50:57 +02:00
Yuri Karamian a964ee1930 fix: restrict vault paths 2026-08-17 18:49:32 +02:00
Yuri Karamian 2d57577338 fix: update Rust dependencies 2026-08-17 18:43:11 +02:00
Yuri Karamian 206faed113 fix: update frontend dependencies 2026-08-17 18:37:57 +02:00
Yuri Karamian b3c292d6e2 test(paths): cover cross-platform asset resolution 2026-08-17 18:35:26 +02:00
Yuri Karamian 43f15962f7 Revert "chore(release): prepare v1.3.5"
This reverts commit ade146f9f3.
2026-08-17 17:03:01 +02:00
Yuri Karamian ade146f9f3 chore(release): prepare v1.3.5 2026-08-17 16:50:14 +02:00
Yuri Karamian b253ec4121 fix(paths): preserve cross-platform asset paths 2026-08-17 15:58:20 +02:00
Yuri Karamian c4a91b8f1c fix(sorting): sort numeric names naturally 2026-08-15 16:18:22 +02:00
Yuri Karamian 87c879bcac fix(notebooks): normalize icon paths across platforms 2026-08-15 01:40:14 +02:00
Yuri Karamian 27609fb4f3 Fix Windows internal note links 2026-08-11 02:41:39 +02:00
Yuri Karamian b0555fe648 Add Clear Formatting action to editor context menu 2026-08-08 23:53:27 +02:00
Yuri Karamian 32ef51161d Scroll code block into view after fence input rule 2026-08-07 21:50:34 +02:00
Yuri Karamian 23abd0a19a Add Maintenance tab for vault statistics and cleanup 2026-08-07 17:12:15 +02:00
Yuri Karamian 5f726eb01f Move orphaned attachment cleanup from About to Settings 2026-08-07 17:01:41 +02:00
Yuri Karamian 73f7604187 Speed up note switcher and sync window scaling 2026-08-07 16:51:06 +02:00
Yuri Karamian 7ca226d918 Merge remote-tracking branch 'origin/main' 2026-08-07 01:06:32 +02:00
Yuri Karamian 1cbdf704bd Add opt-in title bar note switcher 2026-08-07 00:56:54 +02:00
Yuri Karamian b5bd5ea151 Document Linux installation options 2026-08-07 00:48:40 +02:00
Yuri Karamian bdf94e2494 Keep Note Info open across note changes 2026-08-06 15:13:43 +02:00
Yuri Karamian 1950c4cc3c Fix system theme pair integration 2026-08-06 15:12:43 +02:00
Yuri Karamian aeddcc6e58 Merge branch 'system-theme-pair' into 'main' 2026-08-06 14:07:34 +02:00
Yuri Karamian bb9d01f57c Merge branch 'custom-theme-derived-vars' into 'main' 2026-08-06 14:03:37 +02:00
Yuri Karamian ac25dfd773 Move note trash action into Note Info 2026-08-06 14:01:47 +02:00
Hadrian Chio e61c66dc26 Add light and dark theme pair for the system appearance setting 2026-08-05 09:24:06 +02:00
Hadrian Chio 3e8aa7f10d Fix custom themes falling back to light divider and tertiary text colors 2026-08-05 08:57:55 +02:00
Yuri Karamian 2dd0985ea9 Add Android image pinch zoom (Closes #115) 2026-08-03 16:56:38 +02:00
Yuri Karamian 18bb6bb702 Fix Linux startup theme flash (#195) 2026-08-03 15:54:17 +02:00
Yuri Karamian fcf48a5b7a Fix Markdown mark round-trips (#219) 2026-08-03 14:04:49 +02:00
Yuri Karamian c7906f4069 Keep source mode last in editor toolbar 2026-08-03 13:31:54 +02:00
Yuri Karamian e6e1ed1ed6 Add note duplication (#24) 2026-08-03 13:23:18 +02:00
Yuri Karamian 1a880a4f96 Add open-note trash action (#177) 2026-08-03 10:45:59 +02:00
Yuri Karamian f4e05ed9c4 Add Markdown source highlighting (#173) 2026-08-03 09:00:43 +02:00
Yuri Karamian 4a1045b41e Preserve collapsible code blocks (#138) 2026-08-03 03:26:06 +02:00
Yuri Karamian c305b5f8dd Add Android camera image capture (#131) 2026-08-03 03:13:04 +02:00
Yuri Karamian b5962af466 Add collapsible section shortcut (#129) 2026-08-03 02:56:42 +02:00
Yuri Karamian 13e83b6689 Restore note scroll positions (#127) 2026-08-03 02:43:40 +02:00
Yuri Karamian 432e4f472a Keep local tests out of repository 2026-08-03 02:31:55 +02:00
Yuri Karamian 8731ca4ec1 Support mixed nested lists (#39) 2026-08-03 02:26:39 +02:00
Yuri Karamian 6b165059cc Refine note info path and history 2026-08-03 02:03:58 +02:00
Yuri Karamian 213797a38e Fix mobile outline navigation (#109) 2026-08-03 01:53:29 +02:00
Yuri Karamian fc3e388b80 Refine custom icon size guidance 2026-08-03 01:53:25 +02:00
Yuri Karamian 1c0359e540 Add custom icon size guidance 2026-08-03 01:33:38 +02:00
Yuri Karamian da859e581b Copy active note path from Info panel 2026-08-03 01:16:30 +02:00
Yuri Karamian 763e673738 Show vault location in Info panel 2026-08-03 01:12:50 +02:00
Yuri Karamian 550d3ab3e9 Add per-notebook icons and sync 2026-08-03 01:05:07 +02:00
Yuri Karamian e62404d4c0 Fix dragging selected notes to notebooks 2026-08-03 00:27:18 +02:00
Yuri Karamian 54e051ba02 Add configurable startup view 2026-08-03 00:12:55 +02:00
Yuri Karamian 344728dbe8 Fix macOS traffic lights after window state changes
Reapply the native traffic-light alignment after resize, focus, scale, and theme events so AppKit window-state transitions cannot leave the controls at their default position.
2026-08-02 23:53:26 +02:00
Yuri Karamian 818e9ad82a Merge branch 'nix-build-fix' into 'main'
fix(nix): Update flake.lock and increment fetcher version

Closes #230

See merge request ArkHost/HelixNotes!1
2026-08-02 21:41:20 +00:00
jervw 4931ee3fab fix(nix): Update flake.lock and increment fetcher version 2026-08-02 21:41:20 +00:00
Yuri Karamian 65e09e8fdd fix(mobile): expose notebook actions 2026-07-25 17:51:33 +02:00
Yuri Karamian 64e521d549 fix(ios): poll vault changes to avoid file descriptor exhaustion 2026-07-25 17:14:42 +02:00
Yuri Karamian b8308d89e8 Update README downloads for v1.3.4 2026-07-24 22:38:47 +02:00
Yuri Karamian 0e5b380f8c Sync detached window typography 2026-07-24 20:55:57 +02:00
Yuri Karamian e76919ab5c Fix mobile navigation and Tasks layout 2026-07-24 20:55:57 +02:00
Yuri Karamian 84ab90fd3f Bump version to 1.3.4 2026-07-24 19:44:21 +02:00
Yuri Karamian 87b191eb63 Fix Android adaptive icon padding 2026-07-24 19:44:21 +02:00
Yuri Karamian 0def9d6d6d Fix iOS vault plugin registration 2026-07-24 16:57:20 +02:00
Yuri Karamian e708d8ee63 Fix macOS traffic light vertical alignment 2026-07-24 16:42:20 +02:00
Yuri Karamian 461001442a Fix macOS traffic light vertical alignment 2026-07-24 16:38:06 +02:00
Yuri Karamian 6b5e923e8e Fix macOS traffic light alignment 2026-07-24 16:31:38 +02:00
Yuri Karamian 289606a746 Fix macOS AppKit build 2026-07-24 16:14:48 +02:00
Yuri Karamian 9c53b3b594 Fix iOS Files vault transitions 2026-07-24 15:54:12 +02:00
Yuri Karamian d497ff8aaf Add iOS Files vault selection 2026-07-24 02:19:00 +02:00
Yuri Karamian 51acd51cb2 Expose iOS vault in Files 2026-07-24 00:44:15 +02:00
Yuri Karamian b4bb3b89d6 Update project links for GitLab migration 2026-07-23 17:58:44 +02:00
Yuri Karamian 9b51aef073 Reveal selected tasks in editor 2026-07-20 13:09:35 +02:00
Yuri Karamian 4aa0b200b9 Fix Windows relative image resolution (#215) 2026-07-20 02:47:11 +02:00
Yuri Karamian 8769b56fd1 Fix strikethrough keyboard shortcut (#205) 2026-07-20 02:42:32 +02:00
Yuri Karamian 06d2cd744f Refine scrollbars and editor spacing (#209) 2026-07-20 02:30:29 +02:00
Yuri Karamian 7428cc7dfb shorten comments 2026-07-20 02:20:14 +02:00
Yuri Karamian 6c89d668fe Fix table sizing and headerless table persistence (#213) 2026-07-20 02:17:38 +02:00
Yuri Karamian 2c76a4747e Fix mobile notebook navigation and sidebar clipping (#220) 2026-07-20 02:08:36 +02:00
Yuri Karamian fd55c00015 Fix note unfiling and relative image paths (#222) 2026-07-20 02:03:15 +02:00
Yuri Karamian 28ef37f354 Fix mobile safe-area layout 2026-07-15 12:00:54 +02:00
Chris Paganon bf5a9f134d fix(editor): refocus open in-note search on Ctrl+F (#216)
Pressing ctrl-F doesn’t refocus the search field if there is already a search term, it only focuses search on 1st open of the search field. This PR fixes it so that every time the user presses CTRL+F, the search field is focused again.

Tested on linux.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/216
2026-07-14 18:36:34 +02:00
Yuri Karamian 2991940ba8 fix: remove transparency from iOS app icons 2026-07-13 20:43:23 +02:00
Yuri Karamian 54352a03d8 Mermaid diagram "Copy failed: The operation is insecure" on Linux 2026-07-10 14:09:56 +02:00
Yuri Karamian c4d1f12b2e fix: use vault-relative paths in wikilinks for cross-device sync 2026-07-10 11:30:06 +02:00
Yuri Karamian aa699007f7 Revert "Exclude gen/ from Cargo package to fix iOS build fingerprint error"
This reverts commit 047a8b3c3d.
2026-07-09 17:08:14 +02:00
Yuri Karamian 047a8b3c3d Exclude gen/ from Cargo package to fix iOS build fingerprint error 2026-07-09 16:56:58 +02:00
Yuri Karamian 6098dd01b4 Add macOS notarization entitlements + iOS mobile guards
- Add entitlements.plist for Developer ID hardened runtime (JIT,
  unsigned memory, library validation, network client)
- Reference entitlements in tauri.conf.json bundle.macOS
- Guard get_install_type() with early mobile return (avoids
  std::process::Command in iOS binary)
- Add cfg(mobile) no-op branch to xdg_open()
2026-07-09 16:46:59 +02:00
Yuri Karamian b16beb9af5 regenerate icons set 2026-07-09 16:24:21 +02:00
mf 95565d7506 fix(editor): scale code block font size with editor zoom (#208)
Code blocks used a hardcoded 13px font-size instead of scaling with --editor-font-size, so they didn't resize with the rest of the editor content when zooming.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/208
2026-07-07 12:04:49 +02:00
lokthare a13d17ed81 Change nix formatter (#206)
the files were formatted with alejandra. the nix community has set a standard for the format and release a new tool.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/206
2026-07-06 15:53:20 +02:00
Yuri Karamian 95515cac9d Properly center macOS traffic lights via objc2 (#169) 2026-07-05 23:59:08 +02:00
Yuri Karamian 21dd2d1681 Improve sidebar notebook/unfiled icons and list indentation 2026-07-05 02:45:55 +02:00
Yuri Karamian 6d5f12c47c Improve sidebar notebook/unfiled icons and list indentation 2026-07-04 20:23:15 +02:00
Andreas Lenhardt d01bd4ea01 update max_token value in ai tests (#204)
#203

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/204
2026-07-04 14:31:07 +02:00
lokthare bd7d66b1e8 Fix nix build (#202)
fix nix build by updating flake.lock and dependencies hashes

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/202
2026-07-04 11:53:56 +02:00
Yuri Karamian 0b9fe69819 Revert PR #200 (custom theme consolidation) - broke search 2026-07-03 16:42:09 +02:00
Dmitry Rubtsov 936c38a21d Fix custom theme not applied on startup (light-theme dividers) (#200)
Launching with a custom dark theme left every divider in light-theme colors until you re-toggled the theme in Settings.

`applyTheme` was copy-pasted across the components and the copies drifted. Three of them (+page.svelte's onMount block, AppLayout.svelte, NoteWindow.svelte) had no custom-* branch, so for a custom theme they stripped the dark class and data-theme attribute, matched nothing, and fell back to the bare light :root values.

`+layout.svelte` applied the custom theme correctly, but `AppLayout` — the always-mounted shell — re-runs its own broken copy from an `$effect` on `$theme`, immediately wiping it out. Dividers gave it away because custom themes override `--border-color` but not `--border-light`, which dividers use.

Fix: consolidate into a single `applyTheme`(which already owns darkThemes/isDarkTheme) with a real `custom-*` branch, and have every call site use it and pass the loaded custom themes so `custom-*` ids resolve.

Reviewed-on: https://codeberg.org/ArkHost/HelixNotes/pulls/200
2026-07-03 13:34:11 +02:00
Yuri Karamian e60e637437 Fix macOS traffic light vertical centering (#169) 2026-06-30 22:16:19 +02:00
Yuri Karamian 479c957698 Robust Obsidian importer: frontmatter normalization, syntax conversion, deprecated property renaming, same-note heading links 2026-06-30 22:10:22 +02:00
Yuri Karamian 13fd70f944 Fix Android note creation delay: throttle file watcher IPC (#191) 2026-06-30 19:48:19 +02:00
Yuri Karamian 015726f896 Add inline restore/delete icons on trashed notes (#188) 2026-06-30 16:41:06 +02:00
Yuri Karamian 5e2c31598c Block note creation in Quick Access/Trash, add icons to trash actions (#188) 2026-06-30 16:13:22 +02:00
Yuri Karamian 24d1ba9f8f Block note creation in Quick Access and Trash views (#188) 2026-06-30 15:59:35 +02:00
Yuri Karamian 5345442de2 Auto-cleanup orphaned attachments on vault open (#190) 2026-06-30 15:54:37 +02:00
Yuri Karamian 6ea2ca0ae2 Keep textarea selection visible when opening AI menu in source mode 2026-06-30 14:40:28 +02:00
Yuri Karamian 6f4f526d07 Fix OpenAI test using max_tokens for GPT-5 models 2026-06-30 14:36:20 +02:00
Yuri Karamian 13bad87500 Fix AI apply-to-note in source mode (#189) 2026-06-30 14:29:44 +02:00
Yuri Karamian acecc9c68d Fix callout body paragraphs merging on reload (#192) 2026-06-30 14:09:25 +02:00
Yuri Karamian 35a8501f2d Fix mobile popup positioning using visualViewport (#193) 2026-06-30 12:51:41 +02:00
Yuri Karamian 09f9df968d Render callouts live on Enter and paste in WYSIWYG (#186) 2026-06-30 12:37:14 +02:00
Yuri Karamian 2c58bf3d9a Fix empty lines round-trip and trim trailing markers (#185) 2026-06-30 11:01:25 +02:00
Yuri Karamian e063f1c73a Clamp formatting-bar dropdown menus into the viewport (#178) 2026-06-28 19:36:16 +02:00
Yuri Karamian cafc0ce1ec Reveal search result in its notebook in the notes list 2026-06-28 19:21:14 +02:00
Yuri Karamian a192723fbd Refresh outline panel when switching notes (#184) 2026-06-28 19:12:29 +02:00
Yuri Karamian b643eeb884 Gate set_mobile_config_dir behind cfg(mobile) to fix desktop dead-code warning (#183) 2026-06-28 19:08:01 +02:00
Yuri Karamian eb042e5760 Tolerate HTTP 403 in MKCOL for non-compliant WebDAV servers (#91) 2026-06-28 19:04:52 +02:00
Yuri Karamian 6251d96193 docs: bump README download links to 1.3.3 2026-06-28 14:49:54 +02:00
238 changed files with 53239 additions and 7883 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
[submodule "packaging/flatpak/shared-modules"]
path = packaging/flatpak/shared-modules
url = https://github.com/flathub/shared-modules.git
+72 -31
View File
@@ -1,7 +1,7 @@
# HelixNotes
[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](https://codeberg.org/ArkHost/HelixNotes/src/branch/main/LICENSE)
[![Latest Release](https://img.shields.io/badge/release-v1.3.2-green)](https://codeberg.org/ArkHost/HelixNotes/releases)
[![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-blue.svg)](https://gitlab.com/ArkHost/HelixNotes/-/blob/main/LICENSE)
[![Latest Release](https://img.shields.io/badge/release-v1.3.6-green)](https://gitlab.com/ArkHost/HelixNotes/-/releases/v1.3.6)
[![Website](https://img.shields.io/badge/web-helixnotes.com-purple)](https://helixnotes.com)
[![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20Windows%20%7C%20macOS%20%7C%20Android-lightgrey)]()
@@ -10,29 +10,45 @@ A local markdown note-taking app built with Tauri, SvelteKit, and Rust.
Your notes are stored as standard Markdown files on your local filesystem.
No cloud, no lock-in.
## Download (v1.3.2)
## Download (v1.3.6)
### Linux
#### Arch / Manjaro (AUR)
#### AppImage
The AppImage works only on Fedora 43+, Arch Linux, and openSUSE Tumbleweed (x86_64).
[Download AppImage](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_amd64.AppImage)
#### Distro-specific packages
##### Fedora 43+ (DNF)
```bash
yay -S helixnotes-appimage-bin
sudo dnf config-manager addrepo \
--from-repofile=https://repo.arkhost.com/helixnotes.repo
sudo dnf install helix-notes
```
#### Debian / Ubuntu / Mint (APT)
##### Debian / Ubuntu / Mint (APT)
```bash
curl -fsSL https://repo.arkhost.com/gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/arkhost.gpg && echo "deb [signed-by=/usr/share/keyrings/arkhost.gpg arch=amd64] https://repo.arkhost.com stable main" | sudo tee /etc/apt/sources.list.d/helixnotes.list && sudo apt update && sudo apt install helix-notes
```
#### Solus (EOPKG)
##### Arch / Manjaro (AUR)
```bash
yay -S helixnotes-appimage-bin
```
##### Solus (EOPKG)
```bash
sudo eopkg it helixnotes
```
#### NixOS
##### NixOS
<details>
<summary>flake.nix</summary>
@@ -42,7 +58,7 @@ sudo eopkg it helixnotes
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
helix-notes = {
url = "git+https://codeberg.org/ArkHost/HelixNotes";
url = "git+https://gitlab.com/ArkHost/HelixNotes";
# inputs.nixpkgs.follows = "nixpkgs";
}
};
@@ -90,59 +106,76 @@ sudo eopkg it helixnotes
```
</details>
#### AppImage (Arch, Fedora 43+, openSUSE Tumbleweed)
#### Manual package downloads
[Download AppImage](https://download.helixnotes.com/releases/v1.3.2/HelixNotes_1.3.2_amd64.AppImage)
#### .deb (manual)
[Download .deb](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_amd64.deb) (Ubuntu 22.04+)
- [.deb](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_amd64.deb) (Ubuntu 22.04+)
- [.rpm](https://download.helixnotes.com/releases/v1.3.6/HelixNotes-1.3.6-1.x86_64.rpm)
### Windows
[Download Installer](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_x64-setup.exe) (Windows 10/11)
[Download Installer](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_x64-setup.exe) (Windows 10/11)
### macOS
[Download .dmg (Apple Silicon)](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_aarch64.dmg) (M-series Macs)
[Download .dmg (Apple Silicon)](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_aarch64.dmg) (M-series Macs)
[Download .dmg (Intel)](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_x64.dmg) (older Macs, or Apple Silicon via Rosetta)
[Download .dmg (Intel)](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_x64.dmg)
> **"HelixNotes is damaged and can't be opened"?** The app isn't damaged. The macOS build isn't notarized by Apple yet, so Gatekeeper blocks it on Apple Silicon. Run this once in Terminal, then open it normally (you'll need to redo it after each update):
>
> ```bash
> xattr -cr /Applications/HelixNotes.app
> ```
The Apple Silicon build is signed and notarized by Apple. The Intel build may still trigger a Gatekeeper warning. If macOS reports that the Intel build is damaged, run this once after installing or updating it:
```bash
xattr -cr /Applications/HelixNotes.app
```
### Android
[Download APK](https://codeberg.org/ArkHost/HelixNotes/releases/download/v1.3.2/HelixNotes_1.3.2_android.apk)
[Download APK](https://download.helixnotes.com/releases/v1.3.6/HelixNotes_1.3.6_android.apk)
---
All releases: [codeberg.org/ArkHost/HelixNotes/releases](https://codeberg.org/ArkHost/HelixNotes/releases)
All releases: [gitlab.com/ArkHost/HelixNotes/-/releases](https://gitlab.com/ArkHost/HelixNotes/-/releases)
## Features
- Markdown editor with toolbar, slash commands, source mode, code highlighting
- **Tasks view**: aggregate `- [ ]` checklists from across all notes, set priority and due dates, work in a list or a calendar (drag a task to reschedule)
- **Tasks view**: aggregate `- [ ]` checklists from across all notes, set priority and due dates, filter Today or Overdue tasks, work in a list or a calendar (drag a task to reschedule)
- `[[Wiki-links]]` and graph view
- Full-text search (Tantivy), CJK-aware for Chinese, Japanese, and Korean
- Outline panel, daily notes with calendar view, tags with autocomplete, drag-and-drop
- Live KaTeX math editor (`/math`, `/imath`) with modal preview, double-click to edit
- Mermaid diagrams (opt-in render, copy as PNG, save as PNG/SVG)
- Encrypted secret blocks (`/secret`) stored as portable `helix-secret` markdown fences
- Insert date/time (`/date`, `/time`, `/now`), color swatches (`/color`), configurable week start
- Insert date/time (`/date`, `/time`, `/now`) with 12-hour or 24-hour timestamps, color swatches (`/color`), configurable week start
- Manual notebook sorting (drag to reorder above, into, or below)
- External `.md` viewer mode with import-to-vault flow
- PDF preview, Obsidian import, "Show in File Manager"
- AI writing tools (Ollama / OpenAI-compatible / Anthropic / OpenAI)
- **Optional WebDAV sync** to your own server (Nextcloud, ownCloud, a NAS): manual or automatic, with keep-both conflict copies
- Version history with diffs, automatic backups
- Version history with main-area diffs and rendered read-only snapshots, automatic backups
- Multi-window, file associations, focus mode, view mode
- Themes (light, dark, and 14 palettes), accent colors, fonts, 80-200% interface scale
- Themes (light, dark, and 14 palettes), accent colors, fonts including bundled Ubuntu and Ubuntu Mono, 80-200% interface scale
- Local plain-text files, no company cloud
### Version history
Changes compares the selected snapshot with the current editor contents, including unsaved edits. Added and removed lines show what restoring that version would change; long unchanged sections can be expanded.
Snapshot displays the stored note read-only, with View source available for its Markdown body. Metadata is separate and is not restored. Snapshot links are inactive, secrets stay locked, and diagrams render only when requested.
Restore replaces the current note's body and asks for confirmation if it would replace an unsaved draft. Inspecting versions does not replace the live editor contents or reset their undo history.
### Note Info
Open **Note info** from the editor toolbar. Expand **Frontmatter** to inspect the original YAML header, including custom keys, without editing it. This shows the last loaded or saved metadata; unsaved changes are not included, and the display updates after saving.
### Saving notes
Notes autosave after three seconds without edits. During continuous typing, a save is queued at least every ten seconds. Ctrl+S (Cmd+S on macOS), switching notes, and closing an editor flush pending changes immediately. A failed save leaves the note marked **Unsaved** and blocks leaving that editor.
Note writes run off the UI thread and replace the file atomically. Unchanged notes are not rewritten. Ordinary saves update only the affected note in the list, wiki-link cache, and Tasks view; search-index updates are batched in the background. External file changes are still picked up by the watcher.
With **Close to tray** enabled and a tray icon available, closing the main window hides it after saving. With the setting off, closing the main window closes the application. The close-to-tray setting takes effect immediately; enabling the tray icon itself requires a restart. Explicit **Quit** exits rather than hiding to the tray.
Full documentation: [helixnotes.com/docs](https://helixnotes.com/docs.html)
## Tech Stack
@@ -155,7 +188,7 @@ Full documentation: [helixnotes.com/docs](https://helixnotes.com/docs.html)
### Prerequisites
- [Rust](https://rustup.rs/) (1.77+)
- [Rust](https://rustup.rs/) (1.88+)
- [Node.js](https://nodejs.org/) (18+)
- [pnpm](https://pnpm.io/)
- System dependencies for Tauri: see [Tauri prerequisites](https://v2.tauri.app/start/prerequisites/)
@@ -167,6 +200,14 @@ pnpm install
pnpm tauri dev
```
### Verification
Run the frontend checks and tests, Rust tests and lints, and production frontend build with one command:
```bash
pnpm verify
```
### Production Build
```bash
@@ -183,4 +224,4 @@ pnpm tauri build
## License
[AGPL-3.0](https://codeberg.org/ArkHost/HelixNotes/src/branch/main/LICENSE)
[AGPL-3.0](https://gitlab.com/ArkHost/HelixNotes/-/blob/main/LICENSE)
Generated
+3 -3
View File
@@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1777268161,
"narHash": "sha256-bxrdOn8SCOv8tN4JbTF/TXq7kjo9ag4M+C8yzzIRYbE=",
"lastModified": 1785571196,
"narHash": "sha256-KoTsyMQqnXQZq8deCEnu4QkyldkwH/bpMMhUcfMdGIw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "1c3fe55ad329cbcb28471bb30f05c9827f724c76",
"rev": "148bab9c1c3c53136ecb44a6ea356a0ed5b39b06",
"type": "github"
},
"original": {
+60 -54
View File
@@ -6,71 +6,77 @@
flake-utils.url = "github:numtide/flake-utils";
};
outputs = {
self,
nixpkgs,
flake-utils,
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = import nixpkgs {inherit system;};
outputs =
{
self,
nixpkgs,
flake-utils,
}:
flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = import nixpkgs { inherit system; };
cargoToml = builtins.fromTOML (builtins.readFile ./src-tauri/Cargo.toml);
pname = cargoToml.package.name;
version = cargoToml.package.version;
in {
packages.default = pkgs.rustPlatform.buildRustPackage {
inherit pname version;
src = ./.;
cargoHash = "sha256-3ihGgdU/1WFa3aOeEi5AcwTFIyGQgxT7Ad0uVuFYB+4=";
pnpmDeps = pkgs.fetchPnpmDeps {
cargoToml = builtins.fromTOML (builtins.readFile ./src-tauri/Cargo.toml);
pname = cargoToml.package.name;
version = cargoToml.package.version;
in
{
packages.default = pkgs.rustPlatform.buildRustPackage {
inherit pname version;
src = ./.;
fetcherVersion = 3;
hash = "sha256-Odmd1gwioCvnnExvCOQwDPCgLyrBfTpeUKHy3BrNtiM=";
};
nativeBuildInputs = with pkgs; [
cargo-tauri.hook
cargoHash = "sha256-P0iXImWYKYPxVj7q2JSuDmd8JvjcKW4DzFUzXeUQZPk=C";
pnpmConfigHook
pnpm
nodejs
pnpmDeps = pkgs.fetchPnpmDeps {
inherit pname version;
src = ./.;
fetcherVersion = 4;
hash = "sha256-odUNKO2D50DG+VpuoTEo5FLMYy5pQSHQBtfHJrhJt78=";
};
pkg-config
jq
moreutils
wrapGAppsHook3
];
nativeBuildInputs = with pkgs; [
cargo-tauri.hook
buildInputs = with pkgs;
lib.optionals stdenv.hostPlatform.isLinux [
webkitgtk_4_1
libayatana-appindicator
pnpmConfigHook
pnpm
nodejs
pkg-config
jq
moreutils
wrapGAppsHook3
];
cargoRoot = "src-tauri";
buildAndTestSubdir = self.packages.${system}.default.cargoRoot;
buildInputs =
with pkgs;
lib.optionals stdenv.hostPlatform.isLinux [
webkitgtk_4_1
libayatana-appindicator
];
# Deactivate the upstream update mechanism
postPatch = ''
jq '
.bundle.createUpdaterArtifacts = false |
.plugins.updater = {"active": false, "pubkey": "", "endpoints": []}
' \
src-tauri/tauri.conf.json | sponge src-tauri/tauri.conf.json
'';
cargoRoot = "src-tauri";
buildAndTestSubdir = self.packages.${system}.default.cargoRoot;
meta = with pkgs.lib; {
description = "HelixNotes desktop application";
homepage = "https://helixnotes.com/";
license = licenses.agpl3Plus;
platforms = platforms.linux ++ platforms.darwin;
mainProgram = "helixnotes";
# Deactivate the upstream update mechanism
postPatch = ''
jq '
.bundle.createUpdaterArtifacts = false |
.plugins.updater = {"active": false, "pubkey": "", "endpoints": []}
' \
src-tauri/tauri.conf.json | sponge src-tauri/tauri.conf.json
'';
meta = with pkgs.lib; {
description = "HelixNotes desktop application";
homepage = "https://helixnotes.com/";
license = licenses.agpl3Plus;
platforms = platforms.linux ++ platforms.darwin;
mainProgram = "helixnotes";
};
};
};
formatter = pkgs.alejandra;
});
formatter = pkgs.nixfmt;
}
);
}
+24 -12
View File
@@ -2,8 +2,9 @@
"name": "helixnotes",
"private": true,
"license": "AGPL-3.0-or-later",
"version": "1.3.3",
"version": "1.3.7",
"type": "module",
"packageManager": "pnpm@11.18.0",
"scripts": {
"dev": "vite dev",
"build": "vite build",
@@ -11,6 +12,10 @@
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test": "node --test tests/*.test.mjs src/lib/utils/*.test.mjs",
"test:rust": "cargo test --manifest-path src-tauri/Cargo.toml",
"lint:rust": "cargo fmt --manifest-path src-tauri/Cargo.toml --check && cargo clippy --manifest-path src-tauri/Cargo.toml --all-targets -- -D warnings",
"verify": "pnpm check && pnpm test && pnpm test:rust && pnpm lint:rust && pnpm build",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"tauri:build": "tauri build"
@@ -18,31 +23,36 @@
"devDependencies": {
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/adapter-static": "^3.0.10",
"@sveltejs/kit": "^2.50.2",
"@sveltejs/kit": "^2.70.2",
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"@tailwindcss/postcss": "^4.1.18",
"@tailwindcss/vite": "^4.1.18",
"@tailwindcss/postcss": "^4.3.3",
"@tailwindcss/vite": "^4.3.3",
"@tauri-apps/cli": "^2.10.0",
"svelte": "^5.49.2",
"@types/node": "26.2.0",
"svelte": "^5.56.9",
"svelte-check": "^4.3.6",
"tailwindcss": "^4.1.18",
"tailwindcss": "^4.3.3",
"typescript": "^5.9.3",
"vite": "^7.3.1"
"vite": "^7.3.6"
},
"dependencies": {
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/language": "^6.12.4",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.13",
"@lezer/highlight": "^1.2.4",
"@tauri-apps/api": "^2.10.1",
"@tauri-apps/plugin-dialog": "^2.6.0",
"@tauri-apps/plugin-fs": "^2.4.5",
"@tauri-apps/plugin-opener": "^2.5.3",
"@tauri-apps/plugin-updater": "^2.10.0",
"@tiptap/core": "^3.19.0",
"@tiptap/extension-code-block-lowlight": "^3.19.0",
"@tiptap/extension-code-block": "^3.19.0",
"@tiptap/extension-color": "^3.19.0",
"@tiptap/extension-details": "^3.19.0",
"@tiptap/extension-highlight": "^3.19.0",
"@tiptap/extension-image": "^3.19.0",
"@tiptap/extension-link": "^3.19.0",
"@tiptap/extension-placeholder": "^3.19.0",
"@tiptap/extension-subscript": "^3.19.0",
"@tiptap/extension-superscript": "^3.19.0",
"@tiptap/extension-table": "^3.19.0",
@@ -59,14 +69,16 @@
"@tiptap/starter-kit": "^3.19.0",
"@types/katex": "^0.16.8",
"@types/markdown-it": "^14.1.2",
"diff": "^9.0.0",
"dompurify": "^3.4.13",
"highlight.js": "^11.11.1",
"katex": "^0.16.28",
"lowlight": "^3.3.0",
"markdown-it": "^14.1.0",
"markdown-it": "^14.3.0",
"markdown-it-mark": "^4.0.0",
"markdown-it-sub": "^2.0.0",
"markdown-it-sup": "^2.0.0",
"markdown-it-task-lists": "^2.1.1",
"mermaid": "^11.14.0"
"mermaid": "^11.16.1"
}
}
+169
View File
@@ -0,0 +1,169 @@
# Flatpak
This builds the Git revision pinned in the manifest inside the GNOME 51 SDK. Rust
and Node dependencies are pinned by the existing lockfiles and downloaded before
the sandboxed, offline build. The shared-modules submodule supplies the Ayatana
tray libraries.
## ArkHost repository
HelixNotes is distributed through ArkHost's signed Flatpak repository at
`https://repo.arkhost.com/flatpak/`, served by Shiny. Install using
[HelixNotes.flatpakref](https://repo.arkhost.com/flatpak/HelixNotes.flatpakref).
The public catalog advertises version 1.3.7.
The application ID is `com.helixnotes.HelixNotes`; the repository collection ID is
`com.arkhost.Flatpak`. Keep both stable so installed applications receive future
updates from the same repository.
Signing fingerprint: `B66171BA8BBE0F590D067B86D02631809E3F7AE2`.
The initial publication was checked using a separate temporary Flatpak store:
the install descriptor, catalog version, signatures and package download passed.
That check did not deploy or launch the application.
`prepare-repository.py` imports a built bundle, prepares AppStream metadata and
static deltas, and signs the application and repository metadata with an OpenPGP
key. It exports only the public key. The signing key stays in the local keyring.
Keep an offline backup of that permanent signing identity.
After building the bundle, prepare a fresh signed output:
```sh
python3 packaging/flatpak/prepare-repository.py \
src-tauri/target/flatpak/HelixNotes_1.3.7_x86_64.flatpak \
--output /path/to/arkhost-flatpak-1.3.7 \
--gpg-key FULL_OPENPGP_FINGERPRINT
```
The script uses the `ostree` command when available, or the system's OSTree
GObject bindings to initialize repositories. This Fedora workstation already
has those bindings. For subsequent releases, add
`--previous-directory /path/to/previous-output` to preserve the publication
history. Always choose a new output directory.
If the signing identity is not ready, `--unsigned` can replace `--gpg-key` for a
local preview. The output will be visibly marked as unsigned and will contain no
install descriptors.
The signed output contains:
```text
repo/ Application repository and update metadata
arkhost.flatpakrepo Adds the ArkHost remote
HelixNotes.flatpakref Adds the remote and installs HelixNotes
```
Unsigned staging omits install links and is not a publishable repository. Keep
the previous signed output when preparing an update so repository history and
delta updates are retained.
Publish the prepared public files under
`/srv/www/repo.arkhost.com/flatpak/` on Shiny using the existing repository
deployment workflow. The publisher prepares local files; it does not connect to
Shiny or change its web configuration. Serve the tree over HTTPS with HTTP
keep-alive enabled. Keep repository summaries and install descriptors fresh in
any HTTP cache; content-addressed objects can be cached longer.
Keep updates scoped to this `flatpak/` subtree. APT/RPM deployments must preserve
it, and Flatpak deployments must preserve the other repository subtrees.
HelixNotes and its updates come from ArkHost. The shared GNOME runtime continues
to come from its existing upstream repository. Users install through
`HelixNotes.flatpakref` and receive updates through Discover, GNOME Software or
`flatpak update`.
## Build
Run from the repository root:
```sh
git submodule update --init packaging/flatpak/shared-modules
flatpak install --user flathub org.flatpak.Builder org.gnome.Platform//51 org.gnome.Sdk//51 org.freedesktop.Sdk.Extension.node24//26.08 org.freedesktop.Sdk.Extension.rust-stable//26.08
flatpak run org.flatpak.Builder --user --force-clean --collection-id=com.arkhost.Flatpak --state-dir=src-tauri/target/flatpak/state --repo=src-tauri/target/flatpak/arkhost-origin src-tauri/target/flatpak/build packaging/flatpak/com.helixnotes.HelixNotes.yml
flatpak build-bundle src-tauri/target/flatpak/arkhost-origin src-tauri/target/flatpak/HelixNotes_1.3.7_x86_64.flatpak com.helixnotes.HelixNotes stable --runtime-repo=https://dl.flathub.org/repo/flathub.flatpakrepo
```
The commands require a user-local Flathub remote. If only a system remote exists,
add the user remote first:
```sh
flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
```
## Install and run
```sh
flatpak install --user https://repo.arkhost.com/flatpak/HelixNotes.flatpakref
flatpak run com.helixnotes.HelixNotes
```
Choose vault folders using the folder picker. Flatpak grants access to the chosen
folders through its document portal; the package does not request access to the
whole home directory. Its settings are separate from native installations.
The document portal does not forward external file-change notifications, so this
build checks visible notes and notebooks about every two seconds in small vaults.
The interval grows with scan cost in larger vaults to limit background CPU use.
It compares file size and precise modification/change timestamps, including changes made
while preserving a note's modification time. Attachments and hidden app data are
excluded from these scans; note contents are read only when a change is detected.
The build sets `HELIXNOTES_INSTALL_TYPE=flatpak`, which suppresses the in-app
updater. Discover, GNOME Software or `flatpak update` handle updates for installs
from the ArkHost repository. The bundle references Flathub for its runtime, which
is installed separately.
## Refresh dependencies
Regenerate both source lists whenever their lockfiles change. The initial lists
were generated with flatpak-builder-tools commit
`9d86d336a39b9af38b86f114b6ce5820fe260f91`:
```sh
uv run --project /path/to/flatpak-builder-tools/node python -m flatpak_node_generator --no-requests-cache --pnpm-store-version v11 --node-sdk-extension org.freedesktop.Sdk.Extension.node24//26.08 -o packaging/flatpak/node-sources.json pnpm pnpm-lock.yaml
uv run /path/to/flatpak-builder-tools/cargo/flatpak-cargo-generator.py -o packaging/flatpak/cargo-sources.json src-tauri/Cargo.lock
```
Keep the pinned pnpm archive/version in the manifest in step with
`package.json`'s `packageManager`. pnpm 11 uses the v11 store; the generator's
default v10 store does not work with it.
The offline install uses `--trust-lockfile` for this reviewed, pinned lockfile.
Flatpak verifies the downloaded sources against the generated checksums. This
keeps pnpm from querying registry metadata and attestations during the offline
build; it does not grant network access to the build sandbox.
The store developer is Yuri Karamian. The Flatpak build overrides Tauri's
identifier only for this package; native packages retain their existing ID.
Version 1.3.7 is published in the ArkHost Flatpak repository with stable package
metadata dated 2026-11-10. GitLab release tags and other platform channels are
managed separately. Keep the manifest pinned to the matching source revision.
The published package targets x86_64. The earlier test bundle in Nextcloud uses
the `com.helixnotes.app` ID and has not been overwritten. Install through the
public link once to use the permanent ID and receive repository updates. The new
ID has a separate Flatpak profile; select the same notes folder through the system
picker.
## Optional Flathub submission
The separate Flathub submission draft has not been checked with Flathub's build
wrapper or linter. See the [submission guide](https://docs.flathub.org/docs/for-app-authors/submission)
and [current requirements](https://docs.flathub.org/docs/for-app-authors/requirements).
The Flathub repository needs these files at its root:
- `com.helixnotes.HelixNotes.yml`
- `cargo-sources.json`
- `node-sources.json`
- `flathub.json`
- The `shared-modules` Git submodule, pinned to
`6be1f986ac28a2b7d745e5ff45a3f8a2d3345083`
Desktop, icon and MetaInfo files are installed from the pinned application source.
The source currently includes the packaging metadata and the Flatpak watcher fix.
It is a preparation revision, not a published v1.3.7 release tag.
Use a branch based on `flathub/flathub`'s `new-pr` branch. Preserve the upstream
submission template. Author the submission description and any review replies
yourself, following Flathub's current requirements. This preparation does not
create a GitHub pull request or publish an application.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,10 @@
[Desktop Entry]
Type=Application
Name=HelixNotes
Comment=Write and organize local Markdown notes
Exec=helixnotes %f
Icon=com.helixnotes.HelixNotes
Terminal=false
Categories=Office;
MimeType=text/markdown;text/x-markdown;
Keywords=Markdown;tasks;wiki;
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2026 Yuri Karamian -->
<component type="desktop-application">
<id>com.helixnotes.HelixNotes</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>AGPL-3.0-or-later</project_license>
<name>HelixNotes</name>
<summary>Write and organize local Markdown notes</summary>
<developer id="com.helixnotes">
<name>Yuri Karamian</name>
</developer>
<description>
<p>HelixNotes keeps your notes as Markdown files in a folder you choose.
Organize them into notebooks, add tags, link related notes and search across
your collection.</p>
<p>The Tasks view brings together checklists from your notes in a list or
calendar.</p>
</description>
<launchable type="desktop-id">com.helixnotes.HelixNotes.desktop</launchable>
<url type="homepage">https://helixnotes.com</url>
<url type="vcs-browser">https://gitlab.com/ArkHost/HelixNotes</url>
<url type="bugtracker">https://gitlab.com/ArkHost/HelixNotes/-/issues</url>
<content_rating type="oars-1.1"/>
<releases>
<release version="1.3.7" type="stable" date="2026-11-10">
<description>
<p>Add notebook and tag icons, ten themes, mobile layout fixes and a
Flatpak package.</p>
</description>
</release>
</releases>
<provides>
<binary>helixnotes</binary>
</provides>
<screenshots>
<screenshot type="default">
<caption>Markdown editor</caption>
<image type="source">https://cdn.helixnotes.com/assets/screenshots/screenshot-1.png</image>
</screenshot>
<screenshot>
<caption>Tasks calendar</caption>
<image type="source">https://cdn.helixnotes.com/assets/screenshots/screenshot-2.png</image>
</screenshot>
</screenshots>
</component>
@@ -0,0 +1,71 @@
app-id: com.helixnotes.HelixNotes
runtime: org.gnome.Platform
runtime-version: '51'
sdk: org.gnome.Sdk
branch: stable
command: helixnotes
sdk-extensions:
- org.freedesktop.Sdk.Extension.node24
- org.freedesktop.Sdk.Extension.rust-stable
finish-args:
- --socket=wayland
- --socket=fallback-x11
- --share=ipc
- --device=dri
- --share=network
- --filesystem=xdg-run/tray-icon:create
- --talk-name=org.kde.StatusNotifierWatcher
- --talk-name=org.freedesktop.FileManager1
build-options:
append-path: /usr/lib/sdk/node24/bin:/usr/lib/sdk/rust-stable/bin
cleanup:
- /include
- /lib/pkgconfig
- /lib/*.a
- /lib/*.la
modules:
- shared-modules/libayatana-appindicator/libayatana-appindicator-gtk3.json
- name: pnpm
buildsystem: simple
build-commands:
- mkdir -p /app/lib/pnpm /app/bin
- cp -a . /app/lib/pnpm/
- ln -s ../lib/pnpm/bin/pnpm.mjs /app/bin/pnpm
cleanup:
- '*'
sources:
- type: archive
url: https://registry.npmjs.org/pnpm/-/pnpm-11.18.0.tgz
sha256: 29c35ca8d2a287988fdee3e0f36e07d9b93783f567b579b7fd5b798a4563dd81
- name: helixnotes
buildsystem: simple
build-options:
env:
CARGO_HOME: /run/build/helixnotes/cargo
CARGO_NET_OFFLINE: 'true'
CARGO_BUILD_JOBS: '4'
XDG_CACHE_HOME: /run/build/helixnotes/flatpak-node/cache
HELIXNOTES_INSTALL_TYPE: flatpak
build-commands:
- pnpm install --offline --frozen-lockfile --trust-lockfile
- pnpm tauri build --no-bundle --config '{"identifier":"com.helixnotes.HelixNotes"}'
- install -Dm755 src-tauri/target/release/helixnotes /app/bin/helixnotes
- install -Dm644 packaging/flatpak/com.helixnotes.HelixNotes.desktop /app/share/applications/com.helixnotes.HelixNotes.desktop
- install -Dm644 packaging/flatpak/com.helixnotes.HelixNotes.metainfo.xml /app/share/metainfo/com.helixnotes.HelixNotes.metainfo.xml
- install -Dm644 src-tauri/icons/icon.svg /app/share/icons/hicolor/scalable/apps/com.helixnotes.HelixNotes.svg
- install -Dm644 src-tauri/icons/128x128.png /app/share/icons/hicolor/128x128/apps/com.helixnotes.HelixNotes.png
- install -Dm644 src-tauri/icons/128x128@2x.png /app/share/icons/hicolor/256x256/apps/com.helixnotes.HelixNotes.png
- install -Dm644 LICENSE /app/share/licenses/com.helixnotes.HelixNotes/LICENSE
sources:
- type: git
url: https://gitlab.com/ArkHost/HelixNotes.git
commit: d5dc7147ab9c8d3fa7a8ce034339e9f2a5b5e260
disable-submodules: true
- cargo-sources.json
- node-sources.json
+3
View File
@@ -0,0 +1,3 @@
{
"only-arches": ["x86_64"]
}
File diff suppressed because it is too large. Load diff
+235
View File
@@ -0,0 +1,235 @@
#!/usr/bin/env python3
"""Prepare a local ArkHost Flatpak repository; never upload or deploy it.
Signed example:
./prepare-repository.py HelixNotes.flatpak --output /tmp/arkhost-signed \
--gpg-key FULL_OPENPGP_FINGERPRINT
For an update, add --previous-directory /path/to/previous/output. Its repository
is copied, preserving old commits and deltas; the previous output is untouched.
The output must be a fresh directory outside the previous directory.
Use --unsigned for local staging while a signing key is unavailable. Unsigned
staging produces no public-key files or installation descriptors. Prepare a new
signed output before distribution; never disable client signature verification.
Requires Python 3, Flatpak, OSTree (CLI or Python GObject bindings) and, for
signed output, GnuPG. Signing uses the normal
GPG agent/pinentry. Only the public key is exported. The input bundle should be
exported with collection ID com.arkhost.Flatpak and contain the canonical app's
x86_64/stable ref. No packages are installed and no network commands are run.
"""
import argparse
import base64
import configparser
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import tempfile
from urllib.parse import urlsplit
APP_ID = "com.helixnotes.HelixNotes"
APP_REF = f"app/{APP_ID}/x86_64/stable"
COLLECTION_ID = "com.arkhost.Flatpak"
RUNTIME_REPO = "https://dl.flathub.org/repo/flathub.flatpakrepo"
DEFAULT_URL = "https://repo.arkhost.com/flatpak/"
def run(*args, capture=False, binary=False):
return subprocess.run(
[str(arg) for arg in args],
check=True,
stdout=subprocess.PIPE if capture else None,
text=not binary,
env={**os.environ, "LC_ALL": "C"},
).stdout
def initialize_repository(repository):
repository.mkdir(parents=True, exist_ok=False)
if shutil.which("ostree"):
run("ostree", f"--repo={repository}", "init", "--mode=archive-z2")
else:
# Fedora already supplies these native bindings with Flatpak. Keep the
# fallback isolated so installations with the CLI do not require them.
run(sys.executable, "-c", (
"import sys, gi; gi.require_version('OSTree', '1.0'); "
"from gi.repository import Gio, OSTree; "
"repo = OSTree.Repo.new(Gio.File.new_for_path(sys.argv[1])); "
"repo.create(OSTree.RepoMode.ARCHIVE_Z2, None)"
), repository)
run("flatpak", "build-update-repo", "--no-update-appstream",
f"--collection-id={COLLECTION_ID}", repository)
def validate_repository(repository):
"""Inspect Flatpak's summary and app metadata, not the bundle's binary format."""
branches = run("flatpak", "repo", "--branches", repository, capture=True)
refs = {
line.split()[0]
for line in branches.splitlines()
if line.split() and line.split()[0].startswith(("app/", "runtime/"))
}
if refs != {APP_REF}:
raise ValueError(f"Expected only {APP_REF}; found {sorted(refs)}")
metadata = configparser.ConfigParser(interpolation=None)
metadata.read_string(
run("flatpak", "repo", f"--metadata={APP_REF}", repository, capture=True)
)
if metadata.get("Application", "name", fallback="") != APP_ID:
raise ValueError("Imported application metadata has an unexpected ID")
runtime = metadata.get("Application", "runtime", fallback="")
if not runtime.startswith("org.gnome.Platform/x86_64/"):
raise ValueError(f"Expected the GNOME x86_64 runtime; found {runtime!r}")
def write_descriptor(path, section, fields):
descriptor = configparser.ConfigParser(interpolation=None)
descriptor.optionxform = str
descriptor[section] = fields
with path.open("x", encoding="utf-8") as stream:
descriptor.write(stream, space_around_delimiters=False)
def prepare(args):
bundle = args.bundle.expanduser().resolve(strict=True)
output = args.output.expanduser().absolute()
if not bundle.is_file():
raise ValueError("The bundle must be a regular file")
if os.path.lexists(output):
raise ValueError("Output already exists; choose a fresh staging directory")
previous = None
if args.previous_directory:
previous = args.previous_directory.expanduser().resolve(strict=True)
if output.resolve().is_relative_to(previous):
raise ValueError("Output must be outside the previous directory")
if not (previous / "repo").is_dir():
raise ValueError("Previous directory must contain a repo directory")
validate_repository(previous / "repo")
old_fingerprint = previous / "gpg-fingerprint.txt"
if args.gpg_key and not old_fingerprint.exists():
raise ValueError("Signing an update requires a previous signed output; omit --previous-directory for the first signed publication")
if args.gpg_key:
if old_fingerprint.read_text().strip().upper() != args.gpg_key:
raise ValueError("Previous repository uses another signing key; key rotation requires a separate plan")
for command in ("flatpak", "gpg") if args.gpg_key else ("flatpak",):
if shutil.which(command) is None:
raise ValueError(f"Required command not found: {command}")
homedir = []
if args.gpg_homedir:
keyring = args.gpg_homedir.expanduser().resolve(strict=True)
if not keyring.is_dir():
raise ValueError("GPG homedir must be an existing directory")
homedir = [f"--gpg-homedir={keyring}"]
output.mkdir(parents=True, exist_ok=False)
incomplete = output / "INCOMPLETE.txt"
incomplete.write_text("Local preparation has not completed. Do not publish this directory.\n")
repository = output / "repo"
# An empty temporary import makes it impossible for an old repo ref to mask
# an input bundle with the wrong app, architecture or branch.
with tempfile.TemporaryDirectory(prefix=".flatpak-import-", dir=output) as scratch:
imported = Path(scratch) / "repo"
initialize_repository(imported)
print("Importing and checking the canonical application bundle", flush=True)
run("flatpak", "build-import-bundle", "--no-update-summary", imported, bundle)
# `flatpak repo` reads summary metadata, so create a private preflight
# summary before inspecting the import. The signed summary comes later.
run("flatpak", "build-update-repo", "--no-update-appstream", imported)
validate_repository(imported)
if previous:
print("Copying the previous repository without pruning its history", flush=True)
shutil.copytree(previous / "repo", repository, copy_function=shutil.copy2)
else:
initialize_repository(repository)
# Recommit onto the hosted branch so each update descends from its last
# published head and uses this repository's collection binding.
run("flatpak", "build-commit-from", f"--src-repo={imported}",
f"--src-ref={APP_REF}", "--no-update-summary", repository, APP_REF)
signing = []
public_key = None
if args.gpg_key:
public_key = output / "arkhost-flatpak.gpg"
gpg_homedir = []
if args.gpg_homedir:
gpg_homedir = ["--homedir", str(keyring)]
exported = run("gpg", "--batch", *gpg_homedir, "--export", args.gpg_key,
capture=True, binary=True)
if not exported:
raise ValueError("GPG exported no public key for the requested fingerprint")
public_key.write_bytes(exported)
signing = [f"--gpg-sign={args.gpg_key}", *homedir]
print("Signing the application commit", flush=True)
run("flatpak", "build-sign", "--arch=x86_64", *signing,
repository, APP_ID, "stable")
print("Updating AppStream, summary and static deltas", flush=True)
run("flatpak", "build-update-repo", "--generate-static-deltas",
"--default-branch=stable", f"--collection-id={COLLECTION_ID}",
"--title=ArkHost Flatpak Repository", "--homepage=https://arkhost.com",
*signing, *([f"--gpg-import={public_key}"] if public_key else []), repository)
validate_repository(repository)
if args.unsigned:
(output / "UNSIGNED-STAGING.txt").write_text(
"UNSIGNED LOCAL STAGING. Do not publish this repository.\n"
"No installation descriptors or public-key files were generated.\n"
"Prepare a fresh output with --gpg-key before distribution.\n"
)
print(f"Unsigned staging ready: {output}. No installation links generated.", flush=True)
else:
(output / "gpg-fingerprint.txt").write_text(args.gpg_key + "\n")
encoded_key = base64.b64encode(exported).decode("ascii")
repository_url = args.url.rstrip("/") + "/repo/"
common = {"Url": repository_url, "GPGKey": encoded_key,
"DeploySideloadCollectionID": COLLECTION_ID}
write_descriptor(output / "arkhost.flatpakrepo", "Flatpak Repo", {
"Title": "ArkHost Flatpak Repository", "Homepage": "https://arkhost.com",
"DefaultBranch": "stable", **common,
})
write_descriptor(output / "HelixNotes.flatpakref", "Flatpak Ref", {
"Title": "HelixNotes", "Name": APP_ID, "Branch": "stable",
"IsRuntime": "false", "SuggestRemoteName": "arkhost",
"RuntimeRepo": RUNTIME_REPO,
"Description": "Local Markdown notes by Yuri Karamian.", **common,
})
print(f"Signed repository and installation descriptors ready: {output}", flush=True)
incomplete.unlink()
print("Nothing was uploaded, deployed or installed.", flush=True)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("bundle", type=Path, help="Canonical HelixNotes x86_64/stable .flatpak bundle")
parser.add_argument("--output", required=True, type=Path, help="Fresh output directory")
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("--gpg-key", help="Full signing-key fingerprint (40 or 64 hexadecimal characters)")
mode.add_argument("--unsigned", action="store_true", help="Local staging only; generate no installation descriptors")
parser.add_argument("--gpg-homedir", type=Path, help="Existing GPG home; otherwise use the normal keyring")
parser.add_argument("--url", default=DEFAULT_URL, help="Public base URL, excluding the repo/ suffix")
parser.add_argument("--previous-directory", type=Path, help="Previous prepared output whose repo/history must be retained")
args = parser.parse_args()
if args.gpg_key:
args.gpg_key = args.gpg_key.upper()
if not re.fullmatch(r"(?:[0-9A-F]{40}|[0-9A-F]{64})", args.gpg_key):
parser.error("--gpg-key must be a complete hexadecimal fingerprint")
if args.gpg_homedir and args.unsigned:
parser.error("--gpg-homedir requires --gpg-key")
url = urlsplit(args.url)
if (url.scheme != "https" or not url.netloc or url.username or url.password
or url.query or url.fragment or any(ord(c) < 33 for c in args.url)):
parser.error("--url must be an absolute HTTPS base URL without credentials, query or fragment")
try:
prepare(args)
except (OSError, ValueError, configparser.Error, subprocess.CalledProcessError) as error:
parser.exit(1, f"Preparation stopped: {error}\nAny partial output was preserved; choose a fresh output to retry.\n")
if __name__ == "__main__":
main()
+794 -713
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -0,0 +1,4 @@
allowBuilds:
esbuild: true
overrides:
cookie: 0.7.2
+84 -276
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "adler2"
@@ -8,17 +8,6 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "ahash"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9"
dependencies = [
"getrandom 0.2.17",
"once_cell",
"version_check",
]
[[package]]
name = "ahash"
version = "0.8.12"
@@ -138,12 +127,6 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
[[package]]
name = "arrayvec"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "async-broadcast"
version = "0.7.2"
@@ -346,18 +329,6 @@ dependencies = [
"crunchy",
]
[[package]]
name = "bitvec"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c"
dependencies = [
"funty",
"radium",
"tap",
"wyz",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -389,29 +360,6 @@ dependencies = [
"piper",
]
[[package]]
name = "borsh"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1da5ab77c1437701eeff7c88d968729e7766172279eab0676857b3d63af7a6f"
dependencies = [
"borsh-derive",
"cfg_aliases",
]
[[package]]
name = "borsh-derive"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0686c856aa6aac0c4498f936d7d6a02df690f614c03e4d906d1018062b5c5e2c"
dependencies = [
"once_cell",
"proc-macro-crate 3.4.0",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "brotli"
version = "8.0.2"
@@ -439,40 +387,6 @@ version = "3.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
[[package]]
name = "byte-unit"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c6d47a4e2961fb8721bcfc54feae6455f2f64e7054f9bc67e875f0e77f4c58d"
dependencies = [
"rust_decimal",
"schemars 1.2.1",
"serde",
"utf8-width",
]
[[package]]
name = "bytecheck"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23cdc57ce23ac53c931e88a43d06d070a6fd142f2617be5855eb75efc9beb1c2"
dependencies = [
"bytecheck_derive",
"ptr_meta",
"simdutf8",
]
[[package]]
name = "bytecheck_derive"
version = "0.6.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3db406d29fbcd95542e92559bed4d8ad92636d1ca8b3b72ede10b4bcc010e659"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "bytemuck"
version = "1.25.0"
@@ -624,6 +538,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]]
name = "chacha20"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
dependencies = [
"cfg-if",
"cpufeatures 0.3.0",
"rand_core 0.10.1",
]
[[package]]
name = "chrono"
version = "0.4.44"
@@ -738,6 +663,15 @@ dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -768,9 +702,9 @@ dependencies = [
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
version = "0.9.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
dependencies = [
"crossbeam-utils",
]
@@ -1314,12 +1248,6 @@ dependencies = [
"libc",
]
[[package]]
name = "funty"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"
[[package]]
name = "futf"
version = "0.1.5"
@@ -1590,11 +1518,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi",
"wasip2",
"wasm-bindgen",
]
[[package]]
@@ -1604,10 +1530,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"r-efi",
"rand_core 0.10.1",
"wasip2",
"wasip3",
"wasm-bindgen",
]
[[package]]
@@ -1796,9 +1725,6 @@ name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
dependencies = [
"ahash 0.7.8",
]
[[package]]
name = "hashbrown"
@@ -1806,7 +1732,7 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash 0.8.12",
"ahash",
"allocator-api2",
]
@@ -1850,18 +1776,23 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "helixnotes"
version = "1.3.3"
version = "1.3.7"
dependencies = [
"aho-corasick",
"arboard",
"chrono",
"dirs",
"fs4",
"futures",
"gray_matter",
"image",
"libc",
"log",
"notify",
"objc2-app-kit",
"parking_lot",
"png 0.17.16",
"quick-xml 0.36.2",
"quick-xml",
"rayon",
"regex",
"reqwest 0.12.28",
@@ -1876,11 +1807,13 @@ dependencies = [
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-fs",
"tauri-plugin-ios-vault-access",
"tauri-plugin-log",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
"tauri-plugin-window-state",
"tempfile",
"tokio",
"urlencoding",
"uuid",
@@ -2552,9 +2485,6 @@ name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
dependencies = [
"value-bag",
]
[[package]]
name = "lru"
@@ -2573,9 +2503,9 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "lz4_flex"
version = "0.11.5"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08ab2867e3eeeca90e844d1940eab391c9dc5228783db2ed999acbc0a9ed375a"
checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a"
[[package]]
name = "mac"
@@ -3415,13 +3345,13 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "plist"
version = "1.8.0"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"
checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
dependencies = [
"base64 0.22.1",
"indexmap 2.13.0",
"quick-xml 0.38.4",
"quick-xml",
"serde",
"time",
]
@@ -3574,26 +3504,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "ptr_meta"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0738ccf7ea06b608c10564b31debd4f5bc5e197fc8bfe088f68ae5ce81e7a4f1"
dependencies = [
"ptr_meta_derive",
]
[[package]]
name = "ptr_meta_derive"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b845dbfca988fa33db069c0e230574d15a3088f147a87b64c7589eb662c9ac"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "pure-rust-locales"
version = "0.8.2"
@@ -3617,18 +3527,9 @@ checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
[[package]]
name = "quick-xml"
version = "0.36.2"
version = "0.41.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7649a7b4df05aed9ea7ec6f628c67c9953a43869b8bc50929569b2999d443fe"
dependencies = [
"memchr",
]
[[package]]
name = "quick-xml"
version = "0.38.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
dependencies = [
"memchr",
]
@@ -3655,14 +3556,15 @@ dependencies = [
[[package]]
name = "quinn-proto"
version = "0.11.13"
version = "0.11.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"
dependencies = [
"bytes",
"getrandom 0.3.4",
"getrandom 0.4.1",
"lru-slab",
"rand 0.9.2",
"rand 0.10.2",
"rand_pcg 0.10.2",
"ring",
"rustc-hash 2.1.1",
"rustls",
@@ -3703,12 +3605,6 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "radium"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
[[package]]
name = "rand"
version = "0.7.3"
@@ -3720,7 +3616,7 @@ dependencies = [
"rand_chacha 0.2.2",
"rand_core 0.5.1",
"rand_hc",
"rand_pcg",
"rand_pcg 0.2.1",
]
[[package]]
@@ -3736,12 +3632,13 @@ dependencies = [
[[package]]
name = "rand"
version = "0.9.2"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.5",
"chacha20",
"getrandom 0.4.1",
"rand_core 0.10.1",
]
[[package]]
@@ -3764,16 +3661,6 @@ dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]]
name = "rand_core"
version = "0.5.1"
@@ -3794,12 +3681,9 @@ dependencies = [
[[package]]
name = "rand_core"
version = "0.9.5"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rand_distr"
@@ -3829,6 +3713,15 @@ dependencies = [
"rand_core 0.5.1",
]
[[package]]
name = "rand_pcg"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
dependencies = [
"rand_core 0.10.1",
]
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -3933,15 +3826,6 @@ version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]
name = "rend"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71fe3824f5629716b1589be05dacd749f6aa084c87e00e016714a8cdfccc997c"
dependencies = [
"bytecheck",
]
[[package]]
name = "reqwest"
version = "0.12.28"
@@ -4061,35 +3945,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rkyv"
version = "0.7.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2297bf9c81a3f0dc96bc9521370b88f054168c29826a75e89c55ff196e7ed6a1"
dependencies = [
"bitvec",
"bytecheck",
"bytes",
"hashbrown 0.12.3",
"ptr_meta",
"rend",
"rkyv_derive",
"seahash",
"tinyvec",
"uuid",
]
[[package]]
name = "rkyv_derive"
version = "0.7.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84d7b42d4b8d06048d3ac8db0eb31bcb942cbeb709f0b5f2b2ebde398d3038f5"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "rust-stemmers"
version = "1.2.0"
@@ -4100,22 +3955,6 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "rust_decimal"
version = "1.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61f703d19852dbf87cbc513643fa81428361eb6940f1ac14fd58155d295a3eb0"
dependencies = [
"arrayvec",
"borsh",
"bytes",
"num-traits",
"rand 0.8.5",
"rkyv",
"serde",
"serde_json",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -4229,9 +4068,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.9"
version = "0.103.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a"
dependencies = [
"ring",
"rustls-pki-types",
@@ -4325,12 +4164,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "seahash"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -4572,7 +4405,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.2.17",
"digest",
]
@@ -4598,12 +4431,6 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "siphasher"
version = "0.3.11"
@@ -5005,17 +4832,11 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "tap"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "tar"
version = "0.4.44"
version = "0.4.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a"
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
dependencies = [
"filetime",
"libc",
@@ -5201,14 +5022,22 @@ dependencies = [
"url",
]
[[package]]
name = "tauri-plugin-ios-vault-access"
version = "0.1.0"
dependencies = [
"serde",
"tauri",
"tauri-plugin",
]
[[package]]
name = "tauri-plugin-log"
version = "2.8.0"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7545bd67f070a4500432c826e2e0682146a1d6712aee22a2786490156b574d93"
checksum = "6792296e6f389268016c77db21ebae1fc0568f2fccf88b1ec7e2ea71330afb4c"
dependencies = [
"android_logger",
"byte-unit",
"fern",
"log",
"objc2",
@@ -5953,12 +5782,6 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcfc827f90e53a02eaef5e535ee14266c1d569214c6aa70133a624d8a3164ba"
[[package]]
name = "utf8-width"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1292c0d970b54115d14f2492fe0170adf21d68a1de108eebc51c1df4f346a091"
[[package]]
name = "utf8_iter"
version = "1.0.4"
@@ -5977,12 +5800,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "value-bag"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"
[[package]]
name = "version-compare"
version = "0.2.1"
@@ -6235,12 +6052,12 @@ dependencies = [
[[package]]
name = "wayland-scanner"
version = "0.31.8"
version = "0.31.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5423e94b6a63e68e439803a3e153a9252d5ead12fd853334e2ad33997e3889e3"
checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
dependencies = [
"proc-macro2",
"quick-xml 0.38.4",
"quick-xml",
"quote",
]
@@ -6996,15 +6813,6 @@ dependencies = [
"x11-dl",
]
[[package]]
name = "wyz"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed"
dependencies = [
"tap",
]
[[package]]
name = "x11"
version = "2.21.0"
+23 -3
View File
@@ -1,11 +1,15 @@
[package]
name = "helixnotes"
version = "1.3.3"
version = "1.3.7"
description = "Local markdown note-taking app"
authors = ["HelixNotes"]
license = "AGPL-3.0-or-later"
edition = "2021"
rust-version = "1.77.2"
rust-version = "1.88"
[lints.clippy]
# This style lint is version-dependent and produces over 100 legacy-only diagnostics on Rust 1.88.
uninlined_format_args = "allow"
[lib]
name = "app_lib"
@@ -14,6 +18,9 @@ crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dev-dependencies]
tauri = { version = "2", features = ["test"] }
[dependencies]
tauri = { version = "2", features = ["protocol-asset", "tray-icon", "image-png"] }
tauri-plugin-log = "2"
@@ -25,7 +32,9 @@ serde_json = "1"
serde_yaml = "0.9"
log = "0.4"
notify = "8"
parking_lot = "0.12"
walkdir = "2"
tempfile = "3"
chrono = { version = "0.4", features = ["serde", "unstable-locales"] }
sys-locale = "0.3"
uuid = { version = "1", features = ["v4"] }
@@ -34,14 +43,25 @@ gray_matter = "0.2"
tokio = { version = "1", features = ["full"] }
dirs = "6"
regex = "1"
aho-corasick = "1"
zip = { version = "2", default-features = false, features = ["deflate"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls", "blocking"] }
futures = "0.3"
rayon = "1"
quick-xml = "0.36"
quick-xml = "0.41"
urlencoding = "2"
sha2 = "0.10"
fs4 = { version = "0.8", default-features = false }
rustls = { version = "0.23", default-features = false, features = ["ring", "logging", "std", "tls12"] }
[target.'cfg(target_os = "macos")'.dependencies]
objc2-app-kit = "0.3.2"
[target.'cfg(target_os = "android")'.dependencies]
libc = "0.2"
[target.'cfg(target_os = "ios")'.dependencies]
tauri-plugin-ios-vault-access = { path = "plugins/ios-vault-access" }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-updater = "2"
tauri-plugin-single-instance = "2"
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
</dict>
</plist>
+1 -1
View File
@@ -1,3 +1,3 @@
fn main() {
tauri_build::build()
tauri_build::build()
}
+2 -27
View File
@@ -11,6 +11,7 @@
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-close",
"core:window:allow-show",
"core:window:allow-is-maximized",
"core:window:allow-set-decorations",
"core:window:allow-is-fullscreen",
@@ -23,32 +24,6 @@
"dialog:allow-message",
"dialog:allow-ask",
"dialog:allow-confirm",
"fs:default",
"fs:allow-read",
"fs:allow-write",
"fs:allow-exists",
"fs:allow-mkdir",
"fs:allow-remove",
"fs:allow-rename",
"fs:allow-copy-file",
"fs:allow-stat",
"fs:allow-read-dir",
"fs:allow-read-file",
"fs:allow-write-file",
"fs:allow-watch",
"opener:default",
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "/**" }]
},
{
"identifier": "opener:allow-open-url",
"allow": [
{ "url": "https://**" },
{ "url": "http://**" },
{ "url": "mailto:*" }
]
},
"opener:allow-reveal-item-in-dir"
"fs:allow-read-file"
]
}
+19
View File
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- Hardened runtime entitlements for Developer ID distribution (outside Mac App Store).
Required for notarization. These do NOT enable App Sandbox.
Without these, the WebKit webview and bundled Rust libraries get killed by the
hardened runtime's library validation. -->
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<!-- Network access for auto-updater, AI features, WebDAV sync, image proxy -->
<key>com.apple.security.network.client</key>
<true/>
</dict>
</plist>
@@ -33,6 +33,19 @@ class MainActivity : TauriActivity() {
// paragraph font-size and line-height from viewport heuristics and ignores our CSS (only
// size + line-height were affected; font-family was fine). NORMAL turns it off. (#100)
webView.settings.layoutAlgorithm = android.webkit.WebSettings.LayoutAlgorithm.NORMAL
// Honor the viewport meta tag's scale, which is how the Interface Scale setting is applied
// on Android (WebView zoom APIs are not exposed through Tauri here). (#288)
webView.settings.useWideViewPort = true
}
override fun onPause() {
// Give the editor a chance to persist its current document before Android
// suspends the WebView. The save remains best-effort when the process is killed.
webView?.evaluateJavascript(
"window.dispatchEvent(new Event('app-lifecycle-flush'))",
null
)
super.onPause()
}
override fun onResume() {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.3 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.8 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
<color name="ic_launcher_background">#626ED4</color>
</resources>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 709 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 556 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 961 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 984 B

-9
View File
@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" ry="112" fill="#626ED4"/>
<line x1="128" y1="128" x2="384" y2="384" stroke="#ffffff" stroke-width="8" stroke-opacity="0.5" stroke-linecap="round"/>
<line x1="384" y1="128" x2="128" y2="384" stroke="#ffffff" stroke-width="8" stroke-opacity="0.5" stroke-linecap="round"/>
<circle cx="128" cy="128" r="36" fill="#ffffff"/>
<circle cx="384" cy="128" r="36" fill="#ffffff"/>
<circle cx="128" cy="384" r="36" fill="#ffffff"/>
<circle cx="384" cy="384" r="36" fill="#ffffff"/>
</svg>

Before

Width:  |  Height:  |  Size: 633 B

+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(85.333 85.333) scale(0.666667)">
<line x1="178.45584" y1="178.45584" x2="333.54416" y2="333.54416" stroke="#ffffff" stroke-width="25" stroke-opacity="0.5" stroke-linecap="round"/>
<line x1="337.53708" y1="174.46292" x2="174.46294" y2="337.53708" stroke="#ffffff" stroke-width="25" stroke-opacity="0.5" stroke-linecap="round"/>
<circle cx="153" cy="153" r="36" fill="#ffffff"/>
<circle cx="359" cy="153" r="36" fill="#ffffff"/>
<circle cx="153" cy="359" r="36" fill="#ffffff"/>
<circle cx="359" cy="359" r="36" fill="#ffffff"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 706 B

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 8.9 KiB

+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="512"
height="512"
viewBox="0 0 512 512"
version="1.1"
id="svg5"
xmlns="http://www.w3.org/2000/svg"><rect
width="512"
height="512"
rx="112"
ry="112"
fill="#626ED4"
id="rect1" /><line
x1="178.45584"
y1="178.45584"
x2="333.54416"
y2="333.54416"
stroke="#ffffff"
stroke-width="25"
stroke-opacity="0.5"
stroke-linecap="round"
id="line1" /><line
x1="337.53708"
y1="174.46292"
x2="174.46294"
y2="337.53708"
stroke="#ffffff"
stroke-width="25"
stroke-opacity="0.5"
stroke-linecap="round"
id="line2" /><circle
cx="153"
cy="153"
r="36"
fill="#ffffff"
id="circle2" /><circle
cx="359"
cy="153"
r="36"
fill="#ffffff"
id="circle3" /><circle
cx="153"
cy="359"
r="36"
fill="#ffffff"
id="circle4" /><circle
cx="359"
cy="359"
r="36"
fill="#ffffff"
id="circle5" /></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 667 B

After

Width:  |  Height:  |  Size: 475 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 788 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 788 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 788 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.6 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.4 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.0 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

@@ -0,0 +1,15 @@
[package]
name = "tauri-plugin-ios-vault-access"
version = "0.1.0"
authors = ["HelixNotes"]
description = "iOS Files folder access for HelixNotes"
edition = "2021"
rust-version = "1.77.2"
links = "tauri-plugin-ios-vault-access"
[dependencies]
tauri = "2"
serde = { version = "1", features = ["derive"] }
[build-dependencies]
tauri-plugin = { version = "2", features = ["build"] }
@@ -0,0 +1,3 @@
fn main() {
tauri_plugin::Builder::new(&[]).ios_path("ios").build();
}
@@ -0,0 +1,24 @@
// swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "tauri-plugin-ios-vault-access",
platforms: [.iOS(.v14)],
products: [
.library(
name: "tauri-plugin-ios-vault-access",
type: .static,
targets: ["tauri-plugin-ios-vault-access"]
)
],
dependencies: [
.package(name: "Tauri", path: "../.tauri/tauri-api")
],
targets: [
.target(
name: "tauri-plugin-ios-vault-access",
dependencies: [.byName(name: "Tauri")],
path: "Sources"
)
]
)
@@ -0,0 +1,312 @@
import Foundation
import SwiftRs
import Tauri
import UIKit
import UniformTypeIdentifiers
private struct BookmarkRequest: Decodable {
let bookmarkId: String
}
final class IosVaultAccessPlugin: Plugin, UIDocumentPickerDelegate {
private let fileManager = FileManager.default
private let lock = NSLock()
private var pickerInvoke: Invoke?
private var activeBookmarkId: String?
private var activeURL: URL?
private var stagedBookmarkId: String?
private var stagedURL: URL?
deinit {
rollbackStagedScope()
releaseCurrentScope()
}
@objc func chooseFolder(_ invoke: Invoke) {
DispatchQueue.main.async {
guard self.pickerInvoke == nil else {
invoke.reject("A folder picker is already open.")
return
}
guard let viewController = self.manager.viewController else {
self.pickerInvoke = nil
invoke.reject("Files is unavailable right now. Try again.")
return
}
self.pickerInvoke = invoke
let picker = UIDocumentPickerViewController(
forOpeningContentTypes: [.folder],
asCopy: false
)
picker.delegate = self
picker.allowsMultipleSelection = false
viewController.present(picker, animated: true)
}
}
@objc func resolveFolder(_ invoke: Invoke) throws {
let request = try invoke.parseArgs(BookmarkRequest.self)
do {
invoke.resolve(try resolveBookmark(request.bookmarkId))
} catch {
invoke.reject(message(for: error))
}
}
@objc func releaseActive(_ invoke: Invoke) {
rollbackStagedScope()
releaseCurrentScope()
invoke.resolve()
}
@objc func commitStaged(_ invoke: Invoke) {
commitStagedScope()
invoke.resolve()
}
@objc func rollbackStaged(_ invoke: Invoke) {
rollbackStagedScope()
invoke.resolve()
}
@objc func forgetBookmark(_ invoke: Invoke) throws {
let request = try invoke.parseArgs(BookmarkRequest.self)
do {
let file = try bookmarkFile(for: request.bookmarkId, createDirectory: false)
lock.lock()
let isActive = activeBookmarkId == request.bookmarkId
let isStaged = stagedBookmarkId == request.bookmarkId
lock.unlock()
if fileManager.fileExists(atPath: file.path) {
try fileManager.removeItem(at: file)
}
if isActive {
releaseCurrentScope()
}
if isStaged {
rollbackStagedScope()
}
invoke.resolve()
} catch {
invoke.reject(message(for: error))
}
}
func documentPicker(
_ controller: UIDocumentPickerViewController,
didPickDocumentsAt urls: [URL]
) {
guard let invoke = takePickerInvoke() else { return }
guard let url = urls.first else {
invoke.resolve(cancelledResult())
return
}
do {
guard url.startAccessingSecurityScopedResource() else {
throw AccessError.denied
}
var adopted = false
defer {
if !adopted { url.stopAccessingSecurityScopedResource() }
}
let name = try validateFolder(url)
let bookmarkId = existingBookmarkId(for: url) ?? UUID().uuidString.lowercased()
let bookmark = try url.bookmarkData(
options: .minimalBookmark,
includingResourceValuesForKeys: nil,
relativeTo: nil
)
try bookmark.write(to: bookmarkFile(for: bookmarkId, createDirectory: true), options: .atomic)
stageScope(url: url, bookmarkId: bookmarkId)
adopted = true
invoke.resolve(result(bookmarkId: bookmarkId, url: url, name: name))
} catch {
invoke.reject(message(for: error))
}
}
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
takePickerInvoke()?.resolve(cancelledResult())
}
private func resolveBookmark(_ bookmarkId: String) throws -> [String: Any] {
guard UUID(uuidString: bookmarkId) != nil else { throw AccessError.missing }
lock.lock()
let currentURL = activeBookmarkId == bookmarkId ? activeURL : nil
lock.unlock()
if let currentURL {
return result(bookmarkId: bookmarkId, url: currentURL, name: try validateFolder(currentURL))
}
let data = try Data(contentsOf: bookmarkFile(for: bookmarkId, createDirectory: false))
var stale = false
let url = try URL(
resolvingBookmarkData: data,
options: [],
relativeTo: nil,
bookmarkDataIsStale: &stale
)
guard url.startAccessingSecurityScopedResource() else { throw AccessError.denied }
var adopted = false
defer {
if !adopted { url.stopAccessingSecurityScopedResource() }
}
let name = try validateFolder(url)
if stale {
let refreshed = try url.bookmarkData(
options: .minimalBookmark,
includingResourceValuesForKeys: nil,
relativeTo: nil
)
try refreshed.write(to: bookmarkFile(for: bookmarkId, createDirectory: true), options: .atomic)
}
stageScope(url: url, bookmarkId: bookmarkId)
adopted = true
return result(bookmarkId: bookmarkId, url: url, name: name)
}
private func validateFolder(_ url: URL) throws -> String {
let values = try url.resourceValues(forKeys: [.isDirectoryKey, .nameKey])
guard values.isDirectory == true else { throw AccessError.notFolder }
guard try url.checkResourceIsReachable() else { throw AccessError.unavailable }
return values.name ?? url.lastPathComponent
}
private func stageScope(url: URL, bookmarkId: String) {
lock.lock()
let previous = stagedURL
stagedURL = url
stagedBookmarkId = bookmarkId
lock.unlock()
previous?.stopAccessingSecurityScopedResource()
}
private func commitStagedScope() {
lock.lock()
guard let next = stagedURL else {
lock.unlock()
return
}
let previous = activeURL
activeURL = next
activeBookmarkId = stagedBookmarkId
stagedURL = nil
stagedBookmarkId = nil
lock.unlock()
previous?.stopAccessingSecurityScopedResource()
}
private func rollbackStagedScope() {
lock.lock()
let staged = stagedURL
stagedURL = nil
stagedBookmarkId = nil
lock.unlock()
staged?.stopAccessingSecurityScopedResource()
}
private func releaseCurrentScope() {
lock.lock()
let previous = activeURL
activeURL = nil
activeBookmarkId = nil
lock.unlock()
previous?.stopAccessingSecurityScopedResource()
}
private func takePickerInvoke() -> Invoke? {
let invoke = pickerInvoke
pickerInvoke = nil
return invoke
}
private func bookmarkDirectory(create: Bool) throws -> URL {
let base = try fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
let directory = base.appendingPathComponent("VaultBookmarks", isDirectory: true)
if create {
try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
}
return directory
}
private func bookmarkFile(for id: String, createDirectory: Bool) throws -> URL {
guard UUID(uuidString: id) != nil else { throw AccessError.missing }
let directory = try bookmarkDirectory(create: createDirectory)
return directory.appendingPathComponent("\(id).bookmark")
}
private func existingBookmarkId(for selectedURL: URL) -> String? {
guard
let directory = try? bookmarkDirectory(create: true),
let files = try? fileManager.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: nil
)
else { return nil }
let selectedPath = selectedURL.standardizedFileURL.path
for file in files where file.pathExtension == "bookmark" {
guard let data = try? Data(contentsOf: file) else { continue }
var stale = false
guard
let resolved = try? URL(
resolvingBookmarkData: data,
options: [],
relativeTo: nil,
bookmarkDataIsStale: &stale
),
resolved.standardizedFileURL.path == selectedPath
else { continue }
let id = file.deletingPathExtension().lastPathComponent
if UUID(uuidString: id) != nil { return id }
}
return nil
}
private func result(bookmarkId: String, url: URL, name: String) -> [String: Any] {
["bookmarkId": bookmarkId, "path": url.path, "name": name, "cancelled": false]
}
private func cancelledResult() -> [String: Any] {
["bookmarkId": "", "path": "", "name": "", "cancelled": true]
}
private func message(for error: Error) -> String {
if let accessError = error as? AccessError { return accessError.localizedDescription }
return "The selected folder is unavailable. Open Files and try again."
}
}
private enum AccessError: LocalizedError {
case denied
case missing
case notFolder
case unavailable
var errorDescription: String? {
switch self {
case .denied:
return "HelixNotes no longer has access to this folder. Choose it again in Files."
case .missing:
return "Saved access to this folder is missing. Choose it again in Files."
case .notFolder:
return "The selected item is not a folder."
case .unavailable:
return "The selected folder is unavailable. Open Files and try again."
}
}
}
@_cdecl("init_plugin_ios_vault_access")
func initPlugin() -> Plugin {
IosVaultAccessPlugin()
}
@@ -0,0 +1,84 @@
use serde::{Deserialize, Serialize};
use tauri::{
plugin::{Builder, PluginHandle, TauriPlugin},
Manager, Runtime,
};
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FolderSelection {
pub bookmark_id: String,
pub path: String,
pub name: String,
#[serde(default)]
pub cancelled: bool,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BookmarkRequest<'a> {
bookmark_id: &'a str,
}
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_ios_vault_access);
pub struct IosVaultAccess<R: Runtime>(PluginHandle<R>);
impl<R: Runtime> IosVaultAccess<R> {
pub fn choose_folder(&self) -> Result<FolderSelection, String> {
self.0
.run_mobile_plugin("chooseFolder", ())
.map_err(|error| error.to_string())
}
pub fn resolve_folder(&self, bookmark_id: &str) -> Result<FolderSelection, String> {
self.0
.run_mobile_plugin("resolveFolder", BookmarkRequest { bookmark_id })
.map_err(|error| error.to_string())
}
pub fn release_active(&self) -> Result<(), String> {
self.0
.run_mobile_plugin("releaseActive", ())
.map_err(|error| error.to_string())
}
pub fn commit_staged(&self) -> Result<(), String> {
self.0
.run_mobile_plugin("commitStaged", ())
.map_err(|error| error.to_string())
}
pub fn rollback_staged(&self) -> Result<(), String> {
self.0
.run_mobile_plugin("rollbackStaged", ())
.map_err(|error| error.to_string())
}
pub fn forget_bookmark(&self, bookmark_id: &str) -> Result<(), String> {
self.0
.run_mobile_plugin("forgetBookmark", BookmarkRequest { bookmark_id })
.map_err(|error| error.to_string())
}
}
pub trait IosVaultAccessExt<R: Runtime> {
fn ios_vault_access(&self) -> &IosVaultAccess<R>;
}
impl<R: Runtime, T: Manager<R>> IosVaultAccessExt<R> for T {
fn ios_vault_access(&self) -> &IosVaultAccess<R> {
self.state::<IosVaultAccess<R>>().inner()
}
}
pub fn init<R: Runtime>() -> TauriPlugin<R> {
Builder::new("ios-vault-access")
.setup(|app, api| {
let handle = api.register_ios_plugin(init_plugin_ios_vault_access)?;
app.manage(IosVaultAccess(handle));
Ok(())
})
.build()
}
+96 -50
View File
@@ -8,6 +8,7 @@ const ANTHROPIC_API_URL: &str = "https://api.anthropic.com/v1/messages";
const OPENAI_API_URL: &str = "https://api.openai.com/v1/chat/completions";
const OLLAMA_DEFAULT_URL: &str = "http://localhost:11434";
#[allow(clippy::too_many_arguments)]
pub fn ai_request(
app: AppHandle,
provider: String,
@@ -22,7 +23,11 @@ pub fn ai_request(
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
// Handle all API keys as optional; ollama and v1 completions doesnt always require it.
let key_opt = if api_key.is_empty() { None } else { Some(api_key.as_str()) };
let key_opt = if api_key.is_empty() {
None
} else {
Some(api_key.as_str())
};
let result = match provider.as_str() {
"openai" => {
stream_openai(
@@ -84,6 +89,7 @@ pub fn ai_request(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.clone(),
event_type: "error".to_string(),
text: None,
error: Some(e),
@@ -98,7 +104,37 @@ pub fn ai_request(
/// so both `https://host` and `https://host/v1` work (we append `/v1/chat/completions`).
fn normalize_openai_base(base: &str) -> String {
let b = base.trim().trim_end_matches('/');
b.strip_suffix("/v1").unwrap_or(b).trim_end_matches('/').to_string()
b.strip_suffix("/v1")
.unwrap_or(b)
.trim_end_matches('/')
.to_string()
}
fn openai_request_body(
model: &str,
system_prompt: Option<&str>,
user_message: &str,
stream: bool,
max_tokens: u32,
) -> serde_json::Value {
// GPT-5/6 reject legacy output limits and sampling with their default reasoning.
let reasoning = model.starts_with("gpt-5") || model.starts_with("gpt-6");
let token_key = if reasoning {
"max_completion_tokens"
} else {
"max_tokens"
};
let mut messages = Vec::with_capacity(if system_prompt.is_some() { 2 } else { 1 });
if let Some(system) = system_prompt {
messages.push(json!({ "role": "system", "content": system }));
}
messages.push(json!({ "role": "user", "content": user_message }));
let mut body =
json!({ "model": model, "stream": stream, token_key: max_tokens, "messages": messages });
if stream && !reasoning {
body["temperature"] = json!(0.7);
}
body
}
async fn stream_anthropic(
@@ -107,7 +143,7 @@ async fn stream_anthropic(
model: &str,
system_prompt: &str,
user_message: &str,
_request_id: &str,
request_id: &str,
) -> Result<(), String> {
let client = Client::new();
@@ -160,6 +196,7 @@ async fn stream_anthropic(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(),
text: None,
error: None,
@@ -177,6 +214,7 @@ async fn stream_anthropic(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "text".to_string(),
text: Some(text.to_string()),
error: None,
@@ -188,6 +226,7 @@ async fn stream_anthropic(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(),
text: None,
error: None,
@@ -202,6 +241,7 @@ async fn stream_anthropic(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "error".to_string(),
text: None,
error: Some(msg.to_string()),
@@ -220,6 +260,7 @@ async fn stream_anthropic(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(),
text: None,
error: None,
@@ -236,41 +277,13 @@ async fn stream_openai(
model: &str,
system_prompt: &str,
user_message: &str,
_request_id: &str,
request_id: &str,
) -> Result<(), String> {
let client = Client::new();
let is_gpt5 = model.starts_with("gpt-5");
let token_key = if is_gpt5 {
"max_completion_tokens"
} else {
"max_tokens"
};
let body = openai_request_body(model, Some(system_prompt), user_message, true, 4096);
let mut body = json!({
"model": model,
"stream": true,
token_key: 4096,
"messages": [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": user_message
}
]
});
// GPT-5 models don't support temperature
if !is_gpt5 {
body["temperature"] = json!(0.7);
}
let mut req = client
.post(url)
.header("content-type", "application/json");
let mut req = client.post(url).header("content-type", "application/json");
if let Some(key) = api_key {
req = req.header("Authorization", format!("Bearer {}", key));
@@ -306,6 +319,7 @@ async fn stream_openai(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(),
text: None,
error: None,
@@ -321,6 +335,7 @@ async fn stream_openai(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "text".to_string(),
text: Some(content.to_string()),
error: None,
@@ -335,6 +350,7 @@ async fn stream_openai(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(),
text: None,
error: None,
@@ -349,6 +365,7 @@ async fn stream_openai(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "error".to_string(),
text: None,
error: Some(err.to_string()),
@@ -365,6 +382,7 @@ async fn stream_openai(
let _ = app.emit(
"ai-stream",
AiStreamEvent {
request_id: request_id.to_owned(),
event_type: "done".to_string(),
text: None,
error: None,
@@ -380,7 +398,11 @@ pub async fn test_connection(
model: &str,
base_url: Option<&str>,
) -> Result<String, String> {
let key_opt = if api_key.is_empty() { None } else { Some(api_key) };
let key_opt = if api_key.is_empty() {
None
} else {
Some(api_key)
};
match provider {
"openai" => test_openai(OPENAI_API_URL, Some(api_key), model).await,
"ollama" => {
@@ -405,7 +427,7 @@ async fn test_anthropic(api_key: &str, model: &str) -> Result<String, String> {
let body = json!({
"model": model,
"max_tokens": 10,
"max_tokens": 20,
"messages": [
{
"role": "user",
@@ -435,21 +457,9 @@ async fn test_anthropic(api_key: &str, model: &str) -> Result<String, String> {
async fn test_openai(url: &str, api_key: Option<&str>, model: &str) -> Result<String, String> {
let client = Client::new();
let body = openai_request_body(model, None, "Hi", false, 20);
let body = json!({
"model": model,
"max_tokens": 10,
"messages": [
{
"role": "user",
"content": "Hi"
}
]
});
let mut req = client
.post(url)
.header("content-type", "application/json");
let mut req = client.post(url).header("content-type", "application/json");
if let Some(key) = api_key {
req = req.header("Authorization", format!("Bearer {}", key));
@@ -469,3 +479,39 @@ async fn test_openai(url: &str, api_key: Option<&str>, model: &str) -> Result<St
Err(format!("API error {}: {}", status, body_text))
}
}
#[cfg(test)]
mod request_tests {
use super::*;
#[test]
fn gpt6_streaming_requests_use_supported_parameters() {
let body = openai_request_body(
"gpt-6-astra",
Some("Return Markdown"),
"Revise this",
true,
4096,
);
assert_eq!(body["max_completion_tokens"], 4096);
assert!(body.get("max_tokens").is_none());
assert!(body.get("temperature").is_none());
}
#[test]
fn prior_openai_and_local_models_keep_their_parameter_contract() {
let prior = openai_request_body("gpt-5.5", None, "Hi", false, 20);
assert!(prior.get("max_completion_tokens").is_some());
assert!(prior.get("max_tokens").is_none());
let local = openai_request_body(
"gemma3:4b",
Some("Return Markdown"),
"Revise this",
true,
4096,
);
assert_eq!(local["max_tokens"], 4096);
assert_eq!(local["temperature"], 0.7);
assert!(local.get("max_completion_tokens").is_none());
}
}
+255
View File
@@ -0,0 +1,255 @@
use std::path::Path;
use tauri::{AppHandle, Manager, Runtime};
use tauri_plugin_fs::FsExt;
/// Only configured user-selected vaults may provide an external note's vault-relative root.
pub fn external_note_root<R: Runtime>(
app: &AppHandle<R>,
note_path: &Path,
) -> Result<std::path::PathBuf, String> {
let note = std::fs::canonicalize(note_path).map_err(|error| error.to_string())?;
if let Some(state) = app.try_state::<crate::state::AppState>() {
let (active, mut roots) = {
let config = state.config.lock().map_err(|error| error.to_string())?;
(
config.active_vault.clone(),
config
.vaults
.iter()
.map(|vault| vault.path.clone())
.collect::<Vec<_>>(),
)
};
roots.sort_by_key(|root| std::cmp::Reverse(root.len()));
for root in active.into_iter().chain(roots) {
if let Ok(root) = std::fs::canonicalize(root) {
if note.starts_with(&root) {
return Ok(root);
}
}
}
}
note.parent()
.map(Path::to_path_buf)
.ok_or_else(|| "External note has no parent directory".into())
}
/// Grants asset-protocol access only to a vault selected by the user.
/// `.helixnotes` is added explicitly because Unix glob matching excludes hidden paths.
pub fn allow_vault_assets<R: Runtime>(app: &AppHandle<R>, vault_path: &Path) -> Result<(), String> {
// Keep the canonical native path: Tauri's scope normalizes Unix paths plus
// Windows drive, verbatim, and UNC prefixes when matching asset requests.
let vault = std::fs::canonicalize(vault_path).map_err(|error| {
format!(
"Failed to resolve vault asset path '{}': {error}",
vault_path.display()
)
})?;
let scope = app.asset_protocol_scope();
scope
.allow_directory(&vault, true)
.map_err(|error| error.to_string())?;
scope
.allow_directory(vault.join(".helixnotes"), true)
.map_err(|error| error.to_string())
}
/// Grants access to relative assets next to a Markdown file explicitly opened by the user.
pub fn allow_external_note_assets<R: Runtime>(
app: &AppHandle<R>,
note_path: &Path,
) -> Result<(), String> {
let note = std::fs::canonicalize(note_path).map_err(|error| {
format!(
"Failed to resolve external note path '{}': {error}",
note_path.display()
)
})?;
let parent = note
.parent()
.ok_or_else(|| "External note has no parent directory".to_string())?;
app.asset_protocol_scope()
.allow_directory(parent, true)
.map_err(|error| error.to_string())?;
let root = external_note_root(app, &note)?;
let attachments = root.join(".helixnotes/attachments");
// Never follow a hidden attachment-directory symlink when extending either scope.
if std::fs::canonicalize(&attachments)
.is_ok_and(|canonical| canonical == attachments && canonical.is_dir())
{
app.asset_protocol_scope()
.allow_directory(&attachments, true)
.map_err(|error| error.to_string())?;
if let Some(scope) = app.try_fs_scope() {
scope
.allow_directory(&attachments, true)
.map_err(|error| error.to_string())?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn test_directory(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("helixnotes-{name}-{}", uuid::Uuid::new_v4()))
}
#[test]
fn static_asset_scope_does_not_expose_the_filesystem() {
let config: serde_json::Value =
serde_json::from_str(include_str!("../tauri.conf.json")).unwrap();
let scope = &config["app"]["security"]["assetProtocol"]["scope"];
assert_eq!(scope["allow"], serde_json::json!([]));
assert_eq!(scope["deny"], serde_json::json!([]));
assert_eq!(scope["requireLiteralLeadingDot"], true);
}
#[test]
fn runtime_scope_allows_only_the_selected_vault() {
let root = test_directory("asset-scope");
let vault = root.join("Vault [Cross Platform]");
let attachments = vault.join(".helixnotes").join("attachments");
fs::create_dir_all(&attachments).unwrap();
let note_image = vault.join("images").join("note image.png");
fs::create_dir_all(note_image.parent().unwrap()).unwrap();
fs::write(&note_image, b"image").unwrap();
let attachment = attachments.join("attachment.png");
fs::write(&attachment, b"attachment").unwrap();
let outside = root.join("outside.png");
fs::write(&outside, b"outside").unwrap();
let app = tauri::test::mock_app();
allow_vault_assets(app.handle(), &vault).unwrap();
let scope = app.asset_protocol_scope();
assert!(scope.is_allowed(&note_image));
assert!(scope.is_allowed(&attachment));
assert!(!scope.is_allowed(&outside));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn external_note_scopes_include_its_attachments_but_not_hidden_private_metadata() {
use tauri_plugin_fs::FsExt;
let root = tempfile::tempdir().unwrap();
let parent = root.path().join("external");
let attachments = parent.join(".helixnotes/attachments");
fs::create_dir_all(&attachments).unwrap();
fs::create_dir_all(parent.join(".helixnotes/history")).unwrap();
fs::create_dir_all(parent.join(".ssh")).unwrap();
let note = parent.join("Note.md");
let image = attachments.join("image.png");
let history = parent.join(".helixnotes/history/snapshot.md");
let private = parent.join(".ssh/private.bin");
for file in [&note, &image, &history, &private] {
fs::write(file, b"fixture").unwrap();
}
let app = tauri::test::mock_builder()
.plugin(tauri_plugin_fs::init())
.build(tauri::test::mock_context(tauri::test::noop_assets()))
.unwrap();
app.fs_scope().allow_file(&note).unwrap();
app.fs_scope().allow_directory(&parent, true).unwrap();
let before_private = [
app.fs_scope().is_allowed(&history),
app.fs_scope().is_allowed(&private),
];
allow_external_note_assets(app.handle(), &note).unwrap();
assert!(
app.fs_scope().is_allowed(&image),
"import must be able to read its managed attachments"
);
assert!(
app.asset_protocol_scope().is_allowed(&image),
"the viewer must display managed attachments"
);
for (file, previous) in [&history, &private].into_iter().zip(before_private) {
assert_eq!(
app.fs_scope().is_allowed(file),
previous,
"attachment grants must not widen private metadata access"
);
assert!(!app.asset_protocol_scope().is_allowed(file));
}
}
#[test]
fn external_notebook_uses_its_registered_vault_root_for_attachment_scopes() {
use tauri_plugin_fs::FsExt;
let root = tempfile::tempdir().unwrap();
let vault = root.path().join("source");
fs::create_dir_all(vault.join("Notebook")).unwrap();
fs::create_dir_all(vault.join(".helixnotes/attachments")).unwrap();
let note = vault.join("Notebook/Note.md");
let image = vault.join(".helixnotes/attachments/image.png");
fs::write(&note, b"Note").unwrap();
fs::write(&image, b"Image").unwrap();
let app = tauri::test::mock_builder()
.plugin(tauri_plugin_fs::init())
.manage(crate::state::AppState::new(crate::types::AppConfig {
vaults: vec![crate::types::VaultConfig {
path: vault.to_string_lossy().into_owned(),
..Default::default()
}],
..Default::default()
}))
.build(tauri::test::mock_context(tauri::test::noop_assets()))
.unwrap();
allow_external_note_assets(app.handle(), &note).unwrap();
assert!(app.asset_protocol_scope().is_allowed(&image));
assert!(app.fs_scope().is_allowed(&image));
}
#[cfg(unix)]
#[test]
fn external_attachment_scope_does_not_follow_hidden_directory_symlinks() {
use tauri_plugin_fs::FsExt;
let root = tempfile::tempdir().unwrap();
let parent = root.path().join("external");
let private = root.path().join("private");
fs::create_dir_all(parent.join(".helixnotes")).unwrap();
fs::create_dir(&private).unwrap();
let note = parent.join("Note.md");
let file = private.join("private.bin");
fs::write(&note, b"Note").unwrap();
fs::write(&file, b"private fixture").unwrap();
std::os::unix::fs::symlink(&private, parent.join(".helixnotes/attachments")).unwrap();
let app = tauri::test::mock_builder()
.plugin(tauri_plugin_fs::init())
.build(tauri::test::mock_context(tauri::test::noop_assets()))
.unwrap();
allow_external_note_assets(app.handle(), &note).unwrap();
assert!(!app.fs_scope().is_allowed(&file));
assert!(!app.asset_protocol_scope().is_allowed(&file));
}
#[test]
fn external_note_scope_allows_relative_assets_only_below_its_directory() {
let root = test_directory("external-note-assets");
let note_dir = root.join("shared note");
let assets = note_dir.join("images");
fs::create_dir_all(&assets).unwrap();
let note = note_dir.join("note.md");
let image = assets.join("image.png");
let outside = root.join("outside.png");
fs::write(&note, b"note").unwrap();
fs::write(&image, b"image").unwrap();
fs::write(&outside, b"outside").unwrap();
let app = tauri::test::mock_app();
allow_external_note_assets(app.handle(), &note).unwrap();
let scope = app.asset_protocol_scope();
assert!(scope.is_allowed(&note));
assert!(scope.is_allowed(&image));
assert!(!scope.is_allowed(&outside));
fs::remove_dir_all(root).unwrap();
}
}
+1107 -169
View File
File diff suppressed because it is too large. Load diff
+4180 -1233
View File
File diff suppressed because it is too large. Load diff
+295 -75
View File
@@ -1,48 +1,156 @@
use std::fs;
use std::path::{Path, PathBuf};
use std::path::{Component, Path, PathBuf};
use chrono::{DateTime, Utc};
use crate::types::VersionEntry;
fn safe_path_component<'a>(value: &'a str, label: &str) -> Result<&'a str, String> {
let mut components = Path::new(value).components();
if value.is_empty()
|| !matches!(components.next(), Some(Component::Normal(_)))
|| components.next().is_some()
{
return Err(format!("Invalid {label}"));
}
Ok(value)
}
/// Directory: .helixnotes/history/<note-id>/
fn history_dir(vault_path: &str, note_id: &str) -> PathBuf {
Path::new(vault_path)
.join(".helixnotes")
.join("history")
.join(note_id)
fn history_dir(vault_path: &str, note_id: &str) -> Result<PathBuf, String> {
let mut dir = PathBuf::from(vault_path);
// Each level must be a real folder. A link here (carried in by git, a file-sync tool or an
// extracted archive) would send snapshots, and the pruning that deletes old ones, to whatever
// folder it points at.
for part in [
".helixnotes",
"history",
safe_path_component(note_id, "note ID")?,
] {
dir.push(part);
if fs::symlink_metadata(&dir).is_ok_and(|meta| !meta.file_type().is_dir()) {
return Err("Version history folder is not a real folder".to_string());
}
}
Ok(dir)
}
/// `2026-01-02T03-04-05.md` or `2026-01-02T03-04-05.678.md`: the only names snapshots are given.
fn is_snapshot_name(name: &str) -> bool {
let Some(stem) = name.strip_suffix(".md") else {
return false;
};
let (Some(time), Some(fraction)) = (stem.get(..19), stem.get(19..)) else {
return false;
};
chrono::NaiveDateTime::parse_from_str(time, "%Y-%m-%dT%H-%M-%S").is_ok()
&& (fraction.is_empty()
|| fraction.strip_prefix('.').is_some_and(|digits| {
!digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit())
}))
}
/// A snapshot the app wrote: a regular file (never a link) with a snapshot name.
fn is_snapshot_file(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(is_snapshot_name)
&& fs::symlink_metadata(path).is_ok_and(|meta| meta.file_type().is_file())
}
fn snapshot_path(dir: &Path, raw_content: &str) -> Result<(), String> {
use std::io::Write;
let mut temporary = tempfile::Builder::new()
.prefix(".helixnotes-history-")
.tempfile_in(dir)
.map_err(|error| error.to_string())?;
temporary
.write_all(raw_content.as_bytes())
.map_err(|error| error.to_string())?;
temporary
.as_file()
.sync_all()
.map_err(|error| error.to_string())?;
let mut instant = Utc::now();
loop {
// Fractional seconds keep timestamps valid RFC3339 for the UI while
// allowing multiple versions within one second.
let timestamp = instant.format("%Y-%m-%dT%H-%M-%S%.3f");
let path = dir.join(format!("{timestamp}.md"));
match crate::vault::operations::persist_without_replacing(temporary, &path) {
Ok(_) => return Ok(()),
Err(error) if error.error.kind() == std::io::ErrorKind::AlreadyExists => {
temporary = error.file;
instant += chrono::Duration::milliseconds(1);
}
Err(error) => return Err(error.error.to_string()),
}
}
}
fn version_timestamp(filename: &str) -> String {
match (filename.get(..13), filename.get(14..16), filename.get(17..)) {
(Some(hour), Some(minute), Some(rest))
if filename.as_bytes().get(10) == Some(&b'T')
&& filename.as_bytes().get(13) == Some(&b'-')
&& filename.as_bytes().get(16) == Some(&b'-') =>
{
format!("{hour}:{minute}:{rest}Z")
}
_ => filename.to_string(),
}
}
fn snapshot_filename(timestamp: &str) -> String {
let time = timestamp.strip_suffix('Z').unwrap_or(timestamp);
match (time.get(..13), time.get(14..16), time.get(17..)) {
(Some(hour), Some(minute), Some(rest))
if time.as_bytes().get(10) == Some(&b'T')
&& time.as_bytes().get(13) == Some(&b':')
&& time.as_bytes().get(16) == Some(&b':') =>
{
format!("{hour}-{minute}-{rest}.md")
}
_ => format!("{timestamp}.md"),
}
}
/// Save a version snapshot if enough time has passed since the last one.
/// Minimum interval: 5 minutes between snapshots.
pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) {
let dir = history_dir(vault_path, note_id);
let Ok(dir) = history_dir(vault_path, note_id) else {
log::warn!("Skipping history snapshot with an invalid note ID");
return;
};
// Check if we should create a snapshot (5 min cooldown)
// Old second-resolution and new fractional-second names share the first
// 19 ASCII bytes. Ignore arbitrary files (including malformed Unicode).
if let Ok(entries) = fs::read_dir(&dir) {
let mut files: Vec<String> = entries
.filter_map(|e| e.ok())
.filter_map(|e| e.file_name().to_str().map(|s| s.to_string()))
.filter(|n| n.ends_with(".md"))
.collect();
files.sort();
if let Some(last) = files.last() {
if let Some(ts) = last.strip_suffix(".md") {
// Parse timestamp: 2026-02-08T18-30-00.md
if let Some(t_pos) = ts.find('T') {
let date_part = &ts[..t_pos];
let time_part = &ts[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
let iso = format!("{}T{}Z", date_part, time_colons);
if let Ok(last_time) = iso.parse::<DateTime<Utc>>() {
let elapsed = Utc::now() - last_time;
if elapsed.num_minutes() < 5 {
return; // Too soon, skip
}
}
let latest = entries
.filter_map(|entry| {
let name = entry.ok()?.file_name();
let name = name.to_str()?;
if !name.ends_with(".md") {
return None;
}
}
let (Some(hour), Some(minute), Some(second)) =
(name.get(..13), name.get(14..16), name.get(17..19))
else {
return None;
};
if name.as_bytes().get(10) != Some(&b'T')
|| name.as_bytes().get(13) != Some(&b'-')
|| name.as_bytes().get(16) != Some(&b'-')
{
return None;
}
format!("{hour}:{minute}:{second}Z")
.parse::<DateTime<Utc>>()
.ok()
})
.max();
if latest.is_some_and(|last| (Utc::now() - last).num_minutes() < 5) {
return;
}
}
@@ -52,12 +160,8 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve
return;
}
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string();
let filename = format!("{}.md", timestamp);
let path = dir.join(&filename);
if let Err(e) = fs::write(&path, raw_content) {
eprintln!("Failed to write version snapshot: {}", e);
if let Err(error) = snapshot_path(&dir, raw_content) {
eprintln!("Failed to write version snapshot: {error}");
return;
}
@@ -68,31 +172,26 @@ pub fn maybe_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_ve
}
/// Force-create a version snapshot, bypassing the cooldown.
pub fn force_snapshot(vault_path: &str, note_id: &str, raw_content: &str, max_versions: u32) {
let dir = history_dir(vault_path, note_id);
pub fn force_snapshot(
vault_path: &str,
note_id: &str,
raw_content: &str,
max_versions: u32,
) -> Result<(), String> {
let dir = history_dir(vault_path, note_id)?;
fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
if let Err(e) = fs::create_dir_all(&dir) {
eprintln!("Failed to create history dir: {}", e);
return;
}
let timestamp = Utc::now().format("%Y-%m-%dT%H-%M-%S").to_string();
let filename = format!("{}.md", timestamp);
let path = dir.join(&filename);
if let Err(e) = fs::write(&path, raw_content) {
eprintln!("Failed to write version snapshot: {}", e);
return;
}
snapshot_path(&dir, raw_content)?;
if max_versions > 0 {
let _ = prune_versions(&dir, max_versions);
prune_versions(&dir, max_versions)?;
}
Ok(())
}
/// List all version snapshots for a note, newest first.
pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry>, String> {
let dir = history_dir(vault_path, note_id);
let dir = history_dir(vault_path, note_id)?;
if !dir.exists() {
return Ok(Vec::new());
}
@@ -102,7 +201,7 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
for entry in fs::read_dir(&dir).map_err(|e| e.to_string())? {
let entry = entry.map_err(|e| e.to_string())?;
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "md") {
if is_snapshot_file(&path) {
let filename = path
.file_stem()
.unwrap_or_default()
@@ -110,16 +209,7 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
.to_string();
let meta = fs::metadata(&path).map_err(|e| e.to_string())?;
// Parse timestamp from filename
let timestamp = if let Some(t_pos) = filename.find('T') {
let date_part = &filename[..t_pos];
let time_part = &filename[t_pos + 1..];
let time_colons = time_part.replace('-', ":");
format!("{}T{}Z", date_part, time_colons)
} else {
filename.clone()
};
let timestamp = version_timestamp(&filename);
entries.push(VersionEntry {
timestamp,
size: meta.len(),
@@ -134,17 +224,14 @@ pub fn list_versions(vault_path: &str, note_id: &str) -> Result<Vec<VersionEntry
/// Get the raw content of a specific version.
pub fn get_version(vault_path: &str, note_id: &str, timestamp: &str) -> Result<String, String> {
// Convert ISO timestamp back to filename: 2026-02-08T18:30:00Z → 2026-02-08T18-30-00.md
let filename = if let Some(t_pos) = timestamp.find('T') {
let date_part = &timestamp[..t_pos];
let time_part = timestamp[t_pos + 1..].trim_end_matches('Z');
let time_dashes = time_part.replace(':', "-");
format!("{}.md", format!("{}T{}", date_part, time_dashes))
} else {
format!("{}.md", timestamp)
};
safe_path_component(timestamp, "version timestamp")?;
// Accept both legacy second-resolution names and unique suffixes.
let filename = snapshot_filename(timestamp);
let path = history_dir(vault_path, note_id).join(&filename);
let path = history_dir(vault_path, note_id)?.join(&filename);
if !is_snapshot_file(&path) {
return Err("Version not found".to_string());
}
fs::read_to_string(&path).map_err(|e| format!("Version not found: {}", e))
}
@@ -154,7 +241,8 @@ fn prune_versions(dir: &Path, max: u32) -> Result<(), String> {
.map_err(|e| e.to_string())?
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.extension().map_or(false, |ext| ext == "md"))
// Only snapshots are counted and removed, never other Markdown files that ended up here.
.filter(|p| is_snapshot_file(p))
.collect();
// Sort by name (timestamps sort lexicographically) - newest last
@@ -169,3 +257,135 @@ fn prune_versions(dir: &Path, max: u32) -> Result<(), String> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::{get_version, list_versions};
use std::fs;
use uuid::Uuid;
#[test]
fn rejects_history_path_traversal() {
let vault =
std::env::temp_dir().join(format!("helixnotes-history-test-{}", Uuid::new_v4()));
let metadata = vault.join(".helixnotes");
let escaped_history = metadata.join("escaped");
fs::create_dir_all(&escaped_history).unwrap();
fs::write(escaped_history.join("2026-01-01T00-00-00.md"), "escaped").unwrap();
fs::create_dir_all(metadata.join("history").join("safe")).unwrap();
fs::write(metadata.join("secret.md"), "secret").unwrap();
assert!(list_versions(&vault.to_string_lossy(), "../escaped").is_err());
assert!(get_version(&vault.to_string_lossy(), "safe", "../../secret").is_err());
fs::remove_dir_all(vault).unwrap();
}
#[test]
fn rapid_forced_versions_are_individually_retrievable_and_prunable() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path().to_str().unwrap();
for index in 0..200 {
super::force_snapshot(root, "note", &format!("snapshot {index}"), 0).unwrap();
}
let versions = list_versions(root, "note").unwrap();
assert_eq!(versions.len(), 200);
let contents: std::collections::HashSet<_> = versions
.iter()
.map(|version| get_version(root, "note", &version.timestamp).unwrap())
.collect();
assert_eq!(contents.len(), 200);
assert!(contents.contains("snapshot 0"));
assert!(contents.contains("snapshot 199"));
super::force_snapshot(root, "note", "latest", 10).unwrap();
let retained = list_versions(root, "note").unwrap();
assert_eq!(retained.len(), 10);
assert_eq!(
get_version(root, "note", &retained[0].timestamp).unwrap(),
"latest"
);
}
#[test]
fn legacy_versions_remain_readable_and_recent_unique_versions_observe_cooldown() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path().to_str().unwrap();
let history = vault.path().join(".helixnotes/history/note");
fs::create_dir_all(&history).unwrap();
fs::write(history.join("2026-01-01T00-00-00.md"), "legacy").unwrap();
fs::write(history.join("2026-01-01T1é-00-00.md"), "unusual filename").unwrap();
super::force_snapshot(root, "note", "new", 0).unwrap();
super::maybe_snapshot(root, "note", "too soon", 0);
let versions = list_versions(root, "note").unwrap();
// The file that is not named like a snapshot is neither a version nor in the way.
assert_eq!(versions.len(), 2);
assert_eq!(
get_version(root, "note", "2026-01-01T00:00:00Z").unwrap(),
"legacy"
);
assert_eq!(
get_version(root, "note", &versions[0].timestamp).unwrap(),
"new"
);
}
#[cfg(unix)]
#[test]
fn a_linked_history_folder_is_never_written_to_or_pruned() {
use std::os::unix::fs::symlink;
let vault = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let root = vault.path().to_str().unwrap();
// A folder of ordinary notes somewhere else, more than the pruning limit.
for index in 0..25 {
fs::write(
outside.path().join(format!("note-{index:02}.md")),
"precious",
)
.unwrap();
}
let history = vault.path().join(".helixnotes/history");
fs::create_dir_all(&history).unwrap();
symlink(outside.path(), history.join("linked")).unwrap();
assert!(super::force_snapshot(root, "linked", "new", 20).is_err());
super::maybe_snapshot(root, "linked", "new", 20);
assert!(list_versions(root, "linked").is_err());
assert!(get_version(root, "linked", "note-00").is_err());
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 25);
// The same when a higher level is the link.
let second = tempfile::tempdir().unwrap();
fs::create_dir_all(second.path().join(".helixnotes")).unwrap();
symlink(outside.path(), second.path().join(".helixnotes/history")).unwrap();
assert!(super::force_snapshot(second.path().to_str().unwrap(), "note", "new", 20).is_err());
assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 25);
}
#[test]
fn pruning_and_listing_only_touch_snapshots() {
let vault = tempfile::tempdir().unwrap();
let root = vault.path().to_str().unwrap();
let history = vault.path().join(".helixnotes/history/note");
fs::create_dir_all(&history).unwrap();
// Markdown files that are not snapshots, sorting before and after real ones.
fs::write(history.join("README.md"), "keep").unwrap();
fs::write(history.join("zz-00.md"), "keep").unwrap();
fs::write(history.join("2026-01-01T00-00-00.md"), "old").unwrap();
fs::write(history.join("2026-01-02T00-00-00.123.md"), "newer").unwrap();
super::force_snapshot(root, "note", "newest", 2).unwrap();
let versions = list_versions(root, "note").unwrap();
assert_eq!(versions.len(), 2);
assert!(!history.join("2026-01-01T00-00-00.md").exists());
assert!(history.join("README.md").exists() && history.join("zz-00.md").exists());
assert!(get_version(root, "note", "zz-00").is_err());
#[cfg(unix)]
{
let target = vault.path().join("secret.md");
fs::write(&target, "outside history").unwrap();
std::os::unix::fs::symlink(&target, history.join("2026-01-03T00-00-00.md")).unwrap();
assert!(get_version(root, "note", "2026-01-03T00:00:00Z").is_err());
assert_eq!(list_versions(root, "note").unwrap().len(), 2);
}
}
}
+304
View File
@@ -0,0 +1,304 @@
use reqwest::{
blocking::{Client, Response},
redirect::Policy,
StatusCode, Url,
};
use std::io::Read;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs};
use std::time::Duration;
const MAX_IMAGE_BYTES: u64 = 20 * 1024 * 1024;
const MAX_REDIRECTS: usize = 5;
pub struct ImageResponse {
pub content_type: String,
pub body: Vec<u8>,
}
pub enum ProxyError {
Invalid(String),
Blocked(String),
Fetch(String),
}
impl ProxyError {
pub fn status(&self) -> u16 {
match self {
Self::Invalid(_) => 400,
Self::Blocked(_) => 403,
Self::Fetch(_) => 502,
}
}
pub fn message(&self) -> &str {
match self {
Self::Invalid(message) | Self::Blocked(message) | Self::Fetch(message) => message,
}
}
}
fn is_public_ipv4(ip: Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
!(a == 0
|| a == 10
|| a == 127
|| a >= 224
|| (a == 100 && (64..=127).contains(&b))
|| (a == 169 && b == 254)
|| (a == 172 && (16..=31).contains(&b))
|| (a == 192 && b == 168)
|| (a == 192 && b == 0 && c == 0)
|| (a == 192 && b == 0 && c == 2)
|| (a == 198 && (b == 18 || b == 19))
|| (a == 198 && b == 51 && c == 100)
|| (a == 203 && b == 0 && c == 113))
}
fn is_public_ipv6(ip: Ipv6Addr) -> bool {
if ip.is_unspecified() || ip.is_loopback() || ip.to_ipv4().is_some() {
return false;
}
let first = ip.segments()[0];
(0x2000..=0x3fff).contains(&first) && ip.segments()[..2] != [0x2001, 0x0db8]
}
fn is_public_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => is_public_ipv4(ip),
IpAddr::V6(ip) => is_public_ipv6(ip),
}
}
fn normalized_host(host: &str) -> String {
host.trim_start_matches('[')
.trim_end_matches(']')
.trim_end_matches('.')
.to_ascii_lowercase()
}
fn validate_url(raw_url: &str) -> Result<Url, ProxyError> {
let url = Url::parse(raw_url).map_err(|_| ProxyError::Invalid("Invalid image URL".into()))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(ProxyError::Invalid(
"Only HTTP and HTTPS images are supported".into(),
));
}
if !url.username().is_empty() || url.password().is_some() {
return Err(ProxyError::Invalid(
"Image URLs must not contain credentials".into(),
));
}
let expected_port = if url.scheme() == "https" { 443 } else { 80 };
if url.port_or_known_default() != Some(expected_port) {
return Err(ProxyError::Blocked("Non-standard image URL port".into()));
}
let host = url
.host_str()
.ok_or_else(|| ProxyError::Invalid("Image URL has no host".into()))?;
if host.ends_with('.') {
return Err(ProxyError::Invalid(
"Image URL host must not have a trailing dot".into(),
));
}
let normalized = normalized_host(host);
if normalized == "localhost" || normalized.ends_with(".localhost") {
return Err(ProxyError::Blocked(
"Local image hosts are not allowed".into(),
));
}
if let Ok(ip) = normalized.parse::<IpAddr>() {
if !is_public_ip(ip) {
return Err(ProxyError::Blocked(
"Private image addresses are not allowed".into(),
));
}
}
Ok(url)
}
fn resolve_public_host(url: &Url) -> Result<(String, Vec<SocketAddr>), ProxyError> {
let host = url
.host_str()
.ok_or_else(|| ProxyError::Invalid("Image URL has no host".into()))?;
let host = normalized_host(host);
let port = url
.port_or_known_default()
.ok_or_else(|| ProxyError::Invalid("Image URL has no port".into()))?;
let addresses: Vec<_> = (host.as_str(), port)
.to_socket_addrs()
.map_err(|error| ProxyError::Fetch(format!("Could not resolve image host: {error}")))?
.collect();
if addresses.is_empty() {
return Err(ProxyError::Fetch(
"Image host resolved to no addresses".into(),
));
}
if addresses.iter().any(|address| !is_public_ip(address.ip())) {
return Err(ProxyError::Blocked(
"Image host resolves to a private address".into(),
));
}
Ok((host, addresses))
}
// Redirects are followed by `fetch`, one hop at a time, so every hop gets the same checks.
fn image_client(host: &str, addresses: &[SocketAddr]) -> Result<Client, ProxyError> {
Client::builder()
.timeout(Duration::from_secs(30))
.redirect(Policy::none())
.resolve_to_addrs(host, addresses)
.build()
.map_err(|error| ProxyError::Fetch(format!("Could not create image client: {error}")))
}
/// The validated target of a redirect response, or `None` when the response is not a redirect.
fn redirect_target(
url: &Url,
status: StatusCode,
location: Option<&str>,
) -> Result<Option<Url>, ProxyError> {
if !matches!(status.as_u16(), 301 | 302 | 303 | 307 | 308) {
return Ok(None);
}
let target = location
.and_then(|location| url.join(location).ok())
.ok_or_else(|| ProxyError::Fetch("Image redirect has no usable target".into()))?;
validate_url(target.as_str()).map(Some)
}
pub fn fetch(raw_url: &str) -> Result<ImageResponse, ProxyError> {
let mut url = validate_url(raw_url)?;
for _ in 0..=MAX_REDIRECTS {
// Each hop is resolved, checked for private addresses and pinned to that answer,
// so a redirect cannot reach a host that a direct image URL could not.
let (host, addresses) = resolve_public_host(&url)?;
let client = image_client(&host, &addresses)?;
let response = client
.get(url.clone())
.send()
.map_err(|error| ProxyError::Fetch(format!("Image request failed: {error}")))?;
let location = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|value| value.to_str().ok());
match redirect_target(&url, response.status(), location)? {
Some(target) => url = target,
None => return read_image(response),
}
}
Err(ProxyError::Fetch("Image redirected too many times".into()))
}
fn read_image(mut response: Response) -> Result<ImageResponse, ProxyError> {
if !response.status().is_success() {
return Err(ProxyError::Fetch(format!(
"Image server returned {}",
response.status()
)));
}
if response
.content_length()
.is_some_and(|length| length > MAX_IMAGE_BYTES)
{
return Err(ProxyError::Blocked("Image exceeds the 20 MiB limit".into()));
}
let content_type = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or("")
.to_string();
if !content_type.to_ascii_lowercase().starts_with("image/") {
return Err(ProxyError::Blocked(
"Remote resource is not an image".into(),
));
}
let mut body = Vec::new();
response
.by_ref()
.take(MAX_IMAGE_BYTES + 1)
.read_to_end(&mut body)
.map_err(|error| ProxyError::Fetch(format!("Could not read image: {error}")))?;
if body.len() as u64 > MAX_IMAGE_BYTES {
return Err(ProxyError::Blocked("Image exceeds the 20 MiB limit".into()));
}
Ok(ImageResponse { content_type, body })
}
#[cfg(test)]
mod tests {
use super::{is_public_ip, redirect_target, validate_url};
use reqwest::{StatusCode, Url};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
#[test]
fn blocks_local_and_private_networks() {
for ip in [
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1)),
IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254)),
IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
IpAddr::V6(Ipv6Addr::LOCALHOST),
"fc00::1".parse().unwrap(),
"fe80::1".parse().unwrap(),
] {
assert!(!is_public_ip(ip), "{ip}");
}
assert!(is_public_ip("93.184.216.34".parse().unwrap()));
assert!(is_public_ip(
"2606:2800:220:1:248:1893:25c8:1946".parse().unwrap()
));
}
#[test]
fn validates_only_public_web_image_urls() {
for url in [
"file:///etc/passwd",
"http://localhost/image.png",
"http://127.0.0.1/image.png",
"http://[::1]/image.png",
"http://example.com:8080/image.png",
"https://example.com./image.png",
"https://user:pass@example.com/image.png",
] {
assert!(validate_url(url).is_err(), "{url}");
}
assert!(validate_url("https://example.com/image.png").is_ok());
assert!(validate_url("http://93.184.216.34/image.png").is_ok());
}
#[test]
fn redirects_are_followed_to_other_public_hosts_only() {
let url = Url::parse("https://example.com/a/image.png").unwrap();
let target = |status: u16, location: Option<&str>| {
redirect_target(&url, StatusCode::from_u16(status).unwrap(), location)
};
let ok = |status, location| target(status, Some(location)).ok().unwrap().unwrap();
assert_eq!(
ok(301, "https://cdn.example.net/image.png").as_str(),
"https://cdn.example.net/image.png"
);
assert_eq!(
ok(302, "/b/image.png").as_str(),
"https://example.com/b/image.png"
);
assert_eq!(
ok(307, "other.png").as_str(),
"https://example.com/a/other.png"
);
assert!(target(200, None).ok().unwrap().is_none());
assert!(target(304, None).ok().unwrap().is_none());
for location in [
"http://localhost/image.png",
"http://127.0.0.1/image.png",
"http://169.254.169.254/latest/meta-data",
"http://[::1]/image.png",
"https://example.net:8443/image.png",
"https://user:pass@example.net/image.png",
"file:///etc/passwd",
] {
assert!(target(302, Some(location)).is_err(), "{location}");
}
assert!(target(302, None).is_err());
}
}
+211 -91
View File
@@ -1,7 +1,9 @@
mod ai;
mod asset_scope;
mod backup;
mod commands;
mod history;
mod image_proxy;
mod search;
mod state;
mod sync;
@@ -11,6 +13,7 @@ mod vault;
use state::AppState;
#[allow(unused_imports)]
use tauri::{Emitter, Manager};
use tauri_plugin_fs::FsExt;
#[cfg(desktop)]
use tauri::{
@@ -34,8 +37,6 @@ pub fn run() {
let config = commands::load_app_config();
#[cfg(desktop)]
let show_tray = config.show_tray_icon;
#[cfg(desktop)]
let close_to_tray = config.close_to_tray && show_tray;
let app_state = AppState::new(config);
// Inject the compile-time platform so the frontend never sniffs the (sometimes
@@ -56,7 +57,30 @@ pub fn run() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_opener::init())
.on_webview_event(|webview, event| {
if let tauri::WebviewEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) = event {
let scope = webview.fs_scope();
for path in paths {
if path.is_file() {
let _ = scope.allow_file(path);
}
}
}
})
.on_page_load(|webview, payload| {
#[cfg(target_os = "macos")]
if webview.label() == "main"
&& matches!(payload.event(), tauri::webview::PageLoadEvent::Finished)
{
queue_macos_traffic_light_fix(&webview.window());
}
#[cfg(not(target_os = "macos"))]
let _ = (webview, payload);
})
.setup(move |app| {
#[cfg(target_os = "ios")]
app.handle().plugin(tauri_plugin_ios_vault_access::init())?;
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
@@ -80,6 +104,20 @@ pub fn run() {
});
}
let active_vault = app
.state::<AppState>()
.config
.lock()
.ok()
.and_then(|config| config.active_vault.clone());
if let Some(vault_path) = active_vault {
if let Err(error) =
asset_scope::allow_vault_assets(app.handle(), std::path::Path::new(&vault_path))
{
log::warn!("Failed to restore the vault asset scope: {error}");
}
}
#[cfg(desktop)]
if show_tray {
setup_tray(app)?;
@@ -99,10 +137,18 @@ pub fn run() {
std::env::current_dir().unwrap_or_default().join(&path)
};
if let Some(resolved_str) = resolved.to_str() {
if resolved.is_file() {
let _ = app.fs_scope().allow_file(&resolved);
if let Some(parent) = resolved.parent() {
let _ = app.fs_scope().allow_directory(parent, true);
}
let _ =
asset_scope::allow_external_note_assets(app.handle(), &resolved);
}
let app_state = app.state::<AppState>();
let _ = app_state.pending_open_file.lock().map(|mut p| {
*p = Some(resolved_str.to_string());
});
if let Err(error) = app_state.enqueue_open_file(resolved_str.to_string()) {
log::error!("Could not queue startup file: {error}");
}
}
}
}
@@ -112,15 +158,22 @@ pub fn run() {
.manage(app_state)
.invoke_handler(tauri::generate_handler![
commands::open_vault,
commands::choose_external_vault,
commands::restore_external_vault,
commands::remove_vault,
commands::get_app_config,
#[cfg(desktop)]
commands::complete_window_close,
commands::set_theme,
commands::set_system_themes,
commands::set_accent_color,
commands::save_custom_theme,
commands::delete_custom_theme,
commands::export_custom_theme,
commands::import_custom_themes,
commands::set_font_size,
commands::set_scroll_to_change_font_size,
commands::set_toolbar_layout,
commands::set_font_family,
commands::set_line_height,
commands::set_ui_scale,
@@ -134,13 +187,16 @@ pub fn run() {
commands::get_notes,
commands::read_note,
commands::save_note,
commands::import_note,
commands::create_note,
commands::duplicate_note,
commands::create_daily_note,
commands::rename_note,
commands::delete_note,
commands::move_note,
commands::get_all_tags,
commands::get_all_note_titles,
commands::get_note_switcher_titles,
commands::get_graph_data,
commands::get_tasks,
commands::set_task_done,
@@ -155,12 +211,18 @@ pub fn run() {
commands::empty_trash,
commands::load_vault_state,
commands::save_vault_state,
commands::copy_text_to_clipboard,
commands::read_clipboard_contents,
commands::read_clipboard_image,
commands::copy_image_to_clipboard,
commands::save_image,
commands::save_attachment,
commands::get_notebook_icons,
commands::set_notebook_icon,
commands::import_notebook_icon,
commands::get_tag_styles,
commands::set_tag_style,
commands::import_tag_icon,
commands::set_general_settings,
commands::get_quick_access,
commands::add_quick_access,
@@ -171,6 +233,7 @@ pub fn run() {
commands::trash_orphaned_attachments,
commands::import_obsidian,
commands::open_file,
commands::reveal_file,
commands::open_url,
commands::copy_file_to,
commands::write_bytes_to,
@@ -192,78 +255,30 @@ pub fn run() {
commands::get_install_type,
commands::is_mobile_platform,
commands::get_pending_open_file,
commands::ack_pending_open_file,
#[cfg(desktop)]
commands::cancel_window_close,
])
.register_asynchronous_uri_scheme_protocol("imgproxy", |_ctx, request, responder| {
let path = request.uri().path().to_string();
std::thread::spawn(move || {
let encoded = path.strip_prefix('/').unwrap_or(&path);
let external_url = percent_decode(encoded);
if !external_url.starts_with("http://") && !external_url.starts_with("https://") {
let _ = responder.respond(
let response = match image_proxy::fetch(&external_url) {
Ok(image) => tauri::http::Response::builder()
.status(200)
.header("Content-Type", image.content_type)
.header("Access-Control-Allow-Origin", "*")
.header("X-Content-Type-Options", "nosniff")
.body(image.body),
Err(error) => {
log::warn!("Blocked external image request: {}", error.message());
tauri::http::Response::builder()
.status(400)
.status(error.status())
.body(Vec::new())
.unwrap(),
);
return;
}
let client = match reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
{
Ok(c) => c,
Err(_) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(502)
.body(Vec::new())
.unwrap(),
);
return;
}
};
match client.get(&external_url).send() {
Ok(resp) => {
let content_type = resp
.headers()
.get("content-type")
.and_then(|h| h.to_str().ok())
.unwrap_or("application/octet-stream")
.to_string();
let status = resp.status().as_u16();
match resp.bytes() {
Ok(bytes) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(status)
.header("Content-Type", &content_type)
.header("Access-Control-Allow-Origin", "*")
.body(bytes.to_vec())
.unwrap(),
);
}
Err(_) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(502)
.body(Vec::new())
.unwrap(),
);
}
}
}
Err(_) => {
let _ = responder.respond(
tauri::http::Response::builder()
.status(502)
.body(Vec::new())
.unwrap(),
);
}
}
responder.respond(response.expect("valid image proxy response"));
});
});
@@ -290,42 +305,91 @@ pub fn run() {
std::path::Path::new(&cwd).join(path)
};
if let Some(resolved_str) = resolved.to_str() {
let _ = app.emit("open-file", resolved_str.to_string());
if resolved.is_file() {
let _ = app.fs_scope().allow_file(&resolved);
if let Some(parent) = resolved.parent() {
let _ = app.fs_scope().allow_directory(parent, true);
}
let _ = asset_scope::allow_external_note_assets(app, &resolved);
}
if let Err(error) = app
.state::<AppState>()
.enqueue_open_file(resolved_str.to_string())
{
log::error!("Could not queue open file: {error}");
} else {
let _ = app.emit("open-file-pending", ());
}
}
}
}));
builder = builder.plugin(tauri_plugin_updater::Builder::new().build());
builder = builder.plugin(tauri_plugin_window_state::Builder::default().build());
let window_state_builder = tauri_plugin_window_state::Builder::default();
#[cfg(target_os = "linux")]
let window_state_builder = window_state_builder.with_state_flags(
tauri_plugin_window_state::StateFlags::SIZE
| tauri_plugin_window_state::StateFlags::POSITION
| tauri_plugin_window_state::StateFlags::MAXIMIZED
| tauri_plugin_window_state::StateFlags::DECORATIONS
| tauri_plugin_window_state::StateFlags::FULLSCREEN,
);
builder = builder.plugin(window_state_builder.build());
builder = builder.on_window_event(move |window, event| {
match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
// Only hide to tray for the main window
if close_to_tray && window.label() == "main" {
api.prevent_close();
let _ = window.hide();
#[cfg(target_os = "macos")]
if window.label() == "main"
&& matches!(
event,
tauri::WindowEvent::Resized(_)
| tauri::WindowEvent::Focused(true)
| tauri::WindowEvent::ScaleFactorChanged { .. }
| tauri::WindowEvent::ThemeChanged(_)
)
{
// AppKit can restore the default button Y position after window-state
// changes. Queue this pass so it runs after AppKit finishes its layout.
queue_macos_traffic_light_fix(window);
}
// Closing the main window also requests a save-aware close of note windows.
if matches!(event, tauri::WindowEvent::Destroyed) && window.label() == "main" {
for (label, win) in window.app_handle().webview_windows() {
if label.starts_with("note-") {
let _ = win.close();
}
}
tauri::WindowEvent::Destroyed => {
// When main window is destroyed, close all note windows
if window.label() == "main" {
let app = window.app_handle();
for (label, win) in app.webview_windows() {
if label.starts_with("note-") {
let _ = win.close();
}
}
}
}
_ => {}
}
});
}
builder
.run(tauri::generate_context!())
.expect("error while running tauri application");
let app = builder
.build(tauri::generate_context!())
.expect("error while building tauri application");
app.run(|app, event| {
#[cfg(desktop)]
if let tauri::RunEvent::ExitRequested {
code: Some(_), api, ..
} = event
{
let windows = app.webview_windows();
if !windows.is_empty() {
// Menu/tray Quit must give each editor the same save opportunity
// as a window close. The app exits once the last window closes.
api.prevent_exit();
app.state::<AppState>()
.quitting
.store(true, std::sync::atomic::Ordering::Relaxed);
for window in windows.values() {
if let Err(error) = window.close() {
log::error!("Failed to close window during quit: {error}");
}
}
}
}
#[cfg(mobile)]
let _ = (app, event);
});
}
#[cfg(desktop)]
@@ -334,7 +398,7 @@ fn setup_tray(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let quit = MenuItemBuilder::with_id("quit", "Quit").build(app)?;
let menu = MenuBuilder::new(app).items(&[&show, &quit]).build()?;
let _tray = TrayIconBuilder::new()
let _tray = TrayIconBuilder::with_id("helixnotes")
.icon(
Image::from_path("icons/32x32.png")
.unwrap_or_else(|_| app.default_window_icon().cloned().unwrap()),
@@ -387,3 +451,59 @@ fn percent_decode(input: &str) -> String {
}
String::from_utf8_lossy(&output).to_string()
}
#[cfg(target_os = "macos")]
fn queue_macos_traffic_light_fix(window: &tauri::Window) {
let window_on_main = window.clone();
let _ = window.run_on_main_thread(move || {
fix_macos_traffic_lights(&window_on_main);
});
}
#[cfg(target_os = "macos")]
fn fix_macos_traffic_lights(window: &tauri::Window) {
use objc2_app_kit::{NSView, NSWindow, NSWindowButton};
const TITLEBAR_HEIGHT: f64 = 34.0;
const LEFT_INSET: f64 = 12.0;
let ns_window_ptr = match window.ns_window() {
Ok(ptr) => ptr,
Err(_) => return,
};
let ns_window: &NSWindow = unsafe { &*(ns_window_ptr as *const NSWindow) };
let close = match ns_window.standardWindowButton(NSWindowButton::CloseButton) {
Some(button) => button,
None => return,
};
let miniaturize = match ns_window.standardWindowButton(NSWindowButton::MiniaturizeButton) {
Some(button) => button,
None => return,
};
let zoom = match ns_window.standardWindowButton(NSWindowButton::ZoomButton) {
Some(button) => button,
None => return,
};
let window_height = ns_window.frame().size.height;
if window_height <= 0.0 {
return;
}
let close_frame = NSView::frame(&close);
let button_spacing = NSView::frame(&miniaturize).origin.x - close_frame.origin.x;
for (index, button) in [&close, &miniaturize, &zoom].into_iter().enumerate() {
let button_superview = match unsafe { button.superview() } {
Some(view) => view,
None => return,
};
let mut frame = NSView::frame(button);
let top_inset = ((TITLEBAR_HEIGHT - frame.size.height) / 2.0).max(0.0);
let mut target = frame.origin;
target.y = window_height - top_inset - frame.size.height;
frame.origin.y = button_superview.convertPoint_fromView(target, None).y;
frame.origin.x = LEFT_INSET + index as f64 * button_spacing;
button.setFrameOrigin(frame.origin);
}
}
+1 -1
View File
@@ -2,5 +2,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
app_lib::run();
}
+1518 -218
View File
File diff suppressed because it is too large. Load diff
+292 -8
View File
@@ -1,28 +1,312 @@
use crate::search::SearchIndex;
use crate::search::{SearchIndex, SearchIndexShutdown};
use crate::types::AppConfig;
use notify::RecommendedWatcher;
use crate::vault::watcher::VaultWatcher;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::AtomicBool;
use std::sync::Mutex;
use std::sync::Arc;
use std::sync::{Arc, Mutex, Weak};
use tauri::AppHandle;
#[cfg(desktop)]
use tauri::{Manager, Runtime, Url};
#[cfg(desktop)]
fn is_detached_window_for_vault(label: &str, url: &Url, target_path: &str) -> bool {
label.starts_with("note-")
&& url
.query_pairs()
.any(|(key, value)| key == "vault" && value == target_path)
}
struct CachedSearchIndex {
index: Weak<SearchIndex>,
shutdown: Arc<SearchIndexShutdown>,
}
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PendingOpenFile {
pub id: u64,
pub path: String,
}
#[derive(Default)]
struct PendingOpenFiles {
next_id: u64,
requests: VecDeque<PendingOpenFile>,
}
pub struct AppState {
pub config: Mutex<AppConfig>,
pub search_index: Mutex<Option<Arc<SearchIndex>>>,
pub watcher: Mutex<Option<RecommendedWatcher>>,
search_indexes: Mutex<HashMap<String, CachedSearchIndex>>,
pub watchers: Mutex<HashMap<String, VaultWatcher>>,
pub vault_transition: tokio::sync::Mutex<()>,
pub vault_maintenance: Arc<tokio::sync::Mutex<()>>,
pub note_save: Arc<tokio::sync::Mutex<()>>,
pub importing: AtomicBool,
pub syncing: AtomicBool,
pub pending_open_file: Mutex<Option<String>>,
#[cfg(desktop)]
pub quitting: AtomicBool,
pending_open_files: Mutex<PendingOpenFiles>,
}
impl AppState {
pub fn enqueue_open_file(&self, path: String) -> Result<(), String> {
let mut pending = self
.pending_open_files
.lock()
.map_err(|error| error.to_string())?;
pending.next_id += 1;
let id = pending.next_id;
pending.requests.push_back(PendingOpenFile { id, path });
Ok(())
}
pub fn peek_pending_open_file(&self) -> Result<Option<PendingOpenFile>, String> {
let pending = self
.pending_open_files
.lock()
.map_err(|error| error.to_string())?;
Ok(pending.requests.front().cloned())
}
pub fn ack_pending_open_file(&self, id: u64) -> Result<bool, String> {
let mut pending = self
.pending_open_files
.lock()
.map_err(|error| error.to_string())?;
if pending
.requests
.front()
.is_some_and(|request| request.id == id)
{
pending.requests.pop_front();
Ok(true)
} else {
Ok(false)
}
}
pub fn ensure_vault_watcher(&self, app: &AppHandle, vault_path: &str) -> Result<(), String> {
let mut watchers = self.watchers.lock().map_err(|error| error.to_string())?;
if !watchers.contains_key(vault_path) {
let watcher = crate::vault::watcher::start_watcher(app.clone(), vault_path.to_owned())?;
watchers.insert(vault_path.to_owned(), watcher);
}
Ok(())
}
pub fn retain_vault_watchers(&self) -> Result<(), String> {
let configured: HashSet<String> = {
let config = self.config.lock().map_err(|error| error.to_string())?;
config
.vaults
.iter()
.map(|vault| vault.path.clone())
.chain(config.active_vault.clone())
.collect()
};
let removed = {
let mut watchers = self.watchers.lock().map_err(|error| error.to_string())?;
let removed: Vec<String> = watchers
.keys()
.filter(|path| !configured.contains(*path))
.cloned()
.collect();
removed
.into_iter()
.filter_map(|path| watchers.remove(&path))
.collect::<Vec<_>>()
};
drop(removed);
Ok(())
}
#[cfg(desktop)]
pub fn ensure_no_detached_windows<R: Runtime>(
app: &AppHandle<R>,
target_path: &str,
) -> Result<(), String> {
for (label, window) in app.webview_windows() {
if is_detached_window_for_vault(
&label,
&window.url().map_err(|error| error.to_string())?,
target_path,
) {
return Err(
"Close this vault's detached note windows before forgetting it.".into(),
);
}
}
Ok(())
}
// A refresh worker may outlive a vault switch. Reuse its writer when opening
// that vault again instead of competing for Tantivy's exclusive writer lock.
pub fn search_index_for_vault(&self, vault_path: &str) -> Result<Arc<SearchIndex>, String> {
let mut indexes = self
.search_indexes
.lock()
.map_err(|error| error.to_string())?;
indexes
.retain(|_, cached| cached.index.strong_count() > 0 || !cached.shutdown.is_finished());
if let Some(cached) = indexes.get(vault_path) {
if let Some(index) = cached.index.upgrade() {
return Ok(index);
}
// The last Arc is gone, but its writer may still be shutting down.
cached.shutdown.wait();
}
let index = Arc::new(SearchIndex::new(vault_path)?);
indexes.insert(
vault_path.to_owned(),
CachedSearchIndex {
index: Arc::downgrade(&index),
shutdown: index.shutdown_signal(),
},
);
Ok(index)
}
pub fn validate_vault(&self, vault_path: &str) -> Result<(), String> {
let config = self.config.lock().map_err(|error| error.to_string())?;
if config.active_vault.as_deref() == Some(vault_path)
|| config.vaults.iter().any(|vault| vault.path == vault_path)
{
Ok(())
} else {
Err("Unknown vault".to_string())
}
}
pub fn vault_snapshot(&self, vault_path: &str) -> Result<Option<Arc<SearchIndex>>, String> {
let search = self
.search_index
.lock()
.map_err(|error| error.to_string())?;
let config = self.config.lock().map_err(|error| error.to_string())?;
if config.active_vault.as_deref() == Some(vault_path) {
return Ok(search.clone());
}
if !config.vaults.iter().any(|vault| vault.path == vault_path) {
return Err("Unknown vault".to_string());
}
drop(config);
drop(search);
// Detached windows retain access to configured vaults. Never pair their
// writes with the main window's index, nor hold config during disk I/O.
self.search_index_for_vault(vault_path).map(Some)
}
pub fn active_vault_snapshot(&self) -> Result<(String, Option<Arc<SearchIndex>>), String> {
// Match vault transition and watcher lock order. The vault and its
// optional index must remain paired even if a switch follows the read.
let search = self
.search_index
.lock()
.map_err(|error| error.to_string())?;
let config = self.config.lock().map_err(|error| error.to_string())?;
Ok((
config.active_vault.clone().ok_or("No active vault")?,
search.clone(),
))
}
pub fn active_search(&self) -> Result<(Arc<SearchIndex>, String), String> {
let (vault_path, search) = self.active_vault_snapshot()?;
Ok((search.ok_or("Search index not initialized")?, vault_path))
}
#[cfg(desktop)]
pub fn should_hide_to_tray(&self, label: &str, tray_available: bool) -> Result<bool, String> {
if label != "main"
|| !tray_available
|| self.quitting.load(std::sync::atomic::Ordering::Relaxed)
{
return Ok(false);
}
let config = self.config.lock().map_err(|error| error.to_string())?;
Ok(config.show_tray_icon && config.close_to_tray)
}
pub fn new(config: AppConfig) -> Self {
Self {
config: Mutex::new(config),
search_index: Mutex::new(None),
watcher: Mutex::new(None),
search_indexes: Mutex::new(HashMap::new()),
watchers: Mutex::new(HashMap::new()),
vault_transition: tokio::sync::Mutex::new(()),
vault_maintenance: Arc::new(tokio::sync::Mutex::new(())),
note_save: Arc::new(tokio::sync::Mutex::new(())),
importing: AtomicBool::new(false),
syncing: AtomicBool::new(false),
pending_open_file: Mutex::new(None),
#[cfg(desktop)]
quitting: AtomicBool::new(false),
pending_open_files: Mutex::new(PendingOpenFiles::default()),
}
}
}
#[cfg(all(test, desktop))]
mod tests {
use super::*;
#[test]
fn pending_open_requests_survive_reads_and_only_acknowledge_head() {
let state = AppState::new(AppConfig::default());
state.enqueue_open_file("one.md".into()).unwrap();
state.enqueue_open_file("two.md".into()).unwrap();
let first = state.peek_pending_open_file().unwrap().unwrap();
assert_eq!(first.path, "one.md");
assert_eq!(
state.peek_pending_open_file().unwrap().unwrap().id,
first.id
);
assert!(!state.ack_pending_open_file(first.id + 1).unwrap());
assert_eq!(
state.peek_pending_open_file().unwrap().unwrap().id,
first.id
);
assert!(state.ack_pending_open_file(first.id).unwrap());
let second = state.peek_pending_open_file().unwrap().unwrap();
assert_eq!(second.path, "two.md");
assert!(!state.ack_pending_open_file(first.id).unwrap());
assert!(state.ack_pending_open_file(second.id).unwrap());
assert!(state.peek_pending_open_file().unwrap().is_none());
}
#[test]
fn detached_window_owner_matches_encoded_vault_path_only() {
let url = Url::parse("tauri://localhost/?note=a.md&vault=%2Fvaults%2FA%26B").unwrap();
assert!(is_detached_window_for_vault(
"note-123",
&url,
"/vaults/A&B"
));
assert!(!is_detached_window_for_vault("note-123", &url, "/vaults/A"));
assert!(!is_detached_window_for_vault("main", &url, "/vaults/A&B"));
}
#[test]
fn close_policy_respects_live_settings_window_type_and_explicit_quit() {
let mut state = AppState::new(AppConfig {
show_tray_icon: true,
close_to_tray: true,
..AppConfig::default()
});
assert!(state.should_hide_to_tray("main", true).unwrap());
assert!(!state.should_hide_to_tray("note-123", true).unwrap());
assert!(!state.should_hide_to_tray("main", false).unwrap());
state
.quitting
.store(true, std::sync::atomic::Ordering::Relaxed);
assert!(!state.should_hide_to_tray("main", true).unwrap());
state
.quitting
.store(false, std::sync::atomic::Ordering::Relaxed);
state.config.get_mut().unwrap().close_to_tray = false;
assert!(!state.should_hide_to_tray("main", true).unwrap());
state.config.get_mut().unwrap().close_to_tray = true;
state.config.get_mut().unwrap().show_tray_icon = false;
assert!(!state.should_hide_to_tray("main", true).unwrap());
}
}
+2223 -258
View File
File diff suppressed because it is too large. Load diff
+236 -6
View File
@@ -42,6 +42,37 @@ pub struct NotebookEntry {
pub note_count: usize,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct TagStyle {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "lowercase")]
pub enum TagStyleChange {
Icon(Option<String>),
Color(Option<String>),
Reset,
}
impl TagStyle {
pub fn is_empty(&self) -> bool {
self.icon
.as_ref()
.map(|value| value.trim().is_empty())
.unwrap_or(true)
&& self
.color
.as_ref()
.map(|value| value.trim().is_empty())
.unwrap_or(true)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteContent {
pub path: String,
@@ -54,6 +85,8 @@ pub struct NoteContent {
pub struct VaultConfig {
pub path: String,
pub name: String,
#[serde(default)]
pub bookmark_id: Option<String>,
// Per-vault WebDAV sync (was previously global on AppConfig; those fields are kept deprecated for migration).
#[serde(default)]
pub sync_provider: Option<String>,
@@ -69,8 +102,13 @@ pub struct VaultConfig {
pub sync_on_change: bool,
#[serde(default)]
pub sync_interval_minutes: u32,
/// Folders to list on the server at once; 0 means the default.
#[serde(default)]
pub sync_folder_requests: u32,
#[serde(default)]
pub last_sync_time: Option<String>,
#[serde(default)]
pub last_backup_time: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -94,15 +132,76 @@ pub struct CustomTheme {
pub colors: CustomThemeColors,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StartupView {
Daily,
QuickAccess,
Tasks,
#[default]
#[serde(other)]
All,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolbarLayout {
pub main: Vec<String>,
pub more: Vec<String>,
}
/// Keeps the entries of a list that still parse and drops the rest, so one damaged entry (a custom
/// theme missing a color, say) does not make the whole configuration unreadable.
fn lenient_list<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::de::DeserializeOwned,
{
let values = Vec::<serde_json::Value>::deserialize(deserializer).unwrap_or_default();
Ok(values
.into_iter()
.filter_map(|value| serde_json::from_value(value).ok())
.collect())
}
/// An optional setting that no longer parses is treated as not set.
fn lenient_option<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::de::DeserializeOwned,
{
let value = serde_json::Value::deserialize(deserializer).unwrap_or(serde_json::Value::Null);
Ok(serde_json::from_value(value).ok())
}
// Missing keys take their default: a configuration written by an older version, or edited by
// hand, must still load instead of being replaced by a blank one.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AppConfig {
#[serde(deserialize_with = "lenient_list")]
pub vaults: Vec<VaultConfig>,
pub active_vault: Option<String>,
#[serde(default)]
pub active_bookmark_id: Option<String>,
pub theme: String,
/// Themes used when `theme` is "system": the frontend picks one by the OS color scheme.
/// Default to the plain "light"/"dark" schemes so existing configs keep their behavior.
#[serde(default = "default_system_light_theme")]
pub system_light_theme: String,
#[serde(default = "default_system_dark_theme")]
pub system_dark_theme: String,
#[serde(default)]
pub accent_color: Option<String>,
#[serde(default)]
pub font_size: Option<u32>,
/// The size chosen in Appearance. Zooming changes `font_size` only, and resetting the zoom
/// returns to this.
#[serde(default)]
pub preferred_font_size: Option<u32>,
#[serde(default = "default_true")]
pub scroll_to_change_font_size: bool,
#[serde(default, deserialize_with = "lenient_option")]
pub toolbar_layout: Option<ToolbarLayout>,
#[serde(default)]
pub font_family: Option<String>,
#[serde(default)]
@@ -116,6 +215,8 @@ pub struct AppConfig {
#[serde(default = "default_true")]
pub show_note_dates: bool,
#[serde(default)]
pub show_note_switcher: bool,
#[serde(default)]
pub time_format: String,
#[serde(default = "default_week_start")]
pub week_start: String,
@@ -156,8 +257,6 @@ pub struct AppConfig {
#[serde(default)]
pub backup_location: Option<String>,
#[serde(default)]
pub last_backup_time: Option<String>,
#[serde(default)]
pub backup_include_attachments: bool,
#[serde(default = "default_max_versions")]
pub max_versions_per_note: u32,
@@ -182,12 +281,16 @@ pub struct AppConfig {
#[serde(default)]
pub default_view_mode: bool,
#[serde(default)]
pub new_notes_in_source_mode: bool,
#[serde(default)]
pub show_tray_icon: bool,
#[serde(default)]
pub close_to_tray: bool,
#[serde(default = "default_true")]
pub enable_wiki_links: bool,
#[serde(default)]
pub startup_view: StartupView,
#[serde(default)]
pub restore_last_session: bool,
// DEPRECATED: WebDAV sync moved to per-vault VaultConfig. Kept for one release to migrate old configs.
#[serde(default)]
@@ -206,7 +309,7 @@ pub struct AppConfig {
pub sync_interval_minutes: u32,
#[serde(default)]
pub last_sync_time: Option<String>,
#[serde(default)]
#[serde(default, deserialize_with = "lenient_list")]
pub custom_themes: Vec<CustomTheme>,
}
@@ -247,7 +350,15 @@ fn default_max_versions() -> u32 {
}
fn default_ai_model() -> String {
"claude-sonnet-4-6".to_string()
"claude-sonnet-5".to_string()
}
fn default_system_light_theme() -> String {
"light".to_string()
}
fn default_system_dark_theme() -> String {
"dark".to_string()
}
impl Default for AppConfig {
@@ -255,15 +366,22 @@ impl Default for AppConfig {
Self {
vaults: Vec::new(),
active_vault: None,
active_bookmark_id: None,
theme: "system".to_string(),
system_light_theme: default_system_light_theme(),
system_dark_theme: default_system_dark_theme(),
accent_color: None,
font_size: None,
preferred_font_size: None,
scroll_to_change_font_size: true,
toolbar_layout: None,
font_family: None,
line_height: None,
ui_scale: None,
content_width: None,
compact_notes: false,
show_note_dates: true,
show_note_switcher: false,
time_format: "relative".to_string(),
week_start: "monday".to_string(),
daily_title_format: "localized".to_string(),
@@ -284,7 +402,6 @@ impl Default for AppConfig {
backup_frequency: "24h".to_string(),
backup_max_count: 10,
backup_location: None,
last_backup_time: None,
backup_include_attachments: false,
max_versions_per_note: 20,
ai_provider: None,
@@ -294,12 +411,14 @@ impl Default for AppConfig {
ollama_api_key: None,
openai_compatible_base_url: None,
openai_compatible_api_key: None,
ai_model: "claude-sonnet-4-6".to_string(),
ai_model: default_ai_model(),
ai_writing_style: None,
default_view_mode: false,
new_notes_in_source_mode: false,
show_tray_icon: false,
close_to_tray: false,
enable_wiki_links: true,
startup_view: StartupView::All,
restore_last_session: false,
sync_provider: None,
webdav_url: None,
@@ -375,24 +494,66 @@ impl Default for VaultState {
}
}
/// Half-open UTF-16 offsets into the corresponding plain-text result field.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchMatch {
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SearchTargetField {
Body,
Title,
Tags,
}
/// Half-open UTF-16 offsets into the indexed field, with exact source context.
/// Body excludes frontmatter; tags use the indexed space-joined values.
/// Text is capped at 240 Unicode scalars and each context at 32 scalars.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchTarget {
pub field: SearchTargetField,
pub start: usize,
pub end: usize,
pub text: String,
pub before: String,
pub after: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
pub path: String,
pub title: String,
pub snippet: String,
pub score: f32,
pub title_matches: Vec<SearchMatch>,
pub snippet_matches: Vec<SearchMatch>,
pub match_target: Option<SearchTarget>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SearchPage {
pub results: Vec<SearchResult>,
pub total: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEvent {
pub vault_path: String,
pub event_type: String,
pub path: String,
pub note: Option<NoteEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportResult {
pub files_converted: u64,
pub links_converted: u64,
pub frontmatter_normalized: u64,
pub syntax_converted: u64,
pub attachments_moved: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -410,6 +571,9 @@ pub struct BackupEntry {
pub path: String,
pub size: u64,
pub created: String,
/// The archive was made from a different vault folder. All vaults share one backup folder.
#[serde(default)]
pub other_vault: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -420,6 +584,7 @@ pub struct VersionEntry {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AiStreamEvent {
pub request_id: String,
pub event_type: String, // "text", "done", "error"
pub text: Option<String>,
pub error: Option<String>,
@@ -461,3 +626,68 @@ pub struct TaskItem {
pub due: Option<String>,
pub priority: Option<String>,
}
#[cfg(test)]
mod startup_view_tests {
use super::{AppConfig, StartupView};
#[test]
fn serializes_supported_startup_views() {
for (view, expected) in [
(StartupView::All, "\"all\""),
(StartupView::QuickAccess, "\"quickaccess\""),
(StartupView::Tasks, "\"tasks\""),
(StartupView::Daily, "\"daily\""),
] {
assert_eq!(serde_json::to_string(&view).unwrap(), expected);
}
}
#[test]
fn unknown_startup_view_falls_back_to_all_notes() {
assert_eq!(
serde_json::from_str::<StartupView>("\"future-view\"").unwrap(),
StartupView::All
);
}
#[test]
fn existing_configs_default_system_theme_pair() {
let mut value = serde_json::to_value(AppConfig::default()).unwrap();
let object = value.as_object_mut().unwrap();
object.remove("system_light_theme");
object.remove("system_dark_theme");
let config: AppConfig = serde_json::from_value(value).unwrap();
assert_eq!(config.system_light_theme, "light");
assert_eq!(config.system_dark_theme, "dark");
}
#[test]
fn note_switcher_is_opt_in_for_new_and_existing_configs() {
let config = AppConfig::default();
assert!(!config.show_note_switcher);
let mut value = serde_json::to_value(config).unwrap();
value.as_object_mut().unwrap().remove("show_note_switcher");
let config: AppConfig = serde_json::from_value(value).unwrap();
assert!(!config.show_note_switcher);
}
#[test]
fn scroll_font_sizing_stays_enabled_for_new_and_existing_configs() {
let config = AppConfig::default();
assert!(config.scroll_to_change_font_size);
let mut value = serde_json::to_value(config).unwrap();
value
.as_object_mut()
.unwrap()
.remove("scroll_to_change_font_size");
let config: AppConfig = serde_json::from_value(value).unwrap();
assert!(config.scroll_to_change_font_size);
}
}
+357 -51
View File
@@ -1,9 +1,70 @@
use crate::types::NoteMeta;
use chrono::{NaiveDate, NaiveDateTime, Utc};
use gray_matter::engine::YAML;
use gray_matter::Matter;
use gray_matter::engine::{Engine, YAML as UnboundedYaml};
use gray_matter::{Matter, Pod};
use serde::{Deserialize, Serialize};
const MAX_FRONTMATTER_BYTES: usize = 64 * 1024;
const MAX_FRONTMATTER_ALIASES: usize = 16;
const MAX_FRONTMATTER_INDENT: usize = 200;
const MAX_FRONTMATTER_INDICATORS: usize = 32;
/// YAML frontmatter engine for notes, which are untrusted input (sync, import, shared vaults).
/// The underlying loader expands every alias by copying and recurses once per nesting level, so a
/// note of a few hundred bytes could take gigabytes or overflow the stack and take the app down
/// at every start. Frontmatter outside these bounds is treated as carrying no metadata.
pub struct BoundedYaml;
impl Engine for BoundedYaml {
fn parse(content: &str) -> Pod {
if frontmatter_within_bounds(content) {
UnboundedYaml::parse(content)
} else {
Pod::Null
}
}
}
fn frontmatter_within_bounds(content: &str) -> bool {
if content.len() > MAX_FRONTMATTER_BYTES {
return false;
}
// Aliases multiply: with few of them the expansion stays small whatever they point at.
let bytes = content.as_bytes();
let aliases = bytes
.iter()
.enumerate()
.filter(|&(index, &byte)| {
byte == b'*'
&& (index == 0
|| matches!(
bytes[index - 1],
b' ' | b'\t' | b'\n' | b'[' | b',' | b':' | b'-' | b'{'
))
&& bytes
.get(index + 1)
.is_some_and(|next| next.is_ascii_alphanumeric() || matches!(next, b'_' | b'-'))
})
.count();
if aliases > MAX_FRONTMATTER_ALIASES {
return false;
}
// Block nesting deepens by indentation, or by indicators chained on one line (`- - - x`).
content.lines().all(|line| {
let indent = line.len() - line.trim_start_matches(' ').len();
let mut rest = &line.as_bytes()[indent..];
let mut indicators = 0;
while let [b'-' | b'?' | b':', b' ' | b'\t', tail @ ..] = rest {
indicators += 1;
rest = tail;
while let [b' ' | b'\t', tail @ ..] = rest {
rest = tail;
}
}
indent <= MAX_FRONTMATTER_INDENT && indicators <= MAX_FRONTMATTER_INDICATORS
})
}
#[derive(Debug, Serialize, Deserialize, Default)]
struct RawFrontmatter {
id: Option<String>,
@@ -15,7 +76,7 @@ struct RawFrontmatter {
}
/// Try to parse a date string in multiple common formats.
fn parse_date_flexible(s: &str) -> Option<chrono::DateTime<Utc>> {
pub fn parse_date_flexible(s: &str) -> Option<chrono::DateTime<Utc>> {
let s = s.trim();
// RFC 3339 / ISO 8601 with timezone (e.g. 2024-01-15T10:30:00+00:00)
if let Ok(dt) = s.parse::<chrono::DateTime<Utc>>() {
@@ -40,14 +101,60 @@ fn parse_date_flexible(s: &str) -> Option<chrono::DateTime<Utc>> {
None
}
/// Reads the known keys one by one. Frontmatter written by other editors is often shaped a little
/// differently (`tags: work`, `pinned: yes`, a numeric title or id); reading it as one strict
/// record dropped every field when a single one did not fit, and the next save then wrote a new id,
/// the file name as title and no tags over the originals.
fn read_frontmatter(data: Option<Pod>) -> RawFrontmatter {
let Some(serde_json::Value::Object(fields)) =
data.and_then(|data| data.deserialize::<serde_json::Value>().ok())
else {
return RawFrontmatter::default();
};
let text = |value: &serde_json::Value| match value {
serde_json::Value::String(text) => Some(text.clone()),
serde_json::Value::Number(number) => Some(number.to_string()),
serde_json::Value::Bool(flag) => Some(flag.to_string()),
_ => None,
};
let tags = fields.get("tags").map(|value| match value {
serde_json::Value::Array(items) => items.iter().filter_map(text).collect(),
// `tags: work` and `tags: a, b` are common outside this app.
other => text(other)
.map(|joined| {
joined
.split(',')
.map(|tag| tag.trim().to_string())
.filter(|tag| !tag.is_empty())
.collect()
})
.unwrap_or_default(),
});
let pinned = fields.get("pinned").and_then(|value| match value {
serde_json::Value::Bool(flag) => Some(*flag),
serde_json::Value::Number(number) => Some(number.as_f64() != Some(0.0)),
serde_json::Value::String(word) => match word.trim().to_ascii_lowercase().as_str() {
"true" | "yes" | "on" | "1" => Some(true),
"false" | "no" | "off" | "0" => Some(false),
_ => None,
},
_ => None,
});
RawFrontmatter {
id: fields.get("id").and_then(text),
title: fields.get("title").and_then(text),
tags,
pinned,
created: fields.get("created").and_then(text),
modified: fields.get("modified").and_then(text),
}
}
pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
let matter = Matter::<YAML>::new();
let matter = Matter::<BoundedYaml>::new();
let result = matter.parse(raw);
let fm: RawFrontmatter = result
.data
.and_then(|d| d.deserialize().ok())
.unwrap_or_default();
let fm = read_frontmatter(result.data);
let title = fm.title.unwrap_or_else(|| filename_to_title(filename));
@@ -77,18 +184,15 @@ pub fn parse_note(raw: &str, filename: &str) -> (NoteMeta, String) {
(meta, content)
}
/// Ensure the body starts with `# Title` heading for external app compatibility.
/// If the body already starts with `# Title`, leave it as-is.
/// Ensure the body starts with a top-level heading for external app compatibility, adding
/// `# Title` when it has none. A body that already opens with a top-level heading is left alone
/// even when that heading differs from the title: adding another one above it stacked a new
/// heading on every title change (`# New`, `# Old`, ...).
fn ensure_title_heading(body: &str, title: &str) -> String {
let trimmed = body.trim_start();
// Check if body already starts with `# Title`
if let Some(rest) = trimmed.strip_prefix("# ") {
let first_line_end = rest.find('\n').unwrap_or(rest.len());
let heading_text = rest[..first_line_end].trim();
if heading_text.eq_ignore_ascii_case(title.trim()) {
return body.to_string();
}
if trimmed.starts_with("# ") {
return body.to_string();
}
// Don't add heading to empty notes (new/blank notes)
@@ -100,29 +204,24 @@ fn ensure_title_heading(body: &str, title: &str) -> String {
format!("# {}\n\n{}", title, body)
}
/// The frontmatter block for a note that has none yet. Written through the YAML serializer like
/// `merge_frontmatter`: assembled by hand, a title with a backslash or a tag such as `2024`,
/// `true` or `a: b` came out as YAML the app could not read back.
pub fn serialize_frontmatter(meta: &NoteMeta) -> String {
let tags_str = if meta.tags.is_empty() {
"[]".to_string()
} else {
format!(
"[{}]",
meta.tags
.iter()
.map(|t| format!("{}", t))
.collect::<Vec<_>>()
.join(", ")
)
};
format!(
"---\nid: \"{}\"\ntitle: \"{}\"\ntags: {}\npinned: {}\ncreated: {}\nmodified: {}\n---\n",
meta.id,
meta.title.replace('"', "\\\""),
tags_str,
meta.pinned,
meta.created.to_rfc3339(),
meta.modified.to_rfc3339(),
)
let text = |value: &str| serde_yaml::Value::String(value.to_string());
let mut mapping = serde_yaml::Mapping::new();
mapping.insert(text("id"), text(&meta.id));
mapping.insert(text("title"), text(&meta.title));
mapping.insert(
text("tags"),
serde_yaml::Value::Sequence(meta.tags.iter().map(|tag| text(tag)).collect()),
);
mapping.insert(text("pinned"), serde_yaml::Value::Bool(meta.pinned));
mapping.insert(text("created"), text(&meta.created.to_rfc3339()));
mapping.insert(text("modified"), text(&meta.modified.to_rfc3339()));
let yaml = serde_yaml::to_string(&serde_yaml::Value::Mapping(mapping))
.expect("strings, booleans and a list always serialize");
format!("---\n{yaml}---\n")
}
pub fn update_note_raw(meta: &NoteMeta, body: &str) -> String {
@@ -134,7 +233,7 @@ pub fn update_note_raw(meta: &NoteMeta, body: &str) -> String {
/// Merge NoteMeta fields into existing frontmatter, preserving unknown YAML keys.
/// Falls back to serialize_frontmatter() if the original has no frontmatter.
pub fn merge_frontmatter(original_raw: &str, meta: &NoteMeta, body: &str) -> String {
let matter = Matter::<YAML>::new();
let matter = Matter::<BoundedYaml>::new();
let parsed = matter.parse(original_raw);
// If original had no frontmatter, use the simple serializer
@@ -191,7 +290,7 @@ pub fn merge_frontmatter(original_raw: &str, meta: &NoteMeta, body: &str) -> Str
format!("---\n{}---\n{}", yaml_str, body_with_heading)
}
fn filename_to_title(filename: &str) -> String {
pub fn filename_to_title(filename: &str) -> String {
let stem = filename.trim_end_matches(".md");
// Only replace dashes/underscores acting as word separators (between non-space chars).
// Keep dashes that are surrounded by spaces (e.g. "Title - Subtitle").
@@ -214,13 +313,9 @@ fn filename_to_title(filename: &str) -> String {
/// Quick title extraction from raw note content (frontmatter only, no full parse)
pub fn extract_title(raw: &str) -> Option<String> {
let matter = Matter::<YAML>::new();
let matter = Matter::<BoundedYaml>::new();
let result = matter.parse(raw);
let fm: RawFrontmatter = result
.data
.and_then(|d| d.deserialize().ok())
.unwrap_or_default();
fm.title
read_frontmatter(result.data).title
}
pub fn extract_preview(content: &str, max_len: usize) -> String {
@@ -279,7 +374,7 @@ fn strip_html_and_markdown(input: &str) -> String {
chars.next(); // skip '['
let mut depth = 1;
// Skip alt text
while let Some(c) = chars.next() {
for c in chars.by_ref() {
if c == '[' {
depth += 1;
}
@@ -294,7 +389,7 @@ fn strip_html_and_markdown(input: &str) -> String {
if chars.peek() == Some(&'(') {
chars.next();
let mut depth = 1;
while let Some(c) = chars.next() {
for c in chars.by_ref() {
if c == '(' {
depth += 1;
}
@@ -313,7 +408,7 @@ fn strip_html_and_markdown(input: &str) -> String {
if ch == '[' {
let mut link_text = String::new();
let mut depth = 1;
while let Some(c) = chars.next() {
for c in chars.by_ref() {
if c == '[' {
depth += 1;
}
@@ -329,7 +424,7 @@ fn strip_html_and_markdown(input: &str) -> String {
if chars.peek() == Some(&'(') {
chars.next();
let mut depth = 1;
while let Some(c) = chars.next() {
for c in chars.by_ref() {
if c == '(' {
depth += 1;
}
@@ -422,4 +517,215 @@ mod tests {
eprintln!("Stripped: {:?}", stripped);
assert!(stripped.contains("Telefoonnummer"));
}
fn alias_bomb(levels: usize, width: usize) -> String {
let mut note = format!(
"---\ntitle: Bomb\na0: &a0 [{}]\n",
vec!["1"; width].join(",")
);
for level in 1..levels {
let alias = format!("*a{}", level - 1);
note.push_str(&format!(
"a{level}: &a{level} [{}]\n",
vec![alias.as_str(); width].join(",")
));
}
note.push_str("---\nbody\n");
note
}
/// Runs on a stack the size of the app's worker threads, where the unbounded loader overflowed.
fn on_worker_stack<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static) -> T {
std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(work)
.unwrap()
.join()
.unwrap()
}
#[test]
fn hostile_frontmatter_is_read_as_a_note_without_metadata() {
let nested_on_one_line = format!("---\nt: {}x\n---\nbody\n", "- ".repeat(2400));
let mut nested_by_indent = String::from("---\nt:\n");
for depth in 0..400 {
note_line(&mut nested_by_indent, depth);
}
nested_by_indent.push_str("---\nbody\n");
let oversized = format!(
"---\ntitle: Big\nfiller: \"{}\"\n---\nbody\n",
"x".repeat(MAX_FRONTMATTER_BYTES)
);
for note in [
alias_bomb(10, 8),
alias_bomb(40, 2),
nested_on_one_line,
nested_by_indent,
oversized,
] {
let started = std::time::Instant::now();
let (title, content, extracted, merged) = on_worker_stack(move || {
let (meta, content) = parse_note(&note, "Fallback Name.md");
let merged = merge_frontmatter(&note, &meta, &content);
(meta.title, content, extract_title(&note), merged)
});
assert!(started.elapsed() < std::time::Duration::from_secs(2));
// No metadata is taken from it, and the body is still split off as usual.
assert_eq!(title, "Fallback Name");
assert_eq!(content, "body");
assert_eq!(extracted, None);
assert!(
merged.ends_with("body"),
"{}",
&merged[merged.len().saturating_sub(40)..]
);
}
}
fn note_line(note: &mut String, depth: usize) {
note.push_str(&" ".repeat(depth));
note.push_str("-\n");
}
#[test]
fn ordinary_frontmatter_is_unaffected_by_the_bounds() {
let (meta, content) = parse_note(
"---\nid: abc\ntitle: \"*Starred* title: 5*3\"\ntags:\n - one\n - two\npinned: true\n---\n# Body\n",
"x.md",
);
assert_eq!(meta.id, "abc");
assert_eq!(meta.title, "*Starred* title: 5*3");
assert_eq!(meta.tags, vec!["one", "two"]);
assert!(meta.pinned);
assert_eq!(content, "# Body");
// A few aliases and modest nesting are ordinary YAML.
let (meta, _) = parse_note(
"---\ntitle: Shared\nbase: &base [a, b]\ntags: *base\nextra:\n - - nested\n - list\n---\nbody\n",
"x.md",
);
assert_eq!(meta.title, "Shared");
assert_eq!(meta.tags, vec!["a", "b"]);
assert!(frontmatter_within_bounds(&format!(
"title: {}",
"x".repeat(MAX_FRONTMATTER_BYTES - 16)
)));
}
#[test]
fn one_field_of_another_shape_no_longer_drops_the_rest() {
let note = |extra: &str| format!("---\nid: keep-me\ntitle: Kept\n{extra}\n---\nbody\n");
let (meta, _) = parse_note(&note("tags: work"), "File.md");
assert_eq!((meta.id.as_str(), meta.title.as_str()), ("keep-me", "Kept"));
assert_eq!(meta.tags, vec!["work"]);
let (meta, _) = parse_note(&note("tags: a, b ,c\npinned: yes"), "File.md");
assert_eq!(meta.tags, vec!["a", "b", "c"]);
assert!(meta.pinned);
assert_eq!(meta.id, "keep-me");
// Numbers where text is expected are read as text.
let (meta, _) = parse_note(
"---\nid: 20231014\ntitle: 2024\ntags: [1, two, true]\npinned: 0\n---\nbody\n",
"File.md",
);
assert_eq!(
(meta.id.as_str(), meta.title.as_str()),
("20231014", "2024")
);
assert_eq!(meta.tags, vec!["1", "two", "true"]);
assert!(!meta.pinned);
assert_eq!(
extract_title("---\ntitle: 2024\ntags: work\n---\nbody\n").as_deref(),
Some("2024")
);
// A field that makes no sense is skipped on its own.
let (meta, _) = parse_note(&note("tags: {a: b}\npinned: maybe"), "File.md");
assert_eq!(meta.id, "keep-me");
assert!(meta.tags.is_empty());
assert!(!meta.pinned);
// Saving keeps the identity and writes the tags as a list.
let (meta, content) = parse_note(&note("tags: work\naliases: [x]"), "File.md");
let saved = merge_frontmatter(&note("tags: work\naliases: [x]"), &meta, &content);
let (again, _) = parse_note(&saved, "File.md");
assert_eq!(
(again.id.as_str(), again.title.as_str()),
("keep-me", "Kept")
);
assert_eq!(again.tags, vec!["work"]);
assert!(saved.contains("aliases:"));
}
#[test]
fn new_frontmatter_reads_back_whatever_the_title_and_tags_contain() {
for (title, tags) in [
("C:\\Users\\tom", vec!["2024", "true"]),
("Plain", vec!["foo: bar", "a,b"]),
("Say \"hi\" and 'bye'", vec!["#hash", "- dash"]),
("\\sum x", vec!["null", "~", "1.5"]),
(
"Tab\there: colon # hash",
vec!["[x]", "{y}", "*star", "&amp"],
),
("- leading dash", vec![]),
("", vec!["yes"]),
] {
let meta = NoteMeta {
id: "the-id".into(),
title: title.into(),
tags: tags.iter().map(|tag| tag.to_string()).collect(),
pinned: true,
created: Utc::now(),
modified: Utc::now(),
};
let raw = update_note_raw(&meta, "body\n");
let (back, content) = parse_note(&raw, "Fallback.md");
assert_eq!(back.id, "the-id", "{raw}");
assert_eq!(back.title, title, "{raw}");
assert_eq!(back.tags, meta.tags, "{raw}");
assert!(back.pinned);
assert_eq!(back.created.timestamp(), meta.created.timestamp());
assert!(content.ends_with("body"));
}
}
#[test]
fn a_title_heading_is_added_only_when_the_body_has_no_top_level_heading() {
let meta = |title: &str| NoteMeta {
id: "id".into(),
title: title.into(),
tags: vec![],
pinned: false,
created: Utc::now(),
modified: Utc::now(),
};
let body_of = |raw: String| parse_note(&raw, "x.md").1;
// No heading yet: the title becomes one.
assert_eq!(
body_of(update_note_raw(&meta("New"), "Text.\n")),
"# New\n\nText."
);
// A heading that differs from the title is not buried under a second one.
assert_eq!(
body_of(update_note_raw(&meta("New"), "# Old\n\nText.\n")),
"# Old\n\nText."
);
let original = "---\nid: id\ntitle: Old\n---\n# Old\n\nText.\n";
assert_eq!(
body_of(merge_frontmatter(
original,
&meta("New"),
"# Old\n\nText.\n"
)),
"# Old\n\nText."
);
// Saving again and again never grows the note.
let once = merge_frontmatter(original, &meta("New"), "# Old\n\nText.\n");
let (_, body) = parse_note(&once, "x.md");
assert_eq!(
body_of(merge_frontmatter(&once, &meta("Newer"), &body)),
"# Old\n\nText."
);
// Lower-level headings and empty notes behave as before.
assert_eq!(
body_of(update_note_raw(&meta("New"), "## Section\n")),
"# New\n\n## Section"
);
assert!(update_note_raw(&meta("New"), "\n").ends_with("---\n\n"));
}
}
File diff suppressed because it is too large. Load diff
+6
View File
@@ -1,3 +1,9 @@
pub mod frontmatter;
pub mod import;
pub mod operations;
#[cfg(target_os = "linux")]
mod portal_watcher;
pub mod watcher;
#[cfg(test)]
mod note_import_tests;
+495
View File
@@ -0,0 +1,495 @@
use super::operations::{
ensure_vault_structure, import_note as import_from_root, ExternalNoteReference,
};
fn import_note(
vault: &str,
source: &str,
notebook: Option<&str>,
raw: &str,
references: Vec<ExternalNoteReference>,
authorize: impl Fn(&Path) -> Result<(), String>,
) -> Result<crate::types::NoteContent, String> {
import_from_root(
vault,
source,
Path::new(source).parent().unwrap(),
notebook,
raw,
references,
authorize,
)
}
use std::fs;
use std::path::{Path, PathBuf};
fn reference(raw: &str, original: &str, href: &str, html: bool) -> ExternalNoteReference {
let from = raw.find(original).unwrap();
ExternalNoteReference {
from,
to: from + original.len(),
href: href.into(),
html,
pdf: false,
}
}
fn fixture(raw: &str) -> (tempfile::TempDir, String, PathBuf) {
let root = tempfile::tempdir().unwrap();
let vault = root.path().join("vault").to_string_lossy().into_owned();
ensure_vault_structure(&vault).unwrap();
let external = root.path().join("external");
fs::create_dir_all(external.join("images")).unwrap();
let source = external.join("External.md");
fs::write(&source, raw).unwrap();
(root, vault, source)
}
fn attachments(vault: &str) -> Vec<PathBuf> {
fs::read_dir(Path::new(vault).join(".helixnotes/attachments"))
.unwrap()
.map(|entry| entry.unwrap().path())
.collect()
}
#[test]
fn imports_relative_files_once_preserving_originals_frontmatter_and_literal_content() {
let raw = "---\r\ntitle: Portable\r\ncustom: 雪 📝\r\n---\r\n![One](images/café%20雪.png)\r\n![Two](images/./café%20雪.png)\r\n<a href=\"images/report.pdf#page=2&amp;mode=fit\">PDF</a>\r\n\r\n~~~md\r\n![Example](missing.png)\r\n~~~\r\n";
for notebook in [None, Some("Projects/Nested")] {
let (_root, vault, source) = fixture(raw);
let parent = source.parent().unwrap();
fs::write(parent.join("images/café 雪.png"), b"image bytes").unwrap();
fs::write(parent.join("images/report.pdf"), b"pdf bytes").unwrap();
fs::create_dir_all(Path::new(&vault).join("Projects/Nested")).unwrap();
let references = vec![
reference(raw, "images/café%20雪.png", "images/café%20雪.png", false),
reference(
raw,
"images/./café%20雪.png",
"images/./café%20雪.png",
false,
),
reference(
raw,
"images/report.pdf#page=2&amp;mode=fit",
"images/report.pdf#page=2&mode=fit",
true,
),
];
let note = import_note(
&vault,
source.to_str().unwrap(),
notebook,
raw,
references,
|path| {
if path.starts_with(parent) {
Ok(())
} else {
Err("Not selected".into())
}
},
)
.unwrap();
assert!(note
.raw
.starts_with("---\r\ntitle: Portable\r\ncustom: 雪 📝\r\n---\r\n"));
assert!(note.raw.contains("![Example](missing.png)"));
assert!(note.raw.contains("#page=2&amp;mode=fit"));
assert_eq!(fs::read_to_string(&source).unwrap(), raw);
assert_eq!(fs::read_to_string(&note.path).unwrap(), note.raw);
let files = attachments(&vault);
assert_eq!(
files.len(),
2,
"aliases of one file share one portable copy"
);
for file in files {
let filename = urlencoding::encode(file.file_name().unwrap().to_str().unwrap());
let relative = format!(".helixnotes/attachments/{filename}");
assert!(note.raw.contains(&relative));
assert!(Path::new(&vault)
.join(urlencoding::decode(&relative).unwrap().as_ref())
.is_file());
}
assert_eq!(
fs::read(parent.join("images/café 雪.png")).unwrap(),
b"image bytes"
);
assert_eq!(
fs::read(parent.join("images/report.pdf")).unwrap(),
b"pdf bytes"
);
}
}
#[test]
fn imported_pdf_embeds_keep_the_vault_root_path_convention_in_nested_notebooks() {
let raw = "<div data-pdf-src=\"images/report.pdf\" data-pdf-name=\"Report\"></div>";
let (_root, vault, source) = fixture(raw);
fs::write(source.parent().unwrap().join("images/report.pdf"), b"pdf").unwrap();
fs::create_dir_all(Path::new(&vault).join("Projects/Nested")).unwrap();
let mut pdf = reference(raw, "images/report.pdf", "images/report.pdf", true);
pdf.pdf = true;
let note = import_note(
&vault,
source.to_str().unwrap(),
Some("Projects/Nested"),
raw,
vec![pdf],
|_| Ok(()),
)
.unwrap();
assert!(note.raw.contains("data-pdf-src=\".helixnotes/attachments/"));
assert!(note.raw.contains("data-pdf-name=\"Report\""));
assert_eq!(attachments(&vault).len(), 1);
}
#[test]
fn imported_document_links_remain_managed_and_stable_after_note_and_notebook_moves() {
let raw = "[Report](images/report.pdf#page=2)";
let (_root, vault, source) = fixture(raw);
fs::write(source.parent().unwrap().join("images/report.pdf"), b"pdf").unwrap();
fs::create_dir_all(Path::new(&vault).join("Projects/Nested")).unwrap();
fs::create_dir_all(Path::new(&vault).join("Archive")).unwrap();
let note = import_note(
&vault,
source.to_str().unwrap(),
Some("Projects/Nested"),
raw,
vec![reference(
raw,
"images/report.pdf#page=2",
"images/report.pdf#page=2",
false,
)],
|_| Ok(()),
)
.unwrap();
assert!(
note.raw.starts_with("[Report](.helixnotes/attachments/"),
"managed links must not depend on notebook depth"
);
let href = note
.raw
.strip_prefix("[Report](")
.unwrap()
.strip_suffix(')')
.unwrap();
let attachment = Path::new(&vault).join(
urlencoding::decode(href.split('#').next().unwrap())
.unwrap()
.as_ref(),
);
assert_eq!(fs::read(attachment).unwrap(), b"pdf");
let moved = super::operations::move_note(&vault, &note.path, &vault)
.unwrap()
.0;
assert_eq!(fs::read_to_string(moved).unwrap(), note.raw);
// Imported managed paths remain stable when their containing notebook is moved too.
let second = import_note(
&vault,
source.to_str().unwrap(),
Some("Projects/Nested"),
raw,
vec![reference(
raw,
"images/report.pdf#page=2",
"images/report.pdf#page=2",
false,
)],
|_| Ok(()),
)
.unwrap();
super::operations::move_notebook(
&vault,
Path::new(&vault).join("Projects").to_str().unwrap(),
Path::new(&vault).join("Archive").to_str().unwrap(),
)
.unwrap();
assert_eq!(
fs::read_to_string(Path::new(&vault).join("Archive/Projects/Nested/External.md")).unwrap(),
second.raw
);
}
#[test]
fn import_does_not_replace_existing_note_or_same_named_attachment() {
let raw = "![Image](images/photo.png)";
let (_root, vault, source) = fixture(raw);
fs::write(
source.parent().unwrap().join("images/photo.png"),
b"new image",
)
.unwrap();
fs::write(Path::new(&vault).join("External.md"), b"keep note").unwrap();
fs::write(
Path::new(&vault).join(".helixnotes/attachments/photo.png"),
b"keep image",
)
.unwrap();
let note = import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![reference(
raw,
"images/photo.png",
"images/photo.png",
false,
)],
|_| Ok(()),
)
.unwrap();
assert!(note.path.ends_with("External (2).md"));
assert_eq!(
fs::read(Path::new(&vault).join("External.md")).unwrap(),
b"keep note"
);
assert_eq!(
fs::read(Path::new(&vault).join(".helixnotes/attachments/photo.png")).unwrap(),
b"keep image"
);
assert_eq!(attachments(&vault).len(), 2);
}
#[test]
fn stale_sources_missing_files_and_denied_attachments_publish_nothing() {
let raw = "![Image](images/photo.png)";
let (_root, vault, source) = fixture(raw);
let plan = || {
vec![reference(
raw,
"images/photo.png",
"images/photo.png",
false,
)]
};
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
"stale",
plan(),
|_| Ok(())
)
.is_err());
assert!(
import_note(&vault, source.to_str().unwrap(), None, raw, plan(), |_| Ok(
()
))
.is_err()
);
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
let denied = import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
plan(),
|path| {
if path == source {
Ok(())
} else {
Err("Attachment not selected".into())
}
},
);
assert!(denied.unwrap_err().contains("not selected"));
assert!(attachments(&vault).is_empty());
assert!(!Path::new(&vault).join("External.md").exists());
assert_eq!(fs::read_to_string(&source).unwrap(), raw);
}
#[test]
fn invalid_destinations_ranges_and_absolute_references_are_rejected() {
let raw = "雪 ![Image](images/photo.png)";
let (_root, vault, source) = fixture(raw);
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
assert!(import_note(
&vault,
source.to_str().unwrap(),
Some("../escape"),
raw,
vec![],
|_| Ok(())
)
.is_err());
for href in [
"/private.png",
"%2Fprivate.png",
"C:/private.png",
"https://example.com/file.png",
"Related.md",
] {
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![reference(raw, "images/photo.png", href, false)],
|_| Ok(())
)
.is_err());
}
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![ExternalNoteReference {
from: 1,
to: 3,
href: "images/photo.png".into(),
html: false,
pdf: false,
}],
|_| Ok(())
)
.is_err());
let plan = vec![
reference(raw, "images/photo.png", "images/photo.png", false),
reference(raw, "images/photo.png", "images/photo.png", false),
];
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
plan,
|_| Ok(())
)
.is_err());
assert!(attachments(&vault).is_empty());
}
#[test]
fn failed_note_publication_removes_only_its_new_attachments() {
let raw = "![Image](images/photo.png)";
let (_root, vault, source) = fixture(raw);
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
fs::write(Path::new(&vault).join("External.md"), b"keep").unwrap();
for number in 2..=100 {
fs::write(
Path::new(&vault).join(format!("External ({number}).md")),
b"keep",
)
.unwrap();
}
let original_asset = Path::new(&vault).join(".helixnotes/attachments/original.png");
fs::write(&original_asset, b"keep attachment").unwrap();
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![reference(
raw,
"images/photo.png",
"images/photo.png",
false
)],
|_| Ok(())
)
.is_err());
assert_eq!(attachments(&vault), vec![original_asset]);
assert_eq!(
fs::read(Path::new(&vault).join("External.md")).unwrap(),
b"keep"
);
assert_eq!(fs::read_to_string(&source).unwrap(), raw);
assert!(!fs::read_dir(&vault).unwrap().any(|entry| entry
.unwrap()
.file_name()
.to_string_lossy()
.starts_with(".helixnotes-import-")));
}
#[test]
fn note_content_cannot_import_parent_files_or_hidden_secrets_from_a_broad_scope() {
let raw = "[File](asset.bin)";
let (root, vault, source) = fixture(raw);
let parent = source.parent().unwrap();
for name in [
".ssh/key.bin",
".helixnotes/history/private.bin",
".helixnotes/attachments/photo.bin",
] {
let file = parent.join(name);
fs::create_dir_all(file.parent().unwrap()).unwrap();
fs::write(file, b"private fixture").unwrap();
}
fs::write(root.path().join("private.bin"), b"private outside fixture").unwrap();
for href in [
"../private.bin",
".ssh/key.bin",
".helixnotes/history/private.bin",
] {
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![reference(raw, "asset.bin", href, false)],
|_| Ok(())
)
.is_err());
assert!(attachments(&vault).is_empty());
assert!(!Path::new(&vault).join("External.md").exists());
}
let note = import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![reference(
raw,
"asset.bin",
".helixnotes/attachments/photo.bin",
false,
)],
|_| Ok(()),
)
.unwrap();
assert!(note.raw.contains(".helixnotes/attachments/"));
assert_eq!(attachments(&vault).len(), 1);
}
#[cfg(unix)]
#[test]
fn import_rejects_attachment_and_notebook_destinations_that_follow_symlinks() {
let raw = "![Image](images/photo.png)";
let (root, vault, source) = fixture(raw);
fs::write(source.parent().unwrap().join("images/photo.png"), b"image").unwrap();
let outside = root.path().join("outside");
fs::create_dir(&outside).unwrap();
std::os::unix::fs::symlink(&outside, Path::new(&vault).join("Notebook")).unwrap();
assert!(import_note(
&vault,
source.to_str().unwrap(),
Some("Notebook"),
raw,
vec![],
|_| Ok(())
)
.is_err());
let directory = Path::new(&vault).join(".helixnotes/attachments");
fs::remove_dir(&directory).unwrap();
std::os::unix::fs::symlink(&outside, &directory).unwrap();
assert!(import_note(
&vault,
source.to_str().unwrap(),
None,
raw,
vec![reference(
raw,
"images/photo.png",
"images/photo.png",
false
)],
|_| Ok(())
)
.is_err());
assert!(fs::read_dir(outside).unwrap().next().is_none());
}
File diff suppressed because it is too large. Load diff
+353
View File
@@ -0,0 +1,353 @@
//! Metadata polling for portal directories that do not forward host inotify events.
use notify::event::{CreateKind, ModifyKind, RemoveKind};
use notify::{Event, EventKind};
use std::collections::HashMap;
use std::fs::{self, Metadata};
use std::io::ErrorKind;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::{Duration, Instant};
use walkdir::WalkDir;
use super::operations::is_hidden;
#[derive(Debug, PartialEq, Eq)]
enum Fingerprint {
Directory,
Note {
size: u64,
modified: (i64, i64),
changed: (i64, i64),
},
}
impl Fingerprint {
fn from_metadata(metadata: &Metadata) -> Self {
if metadata.is_dir() {
// Track directory presence, not child mutations or synthetic portal inode IDs.
Self::Directory
} else {
Self::Note {
size: metadata.len(),
modified: (metadata.mtime(), metadata.mtime_nsec()),
changed: (metadata.ctime(), metadata.ctime_nsec()),
}
}
}
}
type Snapshot = HashMap<PathBuf, Fingerprint>;
fn scan(root: &Path) -> notify::Result<Snapshot> {
let metadata =
fs::metadata(root).map_err(|error| notify::Error::io(error).add_path(root.to_owned()))?;
if !metadata.is_dir() {
return Err(
notify::Error::generic("Vault root is not a directory").add_path(root.to_owned())
);
}
let mut snapshot = Snapshot::new();
let entries = WalkDir::new(root)
.follow_links(false)
.into_iter()
.filter_entry(|entry| entry.depth() == 0 || !is_hidden(entry.path()));
for entry in entries {
let entry = match entry {
Ok(entry) => entry,
Err(error)
if error.depth() > 0
&& error
.io_error()
.is_some_and(|error| error.kind() == ErrorKind::NotFound) =>
{
continue;
}
Err(error) => {
return Err(notify::Error::generic(&error.to_string())
.add_path(error.path().unwrap_or(root).to_owned()));
}
};
let path = entry.path();
if !entry.file_type().is_dir()
&& path.extension().and_then(|extension| extension.to_str()) != Some("md")
{
continue;
}
let metadata = match fs::metadata(path) {
Ok(metadata) => metadata,
Err(error) if entry.depth() > 0 && error.kind() == ErrorKind::NotFound => continue,
Err(error) => return Err(notify::Error::io(error).add_path(path.to_owned())),
};
// Match note scanning's file symlinks without traversing directory symlinks.
if metadata.is_file() || (metadata.is_dir() && !entry.file_type().is_symlink()) {
snapshot.insert(path.to_owned(), Fingerprint::from_metadata(&metadata));
}
}
Ok(snapshot)
}
fn changes(before: &Snapshot, after: &Snapshot) -> Vec<Event> {
let mut events = Vec::new();
for (path, fingerprint) in after {
let kind = match before.get(path) {
None => EventKind::Create(CreateKind::Any),
Some(previous) if previous != fingerprint => EventKind::Modify(ModifyKind::Any),
Some(_) => continue,
};
events.push(Event::new(kind).add_path(path.clone()));
}
for path in before.keys().filter(|path| !after.contains_key(*path)) {
events.push(Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path.clone()));
}
events
}
pub struct PortalWatcher {
_stop: mpsc::Sender<()>,
}
impl PortalWatcher {
pub fn start(
root: PathBuf,
events: mpsc::Sender<notify::Result<Event>>,
interval: Duration,
) -> Result<Self, String> {
let started = Instant::now();
let mut previous = scan(&root).map_err(|error| error.to_string())?;
// Portal metadata calls consume host daemon CPU too. Large vaults trade
// detection latency for idle time instead of scanning continuously.
let mut delay = interval.max(started.elapsed().saturating_mul(20));
let (stop, stopped) = mpsc::channel();
std::thread::Builder::new()
.name("portal-vault-watch".into())
.spawn(move || {
while matches!(stopped.recv_timeout(delay), Err(RecvTimeoutError::Timeout)) {
let started = Instant::now();
match scan(&root) {
Ok(current) => {
for event in changes(&previous, &current) {
if events.send(Ok(event)).is_err() {
return;
}
}
previous = current;
}
Err(error) => {
// A partial or inaccessible scan cannot prove that notes were deleted.
if events.send(Err(error)).is_err() {
return;
}
}
}
delay = interval.max(started.elapsed().saturating_mul(20));
}
})
.map_err(|error| error.to_string())?;
Ok(Self { _stop: stop })
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::{File, FileTimes};
use std::os::unix::fs::symlink;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
fn set_modified(path: &Path, time: SystemTime) {
File::options()
.write(true)
.open(path)
.unwrap()
.set_times(FileTimes::new().set_modified(time))
.unwrap();
}
fn assert_modified(before: &Snapshot, root: &Path, note: &Path) {
let events = changes(before, &scan(root).unwrap());
assert_eq!(events.len(), 1, "{events:?}");
assert_eq!(events[0].paths, [note]);
assert_eq!(events[0].kind, EventKind::Modify(ModifyKind::Any));
}
#[test]
fn same_size_edit_with_restored_mtime_uses_ctime() {
let vault = tempfile::tempdir().unwrap();
let note = vault.path().join("Note.md");
fs::write(&note, "before").unwrap();
let modified = fs::metadata(&note).unwrap().modified().unwrap();
let before = scan(vault.path()).unwrap();
std::thread::sleep(Duration::from_millis(2));
fs::write(&note, "after!").unwrap();
set_modified(&note, modified);
assert_eq!(fs::metadata(&note).unwrap().modified().unwrap(), modified);
assert_modified(&before, vault.path(), &note);
}
#[test]
fn backdated_and_fractional_modification_times_are_detected() {
let vault = tempfile::tempdir().unwrap();
let note = vault.path().join("Note.md");
fs::write(&note, "before").unwrap();
set_modified(&note, UNIX_EPOCH + Duration::new(1000, 100));
let before = scan(vault.path()).unwrap();
fs::write(&note, "after!").unwrap();
set_modified(&note, UNIX_EPOCH + Duration::new(1000, 200));
let metadata = fs::metadata(&note).unwrap();
assert_eq!((metadata.mtime(), metadata.mtime_nsec()), (1000, 200));
assert_modified(&before, vault.path(), &note);
let before = scan(vault.path()).unwrap();
set_modified(&note, UNIX_EPOCH + Duration::from_secs(10));
assert_modified(&before, vault.path(), &note);
}
#[test]
fn atomic_replacement_with_preserved_mtime_changes_ctime() {
let vault = tempfile::tempdir().unwrap();
let note = vault.path().join("Note.md");
let temporary = vault.path().join(".replacement");
fs::write(&note, "before").unwrap();
let metadata = fs::metadata(&note).unwrap();
let before = scan(vault.path()).unwrap();
std::thread::sleep(Duration::from_millis(2));
fs::write(&temporary, "after!").unwrap();
set_modified(&temporary, metadata.modified().unwrap());
fs::rename(&temporary, &note).unwrap();
let replaced = fs::metadata(&note).unwrap();
assert_eq!(replaced.modified().unwrap(), metadata.modified().unwrap());
assert_ne!(
(replaced.ctime(), replaced.ctime_nsec()),
(metadata.ctime(), metadata.ctime_nsec())
);
assert_modified(&before, vault.path(), &note);
}
#[test]
fn nested_directory_create_rename_and_remove_keep_both_sides() {
let vault = tempfile::tempdir().unwrap();
let before = scan(vault.path()).unwrap();
let old = vault.path().join("Old");
fs::create_dir_all(old.join("Nested")).unwrap();
fs::write(old.join("Nested/Note.md"), "note").unwrap();
let current = scan(vault.path()).unwrap();
let created = changes(&before, &current);
assert_eq!(created.len(), 3);
assert!(created.iter().all(|event| event.kind.is_create()));
let new = vault.path().join("New");
fs::rename(&old, &new).unwrap();
let renamed = scan(vault.path()).unwrap();
let events = changes(&current, &renamed);
assert_eq!(
events.iter().filter(|event| event.kind.is_create()).count(),
3
);
assert_eq!(
events.iter().filter(|event| event.kind.is_remove()).count(),
3
);
fs::remove_dir_all(&new).unwrap();
let events = changes(&renamed, &scan(vault.path()).unwrap());
assert_eq!(events.len(), 3);
assert!(events.iter().all(|event| event.kind.is_remove()));
}
#[test]
fn hidden_resources_and_attachment_changes_are_excluded() {
let vault = tempfile::tempdir().unwrap();
for name in [
".helixnotes",
".hidden",
"assets",
"_attachments",
"node_modules",
] {
fs::create_dir(vault.path().join(name)).unwrap();
fs::write(vault.path().join(name).join("Hidden.md"), "hidden").unwrap();
}
let before = scan(vault.path()).unwrap();
assert_eq!(
before.len(),
1,
"only the explicitly selected vault root should be present"
);
fs::write(vault.path().join("image.png"), "attachment").unwrap();
fs::write(vault.path().join(".hidden.md"), "hidden").unwrap();
assert!(changes(&before, &scan(vault.path()).unwrap()).is_empty());
}
#[test]
fn note_symlinks_are_watched_without_following_directory_symlinks() {
let vault = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let note = vault.path().join("Note.md");
let alias = vault.path().join("Alias.md");
fs::write(&note, "before").unwrap();
fs::write(outside.path().join("Outside.md"), "outside").unwrap();
symlink(&note, &alias).unwrap();
symlink(outside.path(), vault.path().join("Directory.md")).unwrap();
symlink(
vault.path().join("Missing.md"),
vault.path().join("Broken.md"),
)
.unwrap();
let before = scan(vault.path()).unwrap();
assert_eq!(before.len(), 3);
assert!(before.contains_key(&alias));
set_modified(&note, UNIX_EPOCH + Duration::from_secs(1000));
let events = changes(&before, &scan(vault.path()).unwrap());
assert_eq!(events.len(), 2);
assert!(events.iter().all(|event| event.kind.is_modify()));
}
#[test]
fn scan_errors_do_not_publish_partial_snapshots_and_recovery_detects_edits() {
let vault = tempfile::tempdir().unwrap();
let note = vault.path().join("Note.md");
fs::write(&note, "before").unwrap();
let (sender, receiver) = mpsc::channel();
let watcher =
PortalWatcher::start(vault.path().to_owned(), sender, Duration::from_millis(20))
.unwrap();
let broken = vault.path().join("Loop.md");
symlink(&broken, &broken).unwrap();
assert!(receiver
.recv_timeout(Duration::from_secs(2))
.unwrap()
.is_err());
set_modified(&note, UNIX_EPOCH + Duration::from_secs(1000));
fs::remove_file(&broken).unwrap();
let deadline = Instant::now() + Duration::from_secs(2);
loop {
let event = receiver
.recv_timeout(deadline.saturating_duration_since(Instant::now()))
.unwrap();
if let Ok(event) = event {
assert_eq!(event.paths.as_slice(), std::slice::from_ref(&note));
assert!(event.kind.is_modify());
break;
}
}
drop(watcher);
}
#[test]
fn initial_failure_is_synchronous_and_drop_wakes_a_long_poll() {
let vault = tempfile::tempdir().unwrap();
let (sender, _receiver) = mpsc::channel();
assert!(PortalWatcher::start(
vault.path().join("Missing"),
sender,
Duration::from_secs(60)
)
.is_err());
let (sender, receiver) = mpsc::channel();
let watcher =
PortalWatcher::start(vault.path().to_owned(), sender, Duration::from_secs(60)).unwrap();
drop(watcher);
assert!(matches!(
receiver.recv_timeout(Duration::from_secs(2)),
Err(mpsc::RecvTimeoutError::Disconnected)
));
}
}
Loaded 100 of 238 files, more files were not shown because too many files have changed in this diff. Show more