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::Filefor random access;config_dir(),temp_dir(),cwd(),args(),arg_value("--open"),env(name),time_us(),date().plat::user_dir(plat::DIR_DOCUMENTS)(alsoDIR_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 (~/Dokumenteon 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; onfalsethe item is still in its place, so offerdeleteonly 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_checkeddistinguishes a missing path (Some(0)) from access errors (None); Linux also rejects special files.FileLock::acquire(path)returns a nonblocking exclusive sidecar guard orNonefor 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::SourceLibrarystores an independent bibliography and its ID watermark;SourceLibraryEditoradds atomic edits and bounded undo/redo.doc_io::LibraryStoreowns the strict native XML codec, bounded reads, lock/conflict checks and atomic backup/write sequence.prepare_recoverycaptures 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::Noteowns rich paragraphs; anInline::NoteReferenceanchors it exactly once in the main body. UseEdit::InsertNote,SetNoteKindandRemoveNotefor atomic history. Paragraph edits, search and citation/source operations also accept note-body paragraph IDs.note_numberderives separate decimal sequences from anchor order; never store that display number as the note's identity.doc_ioowns the bounded DOCX note parts and their package relationships, whiledoc_layoutreserves footnotes at page bottoms, continues long notes and appends endnotes. Render eachPage.separatorsitem 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 ofapps/NAME/assets, which are built into the program.config://,data://,cache://andlogs://are the app's own folders, andmem://lives in memory.desktop://,documents://,downloads://,pictures://,music://andvideos://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/PERMISSIONSfile 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, andplatrefuses everything else: a refused path behaves like a missing one, and stderr showsPERMDENY .... 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 OKaskbefore 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 getsUIC_PERMISSION(arg 1: allowed) to try again; a worker thread waits for the answer (60 s, then refused). Headless runs never ask (scripts answer withperm answer ...). Putui.permissions_page(ui.id("perms"))into the settings: it lists the answers, each with a reset. Native plugins bring their own<name>.permissions; whatplatdoes for them needs their rights and the app's (plat::policy::on_behalf).agent.confirm/agent.deny(orActionSpec::confirm()/local_only()) gate agent actions; the agent getsconfirmation_requiredorforbiddenback.A
sandboxline (orsandbox strict) has the operating system enforce the manifest too, as defence in depth against a bug or native code that bypassesplat: 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 (asandboxapp without aprocessrule cannotspawn_self, and files the user picks at run time need a Flatpak's documents portal or anfs.*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::secretkeeps them in the system's store (section 20).Settings:
base::Inireads and writes[section]/key=valuefiles 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 folderSave 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 aSchemawith 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 yourmigrate(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_EXITTypes:
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>(color0xRRGGBB, 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_pageshows a card per section with a switch, number box, text box, combo box or colour button per key and a reset button; labels go throughi18n::t.s.revision()counts changes,s.ini_mut()holds free-form data (recent files).Window placement:
AF_SAVE_STATEin 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 inconfig://windows.ini: the next start opens them where they were (a position off every monitor is centred;--sizewins; Wayland places windows itself).jfgui_STATE=FILEuses another file,jfgui_STATE=0none; test runs never touch it.ui.state_save(&mut ini)/ui.state_load(&ini)do the same with anyIni(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 callimg_all::use_all_codecs()once inApp::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.ImgDecchooses straight output (IMGD_STRAIGHT), the frame / page, a pixel budget and which metadata blobs to keep;ImgMetareceives size, format details, frames, ICC / EXIF / XMP;ImgOptcarries 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 theERR_*codes ofimg_core.- Metadata and colour:
img_core::meta(conversionsconvert/surf_convertbetweenFMT_PARGBandFMT_ARGB,all_opaque),img_core::exif,img_core::icc/icc_xform(colour management,legacy/ASMLIB/docs/modules/COLOR_MANAGEMENT.md).
- Classic calls:
PDF files (
pdf):pdf::Documentwrites them (pages drawn on a canvas, font subsets, images, links, bookmarks).pdf::read::Document::open(bytes)reads any of them, encrypted ones withopen_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 agfx::Surface(a viewer asks for the tiles it shows withregion;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'spdftoppmdraws them. Fonts a document does not embed come from aFontSource(by defaultSystemFonts, the installed fonts throughtext::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 of1..=nwhenn > 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'sPrint; Android: no dialog before the pages, the PDF goes to the system'sPrintManageratend(), whose dialog (a printer or "Save as PDF", paper, copies, pages, a preview) comes afterendreturned (0: the dialog has the job;plat::printthe same with one page). macOS, iOS and the browser have no jobs of several pages yet:beginanswersERR_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.0withPJS_DPI, an image ofpage.w / 72 * 300pixels);PJS_FITscales each image into the printable area.d.abort()drops the job,end()without a page isERR_DIMS. - Tests never see a dialog or paper:
jfgui_PRINT_TO=FILEprints into a file (Windows through the printerjfgui_PRINT_PRINTER, default "Microsoft Print to PDF"; elsewhere the PDF of the pages); without it a run without a window answersERR_UNSUPPORTED(apps/plattest/tests/printdoc.uis).