Chapters

Docs App frameworks

Documents and data

This chapter covers the document layer, the file panels it uses, the file types that decide what opens a file, and where an app keeps its preferences and secrets. The document layer mirrors NSDocument and NSDocumentController, and the panels mirror NSOpenPanel and NSSavePanel.

File access without paths

An app never receives a file path. It asks the shell for a file with the documents permission, the shell shows the panel, and the user picks the file. The app then gets an open file and a grant. The shell resolves the path as the account, so the app cannot read or write anything the user did not choose.

Add the permission to the manifest:

permissions = ["documents"]

Without the permission the answer to a panel request is DocumentEvent::Failed with DocErrorCode::Unsupported. The permission binds no part of the home directory.

The answer to a panel arrives in App::document as a DocumentEvent. A Document value in the event carries the open std::fs::File, the file name, its size, the access mode and a grant that reopens the file later.

ctx.open_document(mode, title, filters) -> u32
Shows the open panel for one file. mode is DocMode::Read or DocMode::Write. filters are type identifiers such as "public.text" or extensions such as "md". The return value is the request id. The answer is DocumentEvent::Opened.
ctx.open_panel(&OpenOptions) -> u32
Shows the open panel with the options below. With multiple set, the answer is always DocumentEvent::OpenedMany { request, docs }, even for one file.
ctx.save_document(suggested_name, filters) -> u32
Shows the save panel. The answer is DocumentEvent::SaveTo with a file to write.
ctx.commit_document(request)
Puts the written save in place. The answer is DocumentEvent::Saved. Nothing at the chosen place changes until the commit.
ctx.abort_document(request)
Throws the save away. The file at the chosen place is untouched.
ctx.reopen_document(grant) -> u32
Opens a file chosen earlier, by its grant. The answer is DocumentEvent::Failed with DocErrorCode::Stale when the file was replaced.
ctx.release_document(grant)
Tells the shell the app no longer needs the grant.

A save follows three steps. The app calls save_document, writes the file in SaveTo, and calls commit_document. The commit replaces the file in one step, so a crash leaves the old copy. The shell answers Failed with Cancelled when the user closes a panel.

Note

The shell shows one panel at a time. A second request while a panel is open is answered with Cancelled.

Open panel options

The OpenOptions struct matches the parts of NSOpenPanel that the shell supports. Every field has a default, so you set only what you need.

FieldAppKitDefault
modethe access the app asks forDocMode::Read
titlemessageempty
filtersallowedContentTypes, matched with uttype::conforms or by extensionnone, so every file is shown
multipleallowsMultipleSelectionfalse
filescanChooseFilestrue
directoriescanChooseDirectoriesfalse
create_directoriescanCreateDirectoriesfalse

A chosen folder is granted as a read-only directory. Pass it to reopen_document to open it again later. A save panel always has New Folder.

Important

Filters only dim the files that do not match. They do not check what the user picks, so check the type of the file you read.

The document model

A document type implements the Document trait in bifrost_app::document. The trait turns bytes into the model and the model back into bytes. It is the counterpart of read(from:ofType:) and data(ofType:). Types are uniform type identifiers.

use bifrost_app::document::{Document, DocumentError};

struct Note {
    text: String,
}

impl Document for Note {
    fn read(bytes: &[u8], _uttype: &str) -> Result<Self, DocumentError> {
        String::from_utf8(bytes.to_vec())
            .map(|text| Note { text })
            .map_err(|_| DocumentError::new("not UTF-8"))
    }
    fn write(&self, _uttype: &str) -> Result<Vec<u8>, DocumentError> {
        Ok(self.text.clone().into_bytes())
    }
    fn untitled() -> Self {
        Note { text: String::new() }
    }
    fn readable_types() -> &'static [&'static str] {
        &["public.plain-text"]
    }
    fn default_type() -> &'static str {
        "public.plain-text"
    }
}

Then the app owns a DocumentController<Note>. The controller holds the open documents, the untitled numbering, the edited flag, autosave and the File menu. It reaches the shell through the DocumentHost trait, which Ctx implements. Wire it into the app like this:

