JFLib

8. Files, settings, images#

  • Files (plat): read_file(path) -> Option<Vec<u8>>, write_file(path, data) -> bool (atomic: a temporary file + rename), file_exists (0 / 1 file / 2 directory), mkdir (with parents), delete, rename, dir_list(path, &mut |name, is_dir, size| ...), plat::File for random access; config_dir(), temp_dir(), cwd(), args(), arg_value("--open"), env(name), time_us(), date(). plat::user_dir(plat::DIR_DOCUMENTS) (also DIR_DESKTOP, DIR_DOWNLOADS, DIR_PICTURES, DIR_MUSIC, DIR_VIDEOS) finds the user's folders where they really are: the Known Folders on Windows (also when moved to OneDrive), the XDG user dirs on Linux (~/Dokumente on a German system). plat::log_dir() is the base folder of logs. plat::trash(path) moves a file or folder into the recycle bin (Windows) or the freedesktop trash (Linux) instead of deleting it; on false the item is still in its place, so offer delete only after asking the user. plat::display_name(path) is what to show the user for a file (content:// documents: their display name). On Android the app's folders are real files of its internal storage and survive restarts (VFS.md, "Android"). file_exists_checked distinguishes a missing path (Some(0)) from access errors (None); Linux also rejects special files. FileLock::acquire(path) returns a nonblocking exclusive sidecar guard or None for busy/error. Keep the guard until the read/compare/write transaction completes and leave the sidecar on disk: deleting it can let another process lock a different file at the same pathname.

  • Document sources: doc_core::SourceLibrary stores an independent bibliography and its ID watermark; SourceLibraryEditor adds atomic edits and bounded undo/redo. doc_io::LibraryStore owns the strict native XML codec, bounded reads, lock/conflict checks and atomic backup/write sequence. prepare_recovery captures a reviewed main/backup snapshot; its token restores only if both files remain unchanged. Profile paths, confirmation dialogs and document-to-library selection belong in the app.

  • Document notes: doc_core::Note owns rich paragraphs; an Inline::NoteReference anchors it exactly once in the main body. Use Edit::InsertNote, SetNoteKind and RemoveNote for atomic history. Paragraph edits, search and citation/source operations also accept note-body paragraph IDs. note_number derives separate decimal sequences from anchor order; never store that display number as the note's identity. doc_io owns the bounded DOCX note parts and their package relationships, while doc_layout reserves footnotes at page bottoms, continues long notes and appends endnotes. Render each Page.separators item alongside its lines. Note bodies have normal paragraph hit-test IDs, so apps can navigate from the preview to their editor.

  • Virtual files: every file function also takes scheme://path. app:// holds the files of apps/NAME/assets, which are built into the program. config://, data://, cache:// and logs:// are the app's own folders, and mem:// lives in memory. desktop://, documents://, downloads://, pictures://, music:// and videos:// are the user's folders (with a manifest only what its rules allow). Your own mounts are folders, overlays, sub-folders and ZIP archives. VFS.md has the details.

    let logo = plat::read_file("app://images/logo.png");
    let ini = base::Ini::load("config://settings.ini");
    plat::write_file("documents://MeinWerkzeug/Bericht.txt", text.as_bytes());
    if !plat::trash("documents://MeinWerkzeug/alt.txt") { /* still there: ask before delete */ }
  • Permissions: an apps/NAME/PERMISSIONS file limits what the app may touch: files below patterns, the user's own files, programs, URL schemes, plugins, printing, the secret store, network hosts and ports. The build checks it, ui::main! installs it, and plat refuses everything else: a refused path behaves like a missing one, and stderr shows PERMDENY .... Without the file everything stays allowed. PERMISSIONS.md has the syntax and the limits.

    fs.write $CONFIG/MeinWerkzeug/**
    fs.write $DOCUMENTS/MeinWerkzeug/**
    fs.user
    url https
    net.connect api.example.com:443
    ask fs.read $PICTURES/** "Bilder einfügen"   # asked at the first access
    agent.confirm document.save                  # an agent needs the user's OK

    ask before a rule asks the user at the first access, in a dialog of the library ("Einmal erlauben", "Immer erlauben", "Ablehnen", "Nie erlauben"); one answer covers the whole line. The UI thread's access is refused while the question is open and the app gets UIC_PERMISSION (arg 1: allowed) to try again; a worker thread waits for the answer (60 s, then refused). Headless runs never ask (scripts answer with perm answer ...). Put ui.permissions_page(ui.id("perms")) into the settings: it lists the answers, each with a reset. Native plugins bring their own <name>.permissions; what plat does for them needs their rights and the app's (plat::policy::on_behalf). agent.confirm / agent.deny (or ActionSpec::confirm() / local_only()) gate agent actions; the agent gets confirmation_required or forbidden back.

    A sandbox line (or sandbox strict) has the operating system enforce the manifest too, as defence in depth against a bug or native code that bypasses plat: Landlock plus seccomp on Linux, process mitigation policies on Windows, applied at start-up before the app's own code. Apps without the line are unchanged. See PERMISSIONS.md "OS sandbox" for what each platform enforces and the limits (a sandbox app without a process rule cannot spawn_self, and files the user picks at run time need a Flatpak's documents portal or an fs.* rule on the folder).

    fn command(&mut self, ui: &mut Ui, id: u32, arg: u32) -> bool {
        if id == UIC_PERMISSION && arg == 1 && self.pending_import {
            self.import(ui); // the user allowed it: the same access again
        }
        true
    }
  • Passwords, tokens, keys never go into settings files: plat::secret keeps them in the system's store (section 20).

  • Settings: base::Ini reads and writes [section] / key=value files and keeps comments and unknown lines:

    let path = format!("{}/MeinWerkzeug/settings.ini", plat::config_dir().unwrap_or_default());
    let mut ini = base::Ini::load(&path);       // a missing file is empty
    let size = ini.get_int("view", "size", 10);
    ini.set_int("view", "size", size + 1);
    ini.save(&path);                            // atomic, creates the folder

    Save settings in App::command(UIC_EXIT) (sent only after a real window ran) and never in test runs.

  • Typed settings (base::settings): declare each key once with its type, default, limits and label, list them in a Schema with a format version, and let the library validate, store and show them. The file keeps only what differs from the default; comments and unknown lines survive. An older file runs your migrate(from, &mut ini) once (base::settings::rename(ini, "old.key", "new.key") helps); a value that does not fit reads as the default (a WARN in the log), numbers are clamped, texts cut.

    use base::{Key, Schema, Settings};
    const DARK: Key<bool> = Key::bool("view.dark", false).label("Dunkles Design");
    const ZOOM: Key<i64> = Key::int("view.zoom", 100, 10, 800).label("Zoom (%)").step(10);
    const UNIT: Key<usize> = Key::choice("view.unit", 0, &[("px", "Pixel"), ("cm", "Zentimeter")]).label("Einheit");
    const NAME: Key<String> = Key::text("user.name", "", 64).label("Name").help("Steht in neuen Dokumenten.");
    const LAST: Key<String> = Key::text("state.last", "", 260).hidden();   // not on the page
    static SCHEMA: Schema = Schema::new(2, &[DARK.d, ZOOM.d, UNIT.d, NAME.d, LAST.d])
        .sections(&[("view", "Ansicht"), ("user", "Benutzer")])
        .migrate(migrate);
    fn migrate(from: u32, ini: &mut base::Ini) {
        if from < 2 {
            base::settings::rename(ini, "view.size", "view.zoom");   // version 1 called it so
        }
    }
    
    let mut s = Settings::open("config://settings.ini", &SCHEMA);   // in App::init
    let zoom: i64 = s.get(&ZOOM);                                    // typed
    s.set(&ZOOM, 120);                                               // clamped; true = changed
    ui.settings_page(ui::wid("settings"), &mut s);                   // the whole page
    s.save();                                                        // in UIC_EXIT

    Types: Key<bool>, Key<i64> (int), Key<f64> (num, with decimals), Key<String> (text, at most N bytes), Key<usize> (choice: the file keeps the word), Key<u32> (color 0xRRGGBB, the file #RRGGBB); .restart() marks keys that take effect after a restart. What a restart reads back is what was set: a text keeps line breaks as blanks and no blanks around it, a reset (or the default) removes every line of the key, and a value too long for a line of the file (64 KiB) is not set. settings_page shows a card per section with a switch, number box, text box, combo box or colour button per key and a reset button; labels go through i18n::t. s.revision() counts changes, s.ini_mut() holds free-form data (recent files).

  • Window placement: AF_SAVE_STATE in the app flags keeps the main window's position, normal size and maximized state and the tool windows' (palettes, WF_TOOL) open flag and placement in config://windows.ini: the next start opens them where they were (a position off every monitor is centred; --size wins; Wayland places windows itself). jfgui_STATE=FILE uses another file, jfgui_STATE=0 none; test runs never touch it. ui.state_save(&mut ini) / ui.state_load(&ini) do the same with any Ini (several layouts, tests). Give tool windows stable ids (ui::wid("palette.layers")).

  • Images (img_core::io): the runtime registers PNG, JPEG, BMP, GIF and SVG (.svg, .svgz: drawn at their intrinsic size, section 31) at start-up and connects the file functions. For every other format call img_all::use_all_codecs() once in App::init (TIFF, TGA, WebP, AVIF, HEIC, JPEG XL, JPEG XR, JPEG 2000, JBIG2, DDS, PDN, PSD).

    match img_core::io::load_ex(path, None, None) {   // any registered format -> FMT_PARGB
        Ok(sf) => {
            self.photo = Some(Rc::new(sf));
            self.photo_ver += 1;
        }
        Err(e) => self.error = Some(format!("Die Datei konnte nicht geöffnet werden ({}).", e)),
    }
    
    let mut opt = img_core::io::opt_init(img_core::io::format_from_path(path)); // paint.net's defaults
    opt.quality = 90;
    if img_core::io::save_opt(path, sf, Some(&opt)) != 0 { /* ERR_* */ }
    • Classic calls: load(path), save(path, &sf), decode(data), save_ex(path, &sf, quality) (PNG / JPEG / BMP / GIF by extension).
    • Extended: detect(data, hint), probe(data, Some(&mut meta)) (header only), decode_ex(data, Some(&dec), Some(&mut meta)), encode(&sf, Some(&opt)), save_opt. ImgDec chooses straight output (IMGD_STRAIGHT), the frame / page, a pixel budget and which metadata blobs to keep; ImgMeta receives size, format details, frames, ICC / EXIF / XMP; ImgOpt carries quality, effort, flags (IOF_*), bit depth, chroma, DDS / TIFF choices and the metadata to embed. Each codec's options are documented in its section of API.md (e.g. img_jxl: effort, progressive, photon noise).
    • format_info(fmt), format_from_path(path), register_dyn(...) (runtime formats of plugins). Errors are the ERR_* codes of img_core.
    • Metadata and colour: img_core::meta (conversions convert / surf_convert between FMT_PARGB and FMT_ARGB, all_opaque), img_core::exif, img_core::icc / icc_xform (colour management, legacy/ASMLIB/docs/modules/COLOR_MANAGEMENT.md).
  • PDF files (pdf): pdf::Document writes them (pages drawn on a canvas, font subsets, images, links, bookmarks). pdf::read::Document::open(bytes) reads any of them, encrypted ones with open_with(bytes, &Options { password, .. }): page_count, page(i).size(), text(i) (the page's text in reading order), page_text(i) (every glyph with its position, for search and selection), info, outlines, links, fields (the form's values), attachments (embedded files such as the XML of a ZUGFeRD invoice). A damaged file is rebuilt from its objects; a hostile one gives an error, never a panic. render(i, &RenderOptions { dpi, region, background, annotations, fonts, .. }) draws a page into a gfx::Surface (a viewer asks for the tiles it shows with region; page_pixels(i, dpi) gives the size): every colour space, embedded fonts and the system's fonts for the others, images, shadings, patterns and transparency, as Poppler's pdftoppm draws them. Fonts a document does not embed come from a FontSource (by default SystemFonts, the installed fonts through text::fontdb).

