bjomarks-gui: the desktop client of bjomarks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-21 21:06:11 +01:00
commit 0651305b87
19 changed files with 4300 additions and 0 deletions

1151
src/app.bjo Normal file

File diff suppressed because it is too large Load diff

287
src/browser.bjo Normal file
View file

@ -0,0 +1,287 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjomarks-gui/src/browser.bjo — the module (bjomarks-gui browser): opens
;; an address in the user's browser.
;;
;; - With BJOMARKS_BROWSER set, that program is started with the address as
;; its one argument, with no shell between.
;; - In a distrobox container, host-spawn runs xdg-open on the host, with the
;; variables that tell it the display. distrobox's own xdg-open gives the
;; host none of them, and the host's xdg-open then finds no browser: "no
;; method available".
;; - Else the system opens it, as a click on a link does: xdg-open on Linux
;; and the BSDs, open on macOS, and the shell on Windows. That opens the
;; browser the user chose.
;; - The opener is waited for, up to 5 seconds. When it ends with an error,
;; the address was not opened, and the text says so. One that runs longer
;; has started a browser that it waits for: that is no error.
;; - Only http and https addresses are opened. A bookmark comes from the
;; files of other devices, and a `file:` address or one of a program's own
;; scheme can start a program on this one.
;;
;; A private window: the user's default browser, as `xdg-settings` names it,
;; is started as its .desktop file says, with its own flag for a private
;; window: --private-window for Firefox and those made from it, --incognito
;; for Chrome and those made from Chromium, and --inprivate for Edge. With
;; BJOMARKS_PRIVATE_BROWSER set, that program is started with the address
;; instead. Another browser, or another system than Linux, has no private
;; window here: `open-private-in-browser` says so, and the app copies the
;; address.
(export Opener opener-for distrobox-host-spawn open-in-browser browser-scheme?
private-flag exec-words private-command open-private-in-browser)
(import (std prelude))
(import (std interop))
(import (std os))
(import (std url))
(import/class
(ProcessStartInfo (: System.Diagnostics.ProcessStartInfo (-> string ProcessStartInfo)))
(Process (: System.Diagnostics.Process))
(Object (: System.Object)))
(import/extern
(shell-execute! (: System.Diagnostics.ProcessStartInfo.UseShellExecute (-> ProcessStartInfo bool void) #:set))
(redirect-output! (: System.Diagnostics.ProcessStartInfo.RedirectStandardOutput
(-> ProcessStartInfo bool void) #:set))
(output-of (: System.Diagnostics.Process.StandardOutput (-> Process System.IO.StreamReader) #:get))
(read-to-end (: System.IO.StreamReader.ReadToEnd (-> System.IO.StreamReader string)))
;; .NET strings, not Bjolang's.
(arguments-of (: System.Diagnostics.ProcessStartInfo.ArgumentList
(-> ProcessStartInfo (System.Collections.ObjectModel.Collection System.String)) #:get))
(add-argument! (: System.Collections.ObjectModel.Collection.Add
(-> (System.Collections.ObjectModel.Collection System.String) System.String void)))
(start-process (: System.Diagnostics.Process.Start (-> ProcessStartInfo Process)))
(wait-for-exit (: System.Diagnostics.Process.WaitForExit (-> Process int bool)))
(exit-code-of (: System.Diagnostics.Process.ExitCode (-> Process int) #:get))
(dispose-process (: System.Diagnostics.Process.Dispose (-> Process void))))
;; True for an http or https address, in any case.
(: (-> string bool))
(defun (browser-scheme? address)
(match (parse-url address)
((Ok u) (match (url-scheme u)
((Some s) (let ((scheme (string-downcase s))) (or (= scheme "http") (= scheme "https"))))
(None #f)))
((Err _) #f)))
;; How an address is opened: a program, with its arguments, or the shell of
;; Windows, which takes the address itself.
(type (: Opener (Union (: Run string (Vec string))
WindowsShell)))
;; The variables that host-spawn gives the host's xdg-open.
;; - With no display, xdg-open tries only browsers that run in a terminal.
;; - Not XDG_CURRENT_DESKTOP: with it, xdg-open uses the desktop's own
;; opener, which needs more of the session's variables, as KDE's needs
;; KDE_SESSION_VERSION. Without it, xdg-open opens the address with the
;; program that is the user's default for it, as xdg-mime says, on any
;; desktop.
(: string)
(def host-variables "DISPLAY,WAYLAND_DISPLAY,XDG_SESSION_TYPE")
;; The opener of `address`. `browser` is BJOMARKS_BROWSER, if it is set, and
;; `host-spawn` is host-spawn, when this program runs in a distrobox
;; container.
(: (-> string (Option string) (Option string) Opener))
(defun (opener-for address browser host-spawn)
(match (Tuple browser host-spawn)
((Tuple (Some program) _) (Run program [address]))
((Tuple None (Some spawn)) (Run spawn ["-no-pty" "-env" host-variables "xdg-open" address]))
(_ (cond
((windows?) WindowsShell)
((macos?) (Run "open" [address]))
(else (Run "xdg-open" [address]))))))
;; The first `name` on the PATH, if there is one.
(: (-> string (Option string)))
(defun (on-path name)
(match (get-environment-variable "PATH")
((Some path)
(def found (vec-filter (fun (dir) (and (not (string-empty? dir)) (file-exists? (path-combine dir name))))
(string-split path ":")))
(if (vec-empty? found) None (Some (path-combine (vec-ref found 0) name))))
(None None)))
;; host-spawn, when this program runs in a container that distrobox made:
;; the file that podman or docker puts in each container is there, and
;; host-spawn is on the PATH. `None` anywhere else.
(: (-> (Option string)))
(defun (distrobox-host-spawn)
(if (or (file-exists? "/run/.containerenv") (file-exists? "/.dockerenv"))
(on-path "host-spawn")
None))
;; How long the opener is waited for, in milliseconds.
(: int)
(def wait-ms 5000)
;; Why the opener `program` that ended with `code` did not open the address.
;; xdg-open ends with 3 when it found no program for the address, and
;; host-spawn ends as the host's xdg-open did.
(: (-> string int string))
(defun (opener-failure program code)
(def name (option-ref-or (path-filename program) program))
(if (and (= code 3) (or (= name "xdg-open") (= name "host-spawn")))
"xdg-open found no program to open it with."
(str name " ended with code " (int->string code) ".")))
;; Starts `program` with `args`, and waits for it a while.
(: (-> string (Vec string) string (Result string string)))
(defun (run-opener program args address)
(def info (ProcessStartInfo. program))
(shell-execute! info #f)
(loop (:for a args) (:do (add-argument! (arguments-of info) (string->clr-string a))))
(def p (start-process info))
(def ended (wait-for-exit p wait-ms))
(def code (if ended (exit-code-of p) 0))
(dispose-process p)
(if (= code 0)
(Ok (str "Opened " address))
(Err (str "Could not open " address ": " (opener-failure program code)))))
;; Gives `address` to the shell of Windows.
(: (-> string (Result string string)))
(defun (shell-open address)
(def info (ProcessStartInfo. address))
(shell-execute! info #t)
(def p (start-process info))
;; Start returns no process when the shell gave the address to one that
;; was already running.
(unless (eq? (cast Object p) (clr-default)) (dispose-process p))
(Ok (str "Opened " address)))
;; Opens `address`, and returns what was done, for the status line: the
;; text says it was opened, or why not. Raises what starting the program
;; raises, such as when BJOMARKS_BROWSER names no program. `#:host-spawn` is
;; host-spawn in a distrobox container: see `distrobox-host-spawn`.
(: (-> string (#:host-spawn (Option string)) (Result string string)))
(defun (open-in-browser address #:host-spawn (distrobox-host-spawn))
(if (not (browser-scheme? address))
(Err (str "Only http and https addresses are opened: " address))
(match (opener-for address (get-environment-variable "BJOMARKS_BROWSER") host-spawn)
((Run program args) (run-opener program args address))
(WindowsShell (shell-open address)))))
;; ---------------------------------------------------------------------------
;; A private window
;; ---------------------------------------------------------------------------
;; The flag that opens a private window in the browser of the .desktop file
;; `id`, such as "org.mozilla.firefox.desktop". None for one not known.
(: (-> string (Option string)))
(defun (private-flag id)
(def name (string-downcase id))
(defun (has? words) (not (vec-empty? (vec-filter (fun (w) (string-contains? name w)) words))))
(cond
((has? ["firefox" "librewolf" "waterfox" "floorp" "zen"]) (Some "--private-window"))
((has? ["edge"]) (Some "--inprivate"))
((has? ["chrome" "chromium" "brave" "vivaldi" "opera"]) (Some "--incognito"))
(else None)))
;; The words of the Exec line `exec` of a .desktop file, without its field
;; codes (%u, %U and the others) and flatpak's @@ marks. A word in double
;; quotes is one word.
(: (-> string (Vec string)))
(defun (exec-words exec)
(def chars (string->list exec))
(def words
(let go ((cs chars) (word "") (quoted #f) (started #f) (out []))
(match cs
((List c rest ...)
(cond
((char=? c #\") (go rest word (not quoted) #t out))
((and (char=? c #\space) (not quoted)) (if started (go rest "" #f #f (vec-add out word)) (go rest "" #f #f out)))
(else (go rest (str word (char->string c)) quoted #t out))))
(_ (if started (vec-add out word) out)))))
(vec-filter (fun (w) (not (or (string-starts-with? w "%") (string-starts-with? w "@@")))) words))
;; The program and its arguments that open `address` in a private window of
;; the browser of the .desktop file `id`, whose Exec line is `exec`.
(: (-> string string string (Option (Tuple string (Vec string)))))
(defun (private-command id exec address)
(def words (exec-words exec))
(match (private-flag id)
((Some flag) #:when (not (vec-empty? words))
(Some (Tuple (vec-ref words 0) (vec-append (vec-drop words 1) [flag address]))))
(_ None)))
;; What `program` with `args` writes, when it ends with 0 within the wait.
(: (-> string (Vec string) (Option string)))
(defun (output-of-program program args)
(: (-> (Option string)))
(defun (run)
(def info (ProcessStartInfo. program))
(shell-execute! info #f)
(redirect-output! info #t)
(loop (:for a args) (:do (add-argument! (arguments-of info) (string->clr-string a))))
(def p (start-process info))
(def text (read-to-end (output-of p)))
(def ended (wait-for-exit p wait-ms))
(def ok (and ended (= (exit-code-of p) 0)))
(dispose-process p)
(if ok (Some (string-trim text)) None))
(match (try (run) #:catch (System.Exception))
((Ok r) r)
((Err _) None)))
;; The folders of .desktop files: the user's, the system's, and flatpak's.
;; In a container, the host's system folders are under /run/host.
(: (-> bool (Vec string)))
(defun (application-folders in-container)
(def home (option-ref-or (get-environment-variable "XDG_DATA_HOME")
(path-combine (home-directory) ".local" "share")))
(def system (vec-filter (fun (d) (not (string-empty? d)))
(string-split (option-ref-or (get-environment-variable "XDG_DATA_DIRS")
"/usr/local/share:/usr/share")
":")))
(def systems (vec-append (if in-container
(vec-append ["/usr/local/share" "/usr/share"] system)
system)
["/var/lib/flatpak/exports/share"]))
(vec-append [(path-combine home "applications")
(path-combine home "flatpak" "exports" "share" "applications")]
(vec-map (fun (d) (path-combine (if in-container (str "/run/host" d) d) "applications")) systems)))
;; The first Exec line of the .desktop file `id`, in `folders`.
(: (-> string (Vec string) (Option string)))
(defun (desktop-exec id folders)
(def found (vec-filter file-exists? (vec-map (fun (d) (path-combine d id)) folders)))
(if (vec-empty? found)
None
(let ((lines (string-split (file-read-text (vec-ref found 0)) "\n")))
(def execs (vec-filter (fun (l) (string-starts-with? l "Exec=")) lines))
(if (vec-empty? execs) None (Some (string-drop (vec-ref execs 0) 5))))))
;; Opens `address` in a private window, and returns what was done, for the
;; status line. `Err` when there is no private window to open it in: see the
;; top of this module.
(: (-> string (#:host-spawn (Option string)) (Result string string)))
(defun (open-private-in-browser address #:host-spawn (distrobox-host-spawn))
(def none (str "No private window here: the browser is not one this app knows how to ask for one."))
(cond
((not (browser-scheme? address)) (Err (str "Only http and https addresses are opened: " address)))
(else
(match (get-environment-variable "BJOMARKS_PRIVATE_BROWSER")
((Some program) (run-opener program [address] address))
(None
(if (or (windows?) (macos?))
(Err none)
(let ((id (match host-spawn
((Some spawn) (output-of-program spawn ["-no-pty" "xdg-settings" "get" "default-web-browser"]))
(None (output-of-program "xdg-settings" ["get" "default-web-browser"])))))
(match (match id
((Some i) (match (desktop-exec i (application-folders (some? host-spawn)))
((Some exec) (private-command i exec address))
(None None)))
(None None))
((Some (Tuple program args))
(match host-spawn
((Some spawn)
(run-opener spawn (vec-append ["-no-pty" "-env" host-variables program] args) address))
(None (run-opener program args address))))
(None (Err none))))))))))

207
src/fetch-button.bjo Normal file
View file

@ -0,0 +1,207 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjomarks-gui/src/fetch-button.bjo — the module (bjomarks-gui fetch-button):
;; the buttons that fetch a title and an archive link, with a spinner while
;; they work.
;;
;; - `fetch-button` is beside the title, and `archive-button` beside the
;; archive link. Both are made by `spinner-button`.
;; - The value of a button is true while its fetch runs. Then the label is hidden, and an
;; arc turns in its place, longer and shorter as it turns. The button
;; keeps its size.
;; - The animation is Avalonia's, in a style of the arc that applies while
;; the arc has the class "spinning". So it runs on the render loop, and
;; only while a fetch runs.
;; - A click sends `FetchPressed`, also while a fetch runs: the program
;; decides what that does.
;;
;; bjogui has no animations, so the button is an Avalonia `Button`, made
;; with (bjogui native).
(export FetchOut fetch-button archive-button)
(import (std prelude))
(import (std interop))
(import (bjogui native))
(import/class
(Object (: System.Object))
(TimeSpan (: System.TimeSpan))
(Control (: Avalonia.Controls.Control))
(Button (: Avalonia.Controls.Button (-> Button)))
(ContentControl (: Avalonia.Controls.ContentControl))
(Grid (: Avalonia.Controls.Grid (-> Grid)))
(Panel (: Avalonia.Controls.Panel))
(Controls (: Avalonia.Controls.Controls))
(TextBlock (: Avalonia.Controls.TextBlock (-> TextBlock)))
(Arc (: Avalonia.Controls.Shapes.Arc (-> Arc)))
(Shape (: Avalonia.Controls.Shapes.Shape))
(IBrush (: Avalonia.Media.IBrush))
(PenLineCap (: Avalonia.Media.PenLineCap))
(Layoutable (: Avalonia.Layout.Layoutable))
(HAlign (: Avalonia.Layout.HorizontalAlignment))
(VAlign (: Avalonia.Layout.VerticalAlignment))
(Visual (: Avalonia.Visual))
(StyledElement (: Avalonia.StyledElement))
(AvaloniaObject (: Avalonia.AvaloniaObject))
(AvaloniaProperty (: Avalonia.AvaloniaProperty))
(Classes (: Avalonia.Controls.Classes))
(Styles (: Avalonia.Styling.Styles))
(IStyle (: Avalonia.Styling.IStyle))
(Style (: Avalonia.Styling.Style (-> Style)))
(StyleBase (: Avalonia.Styling.StyleBase))
(Selector (: Avalonia.Styling.Selector))
(Setter (: Avalonia.Styling.Setter (-> AvaloniaProperty Object Setter)))
(Animation (: Avalonia.Animation.Animation (-> Animation)))
(IAnimation (: Avalonia.Animation.IAnimation))
(KeyFrame (: Avalonia.Animation.KeyFrame (-> KeyFrame)))
(KeyFrames (: Avalonia.Animation.KeyFrames))
(IAnimationSetter (: Avalonia.Animation.IAnimationSetter))
(Cue (: Avalonia.Animation.Cue (-> double Cue)))
(IterationCount (: Avalonia.Animation.IterationCount))
(Easing (: Avalonia.Animation.Easings.Easing))
(SineEaseInOut (: Avalonia.Animation.Easings.SineEaseInOut (-> SineEaseInOut)))
((ICollection %a) (: System.Collections.Generic.ICollection))
((IList %a) (: System.Collections.Generic.IList))
((AvaloniaList %a) (: Avalonia.Collections.AvaloniaList)))
(import/extern
;; Typed, so that a Native AOT build keeps the event.
(on-click! (: Avalonia.Controls.Button.Click #:event)))
(import/extern
(from-ms (: System.TimeSpan.FromMilliseconds (-> double TimeSpan)))
(content! (: Avalonia.Controls.ContentControl.Content (-> ContentControl Object void) #:set))
(children-of (: Avalonia.Controls.Panel.Children (-> Panel Controls) #:get))
(child-at (: Avalonia.Controls.Controls.get_Item (-> Controls int Control)))
(text! (: Avalonia.Controls.TextBlock.Text (-> TextBlock string void) #:set))
(width! (: Avalonia.Layout.Layoutable.Width (-> Layoutable double void) #:set))
(height! (: Avalonia.Layout.Layoutable.Height (-> Layoutable double void) #:set))
(horizontal! (: Avalonia.Layout.Layoutable.HorizontalAlignment (-> Layoutable HAlign void) #:set))
(vertical! (: Avalonia.Layout.Layoutable.VerticalAlignment (-> Layoutable VAlign void) #:set))
(visible! (: Avalonia.Visual.IsVisible (-> Visual bool void) #:set))
(opacity! (: Avalonia.Visual.Opacity (-> Visual double void) #:set))
(start-angle! (: Avalonia.Controls.Shapes.Arc.StartAngle (-> Arc double void) #:set))
(sweep-angle! (: Avalonia.Controls.Shapes.Arc.SweepAngle (-> Arc double void) #:set))
(start-angle-property (: Avalonia.Controls.Shapes.Arc.StartAngleProperty #:get))
(sweep-angle-property (: Avalonia.Controls.Shapes.Arc.SweepAngleProperty #:get))
(stroke! (: Avalonia.Controls.Shapes.Shape.Stroke (-> Shape IBrush void) #:set))
(stroke-thickness! (: Avalonia.Controls.Shapes.Shape.StrokeThickness (-> Shape double void) #:set))
(stroke-cap! (: Avalonia.Controls.Shapes.Shape.StrokeLineCap (-> Shape PenLineCap void) #:set))
(foreground-property (: Avalonia.Controls.Primitives.TemplatedControl.ForegroundProperty #:get))
(get-value (: Avalonia.AvaloniaObject.GetValue (-> AvaloniaObject AvaloniaProperty Object)))
(classes-of (: Avalonia.StyledElement.Classes (-> StyledElement Classes) #:get))
(class-set! (: Avalonia.Controls.Classes.Set (-> Classes string bool void)))
(styles-of (: Avalonia.StyledElement.Styles (-> StyledElement Styles) #:get))
(styles-add! (: Avalonia.Styling.Styles.Add (-> Styles IStyle void)))
(selector! (: Avalonia.Styling.Style.Selector (-> Style Selector void) #:set))
(class-selector (: Avalonia.Styling.Selectors.Class (-> Selector string Selector)))
(animations-of (: Avalonia.Styling.StyleBase.Animations (-> StyleBase (IList IAnimation)) #:get))
(duration! (: Avalonia.Animation.Animation.Duration (-> Animation TimeSpan void) #:set))
(iterations! (: Avalonia.Animation.Animation.IterationCount (-> Animation IterationCount void) #:set))
(easing! (: Avalonia.Animation.Animation.Easing (-> Animation Easing void) #:set))
(forever (: Avalonia.Animation.IterationCount.Infinite #:get))
(key-frames-of (: Avalonia.Animation.Animation.Children (-> Animation KeyFrames) #:get))
(setters-of (: Avalonia.Animation.KeyFrame.Setters (-> KeyFrame (AvaloniaList IAnimationSetter)) #:get))
(cue! (: Avalonia.Animation.KeyFrame.Cue (-> KeyFrame Cue void) #:set))
(add-to! (: System.Collections.Generic.ICollection.Add (-> (ICollection %a) %a void))))
;; What the button sends: it was clicked.
(type (: FetchOut (Union FetchPressed)))
;; The class that makes the arc turn.
(: string)
(def spinning "spinning")
;; An animation of `property` through `values`, evenly spaced, in `ms`
;; milliseconds, again and again.
(: (-> AvaloniaProperty (Vec double) double Animation))
(defun (looping property values ms)
(def a (Animation.))
(duration! a (from-ms ms))
(iterations! a forever)
(def n (vec-length values))
(loop (:for i (range 0 n))
(:do (def k (KeyFrame.))
(cue! k (Cue. (/ (cast double i) (cast double (- n 1)))))
(add-to! (cast (ICollection IAnimationSetter) (setters-of k))
(cast IAnimationSetter (Setter. property (cast Object (vec-ref values i)))))
(add-to! (cast (ICollection KeyFrame) (key-frames-of a)) k)))
a)
;; The style that turns an arc while it has the class "spinning": its start
;; goes round once in 0.9 s, and its length grows and shrinks in 1.6 s, so
;; that the two do not keep step.
(: (-> Style))
(defun (spin-style)
(def s (Style.))
(selector! s (class-selector (clr-default) spinning))
(def turn (looping (cast AvaloniaProperty start-angle-property) [0.0 360.0] 900.0))
(def breathe (looping (cast AvaloniaProperty sweep-angle-property) [60.0 270.0 60.0] 1600.0))
(easing! breathe (cast Easing (SineEaseInOut.)))
(def animations (cast (ICollection IAnimation) (animations-of s)))
(add-to! animations (cast IAnimation turn))
(add-to! animations (cast IAnimation breathe))
s)
(: (-> Control Grid))
(defun (face-of button) (cast Grid (.-Content (cast ContentControl button))))
;; The label and the arc, in the button.
(: (-> Control (Tuple TextBlock Arc)))
(defun (parts-of button)
(def kids (children-of (cast Panel (face-of button))))
(Tuple (cast TextBlock (child-at kids 0)) (cast Arc (child-at kids 1))))
;; The arc is drawn in the colour of the button's text, when the button has
;; one.
(: (-> Control Arc void))
(defun (colour-arc! button arc)
(match (get-value (cast AvaloniaObject button) (cast AvaloniaProperty foreground-property))
((:is Avalonia.Media.IBrush brush) (stroke! (cast Shape arc) brush))
(_ unit)))
;; A button labelled `label`, with a spinner while its value is true.
(: (-> string (Native bool FetchOut)))
(defun (spinner-button label)
(native (fun (send)
(def text (TextBlock.))
(text! text label)
(horizontal! (cast Layoutable text) HAlign.Center)
(vertical! (cast Layoutable text) VAlign.Center)
(def arc (Arc.))
(width! (cast Layoutable arc) 16.0)
(height! (cast Layoutable arc) 16.0)
(horizontal! (cast Layoutable arc) HAlign.Center)
(vertical! (cast Layoutable arc) VAlign.Center)
(start-angle! arc 0.0)
(sweep-angle! arc 270.0)
(stroke-thickness! (cast Shape arc) 2.0)
(stroke-cap! (cast Shape arc) PenLineCap.Round)
(visible! (cast Visual arc) #f)
(styles-add! (styles-of (cast StyledElement arc)) (cast IStyle (spin-style)))
;; One cell: the arc is over the label, and the label gives the
;; button its size.
(def face (Grid.))
(.Add (children-of (cast Panel face)) (cast Control text))
(.Add (children-of (cast Panel face)) (cast Control arc))
(def button (Button.))
(content! (cast ContentControl button) (cast Object face))
(ignore (on-click! button (fun (s e) (send FetchPressed))))
(cast Control button))
(fun (control busy)
(def (Tuple text arc) (parts-of control))
(when busy (colour-arc! control arc))
(opacity! (cast Visual text) (if busy 0.0 1.0))
(visible! (cast Visual arc) busy)
(class-set! (classes-of (cast StyledElement arc)) spinning busy))))
;; The button beside the title of the dialog.
(: fetch-button (Native bool FetchOut))
(def fetch-button (spinner-button "Fetch title"))
;; The button beside the archive link of the dialog.
(: archive-button (Native bool FetchOut))
(def archive-button (spinner-button "Fetch archive"))

172
src/inputs.bjo Normal file
View file

@ -0,0 +1,172 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjomarks-gui/src/inputs.bjo — the module (bjomarks-gui inputs): the two
;; text inputs that bjogui's `text-input` cannot be.
;;
;; - The search box hears Ctrl+N itself. Only the box knows that it has the
;; keyboard, and "Ctrl+N in the search box" goes to the first bookmark,
;; while Ctrl+N elsewhere goes to the next one.
;; - The search box hears Ctrl+Z too, when its value says that Ctrl+Z is
;; the window's. Else the box undoes its typing, and a TextBox takes
;; Ctrl+Z also when it has nothing to undo: the window would never hear it.
;; - The password box shows dots, and hears Enter. The first of a screen
;; takes the keyboard when it is shown.
;;
;; Both are Avalonia `TextBox`es, made with (bjogui native). The keys are
;; heard as they tunnel down to the box, before the box's own handling, so
;; that no key binding of the theme's or the box's can take them first. A
;; key the box hears is handled, and does not reach the window's keys.
(export SearchOut search-box PasswordOut password-box first-password-box)
(import (std prelude))
(import (std interop))
(import (bjogui native))
(import/class
(Object (: System.Object))
(Control (: Avalonia.Controls.Control))
(TextBox (: Avalonia.Controls.TextBox (-> TextBox)))
(Layoutable (: Avalonia.Layout.Layoutable))
(Alignment (: Avalonia.Layout.HorizontalAlignment))
(Interactive (: Avalonia.Interactivity.Interactive))
(RoutedEvent (: Avalonia.Interactivity.RoutedEvent))
(RoutedEventArgs (: Avalonia.Interactivity.RoutedEventArgs))
(Routes (: Avalonia.Interactivity.RoutingStrategies))
(KeyEventArgs (: Avalonia.Input.KeyEventArgs))
(KeyCode (: Avalonia.Input.Key))
(KeyModifiers (: Avalonia.Input.KeyModifiers))
(KeyGesture (: Avalonia.Input.KeyGesture (-> KeyCode KeyModifiers KeyGesture)))
(InputElement (: Avalonia.Input.InputElement))
(NavMethod (: Avalonia.Input.NavigationMethod))
((EventHandler %a) (: System.EventHandler)))
(import/extern
;; Typed, so that a Native AOT build keeps the event.
(on-loaded! (: Avalonia.Controls.Control.Loaded #:event)))
(import/extern
(text-of (: Avalonia.Controls.TextBox.Text (-> TextBox string) #:get))
(text! (: Avalonia.Controls.TextBox.Text (-> TextBox string void) #:set))
(placeholder! (: Avalonia.Controls.TextBox.PlaceholderText (-> TextBox string void) #:set))
(horizontal! (: Avalonia.Layout.Layoutable.HorizontalAlignment (-> Layoutable Alignment void) #:set))
(password-char! (: Avalonia.Controls.TextBox.PasswordChar (-> TextBox System.Char void) #:set))
(text-changing (: Avalonia.Controls.TextBox.TextChangingEvent #:get))
(key-down-event (: Avalonia.Input.InputElement.KeyDownEvent #:get))
(got-focus-event (: Avalonia.Input.InputElement.GotFocusEvent #:get))
(lost-focus-event (: Avalonia.Input.InputElement.LostFocusEvent #:get))
(add-handler (: Avalonia.Interactivity.Interactive.AddHandler
(-> Interactive RoutedEvent Delegate Routes bool void)))
(handled! (: Avalonia.Interactivity.RoutedEventArgs.Handled (-> RoutedEventArgs bool void) #:set))
(key-of (: Avalonia.Input.KeyEventArgs.Key (-> KeyEventArgs KeyCode) #:get))
(modifiers-of (: Avalonia.Input.KeyEventArgs.KeyModifiers (-> KeyEventArgs KeyModifiers) #:get))
(gesture-text (: Avalonia.Input.KeyGesture.ToString (-> KeyGesture string)))
(tag-of (: Avalonia.Controls.Control.Tag (-> Control Object) #:get))
(tag! (: Avalonia.Controls.Control.Tag (-> Control Object void) #:set))
;; Both arguments, as Bjolang does not fill in .NET's optional ones.
(focus! (: Avalonia.Input.InputElement.Focus (-> InputElement NavMethod KeyModifiers bool))))
(: (-> TextBox RoutedEvent Routes (-> RoutedEventArgs void) void))
(defun (listen! box event routes f)
(add-handler (cast Interactive box) event
(cast Delegate (cast Object (: (as-delegate (: (fun (s e) (f e)) (-> Object RoutedEventArgs void)))
(EventHandler RoutedEventArgs))))
routes #f))
;; Calls `(f keys)` for each key pressed in the box, with the keys written as
;; "Ctrl+N" is. When it returns true, the key is handled.
(: (-> TextBox (-> string bool) void))
(defun (on-keys! box f)
(listen! box (cast RoutedEvent key-down-event) Routes.Tunnel
(fun (e)
(def k (cast KeyEventArgs e))
(when (f (gesture-text (KeyGesture. (key-of k) (modifiers-of k))))
(handled! e #t)))))
;; Calls `(f text)` for each change of the text.
(: (-> TextBox (-> string void) void))
(defun (on-text! box f)
(listen! box (cast RoutedEvent text-changing) Routes.Bubble (fun (e) (f (text-of box)))))
;; Sets the text, if it is another: setting the same text moves the caret.
(: (-> Control string void))
(defun (show-text! control value)
(def box (cast TextBox control))
(unless (= (text-of box) value) (text! box value)))
;; What the search box sends: the text, at each change; Ctrl+N; Ctrl+Z, when
;; it is not the box's; and whether it has the keyboard, each time that
;; changes: a removal then leaves the keyboard in the box.
(type (: SearchOut (Union (: SearchTyped string) SearchNext SearchUndo (: SearchFocus bool))))
;; True when Ctrl+Z is the window's, as the box's value last said. It is kept
;; in the box's `Tag`, as the key is heard when no value is at hand.
(: (-> Control bool))
(defun (window-undo? control)
(match (tag-of control)
((:is System.Boolean b) b)
(_ #f)))
;; A search box's value is its text, and whether Ctrl+Z in it is the
;; window's: then the box sends `SearchUndo` and does not undo its typing.
;; The program says so when the last thing done is one that Ctrl+Z undoes,
;; and nothing was typed in the box after it.
(: search-box (Native (Tuple string bool) SearchOut))
(def search-box
(native (fun (send)
(def box (TextBox.))
(placeholder! box "Search: words, t:tag, d:site, a:2024")
(listen! box (cast RoutedEvent got-focus-event) Routes.Bubble (fun (e) (send (SearchFocus #t))))
(listen! box (cast RoutedEvent lost-focus-event) Routes.Bubble (fun (e) (send (SearchFocus #f))))
(on-text! box (fun (s) (send (SearchTyped s))))
(on-keys! box (fun (keys)
(cond
((= keys "Ctrl+N") (send SearchNext) #t)
((and (= keys "Ctrl+Z") (window-undo? (cast Control box)))
(send SearchUndo)
#t)
(else #f))))
(cast Control box))
(fun (control value)
(def (Tuple text window-undo) value)
(tag! control (cast Object window-undo))
(show-text! control text))))
;; What the password box sends: the text, at each change, and Enter.
(type (: PasswordOut (Union (: PasswordTyped string) PasswordEnter)))
;; A password box's value is its placeholder and its text. It stands at the
;; left of the space it is given, as wide as its view says. With
;; `focus-when-shown`, it takes the keyboard when Avalonia has loaded it:
;; bjogui has no command that runs when the window opens.
(: (-> bool (Native (Tuple string string) PasswordOut)))
(defun (password-box-kind focus-when-shown)
(native (fun (send)
(def box (TextBox.))
(password-char! box (cast System.Char 8226))
(horizontal! (cast Layoutable box) Alignment.Left)
(when focus-when-shown
(ignore (on-loaded! (cast Control box)
(fun (s e) (ignore (focus! (cast InputElement box) NavMethod.Unspecified KeyModifiers.None))))))
(on-text! box (fun (s) (send (PasswordTyped s))))
(on-keys! box (fun (keys)
;; Avalonia's Key.Enter and Key.Return are one
;; value, which a gesture writes as "Return".
(if (or (= keys "Enter") (= keys "Return"))
(begin (send PasswordEnter) #t)
#f)))
(cast Control box))
(fun (control value)
(def (Tuple placeholder text) value)
(placeholder! (cast TextBox control) placeholder)
(show-text! control text))))
(: password-box (Native (Tuple string string) PasswordOut))
(def password-box (password-box-kind #f))
;; The first password box of a screen: it has the keyboard when the screen
;; is shown.
(: first-password-box (Native (Tuple string string) PasswordOut))
(def first-password-box (password-box-kind #t))

73
src/main.bjo Normal file
View file

@ -0,0 +1,73 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; (bjomarks-gui) — bookmarks in a window.
;;
;; bjo run . [SHARED [LOCAL]]
;;
;; SHARED is the folder that the devices share, through a file syncer or a
;; mounted WebDAV share: BJOMARKS_SHARED unless given, else the folder chosen
;; on the first screen, else ~/Sync/bookmarks. The first screen lists the
;; folders added, saved in ~/.config/bjomarks/settings.json, with "Add
;; new…" after them; it is there only when neither SHARED nor
;; BJOMARKS_SHARED is given.
;; LOCAL is this device's own folder: BJOMARKS_LOCAL, or "bjomarks" in the
;; user's data folder, unless given. See (bjomarks-gui app) for the window.
;;
;; Enter opens a bookmark with the system's opener (xdg-open on Linux; in a
;; distrobox container, the host's, through host-spawn), or with the program
;; BJOMARKS_BROWSER names: see (bjomarks-gui browser).
;;
;; A title is fetched from the site only when the button beside the title,
;; in the dialog, is clicked.
;;
;; The window has KDE's look: AvaUnion draws it with the session's Union
;; style, colours and fonts, or with the Breeze snapshot it carries when
;; there is no KDE session. BJOMARKS_LOOK=fluent draws it with Avalonia's
;; Fluent theme instead.
(import (std prelude))
(import (std os))
(import (bjogui app))
(import (bjomarks store))
(import (bjomarks-gui app))
(import (bjomarks-gui settings))
(import/class
(UnionTheme (: AvaUnion.UnionTheme (-> UnionTheme))))
(: (-> string (List IStyle)))
(defun (themes look)
(match look
("fluent" (list (fluent-theme)))
(_ (list (cast IStyle (UnionTheme.))))))
(: (-> (Vec string) int string string string))
(defun (arg-or args i variable fallback)
(if (> (vec-length args) i)
(vec-ref args i)
(option-ref-or (get-environment-variable variable) fallback)))
(: (-> (Vec string) int))
(defun (main args)
(def settings (settings-folder))
;; An argument or BJOMARKS_SHARED fixes the shared folder. Else it is the
;; one saved in the settings, which the first screen can change.
(def fixed (or (> (vec-length args) 0) (some? (get-environment-variable "BJOMARKS_SHARED"))))
(def shared (arg-or args 0 "BJOMARKS_SHARED"
(option-ref-or (read-shared-folder settings)
(path-combine (home-directory) "Sync" "bookmarks"))))
;; An argument or BJOMARKS_LOCAL fixes this device's folder. Else each
;; shared folder has one of its own, in the app's data folder.
(def root (path-combine (data-directory) "bjomarks"))
(def local (arg-or args 1 "BJOMARKS_LOCAL" ""))
(def look (option-ref-or (get-environment-variable "BJOMARKS_LOOK") ""))
(run-app (initial-model (folder-storage shared) local #:settings (if fixed "" settings)
#:root (if (string-empty? local) (Some root) None)
#:vaults (if fixed [] (read-vaults settings))) gui-update view
#:windows windows #:keys keys #:subscriptions subscriptions
#:on-close (Some CloseAsked)
#:themes (fun () (themes look))
#:title "Bjomarks" #:width 640.0 #:height 520.0)
0)

105
src/settings.bjo Normal file
View file

@ -0,0 +1,105 @@
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjomarks-gui/src/settings.bjo — the module (bjomarks-gui settings): what
;; the window keeps between runs, in settings.json in a folder of its own.
;;
;; {"shared": "/home/me/Sync/bookmarks",
;; "vaults": ["/home/me/Sync/bookmarks", "/home/me/Sync/work"]}
;;
;; - The folder is "bjomarks" in the user's folder for configuration:
;; ~/.config/bjomarks on Linux, as XDG_CONFIG_HOME says.
;; - "shared" is the shared folder used last: where the vault is.
;; - "vaults" is the shared folders that the user added, in the order they
;; were added. The first screen shows them by the name of the folder.
;; Settings of an earlier version, with "shared" only, have that one.
;; - The fields that this version does not know are kept when it writes.
;; - The file is written whole and then renamed over the old one, so that it
;; is never half written.
(export settings-folder read-shared-folder save-shared-folder! read-vaults save-vaults!)
(import (std prelude))
(import (std os))
(import (text json))
(: string)
(def file-name "settings.json")
;; The folder of the settings: "bjomarks" in the user's folder for
;; configuration.
(: (-> string))
(defun (settings-folder) (path-combine (config-directory) "bjomarks"))
;; The fields of the settings in `folder`, in their order. None when there
;; is no settings file, or it is not a JSON object.
(: (-> string (Option (IArray (Tuple string Json)))))
(defun (read-fields folder)
(def file (path-combine folder file-name))
(if (not (file-exists? file))
None
(match (parse-json (file-read-text file) #:objects 'fields)
((Ok (JsonFields fields)) (Some fields))
(_ None))))
;; The shared folder saved in the settings in `folder`. None when none is
;; saved, or the file cannot be read as settings.
(: (-> string (Option string)))
(defun (read-shared-folder folder)
(match (read-fields folder)
((Some fields)
(match (json-object-ref (JsonFields fields) "shared")
((Some (JsonStr s)) (if (string-empty? (string-trim s)) None (Some s)))
(_ None)))
(None None)))
;; Saves `shared` as the shared folder in the settings in `folder`, and
;; keeps their other fields. Makes `folder` when it is not there. Raises
;; what the file system raises.
(: (-> string string void))
(defun (save-shared-folder! folder shared)
(save-fields! folder [(Tuple "shared" (JsonStr shared))]))
;; The shared folders saved in the settings in `folder`, in their order.
;; Settings with a "shared" and no "vaults" have that one.
(: (-> string (Vec string)))
(defun (read-vaults folder)
(match (read-fields folder)
((Some fields)
(match (json-object-ref (JsonFields fields) "vaults")
((Some (JsonArr items))
(vec-fold (fun (j acc)
(match j
((JsonStr path) (if (or (string-empty? (string-trim path)) (vec-contains? acc path))
acc
(vec-add acc path)))
(_ acc)))
[] (iarray->vec items)))
(_ (match (read-shared-folder folder)
((Some path) [path])
(None [])))))
(None [])))
;; Saves `vaults` in the settings in `folder`, and `last` as the one used
;; last, and keeps their other fields.
(: (-> string (Vec string) string void))
(defun (save-vaults! folder vaults last)
(save-fields! folder [(Tuple "shared" (JsonStr last))
(Tuple "vaults" (JsonArr (vec->iarray (vec-map (fun (p) (JsonStr p)) vaults))))]))
;; Saves `fields` in the settings in `folder`, in place of those of their
;; names, and keeps the others. Makes `folder` when it is not there. Raises
;; what the file system raises.
(: (-> string (Vec (Tuple string Json)) void))
(defun (save-fields! folder fields)
(def names (vec-map fst fields))
(def others (match (read-fields folder)
((Some old) (vec-filter (fun (f) (not (vec-contains? names (fst f)))) (iarray->vec old)))
(None [])))
(def text (json->string (JsonFields (vec->iarray (vec-append others fields)))))
(directory-create folder)
(def file (path-combine folder file-name))
(def partial (str file ".new"))
(file-write-text partial text)
(file-move partial file #:mode MoveReplace))