fn document(&mut self, ctx: &Ctx, ev: DocumentEvent) -> bool {
    self.docs.handle(ctx, ev).is_some()
}
fn main_menu(&self, _: &Ctx) -> Vec<AppMenu> {
    vec![self.docs.file_menu()]
}
fn menu_action(&mut self, ctx: &Ctx, id: u32) -> bool {
    self.docs.menu_action(ctx, id).is_some()
}
fn tick(&mut self, ctx: &Ctx, t: f64) -> bool {
    self.docs.tick(ctx, t);
    false
}
fn next_wake(&self, _: f64) -> Option<f64> {
    self.docs.next_wake()
}
fn suspend(&mut self, ctx: &Ctx) {
    self.docs.suspend(ctx)
}

The app draws the document. After each edit it calls note_change with the undo manager's change count, so the controller knows whether the content differs from the last save. An app without an undo manager calls mark_edited instead.

DocumentController::new() -> Self
An empty controller. Its Default implementation does the same.
new_document() -> DocId
Adds an untitled document with the smallest free number, as File > New does.
open_panel(host)
Shows the open panel for the document's readable types. Several files may be chosen.
handle(ctx, event) -> Option<Vec<Notice>>
Takes a DocumentEvent. It returns None when the event is not the controller's request. Otherwise it returns the Notice values to act on: Created, Opened, Saved, Reverted, Closed or Failed.
get(id) / get_mut(id) -> Option<&D>
The model of an open document.
active() / set_active(id) / ids()
The document that the window shows, and the open documents in order.
display_name(id) / window_title(id) / file_name(id) / uttype(id)
"Untitled", "Untitled 2" and so on for a new document; the file name for a saved one; the type identifier.

Saving, autosave and closing

The controller saves the way NSDocument does. save writes in place for a saved document and shows the save panel for an untitled one. save_as, rename and move_to use the save panel. duplicate makes an edited untitled copy, and revert reads the file again and reports Notice::Reverted, so you can reset the undo manager.

Autosave runs in place. Call tick on each loop turn and next_wake from App::next_wake. A document saves once autosave_delay has passed since its first unsaved change. The default is 5000 ms (AUTOSAVE_DELAY_MS). suspend writes everything that is unsaved when the app is put away. A failed autosave is not retried until the next change.

The shell draws the edited state. sync sends the title, the edited flag and the file name whenever they change, so the close light shows the edited dot and the title bar shows "Edited".

Note

Rename and Move To copy the file to the new name and leave the old one in place. The broker has no request to delete a file yet.

The File menu and recent documents

file_menu() returns the standard File menu: New, Open, Open Recent, Close, Save, Save As, Duplicate, Rename, Move To and Revert To Saved. The items are enabled for the active document. Return it from main_menu, and pass the chosen id to menu_action. Use document::is_menu_id to test whether an id belongs to the controller.

The controller keeps the ten most recent documents, newest first, in the app preference document.recents. Choosing one reopens it by its grant. A recent file that is gone or replaced leaves the list. clear_recents empties the list and releases the grants.

File types

The uttype module, at bifrost_app::controls::uttype, is the one table of file types. Each entry has an identifier, its parents, its extensions, its MIME type and a description. Use these functions to test a file against the types your app reads.

type_for_extension(name) -> Option<&'static str>
The type of a file name or extension, case-insensitive. None for an unknown extension.
type_for_mime(mime) -> Option<&'static str>
The type of a MIME type.
conforms(id, ancestor) -> bool
Whether a type is the ancestor or inherits from it. conforms("public.png", "public.image") is true, which is the test the open panel uses for filters.
distance(id, ancestor) -> Option<usize>
How many steps up the tree the ancestor is. Used to pick the most specific type.
extensions(id) / preferred_extension(id) / description(id) / mime(id)
The extensions of a type, the one used for a new file name, the human name and the MIME type.

Default apps

An app declares the types and URL schemes it opens in its manifest. The shell keeps the declarations in a registry, bifrost_ui::launch::Registry, which resolves the default app for a type.

handles = ["public.png:owner", "public.text"]
schemes = ["https"]

