RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
mime updated
oxydizer3e68db4fcb0e
diff --git a/build.zig b/build.zigindex f324818..f696451 100644--- a/build.zig+++ b/build.zig@@ -243,7 +243,7 @@ pub fn build(b: *std.Build) void {.use_lld = use_llvm,});editor.root_module.addImport("wayland", wayland);- inline for (.{ "wayland-client", "wayland-cursor", "xkbcommon", "pangocairo", "gio-2.0" }) |lib| editor.root_module.linkSystemLibrary(lib, .{});+ inline for (.{ "wayland-client", "wayland-cursor", "xkbcommon", "pangocairo" }) |lib| editor.root_module.linkSystemLibrary(lib, .{});const install_editor = b.addInstallArtifact(editor, .{});const editor_entry = b.addInstallFileWithDir(b.path("data/rediwm-editor.desktop"), .prefix, "share/applications/rediwm-editor.desktop");b.getInstallStep().dependOn(&install_editor.step);@@ -646,7 +646,7 @@ pub fn build(b: *std.Build) void {lock_step.dependOn(&run_auth_tests.step);test_step.dependOn(&run_auth_tests.step);const editor_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/editor_tests.zig"), .target = target, .optimize = optimize, .link_libc = true }) });- inline for (.{ "pangocairo", "gio-2.0", "xkbcommon" }) |lib| editor_tests.root_module.linkSystemLibrary(lib, .{});+ inline for (.{ "pangocairo", "xkbcommon" }) |lib| editor_tests.root_module.linkSystemLibrary(lib, .{});const run_editor_tests = b.addRunArtifact(editor_tests);test_step.dependOn(&run_editor_tests.step);b.step("test-editor", "Test text document editing and saving").dependOn(&run_editor_tests.step);diff --git a/docs/plans/files-terminal.md b/docs/plans/files-terminal.mdnew file mode 100644index 0000000..a07d67b--- /dev/null+++ b/docs/plans/files-terminal.md@@ -0,0 +1,313 @@+# Files terminal drawer plan++Status: draft, 2026-10-16. Implementation starts with Phase 0 below.++Add a terminal drawer beneath the file list, opened with F4 or a small+terminal icon at the bottom right. Embed libvterm in the Files process and+connect it to the user's shell through a pseudoterminal (PTY). Files owns+the drawer, terminal rendering, input, scrollback, and shell session.++The primary design priority is compositor stability. Keep terminal behaviour+inside Files, presented through its existing Wayland window. Terminal+hosting protocols and special cases in compositor focus, stacking,+projection, tiling, and window lifetime are outside this feature's scope.+Shared UI additions must preserve their existing callers' behaviour.++The drawer slides upward, resizes from its top edge, and follows the Files+window when it moves or resizes. Folder navigation updates the shell's+directory only when it is safe to do so. Hiding the drawer preserves the+session and running commands.++## User experience++```text+┌──────────────┬─────────────────────────────────┐+│ │ Folder path / toolbar │+│ Places ├─────────────────────────────────┤+│ │ │+│ Home │ Files and folders │+│ Documents │ │+│ Downloads ├──────── drag to resize ──────────┤+│ │ >_ Terminal ~/Projects ▾ │+│ │ alex@desktop:~/Projects $ │+│ │ │+│ ├─────────────────────────────────┤+│ │ 24 items [>_] │+└──────────────┴─────────────────────────────────┘+```++The sidebar remains full height. The drawer occupies the file-list column,+above the existing status bar. Its header shows the terminal icon, the+shell's actual directory when known, and a collapse control. Use shared+buttons, icons, separators, and theme tokens. Use the existing terminal+palette tokens, app palette fallbacks, and configured monospace font. The+embedded terminal uses the user's shell configuration; settings from their+external terminal application are not automatically imported.++* **Open and hide:** F4 and the status-bar button toggle visibility. Opening+ focuses the terminal; hiding returns focus to the file list. The tooltip+ is "Terminal · F4", and the visible drawer gives its button an accent+ highlight. F4 fires once per press and also works with terminal focus.+* **Initial size:** start at approximately one-third of the space below the+ Files toolbar. Persist the requested height, clamp it to the current+ window, and retain usable file-list space and terminal rows. Set exact+ minimums after testing compact windows in the prototype. A temporary+ clamp must not overwrite the user's preferred height.+* **Resize:** the top separator has a generous pointer target, vertical+ resize cursor, and shared hover treatment. Dragging changes height+ directly. Outer window resizing changes both the terminal's width and+ available height. Recompute the cell grid and notify the PTY only when+ rows or columns change.+* **Motion:** use the existing panel-slide curve and reduced-motion setting.+ Reversing a toggle continues from the current position. Painting and hit+ testing follow the same visible boundary throughout the slide.+* **Session:** create one terminal session lazily per Files window. Preserve+ it while hidden. Show a restrained launch/error state and a Restart action+ after the terminal exits. Newly opened Files windows start with the drawer+ hidden; remember height, not a previous shell process.+* **Focus:** clicking the file list or sidebar restores Files input. Terminal+ shortcuts and Escape reach the terminal while it is focused, except for+ the explicitly reserved drawer toggle and existing compositor shortcuts.+ Modal Files dialogs take precedence and restore the prior focus on close.++The drawer belongs to normal Files windows. Open/Save/folder chooser dialogs+do not expose it. Include an Open external terminal action using the configured+default terminal, starting a separate session in the current real folder.+Tabs and multiple embedded terminal sessions can follow later.++## Following the current folder++The selected behaviour is to follow Files when the shell is idle, preserving+running commands and partly typed input. Opening starts in the displayed+real directory. Recent, Trash, and archive views retain the last real+directory; if none exists, use the user's home directory.++Navigation publishes a desired directory. Shell integration applies it only+at a safe editing point with an empty command line. While busy or editing,+retain only the latest requested directory and show that following is+pending. Revalidate the request before applying it, and acknowledge the+actual directory afterward. Handle paths that disappear or become+inaccessible without restarting the shell.++Implement this through an explicit shell integration channel. Do not infer+readiness from silence, a window title, or the foreground PID alone, and do+not type a synthetic `cd` command into the terminal. A prompt callback alone+does not prove that the current command line is empty. Phase 0 must prove a+safe mechanism for the first supported shell before automatic following is+claimed. Pass paths as data, including spaces, quotes, newlines, and Unicode.++Shell integration is installed for the launched session without overwriting+the user's startup files. Preserve their startup configuration. Use an+authenticated local channel with bounded messages and explicit session+lifetime, separate from terminal output. Output from a command must not be+interpreted as permission to execute a directory change. Phase 0 establishes+the shell bootstrap and how integration waits for and services requests+without polling or disrupting line editing.++Qualify Bash, Zsh, and Fish separately. Unsupported shells still open in the+correct initial folder, but show that automatic following is unavailable.+For those shells, offer opening an external terminal in the current folder.+A shell reporting its own directory changes updates+the header; it does not automatically navigate Files. Remote shells and+terminal multiplexers suspend following unless explicitly supported.++## Existing code to extend++| Area | Existing entry points | Planned responsibility |+| --- | --- | --- |+| Files state | `src/files/app.zig`, `app_model.zig` | Terminal session, visibility, requested height, focus restoration |+| Files controller | New `src/files/app_terminal.zig` | Drawer actions, lifecycle events, folder-follow state |+| Terminal engine | New `src/files/terminal/` modules | libvterm wrapper, PTY session, rendering, scrollback, input, shell integration |+| Layout and painting | `app_layout.zig`, `app_scroll.zig`, `app_paint.zig` | Drawer geometry, file viewport and scrollbars, header and status button |+| Files input and event loop | `app_keyboard.zig`, `app_pointer.zig`, `main.zig` | Toggle, terminal input, clipboard, PTY readiness, child exit |+| Preferences | `src/files/preferences.zig` | Height persistence with migration from existing formats |+| Shared divider | `src/ui/widgets/splitter.zig` | Horizontal divider support alongside the existing vertical divider |+| External terminal launch | Existing default-app resolution and launch helpers | Explicit external action with configured desktop ID and existing fallback rules |+| Process lifetime | `src/session/app_scope.zig` and existing child tracking | Separate shell app scope, session ownership, exit handling |+| Build | `build.zig` and dependency/install documentation | libvterm dependency for Files and its tests |++`contentBottom()` currently derives the file viewport from the footer and+horizontal scrollbar. Extend that shared geometry so selection, scrolling,+drop targets, edge shadows, and keyboard navigation all stop above the+drawer. Keep App method bodies in concern files with aliases in `app.zig`.++## Terminal architecture++[libvterm](https://www.leonerd.org.uk/code/libvterm/) provides terminal+emulation independently of a graphics toolkit. Files supplies the PTY,+rendering, history storage, and user interaction around it. Keep the wrapper+and session code in Files modules, and link the library into Files and its+test targets. Phase 0 pins the supported dependency version, packaging+requirements, and terminal capabilities.++### Shell and PTY++Select the user's shell from a valid absolute `$SHELL`, then their account+shell, with a documented fallback. Start an interactive session in the+resolved directory. Set up the controlling terminal, process/session groups,+initial window size, inherited environment, and file descriptors explicitly.+Advertise only a verified `TERM`/terminfo combination; qualify colour support+and full-screen applications against that contract.++Files is already multithreaded. Use a safe spawn/helper design for PTY setup+and exec; avoid allocation or other unsafe library work in a forked child.+Place the shell in its own app scope through `app_scope.place`, preserving+the existing nested/headless policy. Shell descendants must not inherit+Files' app scope merely because Files launched them. Reuse or extract the+client-safe launch helpers needed for this without importing compositor+runtime modules into Files.++Use nonblocking reads and queued writes with partial-write handling. Integrate+PTY readiness and child-exit notifications with the existing event loop.+Give each loop iteration a bounded parsing budget so continuous output does+not starve Wayland dispatch, file navigation, or close actions. Poll for+writability only while bytes are queued; apply backpressure to large pastes.++### Screen rendering and scrollback++Wrap libvterm's screen and output callbacks with explicit allocator ownership+and cleanup. Draw the terminal cell grid through the existing Cairo pipeline,+using monospace metrics, theme terminal colours, and a clipped content rect.+Support attributes, cursor modes, alternate screen, wide characters,+combining characters, and font fallback. Confirm these behaviours against+the chosen library version rather than assuming every terminal extension is+implemented.++Own a bounded scrollback ring with both line and byte limits. Define wrapped+line metadata, selection across history, and resize/reflow behaviour in the+prototype. Preserve scrolled-back reading position as output arrives, and+return to the live screen on user input. Reuse the shared scrollbar.++Translate changed cells, cursor movement, and selection changes into Files+damage. Publish through the existing buffer-history path and never paint a+busy shm buffer. Coalesce output bursts into available frames. Hidden or+unmapped drawers continue draining and parsing the PTY with bounded history,+but schedule no terminal paint or cursor-blink frames. Cursor blinking, if+enabled, uses deadlines only while visible and focused. With a steady cursor+and no I/O, the terminal adds no idle wakeups.++### Input and resizing++Add terminal focus within Files and route keys before file-management+shortcuts, after modal UI and plain F4. Use libvterm's input encoding for+special keys and terminal modes. Preserve Ctrl+C, Ctrl+D, Ctrl+Z, Alt keys,+key repeat, compose/dead keys, and text input. Audit Files' existing text-input+support and implement any missing client-side IME handling needed for the+drawer; this must not require a compositor exception.++Support selection, Ctrl+Shift+C/V, bracketed paste, and terminal mouse+reporting. Provide Shift as the local selection override when an application+captures the mouse. Clipboard data goes through the existing Wayland transfer+code. Terminal escape sequences must not silently read or write the desktop+clipboard or launch programs; define the supported OSC policy explicitly.++Keep the cell grid consistent with the current drawable bounds and notify+libvterm and the PTY when its dimensions change. Coalesce updates to a frame,+avoid zero-sized PTYs while collapsed, and preserve the last usable grid+while hidden. The slide and file layout share one animation state, including+reversal and reduced motion. Resizing must preserve terminal state and keep+full-screen applications usable without stretching raster text.++## External terminal action++Open external terminal uses `[compositor] default_terminal` and existing+fallback rules. Preserve desktop-entry arguments, theme handling, app scopes,+and working-directory semantics through client-safe launch helpers. It starts+a new independent session; it does not transfer the embedded shell or its+running jobs. Changing the default terminal affects this action, while the+embedded session continues using its selected shell.++## Session lifetime and failures++Track starting, running, exited, and failed session states separately from+drawer visibility. Hiding while starting must not steal focus on completion.+Handle PTY EOF/hangup and child exit in either order, drain remaining output,+and keep the last screen with exit status and a Restart action. Avoid+automatic restart loops and stale callbacks after destruction.++Normal Files close offers confirmation when a command or shell job is known+to be active, or when activity cannot be established safely. Include hidden+sessions in that check. Cancellation preserves the window and session.+After confirmed close, end the owned PTY session, reap the shell, and release+its integration channel and history. Use bounded asynchronous cleanup and+session-specific ownership; never kill processes by executable name.+Shell integration should report background jobs as well as foreground work.++An unexpected Files crash loses the embedded terminal and closes its PTY;+jobs may receive a hangup according to normal terminal semantics. Session+survival requires an explicit multiplexer or future supervisor and is not+promised by this design. Failure handling must remain within the Files+application and its shell session.++## Implementation phases++### Phase 0 Prove libvterm and shell coordination++- [ ] Pin the library version and dependency delivery, compile a Files-only+ prototype, and record the tested shell and terminfo configuration.+- [ ] Prove safe PTY launch, app-scope placement, Cairo rendering, keyboard+ input, grid resize, alternate screen, Unicode, and shell exit.+- [ ] Establish scrollback and reflow behaviour; measure continuous-output+ responsiveness and memory limits before choosing the final loop budgets.+- [ ] Prove folder following with an empty prompt, partial input, a running+ command, and rapid navigation. Qualify the shell integration transport.+- [ ] Record capability limits and lifecycle decisions before UI polish.++### Phase 1 Add terminal engine and process lifetime++- [ ] Implement the libvterm wrapper, PTY session, bounded input/output work,+ child tracking, app scopes, and cleanup.+- [ ] Implement cell rendering, scrollback, selection, cursor, colours, and+ damage through the Files buffer pipeline.+- [ ] Add terminal input encoding, compose/IME, clipboard, bracketed paste,+ mouse reporting, and the supported escape-sequence policy.++### Phase 2 Build the Files drawer++- [ ] Add controller state, F4, the status icon, header, and launch/exit/error+ states using shared UI controls.+- [ ] Extend the splitter, viewport geometry, scrollbars, hit testing, and+ height preference migration.+- [ ] Add slide animation, reversal, reduced motion, compact layouts, and+ correct focus restoration.++### Phase 3 Add directory following and lifecycle polish++- [ ] Add the qualified shell integration and coalesced desired-directory+ requests, acknowledgements, and actual-directory display.+- [ ] Handle virtual locations, inaccessible paths, unsupported shells,+ nested shells, remote sessions, and multiplexer behaviour explicitly.+- [ ] Complete close-with-command/job, PTY hangup, shell exit/restart,+ launch failure, and hidden-session behaviour.+- [ ] Add Open external terminal with existing default-app resolution and+ explicit independent-session behaviour.++### Phase 4 Validate and document support++- [ ] Extend existing unit suites for geometry, preference migration,+ lifecycle, focus routing, and directory-request state where appropriate.+ Add terminal fixtures for chunked escape sequences, Unicode cells,+ scrollback bounds, partial writes, resize, and allocation failures.+- [ ] Add a focused Files terminal headless suite with an isolated shell and+ deterministic PTY fixtures. Test two Files windows for independent state.+- [ ] Exercise supported shells, copy/paste, dead keys, IME, selection,+ scrolling, mouse modes, and full-screen tools such as `vim` and `top`.+- [ ] Check rapid toggles, divider dragging, outer-window resizing, delayed+ buffer release, grid/list modes, horizontal overflow, modal dialogs,+ workspace slides, minimize/restore, output moves, and fractional scale.+- [ ] Check launch/close/crash races, shell jobs, capture, idle wakeups,+ hidden-session continuity, and memory bounds under sustained output.+ Verify Files navigation and normal compositor interactions remain responsive.+- [ ] Build Debug and `-Doptimize=ReleaseSafe`; run `zig build test`,+ `zig build test-files`, the terminal integration suite, and relevant Files+ controls/decoration/browser and dead-key suites. Exercise normal focus,+ workspace, and minimize behaviour with the drawer open. Review shared UI+ changes against their existing callers.+ Compare existing failures with a separate HEAD worktree before identifying+ regressions.++Follow `TESTING.md`: use isolated headless sessions and temporary home/XDG+directories, set `REDIWM_FILES_DEVICES=0`, and keep shell commands and test+files inside scratch directories. Document the supported libvterm version,+terminal capabilities, shell-integration matrix, and external-terminal action+with the completed feature.diff --git a/docs/plans/mime-associations.md b/docs/plans/mime-associations.mdindex efff3fe..5c718a9 100644--- a/docs/plans/mime-associations.md+++ b/docs/plans/mime-associations.md@@ -14,7 +14,8 @@ store of its own.Both ends of the system already speak GIO and `~/.config/mimeapps.list`:* **Files** resolves a double-click with `associations.launchDefault`- (`g_app_info_get_default_for_type`), shows icons from the same lookup, and+ (`g_app_info_get_default_for_type`, the content type itself comes from+ `src/mime_db.zig` since 2026-10-16), shows icons from the same lookup, andits Open With dialog (`open_with.zig`) lists `g_app_info_get_all_for_type`first, then every other app that takes files or URLs. Ticking "remember"calls `g_app_info_set_as_default_for_type`.diff --git a/src/editor/formats.zig b/src/editor/formats.zigindex 453d1f0..4222071 100644--- a/src/editor/formats.zig+++ b/src/editor/formats.zig@@ -1,8 +1,6 @@//! Filename MIME classification only; the editor validates file contents in its worker.const std = @import("std");-extern fn g_content_type_guess([*:0]const u8, ?[*]const u8, usize, ?*c_int) ?[*:0]u8;-extern fn g_content_type_is_a([*:0]const u8, [*:0]const u8) c_int;-extern fn g_free(?*anyopaque) void;+const mime_db = @import("../mime_db.zig");pub fn candidate(path: []const u8) bool {// README, Makefile, dotfiles and other extensionless documents are common.const extension = std.fs.path.extension(path);@@ -10,14 +8,11 @@ pub fn candidate(path: []const u8) bool {for ([_][]const u8{ ".zig", ".rs", ".go", ".py", ".js", ".ts", ".tsx", ".jsx", ".yaml", ".yml", ".toml", ".ini", ".conf", ".cfg", ".log", ".csv", ".sh" }) |ext| {if (std.ascii.eqlIgnoreCase(extension, ext)) return true;}- var buf: [4096]u8 = undefined;- const name = std.fmt.bufPrintZ(&buf, "{s}", .{path}) catch return false;- const mime = g_content_type_guess(name, null, 0, null) orelse return false;- defer g_free(mime);- return g_content_type_is_a(mime, "text/plain") != 0 or- g_content_type_is_a(mime, "application/json") != 0 or- g_content_type_is_a(mime, "application/xml") != 0 or- g_content_type_is_a(mime, "application/toml") != 0 or+ const mime = mime_db.guess(path);+ return mime_db.isA(mime, "text/plain") or+ mime_db.isA(mime, "application/json") or+ mime_db.isA(mime, "application/xml") or+ mime_db.isA(mime, "application/toml") orstd.ascii.eqlIgnoreCase(std.fs.path.extension(path), ".toml");}test "text preview candidates include config, source and extensionless files" {diff --git a/src/files/AGENTS.md b/src/files/AGENTS.mdindex 3473610..1081b6a 100644--- a/src/files/AGENTS.md+++ b/src/files/AGENTS.md@@ -19,6 +19,23 @@ records are in `app_model.zig`, drawing helpers in `app_draw.zig`, tests in`app_tests.zig`. A new method goes in its group file plus an alias line in`App`; a file that calls a sibling's non-method helper imports it directly.+## File types and associations++* **Types come from `src/mime_db.zig`, not GIO.** It reads shared-mime-info+ (`globs2`, `aliases`, `subclasses`, `icons`, `generic-icons`, the per-type XML+ comments) from `$XDG_DATA_HOME` and `$XDG_DATA_DIRS`, by file name only.+ Files, Properties, the chooser filters, Recent and the Editor share it. It+ was checked against `g_content_type_*` over every glob of the installed+ database: literal names beat suffix globs, which beat wildcard patterns+ regardless of weight, and a `cs` glob repeated without the flag stays+ case sensitive. Re-run that comparison before changing the matching order.+ Returned strings live for the process (a changed `globs2` is picked up at+ most every 5 s by swapping in a new copy; the old one is retired, not freed).+* **Applications and defaults stay on GIO** (`associations.zig`: default app,+ Open With, `mimeapps.list`, launching), so `xdg-open`, browsers and portals+ agree with Files. Only the content type is ours; GIO calls take it as a+ C string through `TypeZ`.+## Git`git.zig` never runs a repository's own programs: a folder's `.git` arrivesdiff --git a/src/files/associations.zig b/src/files/associations.zigindex 5a73f44..69fe716 100644--- a/src/files/associations.zig+++ b/src/files/associations.zig@@ -1,12 +1,13 @@-//! MIME icons and application associations through the system GIO database.+//! MIME icons and application associations. File types and their icons come+//! from `mime_db` (shared-mime-info read directly); applications and defaults+//! go through the system GIO database so every other program agrees.//! Icon candidates run on the directory worker; application snapshots belong//! to the Open With dialog. Neither owns the UI icon cache.const std = @import("std");+const mime_db = @import("../mime_db.zig");const Allocator = std.mem.Allocator;// GLib headers cannot be translated by Zig; declare the stable GIO ABI only.-extern fn g_content_type_guess(filename: [*:0]const u8, data: ?[*]const u8, size: usize, uncertain: ?*c_int) ?[*:0]u8;-extern fn g_content_type_get_icon(content_type: [*:0]const u8) ?*anyopaque;extern fn g_app_info_get_default_for_type(content_type: [*:0]const u8, must_support_uris: c_int) ?*anyopaque;extern fn g_app_info_get_icon(app: *anyopaque) ?*anyopaque;extern fn g_themed_icon_get_type() usize;@@ -26,27 +27,54 @@ pub const Resolver = struct {pub fn candidates(self: *Resolver, filename: [:0]const u8) ![]const []const u8 {// Filename globs come from shared-mime-info, including app-installed// types such as OpenSCAD. Never read arbitrary file contents here.- const content_type = g_content_type_guess(filename, null, 0, null) orelse return &.{};- defer g_free(content_type);- const key = std.mem.span(content_type);+ const key = mime_db.guess(filename);if (self.by_type.get(key)) |cached| return cached;var names: std.ArrayList([]const u8) = .empty;- const mime_icon = g_content_type_get_icon(content_type);- defer if (mime_icon) |icon| g_object_unref(icon);+ var buffer: mime_db.IconBuffer = .{};+ const mime_icons = mime_db.iconNames(key, &buffer);// A specific file icon wins. A plain document fallback must not hide// the icon of the user's associated application.- if (mime_icon) |icon| try appendIcon(self.allocator, &names, icon, true);- if (g_app_info_get_default_for_type(content_type, 0)) |app| {+ try appendMimeIcons(self.allocator, &names, mime_icons, true);+ var type_z: TypeZ = undefined;+ if (type_z.set(key)) |content_type| if (g_app_info_get_default_for_type(content_type, 0)) |app| {defer g_object_unref(app);if (g_app_info_get_icon(app)) |icon| try appendIcon(self.allocator, &names, icon, false);- }- if (mime_icon) |icon| try appendIcon(self.allocator, &names, icon, false);+ };+ try appendMimeIcons(self.allocator, &names, mime_icons, false);const result = try names.toOwnedSlice(self.allocator);try self.by_type.put(self.allocator, try self.allocator.dupe(u8, key), result);return result;}};+/// A MIME type as a C string for GIO calls; types longer than the buffer+/// cannot be real and simply have no application lookup.+const TypeZ = struct {+ buf: [256]u8,++ fn set(self: *TypeZ, mime: []const u8) ?[*:0]const u8 {+ if (mime.len >= self.buf.len) return null;+ @memcpy(self.buf[0..mime.len], mime);+ self.buf[mime.len] = 0;+ return @ptrCast(&self.buf);+ }+};++/// The names a themed GIO icon for the type would carry: each name, then each+/// again with a "-symbolic" suffix as a last resort.+fn appendMimeIcons(a: Allocator, names: *std.ArrayList([]const u8), mime_icons: []const []const u8, specific_only: bool) !void {+ for (mime_icons) |name| {+ if (specific_only and genericDocument(name)) continue;+ try appendName(a, names, name);+ }+ for (mime_icons) |name| {+ if (specific_only and genericDocument(name)) continue;+ const symbolic = try std.fmt.allocPrint(a, "{s}-symbolic", .{name});+ defer a.free(symbolic);+ try appendName(a, names, symbolic);+ }+}+fn appendIcon(a: Allocator, names: *std.ArrayList([]const u8), icon: *anyopaque, specific_only: bool) !void {if (g_type_check_instance_is_a(icon, g_themed_icon_get_type()) != 0) {const candidates = g_themed_icon_get_names(icon);@@ -94,7 +122,6 @@ extern fn g_app_info_get_display_name(app: *anyopaque) [*:0]const u8;extern fn g_app_info_supports_files(app: *anyopaque) c_int;extern fn g_app_info_supports_uris(app: *anyopaque) c_int;extern fn g_app_info_set_as_default_for_type(app: *anyopaque, content_type: [*:0]const u8, err: ?*?*anyopaque) c_int;-extern fn g_content_type_equals(a: [*:0]const u8, b: [*:0]const u8) c_int;extern fn g_get_user_config_dir() [*:0]const u8;extern fn g_key_file_new() *anyopaque;extern fn g_key_file_unref(key_file: *anyopaque) void;@@ -127,9 +154,8 @@ pub const Applications = struct {const owned = try a.alloc([:0]const u8, paths.len);for (paths, 0..) |path, i| {owned[i] = try a.dupeZ(u8, path);- const kind = g_content_type_guess(owned[i], null, 0, null) orelse return error.UnknownContentType;- defer g_free(kind);- if (i == 0) self.content_type = try a.dupeZ(u8, std.mem.span(kind)) else if (!std.mem.eql(u8, self.content_type, std.mem.span(kind))) self.same_type = false;+ const kind = mime_db.guess(owned[i]);+ if (i == 0) self.content_type = try a.dupeZ(u8, kind) else if (!std.mem.eql(u8, self.content_type, kind)) self.same_type = false;}self.paths = owned;const default = if (self.same_type) g_app_info_get_default_for_type(self.content_type, 0) else null;@@ -192,7 +218,7 @@ pub const Applications = struct {var i: usize = 0;while (keys[i]) |key| : (i += 1) {if (std.mem.eql(u8, std.mem.span(key), self.content_type)) continue;- if (g_content_type_equals(key, self.content_type) == 0) continue;+ if (!mime_db.equals(std.mem.span(key), self.content_type)) continue;if (g_app_info_set_as_default_for_type(app, key, null) == 0) return error.DefaultFailed;}}@@ -223,9 +249,9 @@ extern fn g_app_info_get_id(app: *anyopaque) ?[*:0]const u8;pub fn launchDefault(path: []const u8) !void {const filename = try std.heap.c_allocator.dupeZ(u8, path);defer std.heap.c_allocator.free(filename);- const kind = g_content_type_guess(filename, null, 0, null) orelse return error.UnknownContentType;- defer g_free(kind);- const app = g_app_info_get_default_for_type(kind, 0) orelse return error.NoDefaultApplication;+ var kind: TypeZ = undefined;+ const content_type = kind.set(mime_db.guess(filename)) orelse return error.NoDefaultApplication;+ const app = g_app_info_get_default_for_type(content_type, 0) orelse return error.NoDefaultApplication;defer g_object_unref(app);const file = g_file_new_for_path(filename);defer g_object_unref(file);@@ -237,9 +263,9 @@ pub fn launchDefault(path: []const u8) !void {pub fn hasAlternativeDefault(path: []const u8, bundled_id: []const u8) bool {const filename = std.heap.c_allocator.dupeZ(u8, path) catch return false;defer std.heap.c_allocator.free(filename);- const kind = g_content_type_guess(filename, null, 0, null) orelse return false;- defer g_free(kind);- const app = g_app_info_get_default_for_type(kind, 0) orelse return false;+ var kind: TypeZ = undefined;+ const content_type = kind.set(mime_db.guess(filename)) orelse return false;+ const app = g_app_info_get_default_for_type(content_type, 0) orelse return false;defer g_object_unref(app);const id = g_app_info_get_id(app) orelse return true;return !std.mem.eql(u8, std.mem.span(id), bundled_id);diff --git a/src/files/chooser.zig b/src/files/chooser.zigindex 78bd0db..f02bbbb 100644--- a/src/files/chooser.zig+++ b/src/files/chooser.zig@@ -1,11 +1,9 @@//! Shared contract between the portal backend and Files' chooser mode.const std = @import("std");+const mime_db = @import("../mime_db.zig");const c = @cImport({@cInclude("fnmatch.h");});-extern fn g_content_type_guess([*:0]const u8, ?[*]const u8, usize, ?*c_int) ?[*:0]u8;-extern fn g_content_type_is_a([*:0]const u8, [*:0]const u8) c_int;-extern fn g_free(?*anyopaque) void;pub const Mode = enum { open, save, folder };pub const Rule = struct { kind: u32, value: []const u8 };@@ -40,9 +38,7 @@ pub fn matches(filter: Filter, name: []const u8) bool {if (rule.kind == 0) {if (c.fnmatch(pattern, zname, 0) == 0) return true;} else if (rule.kind == 1) {- const mime = g_content_type_guess(zname, null, 0, null) orelse continue;- defer g_free(mime);- if (g_content_type_is_a(mime, pattern) != 0) return true;+ if (mime_db.isA(mime_db.guess(name), rule.value)) return true;}}return false;diff --git a/src/files/properties.zig b/src/files/properties.zigindex 7375917..4a73933 100644--- a/src/files/properties.zig+++ b/src/files/properties.zig@@ -1,6 +1,7 @@//! A snapshot of one file, owned independently of directory refreshes.const std = @import("std");const c = @import("c.zig").api;+const mime_db = @import("../mime_db.zig");const ui = @import("ui").cairo;const theme = @import("ui").theme;const scrollbar = @import("ui").widgets.scrollbar;@@ -13,10 +14,6 @@ const icon_theme = @import("../icon_theme.zig");const Rect = ui.Rect;const centeredTextX = @import("ui").paint.centeredTextX;-extern fn g_content_type_guess(filename: [*:0]const u8, data: ?[*]const u8, size: usize, uncertain: ?*c_int) ?[*:0]u8;-extern fn g_content_type_get_description(content_type: [*:0]const u8) ?[*:0]u8;-extern fn g_free(memory: ?*anyopaque) void;-pub const Action = enum { none, close, open };fn contentShift() f32 {return @max(0, @as(f32, @floatFromInt((chrome.Metrics{}).titlebarHeight())) - 49);@@ -275,11 +272,7 @@ fn describe(a: std.mem.Allocator, path: [:0]const u8, mode: c.mode_t) ![]const uelse => null,};if (simple) |label| return a.dupe(u8, label);- const kind = g_content_type_guess(path, null, 0, null) orelse return a.dupe(u8, "File");- defer g_free(kind);- const description = g_content_type_get_description(kind) orelse return a.dupe(u8, "File");- defer g_free(description);- return a.dupe(u8, std.mem.span(description));+ return mime_db.description(a, mime_db.guess(path));}fn contains(rect: Rect, x: f32, y: f32) bool {diff --git a/src/files/recent.zig b/src/files/recent.zigindex b73fa19..92c9949 100644--- a/src/files/recent.zig+++ b/src/files/recent.zig@@ -1,6 +1,7 @@//! The shared freedesktop recent-file history. All disk work runs on Files' worker.const std = @import("std");const clipboard = @import("clipboard.zig");+const mime_db = @import("../mime_db.zig");const Allocator = std.mem.Allocator;pub const location = "recent:///";@@ -24,8 +25,6 @@ extern fn g_bookmark_file_set_mime_type(bookmark: *anyopaque, uri: [*:0]const u8extern fn g_bookmark_file_add_application(bookmark: *anyopaque, uri: [*:0]const u8, name: [*:0]const u8, exec: [*:0]const u8) void;extern fn g_bookmark_file_to_data(bookmark: *anyopaque, length: *usize, err: ?*?*anyopaque) ?[*:0]u8;extern fn g_file_set_contents_full(filename: [*:0]const u8, data: [*]const u8, length: isize, flags: c_int, mode: c_int, err: ?*?*anyopaque) c_int;-extern fn g_content_type_guess(filename: [*:0]const u8, data: ?[*]const u8, size: usize, uncertain: ?*c_int) ?[*:0]u8;-extern fn g_content_type_get_mime_type(content_type: [*:0]const u8) ?[*:0]u8;extern fn g_strfreev(strings: [*:null]?[*:0]u8) void;extern fn g_free(memory: ?*anyopaque) void;@@ -91,13 +90,9 @@ pub fn record(a: Allocator, io: std.Io, env: std.process.Environ, opened: []consdefer a.free(raw_uri);const uri = try a.dupeZ(u8, raw_uri);defer a.free(uri);- const zpath = try a.dupeZ(u8, opened);- defer a.free(zpath);- const content_type = g_content_type_guess(zpath, null, 0, null);- defer g_free(content_type);- const mime = if (content_type) |t| g_content_type_get_mime_type(t) else null;- defer g_free(mime);- g_bookmark_file_set_mime_type(bookmark, uri, mime orelse "application/octet-stream");+ const mime = try a.dupeZ(u8, mime_db.guess(opened));+ defer a.free(mime);+ g_bookmark_file_set_mime_type(bookmark, uri, mime);g_bookmark_file_add_application(bookmark, uri, "RediWM Files", "rediwm-files %f");const now = g_date_time_new_now_utc();defer g_date_time_unref(now);diff --git a/src/files_tests.zig b/src/files_tests.zigindex 4f57d8e..f6fe1c2 100644--- a/src/files_tests.zig+++ b/src/files_tests.zig@@ -1088,6 +1088,7 @@ test "App clicking dash starts calculation without changing selection" {}test {+ _ = @import("mime_db.zig");_ = @import("files/chooser.zig");_ = @import("config").portals;_ = @import("files/thumb_decode.zig");diff --git a/src/mime_db.zig b/src/mime_db.zignew file mode 100644index 0000000..cf1f3a3--- /dev/null+++ b/src/mime_db.zig@@ -0,0 +1,724 @@+//! Filename MIME classification from the shared-mime-info database, without+//! GIO: `globs2`, `aliases`, `subclasses`, `icons`, `generic-icons` and the+//! per-type XML comments under `$XDG_DATA_HOME` and `$XDG_DATA_DIRS`.+//! Names only; file contents are never read. The database loads on first use,+//! is immutable afterwards, and is rechecked at most every few seconds when+//! asked (a changed `globs2` swaps in a fresh copy). Every returned slice+//! lives for the rest of the process: replaced copies are retired, not freed,+//! because other threads may still hold their strings.+const std = @import("std");+const Allocator = std.mem.Allocator;++pub const unknown = "application/octet-stream";+pub const directory = "inode/directory";++const recheck_seconds = 5;+const max_matches = 32;+const name_max = 255;++const Glob = struct {+ mime: []const u8,+ weight: u8,+ len: u16,+ /// Index of the data directory the entry came from (0 = most specific).+ dir: u8,+};++const Pattern = struct {+ glob: Glob,+ pattern: [:0]const u8,+ case_sensitive: bool,+};++const Parents = std.ArrayList([]const u8);++extern fn fnmatch(pattern: [*:0]const u8, name: [*:0]const u8, flags: c_int) c_int;++pub const Db = struct {+ arena: std.heap.ArenaAllocator,+ /// `<data dir>/mime`, most specific first.+ dirs: std.ArrayList([:0]const u8) = .empty,+ /// Modification time of each directory's `globs2`, for staleness checks.+ stamp: std.ArrayList(i128) = .empty,+ literals: std.StringHashMapUnmanaged(Glob) = .empty,+ literals_ci: std.StringHashMapUnmanaged(Glob) = .empty,+ /// `*.ext` patterns keyed by everything after the `*`.+ suffixes: std.StringHashMapUnmanaged(Glob) = .empty,+ suffixes_ci: std.StringHashMapUnmanaged(Glob) = .empty,+ patterns: std.ArrayList(Pattern) = .empty,+ /// `__NOGLOBS__`: lower-priority directories lose this type's globs.+ no_globs: std.StringHashMapUnmanaged(u8) = .empty,+ aliases: std.StringHashMapUnmanaged([]const u8) = .empty,+ parents: std.StringHashMapUnmanaged(Parents) = .empty,+ icons: std.StringHashMapUnmanaged([]const u8) = .empty,+ generic_icons: std.StringHashMapUnmanaged([]const u8) = .empty,++ pub fn init(backing: Allocator) Db {+ return .{ .arena = .init(backing) };+ }++ pub fn deinit(self: *Db) void {+ self.arena.deinit();+ }++ // ---- loading -------------------------------------------------------++ pub fn addGlobs(self: *Db, text: []const u8, dir: u8) Allocator.Error!void {+ const a = self.arena.allocator();+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |raw| {+ const line = std.mem.trim(u8, raw, " \t\r");+ if (line.len == 0 or line[0] == '#') continue;+ const first = std.mem.indexOfScalar(u8, line, ':') orelse continue;+ const rest = line[first + 1 ..];+ const second = std.mem.indexOfScalar(u8, rest, ':') orelse continue;+ const weight = std.fmt.parseInt(u8, line[0..first], 10) catch continue;+ const mime = rest[0..second];+ var pattern = rest[second + 1 ..];+ var case_sensitive = false;+ if (std.mem.indexOfScalar(u8, pattern, ':')) |colon| {+ var flags = std.mem.splitScalar(u8, pattern[colon + 1 ..], ',');+ while (flags.next()) |flag| {+ if (std.mem.eql(u8, flag, "cs")) case_sensitive = true;+ }+ pattern = pattern[0..colon];+ }+ if (mime.len == 0 or pattern.len == 0) continue;+ const owned_mime = try self.intern(mime);+ if (std.mem.eql(u8, pattern, "__NOGLOBS__")) {+ const entry = try self.no_globs.getOrPut(a, owned_mime);+ if (!entry.found_existing or entry.value_ptr.* > dir) entry.value_ptr.* = dir;+ continue;+ }+ const glob: Glob = .{+ .mime = owned_mime,+ .weight = weight,+ .len = @intCast(@min(pattern.len, std.math.maxInt(u16))),+ .dir = dir,+ };+ const key = if (case_sensitive) try a.dupe(u8, pattern) else try std.ascii.allocLowerString(a, pattern);+ // The database writes a case-sensitive glob and then the same+ // glob again without the flag: the flag sticks.+ if (std.mem.indexOfAny(u8, key, "*?[\\") == null) {+ try self.putGlob(&self.literals, &self.literals_ci, key, pattern, glob, case_sensitive);+ } else if (key[0] == '*' and std.mem.indexOfAny(u8, key[1..], "*?[\\") == null) {+ try self.putGlob(&self.suffixes, &self.suffixes_ci, key[1..], pattern[1..], glob, case_sensitive);+ } else {+ try self.patterns.append(a, .{ .glob = glob, .pattern = try a.dupeZ(u8, key), .case_sensitive = case_sensitive });+ }+ }+ }++ pub fn addAliases(self: *Db, text: []const u8) Allocator.Error!void {+ const a = self.arena.allocator();+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |raw| {+ var fields = std.mem.tokenizeAny(u8, raw, " \t\r");+ const alias = fields.next() orelse continue;+ if (alias[0] == '#') continue;+ const canonical = fields.next() orelse continue;+ const entry = try self.aliases.getOrPut(a, try self.intern(alias));+ if (!entry.found_existing) entry.value_ptr.* = try self.intern(canonical);+ }+ }++ pub fn addSubclasses(self: *Db, text: []const u8) Allocator.Error!void {+ const a = self.arena.allocator();+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |raw| {+ var fields = std.mem.tokenizeAny(u8, raw, " \t\r");+ const child = fields.next() orelse continue;+ if (child[0] == '#') continue;+ const parent = fields.next() orelse continue;+ const entry = try self.parents.getOrPut(a, try self.intern(child));+ if (!entry.found_existing) entry.value_ptr.* = .empty;+ try entry.value_ptr.append(a, try self.intern(parent));+ }+ }++ /// `mime:icon-name` lines, shared by `icons` and `generic-icons`.+ pub fn addIcons(self: *Db, text: []const u8, generic: bool) Allocator.Error!void {+ const a = self.arena.allocator();+ const map = if (generic) &self.generic_icons else &self.icons;+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |raw| {+ const line = std.mem.trim(u8, raw, " \t\r");+ if (line.len == 0 or line[0] == '#') continue;+ const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;+ if (colon == 0 or colon + 1 == line.len) continue;+ const entry = try map.getOrPut(a, try self.intern(line[0..colon]));+ if (!entry.found_existing) entry.value_ptr.* = try a.dupe(u8, line[colon + 1 ..]);+ }+ }++ fn intern(self: *Db, s: []const u8) Allocator.Error![]const u8 {+ return self.arena.allocator().dupe(u8, s);+ }++ fn putGlob(+ self: *Db,+ exact: *std.StringHashMapUnmanaged(Glob),+ folded: *std.StringHashMapUnmanaged(Glob),+ key: []const u8,+ original: []const u8,+ glob: Glob,+ case_sensitive: bool,+ ) Allocator.Error!void {+ const a = self.arena.allocator();+ if (case_sensitive) {+ if (folded.get(key)) |old| if (std.mem.eql(u8, old.mime, glob.mime) and old.dir == glob.dir) {+ _ = folded.remove(key);+ };+ } else if (exact.get(original)) |old| {+ if (std.mem.eql(u8, old.mime, glob.mime) and old.dir == glob.dir) return;+ }+ const map = if (case_sensitive) exact else folded;+ const entry = try map.getOrPut(a, key);+ if (!entry.found_existing or better(glob, entry.value_ptr.*)) entry.value_ptr.* = glob;+ }++ // ---- queries -------------------------------------------------------++ /// Best name match, or null when no glob applies.+ pub fn guess(self: *const Db, base: []const u8) ?[]const u8 {+ if (base.len == 0 or base.len > name_max) return null;+ var lower_buf: [name_max + 1]u8 = undefined;+ const lower = std.ascii.lowerString(&lower_buf, base);+ lower_buf[base.len] = 0;+ const lower_z: [*:0]const u8 = @ptrCast(&lower_buf);+ var base_buf: [name_max + 1]u8 = undefined;+ @memcpy(base_buf[0..base.len], base);+ base_buf[base.len] = 0;+ const base_z: [*:0]const u8 = @ptrCast(&base_buf);++ // Literal names beat suffix globs, which beat general patterns: a+ // lower-weight literal still wins over a heavier wildcard, as in GIO.+ var best: ?Glob = null;+ if (self.literals.get(base)) |g| self.consider(&best, g);+ if (self.literals_ci.get(lower)) |g| self.consider(&best, g);+ if (best == null) {+ var i: usize = 0;+ while (i < base.len) : (i += 1) {+ if (self.suffixes.get(base[i..])) |g| self.consider(&best, g);+ if (self.suffixes_ci.get(lower[i..])) |g| self.consider(&best, g);+ }+ }+ if (best == null) {+ for (self.patterns.items) |p| {+ const name = if (p.case_sensitive) base_z else lower_z;+ if (fnmatch(p.pattern, name, 0) == 0) self.consider(&best, p.glob);+ }+ }+ return if (best) |g| g.mime else null;+ }++ fn consider(self: *const Db, best: *?Glob, g: Glob) void {+ if (self.no_globs.get(g.mime)) |dir| if (g.dir > dir) return;+ if (best.* == null or better(g, best.*.?)) best.* = g;+ }++ pub fn unalias(self: *const Db, mime: []const u8) []const u8 {+ return self.aliases.get(mime) orelse mime;+ }++ pub fn equals(self: *const Db, a: []const u8, b: []const u8) bool {+ return std.mem.eql(u8, self.unalias(a), self.unalias(b));+ }++ pub fn isA(self: *const Db, mime: []const u8, parent: []const u8) bool {+ return self.isAUnaliased(self.unalias(mime), self.unalias(parent), 0);+ }++ fn isAUnaliased(self: *const Db, mime: []const u8, parent: []const u8, depth: u8) bool {+ if (std.mem.eql(u8, mime, parent)) return true;+ // Implicit rules of the specification.+ if (std.mem.eql(u8, parent, unknown) and !std.mem.startsWith(u8, mime, "inode/")) return true;+ if (std.mem.eql(u8, parent, "text/plain") and std.mem.startsWith(u8, mime, "text/")) return true;+ if (depth >= 16) return false;+ const list = self.parents.get(mime) orelse return false;+ for (list.items) |next| {+ if (self.isAUnaliased(self.unalias(next), parent, depth + 1)) return true;+ }+ return false;+ }++ /// Themed icon names in preference order: the type's own icon, the dashed+ /// type name, then its generic icon, without repeats. Slices point into+ /// `self` or `buf`.+ pub fn iconNames(self: *const Db, mime: []const u8, buf: *IconBuffer) []const []const u8 {+ const canonical = self.unalias(mime);+ var count: usize = 0;+ if (self.icons.get(canonical)) |name| count = appendUnique(buf, count, name);+ if (mime.len <= buf.dashed.len) {+ @memcpy(buf.dashed[0..mime.len], mime);+ for (buf.dashed[0..mime.len]) |*ch| {+ if (ch.* == '/') ch.* = '-';+ }+ count = appendUnique(buf, count, buf.dashed[0..mime.len]);+ }+ if (self.generic_icons.get(canonical)) |name| {+ count = appendUnique(buf, count, name);+ } else {+ const suffix = "-x-generic";+ const media_len = std.mem.indexOfScalar(u8, canonical, '/') orelse canonical.len;+ if (media_len + suffix.len <= buf.generic.len) {+ @memcpy(buf.generic[0..media_len], canonical[0..media_len]);+ @memcpy(buf.generic[media_len..][0..suffix.len], suffix);+ count = appendUnique(buf, count, buf.generic[0 .. media_len + suffix.len]);+ }+ }+ return buf.names[0..count];+ }+};++fn appendUnique(buf: *IconBuffer, count: usize, name: []const u8) usize {+ for (buf.names[0..count]) |existing| if (std.mem.eql(u8, existing, name)) return count;+ buf.names[count] = name;+ return count + 1;+}++fn better(a: Glob, b: Glob) bool {+ return a.weight > b.weight or (a.weight == b.weight and a.len > b.len);+}++pub const IconBuffer = struct {+ names: [3][]const u8 = undefined,+ dashed: [160]u8 = undefined,+ generic: [64]u8 = undefined,+};++// ---- process-wide database ------------------------------------------------++var mutex: std.Io.Mutex = .init;+var state: std.atomic.Value(?*Db) = .init(null);+var last_check: std.atomic.Value(i64) = .init(0);++fn io() std.Io {+ return std.Io.Threaded.global_single_threaded.io();+}++fn now() i64 {+ var ts: std.posix.timespec = undefined;+ return switch (std.posix.errno(std.posix.system.clock_gettime(std.posix.CLOCK.MONOTONIC, &ts))) {+ .SUCCESS => ts.sec,+ else => 0,+ };+}++fn current() ?*Db {+ const db = state.load(.acquire) orelse return load();+ const t = now();+ if (t - last_check.load(.monotonic) < recheck_seconds) return db;+ if (!mutex.tryLock()) return db;+ defer mutex.unlock(io());+ last_check.store(t, .monotonic);+ if (!stale(db)) return db;+ return reload();+}++fn load() ?*Db {+ mutex.lockUncancelable(io());+ defer mutex.unlock(io());+ if (state.load(.acquire)) |db| return db;+ last_check.store(now(), .monotonic);+ return reload();+}++fn reload() ?*Db {+ const db = build(std.heap.page_allocator) catch return state.load(.acquire);+ state.store(db, .release);+ return db;+}++fn dataDirs(db: *Db) Allocator.Error!void {+ const a = db.arena.allocator();+ const home = std.c.getenv("XDG_DATA_HOME");+ if (home != null and home.?[0] == '/') {+ try db.dirs.append(a, try std.fmt.allocPrintSentinel(a, "{s}/mime", .{std.mem.span(home.?)}, 0));+ } else if (std.c.getenv("HOME")) |h| {+ try db.dirs.append(a, try std.fmt.allocPrintSentinel(a, "{s}/.local/share/mime", .{std.mem.span(h)}, 0));+ }+ const list = if (std.c.getenv("XDG_DATA_DIRS")) |v| std.mem.span(v) else "";+ var it = std.mem.tokenizeScalar(u8, if (list.len > 0) list else "/usr/local/share:/usr/share", ':');+ while (it.next()) |dir| {+ if (dir[0] != '/') continue;+ try db.dirs.append(a, try std.fmt.allocPrintSentinel(a, "{s}/mime", .{std.mem.trimEnd(u8, dir, "/")}, 0));+ }+}++fn mtime(path: []const u8) i128 {+ const stat = std.Io.Dir.cwd().statFile(io(), path, .{}) catch return 0;+ return stat.mtime.nanoseconds;+}++fn stale(db: *const Db) bool {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ for (db.dirs.items, db.stamp.items) |dir, stamp| {+ const path = std.fmt.bufPrint(&buf, "{s}/globs2", .{dir}) catch continue;+ if (mtime(path) != stamp) return true;+ }+ return false;+}++fn readFile(a: Allocator, dir: []const u8, name: []const u8) ?[]u8 {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = std.fmt.bufPrint(&buf, "{s}/{s}", .{ dir, name }) catch return null;+ return std.Io.Dir.cwd().readFileAlloc(io(), path, a, .limited(16 * 1024 * 1024)) catch null;+}++fn build(backing: Allocator) !*Db {+ const db = try backing.create(Db);+ errdefer backing.destroy(db);+ db.* = Db.init(backing);+ errdefer db.deinit();+ try dataDirs(db);+ const scratch_backing = std.heap.page_allocator;+ for (db.dirs.items, 0..) |dir, i| {+ const index: u8 = @intCast(@min(i, std.math.maxInt(u8)));+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const globs_path = std.fmt.bufPrint(&buf, "{s}/globs2", .{dir}) catch "";+ try db.stamp.append(db.arena.allocator(), mtime(globs_path));+ inline for (.{ "globs2", "aliases", "subclasses", "icons", "generic-icons" }, 0..) |name, kind| {+ if (readFile(scratch_backing, dir, name)) |text| {+ defer scratch_backing.free(text);+ switch (kind) {+ 0 => try db.addGlobs(text, index),+ 1 => try db.addAliases(text),+ 2 => try db.addSubclasses(text),+ 3 => try db.addIcons(text, false),+ else => try db.addIcons(text, true),+ }+ }+ }+ }+ return db;+}++// ---- public API -------------------------------------------------------------++fn baseName(path: []const u8) []const u8 {+ const slash = std.mem.lastIndexOfScalar(u8, path, '/') orelse return path;+ return path[slash + 1 ..];+}++/// MIME type for a file name or path, `application/octet-stream` when no glob+/// matches. A trailing slash means a directory.+pub fn guess(path: []const u8) []const u8 {+ if (std.mem.endsWith(u8, path, "/")) return directory;+ const db = current() orelse return unknown;+ return db.guess(baseName(path)) orelse unknown;+}++pub fn isA(mime: []const u8, parent: []const u8) bool {+ const db = current() orelse return std.mem.eql(u8, mime, parent);+ return db.isA(mime, parent);+}++/// Same type after resolving aliases (`video/x-matroska` = `video/matroska`).+pub fn equals(a: []const u8, b: []const u8) bool {+ const db = current() orelse return std.mem.eql(u8, a, b);+ return db.equals(a, b);+}++/// Icon names to try for a type, best first. Valid until `buf` is reused.+pub fn iconNames(mime: []const u8, buf: *IconBuffer) []const []const u8 {+ const db = current() orelse {+ buf.names[0] = "application-x-generic";+ return buf.names[0..1];+ };+ return db.iconNames(mime, buf);+}++// ---- descriptions -----------------------------------------------------------++/// Locale names to prefer, most specific first, ending with "C": the same+/// order as `g_get_language_names`.+fn languages(a: Allocator, out: *std.ArrayList([]const u8)) Allocator.Error!void {+ const locale = firstSet(&.{ "LC_ALL", "LC_MESSAGES", "LANG" });+ if (std.c.getenv("LANGUAGE")) |list| {+ if (locale != null and !std.mem.eql(u8, locale.?, "C") and !std.mem.eql(u8, locale.?, "POSIX")) {+ var it = std.mem.tokenizeScalar(u8, std.mem.span(list), ':');+ while (it.next()) |name| try variants(a, out, name);+ }+ }+ if (locale) |name| try variants(a, out, name);+ try out.append(a, "C");+}++fn firstSet(names: []const [:0]const u8) ?[]const u8 {+ for (names) |name| {+ if (std.c.getenv(name)) |v| if (v[0] != 0) return std.mem.span(v);+ }+ return null;+}++/// `ll_CC.enc@mod` expands to every combination that keeps `ll`.+fn variants(a: Allocator, out: *std.ArrayList([]const u8), locale: []const u8) Allocator.Error!void {+ var rest = locale;+ var modifier: []const u8 = "";+ var codeset: []const u8 = "";+ var territory: []const u8 = "";+ if (std.mem.indexOfScalar(u8, rest, '@')) |i| {+ modifier = rest[i..];+ rest = rest[0..i];+ }+ if (std.mem.indexOfScalar(u8, rest, '.')) |i| {+ codeset = rest[i..];+ rest = rest[0..i];+ }+ if (std.mem.indexOfScalar(u8, rest, '_')) |i| {+ territory = rest[i..];+ rest = rest[0..i];+ }+ if (rest.len == 0) return;+ var mask: u3 = 7;+ while (true) : (mask -= 1) {+ const name = try std.fmt.allocPrint(a, "{s}{s}{s}{s}", .{+ rest,+ if (mask & 4 != 0) territory else "",+ if (mask & 2 != 0) codeset else "",+ if (mask & 1 != 0) modifier else "",+ });+ var dup = false;+ for (out.items) |existing| dup = dup or std.mem.eql(u8, existing, name);+ if (!dup) try out.append(a, name);+ if (mask == 0) break;+ }+}++/// Localized description of a type ("PNG image"), taken from the per-type XML+/// next to the database; `"<type> type"` when no description exists.+pub fn description(a: Allocator, mime: []const u8) Allocator.Error![]u8 {+ const db = current();+ const type_name = if (db) |d| d.unalias(mime) else mime;+ if (std.mem.indexOfAny(u8, type_name, "\\\x00") != null or std.mem.indexOf(u8, type_name, "..") != null) {+ return std.fmt.allocPrint(a, "{s} type", .{type_name});+ }+ var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);+ defer arena.deinit();+ var langs: std.ArrayList([]const u8) = .empty;+ try languages(arena.allocator(), &langs);+ if (db) |d| {+ var name_buf: [256]u8 = undefined;+ const file = std.fmt.bufPrint(&name_buf, "{s}.xml", .{type_name}) catch return std.fmt.allocPrint(a, "{s} type", .{type_name});+ for (d.dirs.items) |dir| {+ const xml = readFile(arena.allocator(), dir, file) orelse continue;+ if (pickComment(arena.allocator(), xml, langs.items)) |text| return a.dupe(u8, text);+ break;+ }+ }+ return std.fmt.allocPrint(a, "{s} type", .{type_name});+}++fn pickComment(a: Allocator, xml: []const u8, langs: []const []const u8) ?[]const u8 {+ var best: ?[]const u8 = null;+ var best_rank: usize = std.math.maxInt(usize);+ var at: usize = 0;+ while (std.mem.indexOfPos(u8, xml, at, "<comment")) |open| {+ const tag_end = std.mem.indexOfScalarPos(u8, xml, open, '>') orelse break;+ const tag = xml[open + "<comment".len .. tag_end];+ at = tag_end + 1;+ if (tag.len > 0 and tag[tag.len - 1] == '/') continue;+ if (tag.len > 0 and tag[0] != ' ' and tag[0] != '\t' and tag[0] != '\n') continue;+ const close = std.mem.indexOfPos(u8, xml, at, "</comment>") orelse break;+ const body = xml[at..close];+ at = close;+ const lang = attribute(tag, "xml:lang") orelse "C";+ var rank: usize = 0;+ while (rank < langs.len) : (rank += 1) {+ if (std.mem.eql(u8, langs[rank], lang)) break;+ }+ if (rank >= best_rank or rank == langs.len) continue;+ best_rank = rank;+ best = unescape(a, body) catch null;+ if (rank == 0) break;+ }+ return best;+}++fn attribute(tag: []const u8, name: []const u8) ?[]const u8 {+ var at: usize = 0;+ while (std.mem.indexOfPos(u8, tag, at, name)) |i| {+ at = i + name.len;+ var j = at;+ while (j < tag.len and tag[j] == ' ') j += 1;+ if (j >= tag.len or tag[j] != '=') continue;+ j += 1;+ while (j < tag.len and tag[j] == ' ') j += 1;+ if (j >= tag.len or (tag[j] != '"' and tag[j] != '\'')) continue;+ const quote = tag[j];+ const end = std.mem.indexOfScalarPos(u8, tag, j + 1, quote) orelse return null;+ return tag[j + 1 .. end];+ }+ return null;+}++fn unescape(a: Allocator, text: []const u8) Allocator.Error![]const u8 {+ var out: std.ArrayList(u8) = .empty;+ var i: usize = 0;+ while (i < text.len) {+ if (text[i] == '&') {+ const entities = [_]struct { []const u8, u8 }{ .{ "&", '&' }, .{ "<", '<' }, .{ ">", '>' }, .{ """, '"' }, .{ "'", '\'' } };+ var matched = false;+ for (entities) |e| {+ if (std.mem.startsWith(u8, text[i..], e[0])) {+ try out.append(a, e[1]);+ i += e[0].len;+ matched = true;+ break;+ }+ }+ if (matched) continue;+ }+ try out.append(a, text[i]);+ i += 1;+ }+ return out.items;+}++// ---- tests -----------------------------------------------------------------++const testing = std.testing;++fn fixture() !Db {+ var db: Db = .init(testing.allocator);+ errdefer db.deinit();+ try db.addGlobs(+ \\# comment+ \\50:text/plain:*.txt+ \\50:application/gzip:*.gz+ \\50:application/x-compressed-tar:*.tar.gz+ \\50:text/x-makefile:Makefile+ \\50:image/png:*.png+ \\50:image/x-xcf:*.xcf+ \\80:text/html:*.html+ \\50:application/x-pdf-fake:*.PDF:cs+ \\50:application/pdf:*.pdf+ \\50:text/x-manual:*.[1-9]+ \\60:application/x-weird:*.x*y+ \\0:model/skipped:__NOGLOBS__+ \\50:model/skipped:*.skip+ , 0);+ try db.addGlobs("50:model/skipped:*.skip2\n", 1);+ try db.addAliases("video/x-matroska video/matroska\n");+ try db.addSubclasses(+ \\text/x-makefile text/plain+ \\application/x-compressed-tar application/gzip+ \\image/svg+xml application/xml+ \\application/xml text/plain+ );+ try db.addIcons("application/pdf:x-pdf\n", false);+ try db.addIcons("text/x-makefile:text-x-script\n", true);+ return db;+}++test "globs pick literals, longest suffix and highest weight" {+ var db = try fixture();+ defer db.deinit();+ try testing.expectEqualStrings("text/plain", db.guess("notes.txt").?);+ try testing.expectEqualStrings("text/x-makefile", db.guess("Makefile").?);+ try testing.expectEqualStrings("application/x-compressed-tar", db.guess("a.tar.gz").?);+ try testing.expectEqualStrings("application/gzip", db.guess("a.gz").?);+ try testing.expectEqualStrings("text/html", db.guess("index.html").?);+ try testing.expectEqualStrings("text/x-manual", db.guess("ls.1").?);+ try testing.expectEqualStrings("application/x-weird", db.guess("a.xzzy").?);+ try testing.expect(db.guess("noextension") == null);+ try testing.expect(db.guess("") == null);+}++test "matching ignores case unless a glob is case sensitive" {+ var db = try fixture();+ defer db.deinit();+ try testing.expectEqualStrings("image/png", db.guess("PHOTO.PNG").?);+ try testing.expectEqualStrings("application/x-pdf-fake", db.guess("A.PDF").?);+ try testing.expectEqualStrings("application/pdf", db.guess("a.Pdf").?);+}++test "a case-sensitive glob repeated without the flag stays case sensitive" {+ var db: Db = .init(testing.allocator);+ defer db.deinit();+ try db.addGlobs("50:text/x-genie:*.gs:cs\n50:text/x-genie:*.gs\n50:application/x-core:core:cs\n50:application/x-core:core\n", 0);+ try testing.expectEqualStrings("text/x-genie", db.guess("a.gs").?);+ try testing.expect(db.guess("A.GS") == null);+ try testing.expect(db.guess("CORE") == null);+ try testing.expectEqualStrings("application/x-core", db.guess("core").?);+}++test "literals and suffixes outrank heavier wildcard patterns" {+ var db: Db = .init(testing.allocator);+ defer db.deinit();+ try db.addGlobs("60:application/x-sharedlib:*.so.[0-9]*\n50:application/x-trash:*.bak\n", 0);+ try testing.expectEqualStrings("application/x-trash", db.guess("libx.so.1.bak").?);+ try testing.expectEqualStrings("application/x-sharedlib", db.guess("libx.so.1").?);+}++test "NOGLOBS hides a type's globs from lower-priority directories only" {+ var db = try fixture();+ defer db.deinit();+ try testing.expectEqualStrings("model/skipped", db.guess("a.skip").?);+ try testing.expect(db.guess("a.skip2") == null);+}++test "aliases and inheritance" {+ var db = try fixture();+ defer db.deinit();+ try testing.expect(db.equals("video/x-matroska", "video/matroska"));+ try testing.expect(!db.equals("video/mp4", "video/matroska"));+ try testing.expect(db.isA("application/x-compressed-tar", "application/gzip"));+ try testing.expect(db.isA("image/svg+xml", "text/plain"));+ try testing.expect(db.isA("text/x-anything", "text/plain"));+ try testing.expect(db.isA("image/png", unknown));+ try testing.expect(!db.isA("inode/directory", unknown));+ try testing.expect(!db.isA("image/png", "text/plain"));+ try testing.expect(db.isA("video/x-matroska", "video/matroska"));+}++test "icon names follow the type, its dashed name and the generic icon" {+ var db = try fixture();+ defer db.deinit();+ var buf: IconBuffer = .{};+ const pdf = db.iconNames("application/pdf", &buf);+ try testing.expectEqual(@as(usize, 3), pdf.len);+ try testing.expectEqualStrings("x-pdf", pdf[0]);+ try testing.expectEqualStrings("application-pdf", pdf[1]);+ try testing.expectEqualStrings("application-x-generic", pdf[2]);+ var other: IconBuffer = .{};+ const make = db.iconNames("text/x-makefile", &other);+ try testing.expectEqualStrings("text-x-makefile", make[0]);+ try testing.expectEqualStrings("text-x-script", make[1]);+}++test "language variants run from specific to general" {+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);+ defer arena.deinit();+ var out: std.ArrayList([]const u8) = .empty;+ try variants(arena.allocator(), &out, "pt_BR.UTF-8");+ try testing.expectEqual(@as(usize, 4), out.items.len);+ try testing.expectEqualStrings("pt_BR.UTF-8", out.items[0]);+ try testing.expectEqualStrings("pt_BR", out.items[1]);+ try testing.expectEqualStrings("pt.UTF-8", out.items[2]);+ try testing.expectEqualStrings("pt", out.items[3]);+}++test "comments choose the best language and decode entities" {+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);+ defer arena.deinit();+ const xml =+ \\<mime-type type="text/html">+ \\ <comment>HTML & friends</comment>+ \\ <comment xml:lang="pt_BR">documento HTML</comment>+ \\ <comment xml:lang="de">HTML-Dokument</comment>+ \\</mime-type>+ ;+ try testing.expectEqualStrings("documento HTML", pickComment(arena.allocator(), xml, &.{ "pt_BR", "pt", "C" }).?);+ try testing.expectEqualStrings("HTML & friends", pickComment(arena.allocator(), xml, &.{ "fr", "C" }).?);+ try testing.expect(pickComment(arena.allocator(), xml, &.{"fr"}) == null);+}++test "public lookups work against the installed database" {+ // The installed database may be absent in a build sandbox; only check+ // that nothing crashes and unknown names stay unknown.+ try testing.expectEqualStrings(directory, guess("/tmp/"));+ _ = guess("/tmp/archive.tar.gz");+ try testing.expect(isA("text/x-anything", "text/plain"));+}