Logging (plat::log): plat::log!(plat::LOG_INFO, "net", "{} bytes from {}", n, host) formats only when a sink wants the level; plat::log_error / log_warn / log_info / log_debug(target, msg) are the short forms. Every line goes to a 64 KiB ring (up to DEBUG), to stderr (WARN and above) and, with AF_LOG_FILE in the app flags, to logs://APP.log (INFO and above; at 1 MiB it moves to .1, three older files are kept). logs:// is the app's log folder: %LOCALAPPDATA%/APP/Logs on Windows, $XDG_STATE_HOME/APP (~/.local/state/APP) on Linux. jfgui_LOG=error|warn|info|debug|trace sets the levels, jfgui_LOG_FILE=PATH|1|0 the file. A crash or panic prints the ring's last lines and marks the file before the app's crash hook runs, without allocating or waiting: a non-blocking stderr that takes nothing for half a second is given up, the crash line goes to an OS file only (not to a mount's stream) and does not rotate it. log_file refuses a file of a mount without streams or OS files (its lines would arrive only when the log stops). plat::log_recent(max) gives the newest lines for an own report. ui.warn lines are in the log too. The runtime logs start, exit, sleep, session end and settings changes.

Printing (plat::print, plat::PrintDoc): plat::print(&mut job) prints one image on one page (PrintJob: the pixels, title, paper PAPER_*, PJF_LANDSCAPE / PJF_CENTER, scale PJS_FIT / PJS_DPI / PJS_PERCENT, margin), with the system's dialog. A document of several pages (a web page, a report) is a PrintDoc:

let mut job = plat::PrintJob::new(None, "Seite");  // title, paper, PJF_*, margin, scale
job.margin = 1000;                                 // 10 mm (1/100 mm)
let mut d = match plat::PrintDoc::begin(&job, n) { // the dialog: printer, paper, copies, pages 1..=n
    Ok(d) => d,
    Err(_) => return,                              // ERR_CANCEL, ERR_UNSUPPORTED, ERR_IO
};
let page = d.page();                               // the chosen paper in pt (72 per inch), edges
if d.pdf_native() && have_pdf {
    d.add_pdf(&pdf_bytes);                         // Linux: the app's own PDF as it is
} else {
    for k in 1..=n {
        if d.wants(k) {                            // the range the dialog chose
            d.add_image(&render_page(k, &page));   // a PrintSrc, laid out as layout() places it
        }
    }
}
let r = d.end();                                   // 0: on its way to the printer
  • Windows: PrintDlgExW (with a page range of 1..=n when n > 0) and GDI, one page after the other into the spooler; Linux: the portal's dialog, the pages as one PDF of several pages (or the app's own PDF: pdf_native()) handed to the portal's Print; Android: no dialog before the pages, the PDF goes to the system's PrintManager at end(), whose dialog (a printer or "Save as PDF", paper, copies, pages, a preview) comes after end returned (0: the dialog has the job; plat::print the same with one page). macOS, iOS and the browser have no jobs of several pages yet: begin answers ERR_UNSUPPORTED (outside the test variant).
  • Render each page for page() at the printer's resolution or a fixed one (300 dpi: job.dpi_x = 300.0 with PJS_DPI, an image of page.w / 72 * 300 pixels); PJS_FIT scales each image into the printable area. d.abort() drops the job, end() without a page is ERR_DIMS.
  • Tests never see a dialog or paper: jfgui_PRINT_TO=FILE prints into a file (Windows through the printer jfgui_PRINT_PRINTER, default "Microsoft Print to PDF"; elsewhere the PDF of the pages); without it a run without a window answers ERR_UNSUPPORTED (apps/plattest/tests/printdoc.uis).

Source: docs/GUIDE.md in the JFLib repository.