A rank follows a type with a colon: owner, default, alternate or none. A type without a rank has rank default. none means the app can open the type but is never chosen by itself. Without a user choice, the most specific type wins, then the higher rank, then the app that was registered first. A user choice always wins.

Registry methodPurpose
default_for_type(uti)The app that opens a type by default.
default_for_file(name)The same, from a file name.
open_with(name)Every candidate for an Open With menu, with the default marked.
set_default_for_type(uti, app)Records the user’s choice for a type. Fails with SetError::CannotOpen when the app does not declare the type.
default_for_scheme(scheme) and set_default_for_schemeThe same for URL schemes.

Choices are stored in the shell’s preferences. A choice for an app that is not installed is kept and applies again if the app returns.

Important

Not yet available: an SDK call that asks the shell to open a path with its default app, an Open With menu in Files, and opening a file that the user double-clicks in Files through the registry. Apps cannot yet ask the shell to open a file for them.

Preferences and app data

Each app has a private data directory, ctx.data_dir, set from BIFROST_DATA. Use it for files the app owns. Preferences go in ctx.defaults() and ctx.defaults_mut(), the counterpart of NSUserDefaults.standard.

defaults().string(key) / bool(key) / int(key) / double(key) / data(key)
Reads a value. A missing or mistyped key reads as the zero value, as in Foundation: None for a string or data, false, 0 and 0.0 otherwise.
defaults_mut().set_string(key, value) / set_bool / set_int / set_double / set_data
Writes a value. Each change is saved at once to defaults.txt in the data directory, by an atomic replace.
defaults().contains(key) / keys() / defaults_mut().remove(key)
Tests, lists and removes keys.
Note

defaults.txt is readable by the app and its data directory is not private from it. Store secrets in the keychain, not in preferences.

Keychain

The keychain stores secrets that the shell keeps for the app. It is the counterpart of SecItem with kSecClassGenericPassword. The app needs the keychain permission. Without it every call answers Error::NotPermitted.

permissions = ["keychain"]

The calls are asynchronous. Each returns a request id, and the answer arrives in App::keychain as a keychain::Reply, which holds the request id and a Result.

keychain::add(ctx, service, account, secret) -> u32
Stores a new secret. The reply is DuplicateItem when the pair exists.
keychain::get(ctx, service, account) -> u32
Returns the secret in Ok, or ItemNotFound.
keychain::update(ctx, service, account, secret) -> u32
Replaces the secret. The reply is ItemNotFound when there is no such item.
keychain::delete(ctx, service, account) -> u32
Removes the item. The reply is ItemNotFound when there is no such item.

The errors are DuplicateItem, ItemNotFound, NotPermitted, Param and Io(String), and Error::code() returns the matching OSStatus. Names are limited to 255 bytes, secrets to 8 KiB, and an app can hold 256 items. An app sees only its own items, because the shell takes the app id from the connection.

Important

The encryption key sits on the same disk as the items. The keychain keeps secrets from other apps, other users and backups of app data. It does not protect against someone who holds the whole disk, including root.

Not yet available: access groups (sharing items between apps), user-presence access control, accessibility classes for items, certificates and keys, attributes other than service and account, listing all items, and iCloud sync.

Formatting and caching helpers

The format module formats numbers the way Foundation’s formatters do. The output is English and does not depend on the locale.

format::byte_count(bytes: u64) -> String
Decimal units, as macOS shows them: "1 byte", "1.5 MB", "12 GB".
format::duration(seconds: u64) -> String
Positional style: "0:07", "3:25", "1:02:03".
format::relative(delta_seconds: i64) -> String
Relative time. A negative delta is in the past.
format::grouped(n: i64) -> String
Groups digits with commas: "1,234,567".

bifrost_ui::cache::Cache<K, V> is a cost-limited least-recently-used cache, the counterpart of NSCache. Create it with Cache::new(cost_limit), add entries with put(key, value, cost), and read them with get(&key). Entries are evicted when the total cost passes the limit.

Watching folders for changes

