Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

start menu: move .desktop parsing and directory scanning out

Claude53cb563019fa
diff --git a/src/start_menu/applications.zig b/src/start_menu/applications.zig
index 74d06b7..40e04cc 100644
--- a/src/start_menu/applications.zig
+++ b/src/start_menu/applications.zig
@@ -42,260 +42,12 @@ pub const AppEntry = struct {
dbus_activatable: bool = false,
};
-pub const Locale = struct {
- lang: []const u8 = "",
- country: []const u8 = "",
- modifier: []const u8 = "",
-
- pub fn fromEnv(environ: std.process.Environ) Locale {
- const raw = i18n.resolve("", environ);
- return forLanguage(raw);
- }
-
- /// The catalog's bare Portuguese choice follows Brazilian Portuguese.
- /// Keep parsing desktop-entry keys pure so Name[pt_BR] outranks Name[pt].
- pub fn forLanguage(raw: []const u8) Locale {
- var locale = parseLocale(raw);
- if (locale.country.len == 0 and std.ascii.eqlIgnoreCase(locale.lang, "pt")) locale.country = "BR";
- return locale;
- }
-
- pub fn parseLocale(raw: []const u8) Locale {
- var loc = Locale{};
- var rest = raw;
- // Strip encoding (.UTF-8)
- if (std.mem.indexOfScalar(u8, rest, '.')) |dot| {
- const before_dot = rest[0..dot];
- const after_dot = rest[dot + 1 ..];
- if (std.mem.indexOfScalar(u8, after_dot, '@')) |at| {
- loc.modifier = after_dot[at + 1 ..];
- }
- rest = before_dot;
- } else if (std.mem.indexOfScalar(u8, rest, '@')) |at| {
- loc.modifier = rest[at + 1 ..];
- rest = rest[0..at];
- }
-
- if (std.mem.indexOfAny(u8, rest, "_-")) |us| {
- loc.lang = rest[0..us];
- loc.country = rest[us + 1 ..];
- } else {
- loc.lang = rest;
- }
- return loc;
- }
-};
-
-pub const ParsedEntry = struct {
- is_application: bool = false,
- no_display: bool = false,
- hidden: bool = false,
- try_exec: ?[]const u8 = null,
- only_show_in: ?[]const u8 = null,
- not_show_in: ?[]const u8 = null,
- name: ?[]const u8 = null,
- generic_name: ?[]const u8 = null,
- comment: ?[]const u8 = null,
- icon: ?[]const u8 = null,
- startup_wm_class: ?[]const u8 = null,
- exec: ?[]const u8 = null,
- path: ?[]const u8 = null,
- terminal: bool = false,
- keywords: ?[]const u8 = null,
- categories: ?[]const u8 = null,
- dbus_activatable: bool = false,
-};
-
-/// Parses a desktop entry file content.
-pub fn parseDesktopFile(arena: Allocator, content: []const u8, locale: Locale) ?ParsedEntry {
- var entry = ParsedEntry{};
- var in_desktop_entry = false;
-
- // Match priority for localized keys: 0 = unlocalized, 1 = lang, 2 = lang_country, 3 = lang_country@mod
- var name_prio: u8 = 0;
- var generic_prio: u8 = 0;
- var comment_prio: u8 = 0;
- var keywords_prio: u8 = 0;
-
- var lines = std.mem.splitScalar(u8, content, '\n');
- while (lines.next()) |raw_line| {
- const line = std.mem.trim(u8, raw_line, " \t\r");
- if (line.len == 0 or line[0] == '#') continue;
-
- if (line[0] == '[') {
- const close = std.mem.indexOfScalar(u8, line, ']') orelse continue;
- const section = line[1..close];
- in_desktop_entry = std.mem.eql(u8, section, "Desktop Entry");
- continue;
- }
- if (!in_desktop_entry) continue;
-
- const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
- const raw_key = std.mem.trim(u8, line[0..eq], " \t");
- const raw_val = std.mem.trim(u8, line[eq + 1 ..], " \t");
-
- // Split key and locale tag e.g. "Name[de_DE]"
- var key_name = raw_key;
- var key_locale: ?[]const u8 = null;
- if (std.mem.indexOfScalar(u8, raw_key, '[')) |bracket| {
- if (std.mem.endsWith(u8, raw_key, "]")) {
- key_name = raw_key[0..bracket];
- key_locale = raw_key[bracket + 1 .. raw_key.len - 1];
- }
- }
-
- if (std.mem.eql(u8, key_name, "Type")) {
- entry.is_application = std.mem.eql(u8, raw_val, "Application");
- } else if (std.mem.eql(u8, key_name, "NoDisplay")) {
- entry.no_display = std.mem.eql(u8, raw_val, "true");
- } else if (std.mem.eql(u8, key_name, "Hidden")) {
- entry.hidden = std.mem.eql(u8, raw_val, "true");
- } else if (std.mem.eql(u8, key_name, "Terminal")) {
- entry.terminal = std.mem.eql(u8, raw_val, "true");
- } else if (std.mem.eql(u8, key_name, "DBusActivatable")) {
- entry.dbus_activatable = std.mem.eql(u8, raw_val, "true");
- } else if (std.mem.eql(u8, key_name, "TryExec")) {
- entry.try_exec = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "Exec")) {
- entry.exec = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "Path")) {
- entry.path = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "Icon")) {
- entry.icon = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "StartupWMClass")) {
- entry.startup_wm_class = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "Categories")) {
- entry.categories = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "OnlyShowIn")) {
- entry.only_show_in = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "NotShowIn")) {
- entry.not_show_in = unescape(arena, raw_val) catch raw_val;
- } else if (std.mem.eql(u8, key_name, "Name")) {
- const prio = localePriority(key_locale, locale);
- if (prio > name_prio or entry.name == null) {
- entry.name = unescape(arena, raw_val) catch raw_val;
- name_prio = prio;
- }
- } else if (std.mem.eql(u8, key_name, "GenericName")) {
- const prio = localePriority(key_locale, locale);
- if (prio > generic_prio or entry.generic_name == null) {
- entry.generic_name = unescape(arena, raw_val) catch raw_val;
- generic_prio = prio;
- }
- } else if (std.mem.eql(u8, key_name, "Comment")) {
- const prio = localePriority(key_locale, locale);
- if (prio > comment_prio or entry.comment == null) {
- entry.comment = unescape(arena, raw_val) catch raw_val;
- comment_prio = prio;
- }
- } else if (std.mem.eql(u8, key_name, "Keywords")) {
- const prio = localePriority(key_locale, locale);
- if (prio > keywords_prio or entry.keywords == null) {
- entry.keywords = unescape(arena, raw_val) catch raw_val;
- keywords_prio = prio;
- }
- }
- }
-
- if (!entry.is_application or entry.name == null or entry.name.?.len == 0) return null;
- return entry;
-}
-
-fn localePriority(key_loc: ?[]const u8, target: Locale) u8 {
- const k = key_loc orelse return 1; // Unlocalized is lowest valid priority
- if (target.lang.len == 0) return 0;
-
- const parsed = Locale.parseLocale(k);
- if (!std.ascii.eqlIgnoreCase(parsed.lang, target.lang)) return 0;
-
- if (target.modifier.len > 0 and std.mem.eql(u8, parsed.modifier, target.modifier) and
- target.country.len > 0 and std.ascii.eqlIgnoreCase(parsed.country, target.country))
- {
- return 5;
- }
- if (target.country.len > 0 and std.ascii.eqlIgnoreCase(parsed.country, target.country)) {
- return 4;
- }
- if (target.modifier.len > 0 and std.mem.eql(u8, parsed.modifier, target.modifier)) {
- return 3;
- }
- if (parsed.country.len == 0 and parsed.modifier.len == 0) {
- return 2;
- }
- return 0;
-}
-
-fn unescape(allocator: Allocator, s: []const u8) ![]const u8 {
- if (std.mem.indexOfScalar(u8, s, '\\') == null) return s;
- var out: std.ArrayList(u8) = .empty;
- defer out.deinit(allocator);
-
- var i: usize = 0;
- while (i < s.len) {
- if (s[i] == '\\' and i + 1 < s.len) {
- i += 1;
- switch (s[i]) {
- 's' => try out.append(allocator, ' '),
- 'n' => try out.append(allocator, '\n'),
- 't' => try out.append(allocator, '\t'),
- 'r' => try out.append(allocator, '\r'),
- '\\' => try out.append(allocator, '\\'),
- else => try out.append(allocator, s[i]),
- }
- } else {
- try out.append(allocator, s[i]);
- }
- i += 1;
- }
- return out.toOwnedSlice(allocator);
-}
-
-pub fn checkTryExec(try_exec: []const u8, environ: std.process.Environ) bool {
- if (try_exec.len == 0) return true;
- if (try_exec[0] == '/') {
- var buf: [std.posix.PATH_MAX]u8 = undefined;
- if (try_exec.len >= buf.len) return false;
- @memcpy(buf[0..try_exec.len], try_exec);
- buf[try_exec.len] = 0;
- const zpath: [*:0]const u8 = buf[0..try_exec.len :0];
- return c.access(zpath, c.X_OK) == 0;
- }
-
- const path_env = environ.getPosix("PATH") orelse "/usr/local/bin:/usr/bin:/bin";
- var it = std.mem.splitScalar(u8, path_env, ':');
- while (it.next()) |dir| {
- if (dir.len == 0) continue;
- var buf: [std.posix.PATH_MAX]u8 = undefined;
- const candidate = std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ dir, try_exec }) catch continue;
- if (c.access(candidate.ptr, c.X_OK) == 0) return true;
- }
- return false;
-}
-
-pub fn checkDesktopVisibility(parsed: ParsedEntry, current_desktop: ?[]const u8) bool {
- if (parsed.hidden or parsed.no_display) return false;
-
- if (current_desktop) |desk| {
- if (parsed.not_show_in) |not_show| {
- var it = std.mem.splitScalar(u8, not_show, ';');
- while (it.next()) |d| {
- if (d.len > 0 and std.ascii.eqlIgnoreCase(d, desk)) return false;
- }
- }
- if (parsed.only_show_in) |only_show| {
- var found = false;
- var it = std.mem.splitScalar(u8, only_show, ';');
- while (it.next()) |d| {
- if (d.len > 0 and std.ascii.eqlIgnoreCase(d, desk)) {
- found = true;
- break;
- }
- }
- if (!found) return false;
- }
- }
- return true;
-}
+const desktop_file = @import("desktop_file.zig");
+pub const Locale = desktop_file.Locale;
+pub const ParsedEntry = desktop_file.ParsedEntry;
+pub const parseDesktopFile = desktop_file.parseDesktopFile;
+pub const checkTryExec = desktop_file.checkTryExec;
+pub const checkDesktopVisibility = desktop_file.checkDesktopVisibility;
pub const Snapshot = struct {
refs: std.atomic.Value(u32) = std.atomic.Value(u32).init(1),
@@ -706,214 +458,13 @@ fn handleInotify(fd: c_int, mask: wl.EventMask, catalog: *Catalog) c_int {
return 0;
}
-fn copyFiltered(arena: Allocator, entries: []const AppEntry, environ: std.process.Environ) ![]AppEntry {
- var out: std.ArrayList(AppEntry) = .empty;
- errdefer out.deinit(arena);
- for (entries) |e| {
- if (e.try_exec) |try_exec| {
- if (!checkTryExec(try_exec, environ)) continue;
- }
- try out.append(arena, try dupeEntry(arena, e));
- }
- return out.toOwnedSlice(arena);
-}
-
-fn dupeEntry(arena: Allocator, e: AppEntry) !AppEntry {
- return .{
- .id = try arena.dupe(u8, e.id),
- .desktop_file_path = try arena.dupe(u8, e.desktop_file_path),
- .name = try arena.dupe(u8, e.name),
- .generic_name = if (e.generic_name) |s| try arena.dupe(u8, s) else null,
- .comment = if (e.comment) |s| try arena.dupe(u8, s) else null,
- .icon = if (e.icon) |s| try arena.dupe(u8, s) else null,
- .startup_wm_class = if (e.startup_wm_class) |s| try arena.dupe(u8, s) else null,
- .exec = try arena.dupe(u8, e.exec),
- .path = if (e.path) |s| try arena.dupe(u8, s) else null,
- .try_exec = if (e.try_exec) |s| try arena.dupe(u8, s) else null,
- .terminal = e.terminal,
- .keywords = try arena.dupe(u8, e.keywords),
- .categories = try arena.dupe(u8, e.categories),
- .dbus_activatable = e.dbus_activatable,
- };
-}
-
-pub fn resolveApplicationDirs(arena: Allocator, environ: std.process.Environ) ![]const []const u8 {
- var dirs: std.ArrayList([]const u8) = .empty;
-
- if (environ.getPosix("XDG_DATA_HOME")) |dh| {
- try dirs.append(arena, try std.fmt.allocPrint(arena, "{s}/applications", .{dh}));
- } else if (environ.getPosix("HOME")) |home| {
- try dirs.append(arena, try std.fmt.allocPrint(arena, "{s}/.local/share/applications", .{home}));
- }
-
- const data_dirs = environ.getPosix("XDG_DATA_DIRS") orelse "/usr/local/share:/usr/share";
- var it = std.mem.splitScalar(u8, data_dirs, ':');
- while (it.next()) |dir| {
- if (dir.len == 0) continue;
- try dirs.append(arena, try std.fmt.allocPrint(arena, "{s}/applications", .{dir}));
- }
- return dirs.toOwnedSlice(arena);
-}
-
-pub const ScanOutcome = struct {
- entries: []AppEntry,
- sources: []catalog_cache.SourceIdent,
-};
-
-pub fn scanAll(arena: Allocator, io: Io, environ: std.process.Environ) !ScanOutcome {
- return scanAllWithLocale(arena, io, environ, i18n.resolve("", environ));
-}
-
-pub fn scanAllWithLocale(arena: Allocator, io: Io, environ: std.process.Environ, locale_tag: []const u8) !ScanOutcome {
- const locale = Locale.forLanguage(locale_tag);
- const current_desktop = environ.getPosix("XDG_CURRENT_DESKTOP");
- const app_dirs = try resolveApplicationDirs(arena, environ);
-
- var seen: std.StringHashMapUnmanaged(void) = .empty;
- defer seen.deinit(arena);
- var results: std.ArrayList(AppEntry) = .empty;
- var sources: std.ArrayList(catalog_cache.SourceIdent) = .empty;
-
- for (app_dirs) |dir| {
- scanDirectory(arena, io, environ, dir, "", locale, current_desktop, &seen, &results, &sources) catch continue;
- }
- catalog_cache.sortSources(sources.items);
-
- return .{
- .entries = try results.toOwnedSlice(arena),
- .sources = try sources.toOwnedSlice(arena),
- };
-}
-
-fn collectSources(arena: Allocator, io: Io, environ: std.process.Environ) ![]catalog_cache.SourceIdent {
- const app_dirs = try resolveApplicationDirs(arena, environ);
- var sources: std.ArrayList(catalog_cache.SourceIdent) = .empty;
- var seen: std.StringHashMapUnmanaged(void) = .empty;
- defer seen.deinit(arena);
- for (app_dirs) |dir| {
- walkSources(arena, io, dir, &sources, &seen) catch continue;
- }
- catalog_cache.sortSources(sources.items);
- return sources.toOwnedSlice(arena);
-}
-
-fn walkSources(
- arena: Allocator,
- io: Io,
- dir: []const u8,
- sources: *std.ArrayList(catalog_cache.SourceIdent),
- seen: *std.StringHashMapUnmanaged(void),
-) !void {
- var iter = Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return;
- defer iter.close(io);
- var it = iter.iterate();
- while (try it.next(io)) |entry| {
- if (entry.kind == .directory) {
- const child = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, entry.name });
- walkSources(arena, io, child, sources, seen) catch continue;
- continue;
- }
- if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".desktop")) continue;
- const full_file_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, entry.name });
- if (seen.contains(full_file_path)) continue;
- try seen.put(arena, full_file_path, {});
- if (catalog_cache.statPath(io, full_file_path)) |ident| {
- try sources.append(arena, .{
- .path = full_file_path,
- .mtime_sec = ident.mtime_sec,
- .mtime_nsec = ident.mtime_nsec,
- .size = ident.size,
- });
- }
- }
-}
-
-fn scanDirectory(
- arena: Allocator,
- io: Io,
- environ: std.process.Environ,
- base_dir: []const u8,
- rel_sub: []const u8,
- locale: Locale,
- current_desktop: ?[]const u8,
- seen: *std.StringHashMapUnmanaged(void),
- results: *std.ArrayList(AppEntry),
- sources: *std.ArrayList(catalog_cache.SourceIdent),
-) !void {
- var path_buf: [std.posix.PATH_MAX]u8 = undefined;
- const full_dir = if (rel_sub.len == 0)
- base_dir
- else
- std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ base_dir, rel_sub }) catch return;
-
- var iter = Io.Dir.cwd().openDir(io, full_dir, .{ .iterate = true }) catch return;
- defer iter.close(io);
-
- var it = iter.iterate();
- while (try it.next(io)) |entry| {
- if (entry.kind == .directory) {
- var sub_buf: [256]u8 = undefined;
- const next_sub = if (rel_sub.len == 0)
- std.fmt.bufPrint(&sub_buf, "{s}", .{entry.name}) catch continue
- else
- std.fmt.bufPrint(&sub_buf, "{s}-{s}", .{ rel_sub, entry.name }) catch continue;
- scanDirectory(arena, io, environ, base_dir, next_sub, locale, current_desktop, seen, results, sources) catch continue;
- continue;
- }
-
- if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".desktop")) continue;
-
- const full_file_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ full_dir, entry.name });
- if (catalog_cache.statPath(io, full_file_path)) |ident| {
- try sources.append(arena, .{
- .path = full_file_path,
- .mtime_sec = ident.mtime_sec,
- .mtime_nsec = ident.mtime_nsec,
- .size = ident.size,
- });
- }
-
- // Form desktop-file ID
- const desktop_id = if (rel_sub.len == 0)
- try arena.dupe(u8, entry.name)
- else
- try std.fmt.allocPrint(arena, "{s}-{s}", .{ rel_sub, entry.name });
-
- if (seen.contains(desktop_id)) continue;
- try seen.put(arena, desktop_id, {});
-
- const content = Io.Dir.cwd().readFileAlloc(io, full_file_path, arena, .limited(512 * 1024)) catch continue;
-
- const parsed = parseDesktopFile(arena, content, locale) orelse continue;
-
- // Visibility rules
- if (!checkDesktopVisibility(parsed, current_desktop)) continue;
-
- // TryExec check
- if (parsed.try_exec) |try_exec| {
- if (!checkTryExec(try_exec, environ)) continue;
- }
-
- const exec_cmd = parsed.exec orelse continue;
-
- try results.append(arena, .{
- .id = desktop_id,
- .desktop_file_path = full_file_path,
- .name = parsed.name.?,
- .generic_name = parsed.generic_name,
- .comment = parsed.comment,
- .icon = parsed.icon,
- .startup_wm_class = parsed.startup_wm_class,
- .exec = exec_cmd,
- .path = parsed.path,
- .try_exec = parsed.try_exec,
- .terminal = parsed.terminal,
- .keywords = parsed.keywords orelse "",
- .categories = parsed.categories orelse "",
- .dbus_activatable = parsed.dbus_activatable,
- });
- }
-}
+const applications_scan = @import("scan.zig");
+const copyFiltered = applications_scan.copyFiltered;
+pub const resolveApplicationDirs = applications_scan.resolveApplicationDirs;
+pub const ScanOutcome = applications_scan.ScanOutcome;
+pub const scanAll = applications_scan.scanAll;
+pub const scanAllWithLocale = applications_scan.scanAllWithLocale;
+const collectSources = applications_scan.collectSources;
test "desktop file parsing and localization" {
const fixture =
diff --git a/src/start_menu/desktop_file.zig b/src/start_menu/desktop_file.zig
new file mode 100644
index 0000000..572725c
--- /dev/null
+++ b/src/start_menu/desktop_file.zig
@@ -0,0 +1,261 @@
+//! Parsing .desktop files: the locale and localized keys, escapes, TryExec and desktop visibility.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const c = std.posix.system;
+const i18n = @import("i18n");
+
+pub const Locale = struct {
+ lang: []const u8 = "",
+ country: []const u8 = "",
+ modifier: []const u8 = "",
+
+ pub fn fromEnv(environ: std.process.Environ) Locale {
+ const raw = i18n.resolve("", environ);
+ return forLanguage(raw);
+ }
+
+ /// The catalog's bare Portuguese choice follows Brazilian Portuguese.
+ /// Keep parsing desktop-entry keys pure so Name[pt_BR] outranks Name[pt].
+ pub fn forLanguage(raw: []const u8) Locale {
+ var locale = parseLocale(raw);
+ if (locale.country.len == 0 and std.ascii.eqlIgnoreCase(locale.lang, "pt")) locale.country = "BR";
+ return locale;
+ }
+
+ pub fn parseLocale(raw: []const u8) Locale {
+ var loc = Locale{};
+ var rest = raw;
+ // Strip encoding (.UTF-8)
+ if (std.mem.indexOfScalar(u8, rest, '.')) |dot| {
+ const before_dot = rest[0..dot];
+ const after_dot = rest[dot + 1 ..];
+ if (std.mem.indexOfScalar(u8, after_dot, '@')) |at| {
+ loc.modifier = after_dot[at + 1 ..];
+ }
+ rest = before_dot;
+ } else if (std.mem.indexOfScalar(u8, rest, '@')) |at| {
+ loc.modifier = rest[at + 1 ..];
+ rest = rest[0..at];
+ }
+
+ if (std.mem.indexOfAny(u8, rest, "_-")) |us| {
+ loc.lang = rest[0..us];
+ loc.country = rest[us + 1 ..];
+ } else {
+ loc.lang = rest;
+ }
+ return loc;
+ }
+};
+
+pub const ParsedEntry = struct {
+ is_application: bool = false,
+ no_display: bool = false,
+ hidden: bool = false,
+ try_exec: ?[]const u8 = null,
+ only_show_in: ?[]const u8 = null,
+ not_show_in: ?[]const u8 = null,
+ name: ?[]const u8 = null,
+ generic_name: ?[]const u8 = null,
+ comment: ?[]const u8 = null,
+ icon: ?[]const u8 = null,
+ startup_wm_class: ?[]const u8 = null,
+ exec: ?[]const u8 = null,
+ path: ?[]const u8 = null,
+ terminal: bool = false,
+ keywords: ?[]const u8 = null,
+ categories: ?[]const u8 = null,
+ dbus_activatable: bool = false,
+};
+
+/// Parses a desktop entry file content.
+pub fn parseDesktopFile(arena: Allocator, content: []const u8, locale: Locale) ?ParsedEntry {
+ var entry = ParsedEntry{};
+ var in_desktop_entry = false;
+
+ // Match priority for localized keys: 0 = unlocalized, 1 = lang, 2 = lang_country, 3 = lang_country@mod
+ var name_prio: u8 = 0;
+ var generic_prio: u8 = 0;
+ var comment_prio: u8 = 0;
+ var keywords_prio: u8 = 0;
+
+ var lines = std.mem.splitScalar(u8, content, '\n');
+ while (lines.next()) |raw_line| {
+ const line = std.mem.trim(u8, raw_line, " \t\r");
+ if (line.len == 0 or line[0] == '#') continue;
+
+ if (line[0] == '[') {
+ const close = std.mem.indexOfScalar(u8, line, ']') orelse continue;
+ const section = line[1..close];
+ in_desktop_entry = std.mem.eql(u8, section, "Desktop Entry");
+ continue;
+ }
+ if (!in_desktop_entry) continue;
+
+ const eq = std.mem.indexOfScalar(u8, line, '=') orelse continue;
+ const raw_key = std.mem.trim(u8, line[0..eq], " \t");
+ const raw_val = std.mem.trim(u8, line[eq + 1 ..], " \t");
+
+ // Split key and locale tag e.g. "Name[de_DE]"
+ var key_name = raw_key;
+ var key_locale: ?[]const u8 = null;
+ if (std.mem.indexOfScalar(u8, raw_key, '[')) |bracket| {
+ if (std.mem.endsWith(u8, raw_key, "]")) {
+ key_name = raw_key[0..bracket];
+ key_locale = raw_key[bracket + 1 .. raw_key.len - 1];
+ }
+ }
+
+ if (std.mem.eql(u8, key_name, "Type")) {
+ entry.is_application = std.mem.eql(u8, raw_val, "Application");
+ } else if (std.mem.eql(u8, key_name, "NoDisplay")) {
+ entry.no_display = std.mem.eql(u8, raw_val, "true");
+ } else if (std.mem.eql(u8, key_name, "Hidden")) {
+ entry.hidden = std.mem.eql(u8, raw_val, "true");
+ } else if (std.mem.eql(u8, key_name, "Terminal")) {
+ entry.terminal = std.mem.eql(u8, raw_val, "true");
+ } else if (std.mem.eql(u8, key_name, "DBusActivatable")) {
+ entry.dbus_activatable = std.mem.eql(u8, raw_val, "true");
+ } else if (std.mem.eql(u8, key_name, "TryExec")) {
+ entry.try_exec = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "Exec")) {
+ entry.exec = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "Path")) {
+ entry.path = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "Icon")) {
+ entry.icon = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "StartupWMClass")) {
+ entry.startup_wm_class = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "Categories")) {
+ entry.categories = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "OnlyShowIn")) {
+ entry.only_show_in = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "NotShowIn")) {
+ entry.not_show_in = unescape(arena, raw_val) catch raw_val;
+ } else if (std.mem.eql(u8, key_name, "Name")) {
+ const prio = localePriority(key_locale, locale);
+ if (prio > name_prio or entry.name == null) {
+ entry.name = unescape(arena, raw_val) catch raw_val;
+ name_prio = prio;
+ }
+ } else if (std.mem.eql(u8, key_name, "GenericName")) {
+ const prio = localePriority(key_locale, locale);
+ if (prio > generic_prio or entry.generic_name == null) {
+ entry.generic_name = unescape(arena, raw_val) catch raw_val;
+ generic_prio = prio;
+ }
+ } else if (std.mem.eql(u8, key_name, "Comment")) {
+ const prio = localePriority(key_locale, locale);
+ if (prio > comment_prio or entry.comment == null) {
+ entry.comment = unescape(arena, raw_val) catch raw_val;
+ comment_prio = prio;
+ }
+ } else if (std.mem.eql(u8, key_name, "Keywords")) {
+ const prio = localePriority(key_locale, locale);
+ if (prio > keywords_prio or entry.keywords == null) {
+ entry.keywords = unescape(arena, raw_val) catch raw_val;
+ keywords_prio = prio;
+ }
+ }
+ }
+
+ if (!entry.is_application or entry.name == null or entry.name.?.len == 0) return null;
+ return entry;
+}
+
+pub fn localePriority(key_loc: ?[]const u8, target: Locale) u8 {
+ const k = key_loc orelse return 1; // Unlocalized is lowest valid priority
+ if (target.lang.len == 0) return 0;
+
+ const parsed = Locale.parseLocale(k);
+ if (!std.ascii.eqlIgnoreCase(parsed.lang, target.lang)) return 0;
+
+ if (target.modifier.len > 0 and std.mem.eql(u8, parsed.modifier, target.modifier) and
+ target.country.len > 0 and std.ascii.eqlIgnoreCase(parsed.country, target.country))
+ {
+ return 5;
+ }
+ if (target.country.len > 0 and std.ascii.eqlIgnoreCase(parsed.country, target.country)) {
+ return 4;
+ }
+ if (target.modifier.len > 0 and std.mem.eql(u8, parsed.modifier, target.modifier)) {
+ return 3;
+ }
+ if (parsed.country.len == 0 and parsed.modifier.len == 0) {
+ return 2;
+ }
+ return 0;
+}
+
+pub fn unescape(allocator: Allocator, s: []const u8) ![]const u8 {
+ if (std.mem.indexOfScalar(u8, s, '\\') == null) return s;
+ var out: std.ArrayList(u8) = .empty;
+ defer out.deinit(allocator);
+
+ var i: usize = 0;
+ while (i < s.len) {
+ if (s[i] == '\\' and i + 1 < s.len) {
+ i += 1;
+ switch (s[i]) {
+ 's' => try out.append(allocator, ' '),
+ 'n' => try out.append(allocator, '\n'),
+ 't' => try out.append(allocator, '\t'),
+ 'r' => try out.append(allocator, '\r'),
+ '\\' => try out.append(allocator, '\\'),
+ else => try out.append(allocator, s[i]),
+ }
+ } else {
+ try out.append(allocator, s[i]);
+ }
+ i += 1;
+ }
+ return out.toOwnedSlice(allocator);
+}
+
+pub fn checkTryExec(try_exec: []const u8, environ: std.process.Environ) bool {
+ if (try_exec.len == 0) return true;
+ if (try_exec[0] == '/') {
+ var buf: [std.posix.PATH_MAX]u8 = undefined;
+ if (try_exec.len >= buf.len) return false;
+ @memcpy(buf[0..try_exec.len], try_exec);
+ buf[try_exec.len] = 0;
+ const zpath: [*:0]const u8 = buf[0..try_exec.len :0];
+ return c.access(zpath, c.X_OK) == 0;
+ }
+
+ const path_env = environ.getPosix("PATH") orelse "/usr/local/bin:/usr/bin:/bin";
+ var it = std.mem.splitScalar(u8, path_env, ':');
+ while (it.next()) |dir| {
+ if (dir.len == 0) continue;
+ var buf: [std.posix.PATH_MAX]u8 = undefined;
+ const candidate = std.fmt.bufPrintZ(&buf, "{s}/{s}", .{ dir, try_exec }) catch continue;
+ if (c.access(candidate.ptr, c.X_OK) == 0) return true;
+ }
+ return false;
+}
+
+pub fn checkDesktopVisibility(parsed: ParsedEntry, current_desktop: ?[]const u8) bool {
+ if (parsed.hidden or parsed.no_display) return false;
+
+ if (current_desktop) |desk| {
+ if (parsed.not_show_in) |not_show| {
+ var it = std.mem.splitScalar(u8, not_show, ';');
+ while (it.next()) |d| {
+ if (d.len > 0 and std.ascii.eqlIgnoreCase(d, desk)) return false;
+ }
+ }
+ if (parsed.only_show_in) |only_show| {
+ var found = false;
+ var it = std.mem.splitScalar(u8, only_show, ';');
+ while (it.next()) |d| {
+ if (d.len > 0 and std.ascii.eqlIgnoreCase(d, desk)) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) return false;
+ }
+ }
+ return true;
+}
diff --git a/src/start_menu/scan.zig b/src/start_menu/scan.zig
new file mode 100644
index 0000000..8240f25
--- /dev/null
+++ b/src/start_menu/scan.zig
@@ -0,0 +1,222 @@
+//! Scanning application directories into entries, and copying and filtering them.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+const catalog_cache = @import("catalog_cache.zig");
+const i18n = @import("i18n");
+const applications = @import("applications.zig");
+const AppEntry = applications.AppEntry;
+const Locale = applications.Locale;
+const parseDesktopFile = applications.parseDesktopFile;
+const checkTryExec = applications.checkTryExec;
+const checkDesktopVisibility = applications.checkDesktopVisibility;
+
+pub fn copyFiltered(arena: Allocator, entries: []const AppEntry, environ: std.process.Environ) ![]AppEntry {
+ var out: std.ArrayList(AppEntry) = .empty;
+ errdefer out.deinit(arena);
+ for (entries) |e| {
+ if (e.try_exec) |try_exec| {
+ if (!checkTryExec(try_exec, environ)) continue;
+ }
+ try out.append(arena, try dupeEntry(arena, e));
+ }
+ return out.toOwnedSlice(arena);
+}
+
+pub fn dupeEntry(arena: Allocator, e: AppEntry) !AppEntry {
+ return .{
+ .id = try arena.dupe(u8, e.id),
+ .desktop_file_path = try arena.dupe(u8, e.desktop_file_path),
+ .name = try arena.dupe(u8, e.name),
+ .generic_name = if (e.generic_name) |s| try arena.dupe(u8, s) else null,
+ .comment = if (e.comment) |s| try arena.dupe(u8, s) else null,
+ .icon = if (e.icon) |s| try arena.dupe(u8, s) else null,
+ .startup_wm_class = if (e.startup_wm_class) |s| try arena.dupe(u8, s) else null,
+ .exec = try arena.dupe(u8, e.exec),
+ .path = if (e.path) |s| try arena.dupe(u8, s) else null,
+ .try_exec = if (e.try_exec) |s| try arena.dupe(u8, s) else null,
+ .terminal = e.terminal,
+ .keywords = try arena.dupe(u8, e.keywords),
+ .categories = try arena.dupe(u8, e.categories),
+ .dbus_activatable = e.dbus_activatable,
+ };
+}
+
+pub fn resolveApplicationDirs(arena: Allocator, environ: std.process.Environ) ![]const []const u8 {
+ var dirs: std.ArrayList([]const u8) = .empty;
+
+ if (environ.getPosix("XDG_DATA_HOME")) |dh| {
+ try dirs.append(arena, try std.fmt.allocPrint(arena, "{s}/applications", .{dh}));
+ } else if (environ.getPosix("HOME")) |home| {
+ try dirs.append(arena, try std.fmt.allocPrint(arena, "{s}/.local/share/applications", .{home}));
+ }
+
+ const data_dirs = environ.getPosix("XDG_DATA_DIRS") orelse "/usr/local/share:/usr/share";
+ var it = std.mem.splitScalar(u8, data_dirs, ':');
+ while (it.next()) |dir| {
+ if (dir.len == 0) continue;
+ try dirs.append(arena, try std.fmt.allocPrint(arena, "{s}/applications", .{dir}));
+ }
+ return dirs.toOwnedSlice(arena);
+}
+
+pub const ScanOutcome = struct {
+ entries: []AppEntry,
+ sources: []catalog_cache.SourceIdent,
+};
+
+pub fn scanAll(arena: Allocator, io: Io, environ: std.process.Environ) !ScanOutcome {
+ return scanAllWithLocale(arena, io, environ, i18n.resolve("", environ));
+}
+
+pub fn scanAllWithLocale(arena: Allocator, io: Io, environ: std.process.Environ, locale_tag: []const u8) !ScanOutcome {
+ const locale = Locale.forLanguage(locale_tag);
+ const current_desktop = environ.getPosix("XDG_CURRENT_DESKTOP");
+ const app_dirs = try resolveApplicationDirs(arena, environ);
+
+ var seen: std.StringHashMapUnmanaged(void) = .empty;
+ defer seen.deinit(arena);
+ var results: std.ArrayList(AppEntry) = .empty;
+ var sources: std.ArrayList(catalog_cache.SourceIdent) = .empty;
+
+ for (app_dirs) |dir| {
+ scanDirectory(arena, io, environ, dir, "", locale, current_desktop, &seen, &results, &sources) catch continue;
+ }
+ catalog_cache.sortSources(sources.items);
+
+ return .{
+ .entries = try results.toOwnedSlice(arena),
+ .sources = try sources.toOwnedSlice(arena),
+ };
+}
+
+pub fn collectSources(arena: Allocator, io: Io, environ: std.process.Environ) ![]catalog_cache.SourceIdent {
+ const app_dirs = try resolveApplicationDirs(arena, environ);
+ var sources: std.ArrayList(catalog_cache.SourceIdent) = .empty;
+ var seen: std.StringHashMapUnmanaged(void) = .empty;
+ defer seen.deinit(arena);
+ for (app_dirs) |dir| {
+ walkSources(arena, io, dir, &sources, &seen) catch continue;
+ }
+ catalog_cache.sortSources(sources.items);
+ return sources.toOwnedSlice(arena);
+}
+
+pub fn walkSources(
+ arena: Allocator,
+ io: Io,
+ dir: []const u8,
+ sources: *std.ArrayList(catalog_cache.SourceIdent),
+ seen: *std.StringHashMapUnmanaged(void),
+) !void {
+ var iter = Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }) catch return;
+ defer iter.close(io);
+ var it = iter.iterate();
+ while (try it.next(io)) |entry| {
+ if (entry.kind == .directory) {
+ const child = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, entry.name });
+ walkSources(arena, io, child, sources, seen) catch continue;
+ continue;
+ }
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".desktop")) continue;
+ const full_file_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, entry.name });
+ if (seen.contains(full_file_path)) continue;
+ try seen.put(arena, full_file_path, {});
+ if (catalog_cache.statPath(io, full_file_path)) |ident| {
+ try sources.append(arena, .{
+ .path = full_file_path,
+ .mtime_sec = ident.mtime_sec,
+ .mtime_nsec = ident.mtime_nsec,
+ .size = ident.size,
+ });
+ }
+ }
+}
+
+pub fn scanDirectory(
+ arena: Allocator,
+ io: Io,
+ environ: std.process.Environ,
+ base_dir: []const u8,
+ rel_sub: []const u8,
+ locale: Locale,
+ current_desktop: ?[]const u8,
+ seen: *std.StringHashMapUnmanaged(void),
+ results: *std.ArrayList(AppEntry),
+ sources: *std.ArrayList(catalog_cache.SourceIdent),
+) !void {
+ var path_buf: [std.posix.PATH_MAX]u8 = undefined;
+ const full_dir = if (rel_sub.len == 0)
+ base_dir
+ else
+ std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ base_dir, rel_sub }) catch return;
+
+ var iter = Io.Dir.cwd().openDir(io, full_dir, .{ .iterate = true }) catch return;
+ defer iter.close(io);
+
+ var it = iter.iterate();
+ while (try it.next(io)) |entry| {
+ if (entry.kind == .directory) {
+ var sub_buf: [256]u8 = undefined;
+ const next_sub = if (rel_sub.len == 0)
+ std.fmt.bufPrint(&sub_buf, "{s}", .{entry.name}) catch continue
+ else
+ std.fmt.bufPrint(&sub_buf, "{s}-{s}", .{ rel_sub, entry.name }) catch continue;
+ scanDirectory(arena, io, environ, base_dir, next_sub, locale, current_desktop, seen, results, sources) catch continue;
+ continue;
+ }
+
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".desktop")) continue;
+
+ const full_file_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ full_dir, entry.name });
+ if (catalog_cache.statPath(io, full_file_path)) |ident| {
+ try sources.append(arena, .{
+ .path = full_file_path,
+ .mtime_sec = ident.mtime_sec,
+ .mtime_nsec = ident.mtime_nsec,
+ .size = ident.size,
+ });
+ }
+
+ // Form desktop-file ID
+ const desktop_id = if (rel_sub.len == 0)
+ try arena.dupe(u8, entry.name)
+ else
+ try std.fmt.allocPrint(arena, "{s}-{s}", .{ rel_sub, entry.name });
+
+ if (seen.contains(desktop_id)) continue;
+ try seen.put(arena, desktop_id, {});
+
+ const content = Io.Dir.cwd().readFileAlloc(io, full_file_path, arena, .limited(512 * 1024)) catch continue;
+
+ const parsed = parseDesktopFile(arena, content, locale) orelse continue;
+
+ // Visibility rules
+ if (!checkDesktopVisibility(parsed, current_desktop)) continue;
+
+ // TryExec check
+ if (parsed.try_exec) |try_exec| {
+ if (!checkTryExec(try_exec, environ)) continue;
+ }
+
+ const exec_cmd = parsed.exec orelse continue;
+
+ try results.append(arena, .{
+ .id = desktop_id,
+ .desktop_file_path = full_file_path,
+ .name = parsed.name.?,
+ .generic_name = parsed.generic_name,
+ .comment = parsed.comment,
+ .icon = parsed.icon,
+ .startup_wm_class = parsed.startup_wm_class,
+ .exec = exec_cmd,
+ .path = parsed.path,
+ .try_exec = parsed.try_exec,
+ .terminal = parsed.terminal,
+ .keywords = parsed.keywords orelse "",
+ .categories = parsed.categories orelse "",
+ .dbus_activatable = parsed.dbus_activatable,
+ });
+ }
+}