An app learns about files that change on disk from WatchStream, the counterpart of FSEventStream. The stream watches folders recursively and adds subfolders as they appear. It groups the changes to each file over a short delay. The stream runs no thread of its own. The app gives the stream’s file descriptor to its event loop and reads a batch of events when the descriptor is ready.

use bifrost_app::fswatch::{WatchEventFlags, WatchStream, WatchStreamFlags};
use std::time::{Duration, Instant};

let mut watch = WatchStream::new(&[folder.clone()], Duration::from_millis(500), WatchStreamFlags::NONE);
watch.start();

// Add watch.fd() to the event loop. When it is ready:
for ev in watch.poll(Instant::now()) {
    if ev.flags.contains(WatchEventFlags::MODIFIED) {
        reload(&ev.path);
    }
}
WatchStream::new(paths, latency, flags)
A stopped stream over the folders in paths, watched recursively. Call start to begin.
WatchStream::start() and stop()
Begin and end watching. Dropping the stream also stops it.
WatchStream::fd()
The file descriptor the event loop waits on.
WatchStream::poll(now)
Returns the WatchEvent values that are due at now. Each event has a path and flags.
WatchStream::next_deadline(now)
The time until the next batch is due, so the loop can wake for it.
WatchEventFlags::MODIFIED
The contents or metadata of an item changed. The other flags are CREATED, REMOVED, RENAMED, ITEM_IS_DIR and MUST_SCAN_SUB_DIRS.
WatchStreamFlags::NO_DEFER
Delivers the first change after a quiet period at once, without waiting for the delay.
Note

The stream does not keep event ids or a history, so an app that was not running misses the changes made meanwhile. A rename arrives as two RENAMED events, one for each path, and the stream does not pair them. When the event queue overflows, the stream reports MUST_SCAN_SUB_DIRS on the watched folders, and the app must scan them again.

Coordinating file access and presenters

Two processes that share a file can use NativeFileCoordinator (the counterpart of NSFileCoordinator) so that a reader never sees a half-written file. A read runs under a shared lock and a write under an exclusive lock. The lock is held on the folder that contains the item, not on the file, because writers replace files by rename. The lock is advisory: it holds back only the processes that coordinate too. A call that waits longer than LOCK_TIMEOUT, five seconds, returns CoordinationError::Timeout and does not run its closure.

A presenter is an object that shows one file or folder and must hear when another process changes it. Implement FilePresenter and register it with NativeFileCoordinator::add_presenter. The presenter stays registered until its token is dropped. Presenters run on the main thread. The app passes each batch from its WatchStream to file_coordination::deliver_events. A write that this process makes through coordinate_writing is not reported back to its own presenters.

use bifrost_app::file_coordination::{deliver_events, FilePresenter, NativeFileCoordinator};
use std::path::{Path, PathBuf};

struct Viewer {
    url: PathBuf,
}

impl FilePresenter for Viewer {
    fn presented_item_url(&self) -> PathBuf {
        self.url.clone()
    }
    fn presented_item_did_change(&mut self, path: &Path) {
        reload(path);
    }
    fn accommodate_deletion(&mut self, _path: &Path) {
        close_document();
    }
}

let _token = NativeFileCoordinator::add_presenter(Box::new(Viewer { url: file.clone() }));

// Writing side, in another process or in this one:
NativeFileCoordinator.coordinate_writing(&file, |p| std::fs::write(p, &bytes))??;
NativeFileCoordinator::coordinate_reading(path, f)
Runs f under a shared lock on the item’s folder, so writers wait until it returns.
NativeFileCoordinator::coordinate_writing(path, f)
Runs f under an exclusive lock on the item’s folder.
NativeFileCoordinator::add_presenter(presenter)
Registers a FilePresenter and returns a token. Dropping the token removes the presenter.
FilePresenter::presented_item_url()
The file or folder the presenter shows.
FilePresenter::presented_item_did_change(path)
Another process changed the item, or something inside it when it is a folder.
FilePresenter::accommodate_deletion(path)
The item was removed or moved away.
file_coordination::deliver_events(events)
Hands a batch from WatchStream::poll to the registered presenters.
Note

The lock is advisory, so a process that does not coordinate is not blocked. Presenters only hear about changes inside the folders that the app’s WatchStream watches. Not yet done: relinquishing an item when another process asks, saving pending changes on request, and will-move callbacks (a rename reaches the presenter as a change on both paths). Versions and iCloud coordination are not provided.

Encoding and decoding data

Values that implement Encodable and Decodable can be written to JSON or to an XML property list and read back. Integers, floats, bool, String, Date, Option, Vec and maps with String keys all work. A plain struct gets both traits from the codable! macro, which does not need a derive. Write the struct first, then list its fields in the macro. An Option field is left out when it is None, and it reads as None when the key is missing.

use bifrost_app::coding::{codable, Date, JSONDecoder, JSONEncoder};

#[derive(Debug, Clone)]
struct Note {
    title: String,
    pinned: bool,
    edited: Date,
    tags: Vec<String>,
    folder: Option<String>,
}

codable!(Note {
    title: String,
    pinned: bool = false,
    edited: Date,
    tags: Vec<String>,
    folder: Option<String>,
});

let json = JSONEncoder::new().encode(&note);
let back: Note = JSONDecoder::new().decode(&json)?;

A field marked with = default reads as that value when the key is missing from older data.

codable!(Name { field: Type, ... })
Writes the Encodable and Decodable impls for a struct that already exists. A field with = default takes that value when it is missing.
JSONEncoder::new()
A JSON encoder. Set pretty_printed, sorted_keys or date_encoding_strategy on it before encoding.
JSONEncoder::encode(value)
Returns the value as a JSON string.
JSONDecoder::decode(text)
Reads a value of the requested type from JSON text. It returns a CodingError when the text does not match.
PropertyListEncoder::encode(value) and PropertyListDecoder::decode(text)
The same, for XML property lists.
Date
A time in seconds since 1970. It is written as a number, or as ISO 8601 text when the date strategy is Iso8601.
Note

There is no renaming of coding keys. To store a field under another key, write the Encodable and Decodable impls by hand. Binary property lists are not supported, and the only date strategies are the two above. Data cannot be encoded yet.

Locale and localized strings

The locale module follows Foundation. Locale::current reads the locale from the environment. Number, date and byte formatters take a locale, so the same value reads correctly for each user. Strings are localized with the localized! macro, which reads the main bundle that the app sets at launch.

use bifrost_app::locale::{byte_count, set_main_bundle, Bundle, DateFormatter, DateStyle, Locale, NumberFormatter, NumberStyle};
use bifrost_app::localized;

let locale = Locale::current();
set_main_bundle(Bundle::load(&app_dir, &locale));

let price = NumberFormatter::new(locale.clone(), NumberStyle::Currency).string(1234.5);
let mut dates = DateFormatter::new(locale.clone());
dates.date_style = DateStyle::Medium;
let when = dates.string(unix_seconds);
let size = byte_count(&locale, 1_500_000);
let title = localized!("Open Recent", "File menu");
Locale::current()
The locale from LC_ALL, LC_MESSAGES or LANG. A BIFROST_REGION value, when it is set, replaces the region.
Locale::new(identifier)
A locale for an identifier such as en_US or is_IS.
NumberFormatter::new(locale, style)
A formatter for NumberStyle::Decimal, Percent or Currency, with the locale’s separators and grouping.
NumberFormatter::string(value)
Formats a number as text.
DateFormatter::new(locale)
A formatter with no date or time style. Set date_style and time_style, or a pattern.
DateFormatter::set_date_format(pattern)
Sets a fixed pattern, as dateFormat does.
DateFormatter::set_localized_date_format_from_template(template)
Builds a pattern for the locale from a template, as setLocalizedDateFormatFromTemplate does.
DateFormatter::string(unix)
Formats a time in seconds since 1970, in the zone given by tz_offset.
relative_date_time(locale, delta_seconds)
Relative time such as a phrase for yesterday. A negative delta is in the past.
byte_count(locale, bytes)
A file size in the locale’s style.
Bundle::load(dir, locale)
Reads <dir>/<lang>.lproj/Localizable.strings, with English as the fallback.
set_main_bundle(bundle)
Sets the bundle that localized! reads. Call it once at launch.
localized!(key, comment)
The string for key in the main bundle. When no string is found, the key itself is returned.
Note

Only English and Icelandic have built-in data. Other languages format as English. There are no .stringsdict plural rules, no time-zone database (tz_offset is given in seconds), and only the Gregorian calendar. The measurement formatter does not convert between unit systems. The shell does not yet publish a region of its own, so BIFROST_REGION is read only when it is set.

Printing

An app prints a file with PrintOperation. The job takes a PDF or an image, and the paper and margins come from PrintInfo. The printers are the CUPS queues on the system. Choose Destination::Pdf to save the file as a PDF with no printer at all.

use bifrost_app::print::{printers, Destination, Orientation, PrintError, PrintInfo, PrintOperation};

let info = PrintInfo {
    orientation: Orientation::Landscape,
    copies: 2,
    ..Default::default()
};
match PrintOperation::new(pdf_path).with_info(info).to(Destination::Printer(None)).run() {
    Ok(_) => announce("Sent to the printer"),
    Err(PrintError::NoCups) => announce("No printing system is installed"),
    Err(PrintError::Failed(msg)) => announce(&msg),
}
PrintInfo
The paper size, orientation, margins in points, number of copies and page range of a job. The default is A4, portrait, 72 points on each side and one copy.
PrintInfo::paper_size()
The paper size in points, after the orientation is applied.
PrintInfo::imageable()
The area left inside the margins, where the page can be printed.
printers()
The printers that CUPS knows, with the default marked. The list is empty when CUPS is not installed.
available()
Whether CUPS is installed.
PrintOperation::new(document)
A job for a PDF or image file.
PrintOperation::with_info(info) and to(destination)
Set the info and the destination of the job. They return the job, so the calls can be chained.
PrintOperation::run()
Submits the job with lp, or copies the file for Destination::Pdf. It returns the text that lp printed.
Destination::Printer(name)
A printer by name, or the default printer for None.
Destination::Pdf(path)
Copies the document to path.
PrintError::NoCups and PrintError::Failed(message)
CUPS is not installed, or the job was refused, with the message from lp.
Note

There is no print sheet yet. The app draws its own printer and option controls and calls run. Only file documents can be printed: there is no pagination of a view. Printing to a printer needs CUPS on the PC. Save as PDF works without it.

Spell checking

The spellcheck module finds misspelled words and suggests corrections, the counterpart of NSSpellChecker. A checker reads its words from a Dictionary. WordList is a dictionary held in memory, and other word lists can be plugged in by implementing the trait.

use bifrost_app::spellcheck::{SpellChecker, WordList};

let dict = WordList::new("en", ["hello", "world"]);
let checker = SpellChecker::new(Box::new(dict));

if let Some(range) = checker.check_spelling(text, 0) {
    let guesses = checker.guesses(text, range.clone());
    // Show guesses for &text[range]
}
SpellChecker::new(dictionary)
A checker that reads from the given Dictionary.
SpellChecker::check_spelling(text, start)
The byte range of the first misspelled word at or after start, or None.
SpellChecker::guesses(text, range)
Suggested spellings for the word in range.
SpellChecker::correction(text, range)
The best correction for the word in range, or None.
SpellChecker::learn_word(word, defaults) and unlearn_word
Add a word to the user’s words, or remove it. The words are stored in the preferences.
SpellChecker::ignore_word(word)
Ignores a word until the checker is dropped.
SpellChecker::check(text, types)
Returns CheckingResult values for the requested CheckingTypes. It currently returns spelling results only.
CheckingTypes::SPELLING
The spelling bit. The grammar, link, date, address and phone number bits are defined, but they return no results yet.
WordList::new(lang, words)
A dictionary from a list of words. Suggestions are the words one edit away.
words(text)
Splits text into word ranges. Apostrophes inside a word are kept.
Note

There is no grammar checking, because no grammar data exists. No dictionary is bundled, so an app must supply one. Ignored words are not scoped to a document. Links, dates, addresses and phone numbers are found by the detection code, not by this checker. No app uses the checker yet. automatically_corrects_spelling is a flag only, and nothing applies corrections.