diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 1a6d57a..64eef9c 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -11,15 +11,19 @@ body: options: - label: I have looked for any other duplicate issues required: true - - label: I have reproduced the issue on a fresh install of my OS & Ly with default settings, except ones I will mention + - label: I have reproduced the issue with the default config of Ly + required: true + - label: I have reproduced the issue on a fresh install of Ly **as well as** my OS and my desktop environment/window manager, all with **default settings**, except ones I will mention required: false - label: I have confirmed this issue also occurs on the latest development version (found in the `master` branch) required: true + - label: I understand that this issue **will** be closed if requirements are not or not properly met + required: true - type: input id: version attributes: label: Ly version - description: The output of `ly --version`. Please note that only Ly v1.2.0 and above are supported. + description: The output of `ly --version`. Please note that only the latest release and the current version in development are supported. placeholder: 1.1.0-dev.12+2b0301c validations: required: true @@ -41,9 +45,16 @@ body: id: desktop attributes: label: OS + Desktop environment/Window manager - description: Which OS and DE (or WM) did you use when observing the problem? + description: Which operating system and DE (or WM) did you use when observing the problem? validations: required: true + - type: input + id: osimage + attributes: + label: OS version/snapshot used to reproduce + description: Which version (or snapshot if rolling release) of the OS did you use to reproduce the issue? This is only required if you have reproduced the issue on a fresh copy of the OS. + validations: + required: false - type: textarea id: reproduction attributes: diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml index b9a26af..b4cc299 100644 --- a/.github/ISSUE_TEMPLATE/feature.yml +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -20,3 +20,10 @@ body: description: What do you want to be added? Describe the behavior clearly. validations: required: true + - type: textarea + id: alternatives + attributes: + label: Alternatives + description: Are there any alternatives to the new behavior you wish to see being added? + validations: + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 45044a3..606d00f 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -2,11 +2,11 @@ _Replace this with a brief description of your changes_ -## What existing issue does this resolve? +## What existing issue(s) does this resolve? -_Replace this with a reference to an existing issue, or N/A if there is none_ +_Replace this with a reference to (an) existing issue(s), or N/A if there is none_ ## Pre-requisites - [ ] I have tested & confirmed the changes work locally -- [ ] I have run `zig fmt` throughout my changes +- [ ] I have read and fully adhere to the rules set in the contributing guidelines found in `CONTRIBUTING.md` diff --git a/build.zig b/build.zig index fb0d07d..cdb0d1f 100644 --- a/build.zig +++ b/build.zig @@ -1,7 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); -const PatchMap = std.StringHashMap([]const u8); const InitSystem = enum { systemd, openrc, @@ -11,6 +10,12 @@ const InitSystem = enum { sysvinit, freebsd, }; +const InstallType = enum { + installexe, + installnoconf, + uninstallexe, + uninstallnoconf, +}; const min_zig_string = "0.16.0"; const current_zig = builtin.zig_version; @@ -23,21 +28,47 @@ comptime { } } -const ly_version = std.SemanticVersion{ .major = 1, .minor = 4, .patch = 1 }; +const ly_version = std.SemanticVersion{ .major = 1, .minor = 5, .patch = 0 }; -var dest_directory: []const u8 = undefined; -var config_directory: []const u8 = undefined; -var prefix_directory: []const u8 = undefined; -var executable_name: []const u8 = undefined; -var init_system: InitSystem = undefined; -var default_tty_str: []const u8 = undefined; +fn InstallStep( + b: *std.Build, + target: std.Build.ResolvedTarget, + comptime install_type: InstallType, + dest_directory: []const u8, + config_directory: []const u8, + prefix_directory: []const u8, + executable_name: []const u8, + init_system: InitSystem, + default_tty_str: []const u8, +) *std.Build.Step.Run { + const step = b.addRunArtifact(b.addExecutable(.{ + .name = "install", + .root_module = b.createModule(.{ + .root_source_file = b.path("install.zig"), + .target = target, + }), + })); + step.step.dependOn(b.getInstallStep()); + + step.addArgs(&.{ + std.enums.tagName(InstallType, install_type).?, + dest_directory, + config_directory, + prefix_directory, + executable_name, + std.enums.tagName(InitSystem, init_system).?, + default_tty_str, + }); + + return step; +} pub fn build(b: *std.Build) !void { - dest_directory = b.option([]const u8, "dest_directory", "Specify a destination directory for installation") orelse ""; - config_directory = b.option([]const u8, "config_directory", "Specify a default config directory (default is /etc). This path gets embedded into the binary") orelse "/etc"; - prefix_directory = b.option([]const u8, "prefix_directory", "Specify a default prefix directory (default is /usr)") orelse "/usr"; - executable_name = b.option([]const u8, "name", "Specify installed executable file name (default is ly)") orelse "ly"; - init_system = b.option(InitSystem, "init_system", "Specify the target init system (default is systemd)") orelse .systemd; + const dest_directory = b.option([]const u8, "dest_directory", "Specify a destination directory for installation") orelse ""; + const config_directory = b.option([]const u8, "config_directory", "Specify a default config directory (default is /etc). This path gets embedded into the binary") orelse "/etc"; + const prefix_directory = b.option([]const u8, "prefix_directory", "Specify a default prefix directory (default is /usr)") orelse "/usr"; + const executable_name = b.option([]const u8, "name", "Specify installed executable file name (default is ly)") orelse "ly"; + const init_system = b.option(InitSystem, "init_system", "Specify the target init system (default is systemd)") orelse .systemd; const build_options = b.addOptions(); const version_str = try getVersionStr(b, "ly", ly_version); @@ -47,7 +78,7 @@ pub fn build(b: *std.Build) !void { const fallback_uid_min = b.option(std.posix.uid_t, "fallback_uid_min", "Set the fallback minimum UID (default is 1000). This value gets embedded into the binary") orelse 1000; const fallback_uid_max = b.option(std.posix.uid_t, "fallback_uid_max", "Set the fallback maximum UID (default is 60000). This value gets embedded into the binary") orelse 60000; - default_tty_str = try std.fmt.allocPrint(b.allocator, "{d}", .{default_tty}); + const default_tty_str = try std.fmt.allocPrint(b.allocator, "{d}", .{default_tty}); build_options.addOption([]const u8, "config_directory", config_directory); build_options.addOption([]const u8, "prefix_directory", prefix_directory); @@ -69,13 +100,21 @@ pub fn build(b: *std.Build) !void { .optimize = optimize, .link_libc = true, }), - .use_llvm = true, }); + const zlua = b.dependency("zlua", .{ + .target = target, + .optimize = optimize, + .lang = .luajit, + }); + exe.root_module.addImport("zlua", zlua.module("zlua")); + const ly_ui = b.dependency("ly_ui", .{ .target = target, .optimize = optimize, .enable_x11_support = enable_x11_support, + .fallback_uid_min = fallback_uid_min, + .fallback_uid_max = fallback_uid_max, }); exe.root_module.addImport("ly-ui", ly_ui.module("ly-ui")); @@ -90,293 +129,63 @@ pub fn build(b: *std.Build) !void { b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); - run_cmd.step.dependOn(b.getInstallStep()); - if (b.args) |args| run_cmd.addArgs(args); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const installexe_step = b.step("installexe", "Install Ly and the selected init system service"); - installexe_step.makeFn = Installer(true).make; - installexe_step.dependOn(b.getInstallStep()); + installexe_step.dependOn(&InstallStep( + b, + target, + .installexe, + dest_directory, + config_directory, + prefix_directory, + executable_name, + init_system, + default_tty_str, + ).step); const installnoconf_step = b.step("installnoconf", "Install Ly and the selected init system service, but not the configuration file"); - installnoconf_step.makeFn = Installer(false).make; - installnoconf_step.dependOn(b.getInstallStep()); + installnoconf_step.dependOn(&InstallStep( + b, + target, + .installnoconf, + dest_directory, + config_directory, + prefix_directory, + executable_name, + init_system, + default_tty_str, + ).step); const uninstallexe_step = b.step("uninstallexe", "Uninstall Ly and remove the selected init system service"); - uninstallexe_step.makeFn = Uninstaller(true).make; + uninstallexe_step.dependOn(&InstallStep( + b, + target, + .uninstallexe, + dest_directory, + config_directory, + prefix_directory, + executable_name, + init_system, + default_tty_str, + ).step); const uninstallnoconf_step = b.step("uninstallnoconf", "Uninstall Ly and remove the selected init system service, but keep the configuration directory"); - uninstallnoconf_step.makeFn = Uninstaller(false).make; -} - -pub fn Installer(install_config: bool) type { - return struct { - pub fn make(step: *std.Build.Step, _: std.Build.Step.MakeOptions) !void { - var threaded: std.Io.Threaded = .init_single_threaded; - const io = threaded.io(); - const allocator = step.owner.allocator; - - var patch_map = PatchMap.init(allocator); - defer patch_map.deinit(); - - try patch_map.put("$DEFAULT_TTY", default_tty_str); - try patch_map.put("$CONFIG_DIRECTORY", config_directory); - try patch_map.put("$PREFIX_DIRECTORY", prefix_directory); - try patch_map.put("$EXECUTABLE_NAME", executable_name); - - // The "-a" argument doesn't exist on FreeBSD, so we use "-p" - // instead to shutdown the system. - try patch_map.put("$PLATFORM_SHUTDOWN_ARG", if (init_system == .freebsd) "-p" else "-a"); - - try install_ly(allocator, io, patch_map, install_config); - try install_service(allocator, io, patch_map); - } - }; -} - -fn install_ly(allocator: std.mem.Allocator, io: std.Io, patch_map: PatchMap, install_config: bool) !void { - const ly_config_directory = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/ly" }); - - std.Io.Dir.cwd().createDirPath(io, ly_config_directory) catch { - std.debug.print("warn: {s} already exists as a directory.\n", .{ly_config_directory}); - }; - - const ly_custom_sessions_directory = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/ly/custom-sessions" }); - - std.Io.Dir.cwd().createDirPath(io, ly_custom_sessions_directory) catch { - std.debug.print("warn: {s} already exists as a directory.\n", .{ly_custom_sessions_directory}); - }; - - const ly_lang_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/ly/lang" }); - std.Io.Dir.cwd().createDirPath(io, ly_lang_path) catch { - std.debug.print("warn: {s} already exists as a directory.\n", .{ly_lang_path}); - }; - - { - const exe_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/bin" }); - std.Io.Dir.cwd().createDirPath(io, exe_path) catch { - if (!std.mem.eql(u8, dest_directory, "")) { - std.debug.print("warn: {s} already exists as a directory.\n", .{exe_path}); - } - }; - - var executable_dir = std.Io.Dir.cwd().openDir(io, exe_path, .{}) catch unreachable; - defer executable_dir.close(io); - - try installFile(io, "zig-out/bin/ly", executable_dir, exe_path, executable_name, .{}); - } - - { - var config_dir = std.Io.Dir.cwd().openDir(io, ly_config_directory, .{}) catch unreachable; - defer config_dir.close(io); - - if (install_config) { - const patched_config = try patchFile(allocator, io, "res/config.ini", patch_map); - try installText(io, patched_config, config_dir, ly_config_directory, "config.ini", .{}); - - try installFile(io, "res/startup.sh", config_dir, ly_config_directory, "startup.sh", .{ .permissions = .fromMode(0o755) }); - } - - const patched_example_config = try patchFile(allocator, io, "res/config.ini", patch_map); - try installText(io, patched_example_config, config_dir, ly_config_directory, "config.ini.example", .{}); - - const patched_setup = try patchFile(allocator, io, "res/setup.sh", patch_map); - try installText(io, patched_setup, config_dir, ly_config_directory, "setup.sh", .{ .permissions = .fromMode(0o755) }); - - try installFile(io, "res/example.dur", config_dir, ly_config_directory, "example.dur", .{ .permissions = .fromMode(0o755) }); - } - - { - var custom_sessions_dir = std.Io.Dir.cwd().openDir(io, ly_custom_sessions_directory, .{}) catch unreachable; - defer custom_sessions_dir.close(io); - - const patched_readme = try patchFile(allocator, io, "res/custom-sessions/README", patch_map); - try installText(io, patched_readme, custom_sessions_dir, ly_custom_sessions_directory, "README", .{}); - } - - { - var lang_dir = std.Io.Dir.cwd().openDir(io, ly_lang_path, .{}) catch unreachable; - defer lang_dir.close(io); - - const languages = [_][]const u8{ - "ar.ini", - "cat.ini", - "cs.ini", - "de.ini", - "en.ini", - "es.ini", - "fr.ini", - "it.ini", - "ja_JP.ini", - "lv.ini", - "pl.ini", - "pt.ini", - "pt_BR.ini", - "ro.ini", - "ru.ini", - "sr.ini", - "sv.ini", - "tr.ini", - "uk.ini", - "zh_CN.ini", - }; - - inline for (languages) |language| { - try installFile(io, "res/lang/" ++ language, lang_dir, ly_lang_path, language, .{}); - } - } - - { - const pam_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/pam.d" }); - std.Io.Dir.cwd().createDirPath(io, pam_path) catch { - if (!std.mem.eql(u8, dest_directory, "")) { - std.debug.print("warn: {s} already exists as a directory.\n", .{pam_path}); - } - }; - - var pam_dir = std.Io.Dir.cwd().openDir(io, pam_path, .{}) catch unreachable; - defer pam_dir.close(io); - - try installFile(io, if (init_system == .freebsd) "res/pam.d/ly-freebsd" else "res/pam.d/ly-linux", pam_dir, pam_path, "ly", .{ .permissions = .fromMode(0o644) }); - try installFile(io, if (init_system == .freebsd) "res/pam.d/ly-freebsd-autologin" else "res/pam.d/ly-linux-autologin", pam_dir, pam_path, "ly-autologin", .{ .permissions = .fromMode(0o644) }); - } -} - -fn install_service(allocator: std.mem.Allocator, io: std.Io, patch_map: PatchMap) !void { - switch (init_system) { - .systemd => { - const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/lib/systemd/system" }); - std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; - var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; - defer service_dir.close(io); - - const patched_service = try patchFile(allocator, io, "res/ly@.service", patch_map); - try installText(io, patched_service, service_dir, service_path, "ly@.service", .{ .permissions = .fromMode(0o644) }); - - const patched_kmsconvt_service = try patchFile(allocator, io, "res/ly-kmsconvt@.service", patch_map); - try installText(io, patched_kmsconvt_service, service_dir, service_path, "ly-kmsconvt@.service", .{ .permissions = .fromMode(0o644) }); - }, - .openrc => { - const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/init.d" }); - std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; - var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; - defer service_dir.close(io); - - const patched_service = try patchFile(allocator, io, "res/ly-openrc", patch_map); - try installText(io, patched_service, service_dir, service_path, executable_name, .{ .permissions = .fromMode(0o755) }); - }, - .runit => { - const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/sv/ly" }); - std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; - var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; - defer service_dir.close(io); - - const supervise_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ service_path, "supervise" }); - - const patched_conf = try patchFile(allocator, io, "res/ly-runit-service/conf", patch_map); - try installText(io, patched_conf, service_dir, service_path, "conf", .{}); - - try installFile(io, "res/ly-runit-service/finish", service_dir, service_path, "finish", .{ .permissions = .fromMode(0o755) }); - - const patched_run = try patchFile(allocator, io, "res/ly-runit-service/run", patch_map); - try installText(io, patched_run, service_dir, service_path, "run", .{ .permissions = .fromMode(0o755) }); - - std.Io.Dir.cwd().symLink(io, "/run/runit/supervise.ly", supervise_path, .{}) catch |err| { - if (err == error.PathAlreadyExists) { - std.debug.print("warn: /run/runit/supervise.ly already exists as a symbolic link.\n", .{}); - } else { - return err; - } - }; - std.debug.print("info: installed symlink /run/runit/supervise.ly\n", .{}); - }, - .s6 => { - const admin_service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/s6/adminsv/default/contents.d" }); - std.Io.Dir.cwd().createDirPath(io, admin_service_path) catch {}; - var admin_service_dir = std.Io.Dir.cwd().openDir(io, admin_service_path, .{}) catch unreachable; - defer admin_service_dir.close(io); - - const file = try admin_service_dir.createFile(io, "ly-srv", .{}); - file.close(io); - - const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/s6/sv/ly-srv" }); - std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; - var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; - defer service_dir.close(io); - - const patched_run = try patchFile(allocator, io, "res/ly-s6/run", patch_map); - try installText(io, patched_run, service_dir, service_path, "run", .{ .permissions = .fromMode(0o755) }); - - try installFile(io, "res/ly-s6/type", service_dir, service_path, "type", .{}); - }, - .dinit => { - const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/dinit.d" }); - std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; - var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; - defer service_dir.close(io); - - const patched_service = try patchFile(allocator, io, "res/ly-dinit", patch_map); - try installText(io, patched_service, service_dir, service_path, "ly", .{}); - }, - .sysvinit => { - const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/init.d" }); - std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; - var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; - defer service_dir.close(io); - - const patched_service = try patchFile(allocator, io, "res/ly-sysvinit", patch_map); - try installText(io, patched_service, service_dir, service_path, "ly", .{ .permissions = .fromMode(0o755) }); - }, - .freebsd => { - const exe_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/bin" }); - var executable_dir = std.Io.Dir.cwd().openDir(io, exe_path, .{}) catch unreachable; - defer executable_dir.close(io); - - const patched_wrapper = try patchFile(allocator, io, "res/ly-freebsd-wrapper", patch_map); - try installText(io, patched_wrapper, executable_dir, exe_path, "ly_wrapper", .{ .permissions = .fromMode(0o755) }); - }, - } -} - -pub fn Uninstaller(uninstall_config: bool) type { - return struct { - pub fn make(step: *std.Build.Step, _: std.Build.Step.MakeOptions) !void { - var threaded: std.Io.Threaded = .init_single_threaded; - const io = threaded.io(); - const allocator = step.owner.allocator; - - if (uninstall_config) { - try deleteTree(allocator, io, config_directory, "/ly", "ly config directory not found"); - } - - const exe_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ prefix_directory, "/bin/", executable_name }); - var success = true; - std.Io.Dir.cwd().deleteFile(io, exe_path) catch { - std.debug.print("warn: ly executable not found\n", .{}); - success = false; - }; - if (success) std.debug.print("info: deleted {s}\n", .{exe_path}); - - try deleteFile(allocator, io, config_directory, "/pam.d/ly", "ly pam file not found"); - - switch (init_system) { - .systemd => try deleteFile(allocator, io, prefix_directory, "/lib/systemd/system/ly@.service", "systemd service not found"), - .openrc => try deleteFile(allocator, io, config_directory, "/init.d/ly", "openrc service not found"), - .runit => try deleteTree(allocator, io, config_directory, "/sv/ly", "runit service not found"), - .s6 => { - try deleteTree(allocator, io, config_directory, "/s6/sv/ly-srv", "s6 service not found"); - try deleteFile(allocator, io, config_directory, "/s6/adminsv/default/contents.d/ly-srv", "s6 admin service not found"); - }, - .dinit => try deleteFile(allocator, io, config_directory, "/dinit.d/ly", "dinit service not found"), - .sysvinit => try deleteFile(allocator, io, config_directory, "/init.d/ly", "sysvinit service not found"), - .freebsd => try deleteFile(allocator, io, prefix_directory, "/bin/ly_wrapper", "freebsd wrapper not found"), - } - } - }; + uninstallnoconf_step.dependOn(&InstallStep( + b, + target, + .uninstallnoconf, + dest_directory, + config_directory, + prefix_directory, + executable_name, + init_system, + default_tty_str, + ).step); } fn getVersionStr(b: *std.Build, name: []const u8, version: std.SemanticVersion) ![]const u8 { @@ -433,99 +242,3 @@ fn getVersionStr(b: *std.Build, name: []const u8, version: std.SemanticVersion) }, } } - -fn installFile( - io: std.Io, - source_file: []const u8, - destination_directory: std.Io.Dir, - destination_directory_path: []const u8, - destination_file: []const u8, - options: std.Io.Dir.CopyFileOptions, -) !void { - try std.Io.Dir.cwd().copyFile(source_file, destination_directory, destination_file, io, options); - std.debug.print("info: installed {s}/{s}\n", .{ destination_directory_path, destination_file }); -} - -fn patchFile(allocator: std.mem.Allocator, io: std.Io, source_file: []const u8, patch_map: PatchMap) ![]const u8 { - var file = try std.Io.Dir.cwd().openFile(io, source_file, .{}); - defer file.close(io); - - const stat = try file.stat(io); - - var buffer: [4096]u8 = undefined; - var reader = file.reader(io, &buffer); - var text = try reader.interface.readAlloc(allocator, @intCast(stat.size)); - - var iterator = patch_map.iterator(); - while (iterator.next()) |kv| { - const new_text = try std.mem.replaceOwned(u8, allocator, text, kv.key_ptr.*, kv.value_ptr.*); - allocator.free(text); - text = new_text; - } - - return text; -} - -fn installText( - io: std.Io, - text: []const u8, - destination_directory: std.Io.Dir, - destination_directory_path: []const u8, - destination_file: []const u8, - options: std.Io.File.CreateFlags, -) !void { - var file = try destination_directory.createFile(io, destination_file, options); - defer file.close(io); - - var buffer: [1024]u8 = undefined; - var writer = file.writer(io, &buffer); - try writer.interface.writeAll(text); - try writer.interface.flush(); - - std.debug.print("info: installed {s}/{s}\n", .{ destination_directory_path, destination_file }); -} - -fn deleteFile( - allocator: std.mem.Allocator, - io: std.Io, - prefix: []const u8, - file: []const u8, - warning: []const u8, -) !void { - const path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix, file }); - - std.Io.Dir.cwd().deleteFile(io, path) catch |err| { - if (err == error.FileNotFound) { - std.debug.print("warn: {s}\n", .{warning}); - return; - } - - return err; - }; - - std.debug.print("info: deleted {s}\n", .{path}); -} - -fn deleteTree( - allocator: std.mem.Allocator, - io: std.Io, - prefix: []const u8, - directory: []const u8, - warning: []const u8, -) !void { - const path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix, directory }); - - var dir = std.Io.Dir.cwd().openDir(io, path, .{}) catch |err| { - if (err == error.FileNotFound) { - std.debug.print("warn: {s}\n", .{warning}); - return; - } - - return err; - }; - dir.close(io); - - try std.Io.Dir.cwd().deleteTree(io, path); - - std.debug.print("info: deleted {s}\n", .{path}); -} diff --git a/build.zig.zon b/build.zig.zon index 2f4c1be..1d19b69 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .ly, - .version = "1.4.1", + .version = "1.5.0", .fingerprint = 0xa148ffcc5dc2cb59, .minimum_zig_version = "0.16.0", .dependencies = .{ @@ -11,6 +11,10 @@ .url = "git+https://github.com/Hejsil/zig-clap#fc1e5cc3f6d9d3001112385ee6256d694e959d2f", .hash = "clap-0.11.0-oBajB7foAQC3Iyn4IVCkUdYaOVVng5IZkSncySTjNig1", }, + .zlua = .{ + .url = "git+https://github.com/natecraddock/ziglua?ref=zig-0.16#8f271c82baa5fc43aa02a72f6da020c2025d9436", + .hash = "zlua-0.1.0-hGRpC2aABQD4D9PBVH3wAW8k32-I4969MRQ0CpOwoley", + }, }, .paths = .{ "build.zig", diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..eddaffb --- /dev/null +++ b/contributing.md @@ -0,0 +1,29 @@ +# Contributing to Ly + +To contribute to Ly, you have to open a pull request on [Codeberg](https://codeberg.org/fairyglade/ly), as [GitHub](https://github.com/fairyglade/ly) is just a mirror. However, you also have to respect the following rules, otherwise your PR may end up being rejected: + +## AI usage + +While we cannot control your usage of any LLM whatsoever, we do heavily discourage their use for environmental, ethical & moral reasons that you can learn more about on the Internet. However, if you do end up still using them, here are a couple rules you **must absolutely** respect for your PR not to get instantly shot down. Of course, it goes without saying that **all** the other rules in the other sections below **must** be adhered to, even more so when AI is used. + +1. **Communicate through you**, not the AI; as in, responses to reviews or other comments in the PR must be written by you and not an LLM. If English isn't your native language and you have a lot of trouble speaking it, you _may_ use AI, but responses must not be your typical, alienating AI-generated text: https://github.com/realrossmanngroup/no_ai_slop_writing_rules +2. Control the code, as in, **don't vibecode**, especially if you don't know Zig. Don't waste the maintainers's time, and **heavily test your code**, as AI-generated code is typically more error-prone in subtle ways (even if they can be better than humans in some other aspects). Finally, don't generate any "summary" or whatever the AI may come up with during the process. **If you cannot understand the generated code, do not contribute it**. Maintainers are busy and are often simple volunteers, so the less work they have to do, the better. +3. **Be transparent about AI usage**. Precise what AI model was used in the process, and preferably, how you went about creating your changes (i.e. how did you use AI to make the pull request). The more honest you are about it, the more likely your PR will be accepted and merged into the code base. + +If all the above rules are respected, your changes have much more likely to be accepted into the code base. + +## Code style + +You must follow Zig's [style guide](https://ziglang.org/documentation/master/#Style-Guide). In most cases, all you'll have to do is run `zig fmt` after you have completed your changes, though it does not fix everything, notably variable, function & field naming, as well as the maximum length of aline. + +For the former, please refer to the aforementioned style guide in that case. For the latter, you must respect a maximum line length of **80 characters**. For function calls with many parameters or anything similar that may overflow this limit, consider adding a trailing comma to the list so that `zig fmt` can split it into multiple lines. Ideally, few or no lines end up having to get soft wrapped by an editor having this limit set. + +## Commit names & descriptions + +1. **Commit names must be descriptive**, resorting to the commit description if they are too long. In such cases, the commit name **must** be shortened while still making sense. With that said, no particular convention (emojis, prefixes & suffixes, etc.) is mandated for them, and you are free to adopt any one you think is best or that you are used to. +2. **Do not force push**, as PRs will get squashed into a single commit anyway. This erases history and makes it impossible to see the changes done over time and by a particular commit. +3. While not a requirement per se, **consider signing your commits** with an SSH or GPG key for security purposes. This ensures to a lesser extent that you are the person who you claim to be, and reduces the potential amount of malicious contributions that could infiltrate the code base. + +## Additional requirements + +Other requirements (such as testing your code) for merging the changes will be available when you open your pull request via the template (which you **must** use), however, these are not stated here because they may not be mandatory in some cases (e.g. if the changes are still work-in-progress), so they may temporarily be ommitted for a certain period of time until the changes are fully ready to be reviewed, for instance. diff --git a/install.zig b/install.zig new file mode 100644 index 0000000..b5649cd --- /dev/null +++ b/install.zig @@ -0,0 +1,445 @@ +const std = @import("std"); + +const PatchMap = std.StringHashMap([]const u8); +const InitSystem = enum { + systemd, + openrc, + runit, + s6, + dinit, + sysvinit, + freebsd, +}; +const InstallType = enum { + installexe, + installnoconf, + uninstallexe, + uninstallnoconf, +}; + +var dest_directory: []const u8 = undefined; +var config_directory: []const u8 = undefined; +var prefix_directory: []const u8 = undefined; +var executable_name: []const u8 = undefined; +var init_system: InitSystem = undefined; + +pub fn main(init: std.process.Init) !void { + const io = init.io; + const allocator = init.gpa; + + var args = init.minimal.args.iterate(); + if (!args.skip()) return error.NoProgramName; + + const install_type = std.meta.stringToEnum(InstallType, args.next().?).?; + dest_directory = args.next().?; + config_directory = args.next().?; + prefix_directory = args.next().?; + executable_name = args.next().?; + init_system = std.meta.stringToEnum(InitSystem, args.next().?).?; + const default_tty_str = args.next().?; + + switch (install_type) { + .installexe, .installnoconf => { + var patch_map = PatchMap.init(allocator); + defer patch_map.deinit(); + + try patch_map.put("$DEFAULT_TTY", default_tty_str); + try patch_map.put("$CONFIG_DIRECTORY", config_directory); + try patch_map.put("$PREFIX_DIRECTORY", prefix_directory); + try patch_map.put("$EXECUTABLE_NAME", executable_name); + + try installLy(allocator, io, patch_map, install_type == .installexe); + try installService(allocator, io, patch_map); + }, + .uninstallexe, .uninstallnoconf => { + if (install_type == .uninstallexe) { + try deleteTree(allocator, io, config_directory, "/ly", "ly config directory not found"); + } + + const exe_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ prefix_directory, "/bin/", executable_name }); + defer allocator.free(exe_path); + + var success = true; + std.Io.Dir.cwd().deleteFile(io, exe_path) catch { + std.debug.print("warn: ly executable not found\n", .{}); + success = false; + }; + if (success) std.debug.print("info: deleted {s}\n", .{exe_path}); + + try deleteFile(allocator, io, config_directory, "/pam.d/ly", "ly pam file not found"); + + switch (init_system) { + .systemd => try deleteFile(allocator, io, prefix_directory, "/lib/systemd/system/ly@.service", "systemd service not found"), + .openrc => try deleteFile(allocator, io, config_directory, "/init.d/ly", "openrc service not found"), + .runit => try deleteTree(allocator, io, config_directory, "/sv/ly", "runit service not found"), + .s6 => { + try deleteTree(allocator, io, config_directory, "/s6/sv/ly-srv", "s6 service not found"); + try deleteFile(allocator, io, config_directory, "/s6/adminsv/default/contents.d/ly-srv", "s6 admin service not found"); + }, + .dinit => try deleteFile(allocator, io, config_directory, "/dinit.d/ly", "dinit service not found"), + .sysvinit => try deleteFile(allocator, io, config_directory, "/init.d/ly", "sysvinit service not found"), + .freebsd => try deleteFile(allocator, io, prefix_directory, "/bin/ly_wrapper", "freebsd wrapper not found"), + } + }, + } +} + +fn installLy(allocator: std.mem.Allocator, io: std.Io, patch_map: PatchMap, install_config: bool) !void { + const ly_config_directory = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/ly" }); + defer allocator.free(ly_config_directory); + + std.Io.Dir.cwd().createDirPath(io, ly_config_directory) catch { + std.debug.print("warn: {s} already exists as a directory.\n", .{ly_config_directory}); + }; + + const ly_custom_sessions_directory = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/ly/custom-sessions" }); + defer allocator.free(ly_custom_sessions_directory); + + std.Io.Dir.cwd().createDirPath(io, ly_custom_sessions_directory) catch { + std.debug.print("warn: {s} already exists as a directory.\n", .{ly_custom_sessions_directory}); + }; + + const ly_lang_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/ly/lang" }); + defer allocator.free(ly_lang_path); + + std.Io.Dir.cwd().createDirPath(io, ly_lang_path) catch { + std.debug.print("warn: {s} already exists as a directory.\n", .{ly_lang_path}); + }; + + { + const exe_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/bin" }); + defer allocator.free(exe_path); + + std.Io.Dir.cwd().createDirPath(io, exe_path) catch { + if (!std.mem.eql(u8, dest_directory, "")) { + std.debug.print("warn: {s} already exists as a directory.\n", .{exe_path}); + } + }; + + var executable_dir = std.Io.Dir.cwd().openDir(io, exe_path, .{}) catch unreachable; + defer executable_dir.close(io); + + try installFile(io, "zig-out/bin/ly", executable_dir, exe_path, executable_name, .{}); + } + + { + var config_dir = std.Io.Dir.cwd().openDir(io, ly_config_directory, .{}) catch unreachable; + defer config_dir.close(io); + + if (install_config) { + const patched_config = try patchFile(allocator, io, "res/config.ini", patch_map); + defer allocator.free(patched_config); + + try installText(io, patched_config, config_dir, ly_config_directory, "config.ini", .{}); + + try installFile(io, "res/startup.sh", config_dir, ly_config_directory, "startup.sh", .{ .permissions = .fromMode(0o755) }); + } + + const patched_example_config = try patchFile(allocator, io, "res/config.ini", patch_map); + defer allocator.free(patched_example_config); + + try installText(io, patched_example_config, config_dir, ly_config_directory, "config.ini.example", .{}); + + const patched_setup = try patchFile(allocator, io, "res/setup.sh", patch_map); + defer allocator.free(patched_setup); + + try installText(io, patched_setup, config_dir, ly_config_directory, "setup.sh", .{ .permissions = .fromMode(0o755) }); + + try installFile(io, "res/example.dur", config_dir, ly_config_directory, "example.dur", .{ .permissions = .fromMode(0o755) }); + + try installFile(io, "res/example.lua", config_dir, ly_config_directory, "example.lua", .{ .permissions = .fromMode(0o755) }); + } + + { + var custom_sessions_dir = std.Io.Dir.cwd().openDir(io, ly_custom_sessions_directory, .{}) catch unreachable; + defer custom_sessions_dir.close(io); + + const patched_readme = try patchFile(allocator, io, "res/custom-sessions/README", patch_map); + defer allocator.free(patched_readme); + + try installText(io, patched_readme, custom_sessions_dir, ly_custom_sessions_directory, "README", .{}); + } + + { + var lang_dir = std.Io.Dir.cwd().openDir(io, ly_lang_path, .{}) catch unreachable; + defer lang_dir.close(io); + + const languages = [_][]const u8{ + "ar.ini", + "bg.ini", + "cat.ini", + "cs.ini", + "de.ini", + "en.ini", + "eo.ini", + "es.ini", + "fr.ini", + "it.ini", + "ja_JP.ini", + "ku.ini", + "lv.ini", + "pl.ini", + "pt.ini", + "pt_BR.ini", + "ro.ini", + "ru.ini", + "sr.ini", + "sr_Cyrl.ini", + "sv.ini", + "tr.ini", + "uk.ini", + "zh_CN.ini", + "zh_TW.ini", + }; + + inline for (languages) |language| { + try installFile(io, "res/lang/" ++ language, lang_dir, ly_lang_path, language, .{}); + } + } + + { + const pam_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/pam.d" }); + defer allocator.free(pam_path); + + std.Io.Dir.cwd().createDirPath(io, pam_path) catch { + if (!std.mem.eql(u8, dest_directory, "")) { + std.debug.print("warn: {s} already exists as a directory.\n", .{pam_path}); + } + }; + + var pam_dir = std.Io.Dir.cwd().openDir(io, pam_path, .{}) catch unreachable; + defer pam_dir.close(io); + + try installFile(io, if (init_system == .freebsd) "res/pam.d/ly-freebsd" else "res/pam.d/ly-linux", pam_dir, pam_path, "ly", .{ .permissions = .fromMode(0o644) }); + try installFile(io, if (init_system == .freebsd) "res/pam.d/ly-freebsd-autologin" else "res/pam.d/ly-linux-autologin", pam_dir, pam_path, "ly-autologin", .{ .permissions = .fromMode(0o644) }); + } +} + +fn installService(allocator: std.mem.Allocator, io: std.Io, patch_map: PatchMap) !void { + switch (init_system) { + .systemd => { + const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/lib/systemd/system" }); + defer allocator.free(service_path); + + std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; + var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; + defer service_dir.close(io); + + const patched_service = try patchFile(allocator, io, "res/ly@.service", patch_map); + defer allocator.free(patched_service); + + try installText(io, patched_service, service_dir, service_path, "ly@.service", .{ .permissions = .fromMode(0o644) }); + + const patched_kmsconvt_service = try patchFile(allocator, io, "res/ly-kmsconvt@.service", patch_map); + defer allocator.free(patched_kmsconvt_service); + + try installText(io, patched_kmsconvt_service, service_dir, service_path, "ly-kmsconvt@.service", .{ .permissions = .fromMode(0o644) }); + }, + .openrc => { + const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/init.d" }); + defer allocator.free(service_path); + + std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; + var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; + defer service_dir.close(io); + + const patched_service = try patchFile(allocator, io, "res/ly-openrc", patch_map); + defer allocator.free(patched_service); + + try installText(io, patched_service, service_dir, service_path, executable_name, .{ .permissions = .fromMode(0o755) }); + }, + .runit => { + const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/sv/ly" }); + defer allocator.free(service_path); + + std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; + var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; + defer service_dir.close(io); + + const supervise_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ service_path, "supervise" }); + defer allocator.free(supervise_path); + + const patched_conf = try patchFile(allocator, io, "res/ly-runit-service/conf", patch_map); + defer allocator.free(patched_conf); + + try installText(io, patched_conf, service_dir, service_path, "conf", .{}); + + try installFile(io, "res/ly-runit-service/finish", service_dir, service_path, "finish", .{ .permissions = .fromMode(0o755) }); + + const patched_run = try patchFile(allocator, io, "res/ly-runit-service/run", patch_map); + defer allocator.free(patched_run); + + try installText(io, patched_run, service_dir, service_path, "run", .{ .permissions = .fromMode(0o755) }); + + std.Io.Dir.cwd().symLink(io, "/run/runit/supervise.ly", supervise_path, .{}) catch |err| { + if (err == error.PathAlreadyExists) { + std.debug.print("warn: /run/runit/supervise.ly already exists as a symbolic link.\n", .{}); + } else { + return err; + } + }; + std.debug.print("info: installed symlink /run/runit/supervise.ly\n", .{}); + }, + .s6 => { + const admin_service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/s6/adminsv/default/contents.d" }); + std.Io.Dir.cwd().createDirPath(io, admin_service_path) catch {}; + defer allocator.free(admin_service_path); + + var admin_service_dir = std.Io.Dir.cwd().openDir(io, admin_service_path, .{}) catch unreachable; + defer admin_service_dir.close(io); + + const file = try admin_service_dir.createFile(io, "ly-srv", .{}); + file.close(io); + + const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/s6/sv/ly-srv" }); + defer allocator.free(service_path); + + std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; + var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; + defer service_dir.close(io); + + const patched_run = try patchFile(allocator, io, "res/ly-s6/run", patch_map); + defer allocator.free(patched_run); + + try installText(io, patched_run, service_dir, service_path, "run", .{ .permissions = .fromMode(0o755) }); + + try installFile(io, "res/ly-s6/type", service_dir, service_path, "type", .{}); + }, + .dinit => { + const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/dinit.d" }); + defer allocator.free(service_path); + + std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; + var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; + defer service_dir.close(io); + + const patched_service = try patchFile(allocator, io, "res/ly-dinit", patch_map); + defer allocator.free(patched_service); + + try installText(io, patched_service, service_dir, service_path, "ly", .{}); + }, + .sysvinit => { + const service_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, config_directory, "/init.d" }); + defer allocator.free(service_path); + + std.Io.Dir.cwd().createDirPath(io, service_path) catch {}; + var service_dir = std.Io.Dir.cwd().openDir(io, service_path, .{}) catch unreachable; + defer service_dir.close(io); + + const patched_service = try patchFile(allocator, io, "res/ly-sysvinit", patch_map); + defer allocator.free(patched_service); + + try installText(io, patched_service, service_dir, service_path, "ly", .{ .permissions = .fromMode(0o755) }); + }, + .freebsd => { + const exe_path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix_directory, "/bin" }); + defer allocator.free(exe_path); + + var executable_dir = std.Io.Dir.cwd().openDir(io, exe_path, .{}) catch unreachable; + defer executable_dir.close(io); + + const patched_wrapper = try patchFile(allocator, io, "res/ly-freebsd-wrapper", patch_map); + defer allocator.free(patched_wrapper); + + try installText(io, patched_wrapper, executable_dir, exe_path, "ly_wrapper", .{ .permissions = .fromMode(0o755) }); + }, + } +} + +fn installFile( + io: std.Io, + source_file: []const u8, + destination_directory: std.Io.Dir, + destination_directory_path: []const u8, + destination_file: []const u8, + options: std.Io.Dir.CopyFileOptions, +) !void { + try std.Io.Dir.cwd().copyFile(source_file, destination_directory, destination_file, io, options); + std.debug.print("info: installed {s}/{s}\n", .{ destination_directory_path, destination_file }); +} + +fn patchFile(allocator: std.mem.Allocator, io: std.Io, source_file: []const u8, patch_map: PatchMap) ![]const u8 { + var file = try std.Io.Dir.cwd().openFile(io, source_file, .{}); + defer file.close(io); + + const stat = try file.stat(io); + + var buffer: [4096]u8 = undefined; + var reader = file.reader(io, &buffer); + var text = try reader.interface.readAlloc(allocator, @intCast(stat.size)); + + var iterator = patch_map.iterator(); + while (iterator.next()) |kv| { + const new_text = try std.mem.replaceOwned(u8, allocator, text, kv.key_ptr.*, kv.value_ptr.*); + allocator.free(text); + text = new_text; + } + + return text; +} + +fn installText( + io: std.Io, + text: []const u8, + destination_directory: std.Io.Dir, + destination_directory_path: []const u8, + destination_file: []const u8, + options: std.Io.File.CreateFlags, +) !void { + var file = try destination_directory.createFile(io, destination_file, options); + defer file.close(io); + + var buffer: [1024]u8 = undefined; + var writer = file.writer(io, &buffer); + try writer.interface.writeAll(text); + try writer.interface.flush(); + + std.debug.print("info: installed {s}/{s}\n", .{ destination_directory_path, destination_file }); +} + +fn deleteFile( + allocator: std.mem.Allocator, + io: std.Io, + prefix: []const u8, + file: []const u8, + warning: []const u8, +) !void { + const path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix, file }); + defer allocator.free(path); + + std.Io.Dir.cwd().deleteFile(io, path) catch |err| { + if (err == error.FileNotFound) { + std.debug.print("warn: {s}\n", .{warning}); + return; + } + + return err; + }; + + std.debug.print("info: deleted {s}\n", .{path}); +} + +fn deleteTree( + allocator: std.mem.Allocator, + io: std.Io, + prefix: []const u8, + directory: []const u8, + warning: []const u8, +) !void { + const path = try std.Io.Dir.path.join(allocator, &[_][]const u8{ dest_directory, prefix, directory }); + defer allocator.free(path); + + var dir = std.Io.Dir.cwd().openDir(io, path, .{}) catch |err| { + if (err == error.FileNotFound) { + std.debug.print("warn: {s}\n", .{warning}); + return; + } + + return err; + }; + dir.close(io); + + try std.Io.Dir.cwd().deleteTree(io, path); + + std.debug.print("info: deleted {s}\n", .{path}); +} diff --git a/ly-core/build.zig b/ly-core/build.zig index f6574de..f62fb2e 100644 --- a/ly-core/build.zig +++ b/ly-core/build.zig @@ -11,12 +11,18 @@ pub fn build(b: *std.Build) void { .optimize = optimize, }); + const fallback_uid_min = b.option(std.posix.uid_t, "fallback_uid_min", "Set the fallback minimum UID (default is 1000). This value gets embedded into the binary").?; + const fallback_uid_max = b.option(std.posix.uid_t, "fallback_uid_max", "Set the fallback maximum UID (default is 60000). This value gets embedded into the binary").?; + const build_options = b.addOptions(); + build_options.addOption(std.posix.uid_t, "fallback_uid_min", fallback_uid_min); + build_options.addOption(std.posix.uid_t, "fallback_uid_max", fallback_uid_max); + mod.addOptions("build_options", build_options); + const zigini = b.dependency("zigini", .{ .target = target, .optimize = optimize }); mod.addImport("zigini", zigini.module("zigini")); const translate_c = b.dependency("translate_c", .{ .target = target, - .optimize = optimize, }); addCImport(b, mod, translate_c, target, optimize, "pam", "#include "); @@ -45,6 +51,8 @@ pub fn build(b: *std.Build) void { } else if (target.result.os.tag == .freebsd) { addCImport(b, mod, translate_c, target, optimize, "kbio", "#include "); addCImport(b, mod, translate_c, target, optimize, "consio", "#include "); + addCImport(b, mod, translate_c, target, optimize, "sysctl", "#include "); + addCImport(b, mod, translate_c, target, optimize, "reboot", "#include "); } const mod_tests = b.addTest(.{ diff --git a/ly-core/build.zig.zon b/ly-core/build.zig.zon index 8998484..0d84326 100644 --- a/ly-core/build.zig.zon +++ b/ly-core/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .ly_core, - .version = "1.0.1", + .version = "1.1.0", .fingerprint = 0xddda7afda795472, .minimum_zig_version = "0.16.0", .dependencies = .{ @@ -9,8 +9,8 @@ .hash = "zigini-0.5.0-BSkB7e9WAACfyCBABNZiWL3gFMw18GKn3qBcPs8L1Ec1", }, .translate_c = .{ - .url = "git+https://codeberg.org/ziglang/translate-c#7a1a9fdc4ab00835748a6657ecbb835e3d5d45f7", - .hash = "translate_c-0.0.0-Q_BUWvP1BgCjAk6PWv5286tOlvzD9-X-NkuTzh0KxY0Q", + .url = "git+https://codeberg.org/ziglang/translate-c?ref=zig-0.16.x#6fe0ffc4549f15c5f2d9432c2b4460ba90ff85ac", + .hash = "translate_c-1.0.0-Q_BUWo_5BgD4flHdUhA31zOz0XvZk9k7lQv1ouzyNXj2", }, }, .paths = .{ diff --git a/ly-core/src/LogFile.zig b/ly-core/src/LogFile.zig index f60b153..192f338 100644 --- a/ly-core/src/LogFile.zig +++ b/ly-core/src/LogFile.zig @@ -3,50 +3,85 @@ const interop = @import("interop.zig"); const LogFile = @This(); -path: []const u8, +maybe_path: ?[]const u8, could_open_log_file: bool = undefined, -file: std.Io.File = undefined, +maybe_file: ?std.Io.File = null, buffer: []u8, -file_writer: std.Io.File.Writer = undefined, +maybe_file_writer: ?std.Io.File.Writer = null, + +pub fn init(io: std.Io, path: ?[]const u8, buffer: []u8) !LogFile { + var log_file = LogFile{ + .maybe_path = path, + .buffer = buffer, + }; + + if (path) |p| { + log_file.could_open_log_file = try openLogFile(io, p, &log_file); + } else { + std.posix.system.openlog("ly", 0, 0); + log_file.could_open_log_file = true; + } -pub fn init(io: std.Io, path: []const u8, buffer: []u8) !LogFile { - var log_file = LogFile{ .path = path, .buffer = buffer }; - log_file.could_open_log_file = try openLogFile(io, path, &log_file); return log_file; } pub fn reinit(self: *LogFile, io: std.Io) !void { - self.could_open_log_file = try openLogFile(io, self.path, self); + if (self.maybe_path) |path| { + self.could_open_log_file = try openLogFile(io, path, self); + } else { + std.posix.system.openlog("ly", 0, 0); + self.could_open_log_file = true; + } } pub fn deinit(self: *LogFile, io: std.Io) void { - self.file.close(io); + if (self.maybe_file) |file| { + file.close(io); + } else { + std.posix.system.closelog(); + } } pub fn info(self: *LogFile, io: std.Io, category: []const u8, comptime message: []const u8, args: anytype) !void { - var buffer: [128:0]u8 = undefined; - const time = interop.timeAsString(io, &buffer, "%Y-%m-%d %H:%M:%S"); + if (self.maybe_file_writer) |*writer| { + var buffer: [128:0]u8 = undefined; + const time = interop.timeAsString(io, &buffer, "%Y-%m-%d %H:%M:%S"); - try self.file_writer.interface.print("{s} [info/{s}] ", .{ time, category }); - try self.file_writer.interface.print(message, args); - try self.file_writer.interface.writeByte('\n'); - try self.file_writer.interface.flush(); + try writer.interface.print("{s} [info/{s}] ", .{ time, category }); + try writer.interface.print(message, args); + try writer.interface.writeByte('\n'); + try writer.interface.flush(); + } else { + var buffer: [1024]u8 = undefined; + const slice = try std.fmt.bufPrint(&buffer, message, args); + const msg = try std.fmt.bufPrintZ(buffer[slice.len..], "[info/{s}] {s}", .{ category, slice }); + + std.posix.system.syslog(std.posix.LOG.INFO, msg.ptr); + } } pub fn err(self: *LogFile, io: std.Io, category: []const u8, comptime message: []const u8, args: anytype) !void { - var buffer: [128:0]u8 = undefined; - const time = interop.timeAsString(io, &buffer, "%Y-%m-%d %H:%M:%S"); + if (self.maybe_file_writer) |*writer| { + var buffer: [128:0]u8 = undefined; + const time = interop.timeAsString(io, &buffer, "%Y-%m-%d %H:%M:%S"); - try self.file_writer.interface.print("{s} [err/{s}] ", .{ time, category }); - try self.file_writer.interface.print(message, args); - try self.file_writer.interface.writeByte('\n'); - try self.file_writer.interface.flush(); + try writer.interface.print("{s} [err/{s}] ", .{ time, category }); + try writer.interface.print(message, args); + try writer.interface.writeByte('\n'); + try writer.interface.flush(); + } else { + var buffer: [1024]u8 = undefined; + const slice = try std.fmt.bufPrint(&buffer, message, args); + const msg = try std.fmt.bufPrintZ(buffer[slice.len..], "[info/{s}] {s}", .{ category, slice }); + + std.posix.system.syslog(std.posix.LOG.ERR, msg.ptr); + } } fn openLogFile(io: std.Io, path: []const u8, log_file: *LogFile) !bool { var could_open_log_file = true; open_log_file: { - log_file.file = std.Io.Dir.cwd().openFile(io, path, .{ .mode = .write_only }) catch std.Io.Dir.cwd().createFile(io, path, .{ .permissions = .fromMode(0o666) }) catch { + log_file.maybe_file = std.Io.Dir.cwd().openFile(io, path, .{ .mode = .write_only }) catch std.Io.Dir.cwd().createFile(io, path, .{ .permissions = .fromMode(0o666) }) catch { // If we could neither open an existing log file nor create a new // one, abort. could_open_log_file = false; @@ -55,17 +90,17 @@ fn openLogFile(io: std.Io, path: []const u8, log_file: *LogFile) !bool { } if (!could_open_log_file) { - log_file.file = try std.Io.Dir.openFileAbsolute(io, "/dev/null", .{ .mode = .write_only }); + log_file.maybe_file = try std.Io.Dir.openFileAbsolute(io, "/dev/null", .{ .mode = .write_only }); } - var log_file_writer = log_file.file.writer(io, log_file.buffer); + var log_file_writer = log_file.maybe_file.?.writer(io, log_file.buffer); // Seek to the end of the log file if (could_open_log_file) { - const stat = try log_file.file.stat(io); + const stat = try log_file.maybe_file.?.stat(io); try log_file_writer.seekTo(stat.size); } - log_file.file_writer = log_file_writer; + log_file.maybe_file_writer = log_file_writer; return could_open_log_file; } diff --git a/ly-core/src/interop.zig b/ly-core/src/interop.zig index f23583c..d894485 100644 --- a/ly-core/src/interop.zig +++ b/ly-core/src/interop.zig @@ -1,5 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); +const build_options = @import("build_options"); const UidRange = @import("UidRange.zig"); const pwd = @import("pwd"); const stdlib = @import("stdlib"); @@ -13,6 +14,9 @@ pub const utmp = @import("utmp"); // Exists for X11 support only pub const xcb = @import("xcb"); +// FreeBSD only +pub const sysctl = @import("sysctl"); + pub const TimeOfDay = struct { seconds: i64, microseconds: i64, @@ -24,7 +28,7 @@ pub const UsernameEntry = struct { gid: std.posix.gid_t, home: ?[]const u8, shell: ?[]const u8, - passwd_struct: [*c]pwd.passwd, + passwd_struct: [*]pwd.passwd, }; // Contains the platform-specific code @@ -145,25 +149,50 @@ fn PlatformStruct() type { var iterator = std.mem.splitScalar(u8, login_defs_buffer, '\n'); var uid_range = UidRange{}; - var nameFound = false; + var uid_min_Found = false; + var uid_max_Found = false; while (iterator.next()) |line| { const trimmed_line = std.mem.trim(u8, line, " \n\r\t"); if (std.mem.startsWith(u8, trimmed_line, "UID_MIN")) { uid_range.uid_min = try parseValue(std.posix.uid_t, "UID_MIN", trimmed_line); - nameFound = true; + uid_min_Found = true; } else if (std.mem.startsWith(u8, trimmed_line, "UID_MAX")) { uid_range.uid_max = try parseValue(std.posix.uid_t, "UID_MAX", trimmed_line); - nameFound = true; + uid_max_Found = true; } } - if (!nameFound) return error.UidNameNotFound; + if (!(uid_min_Found or uid_max_Found)) { + return error.UidNameNotFound; + } + + if (!uid_min_Found) { + uid_range.uid_min = build_options.fallback_uid_min; + } + + if (!uid_max_Found) { + uid_range.uid_max = build_options.fallback_uid_max; + } return uid_range; } + pub fn shutdownSystemImpl() !void { + std.posix.system.sync(); + if (isError(std.os.linux.reboot(.MAGIC1, .MAGIC2, .POWER_OFF, null))) { + return error.CouldntShutdown; + } + } + + pub fn rebootSystemImpl() !void { + std.posix.system.sync(); + if (isError(std.os.linux.reboot(.MAGIC1, .MAGIC2, .RESTART, null))) { + return error.CouldntShutdown; + } + } + fn parseValue(comptime T: type, name: []const u8, buffer: []const u8) !T { var iterator = std.mem.splitAny(u8, buffer, " \t"); var maybe_value: ?T = null; @@ -194,6 +223,7 @@ fn PlatformStruct() type { .freebsd => struct { pub const kbio = @import("kbio"); pub const consio = @import("consio"); + pub const reboot = @import("reboot"); pub const LedState = c_int; pub const get_led_state = kbio.KDGETLED; @@ -228,6 +258,18 @@ fn PlatformStruct() type { .uid_max = FREEBSD_UID_MAX, }; } + + pub fn shutdownSystemImpl() !void { + if (isError(unistd.reboot(reboot.RB_POWEROFF))) { + return error.CouldntShutdown; + } + } + + pub fn rebootSystemImpl() !void { + if (isError(unistd.reboot(reboot.RB_AUTOBOOT))) { + return error.CouldntReboot; + } + } }, else => @compileError("Unsupported target: " ++ builtin.os.tag), }; @@ -235,7 +277,6 @@ fn PlatformStruct() type { const platform_struct = PlatformStruct(); -// TODO 0.16.0: Can we get away with this? pub fn isError(result: anytype) bool { if (@typeInfo(@TypeOf(result)).int.signedness == .signed) { return result < 0; @@ -340,8 +381,8 @@ pub fn setEnvironmentVariable(allocator: std.mem.Allocator, name: []const u8, va if (status != 0) return error.SetEnvironmentVariableFailed; } -pub fn putEnvironmentVariable(name_and_value: [*c]u8) !void { - const status = stdlib.putenv(name_and_value); +pub fn putEnvironmentVariable(name_and_value: []u8) !void { + const status = stdlib.putenv(name_and_value.ptr); if (status != 0) return error.PutEnvironmentVariableFailed; } @@ -382,3 +423,11 @@ pub fn closePasswordDatabase() void { pub fn getUserIdRange(allocator: std.mem.Allocator, io: std.Io, file_path: []const u8) !UidRange { return platform_struct.getUserIdRange(allocator, io, file_path); } + +pub fn shutdownSystem() !void { + try platform_struct.shutdownSystemImpl(); +} + +pub fn rebootSystem() !void { + try platform_struct.rebootSystemImpl(); +} diff --git a/ly-ui/build.zig b/ly-ui/build.zig index 7397873..b13633f 100644 --- a/ly-ui/build.zig +++ b/ly-ui/build.zig @@ -11,10 +11,15 @@ pub fn build(b: *std.Build) void { .optimize = optimize, }); + const fallback_uid_min = b.option(std.posix.uid_t, "fallback_uid_min", "Set the fallback minimum UID (default is 1000). This value gets embedded into the binary"); + const fallback_uid_max = b.option(std.posix.uid_t, "fallback_uid_max", "Set the fallback maximum UID (default is 60000). This value gets embedded into the binary"); + const ly_core = b.dependency("ly_core", .{ .target = target, .optimize = optimize, .enable_x11_support = enable_x11_support, + .fallback_uid_min = fallback_uid_min, + .fallback_uid_max = fallback_uid_max, }); mod.addImport("ly-core", ly_core.module("ly-core")); @@ -25,7 +30,6 @@ pub fn build(b: *std.Build) void { const translate_c_dep = b.dependency("translate_c", .{ .target = target, - .optimize = optimize, }); const termbox2: Translator = .init(translate_c_dep, .{ diff --git a/ly-ui/build.zig.zon b/ly-ui/build.zig.zon index 2ec2741..68131d1 100644 --- a/ly-ui/build.zig.zon +++ b/ly-ui/build.zig.zon @@ -1,6 +1,6 @@ .{ .name = .ly_ui, - .version = "1.0.1", + .version = "1.1.0", .fingerprint = 0x8d11bf85a74ec803, .minimum_zig_version = "0.16.0", .dependencies = .{ @@ -12,8 +12,8 @@ .hash = "N-V-__8AAAUXBQD6Fwpi9m0MBqWXFFaqW5l1lVrJC2Ynj7a-", }, .translate_c = .{ - .url = "git+https://codeberg.org/ziglang/translate-c#7a1a9fdc4ab00835748a6657ecbb835e3d5d45f7", - .hash = "translate_c-0.0.0-Q_BUWvP1BgCjAk6PWv5286tOlvzD9-X-NkuTzh0KxY0Q", + .url = "git+https://codeberg.org/ziglang/translate-c?ref=zig-0.16.x#6fe0ffc4549f15c5f2d9432c2b4460ba90ff85ac", + .hash = "translate_c-1.0.0-Q_BUWo_5BgD4flHdUhA31zOz0XvZk9k7lQv1ouzyNXj2", }, }, .paths = .{ diff --git a/ly-ui/src/Cell.zig b/ly-ui/src/Cell.zig index 35d0cf0..59eb4aa 100644 --- a/ly-ui/src/Cell.zig +++ b/ly-ui/src/Cell.zig @@ -14,8 +14,8 @@ pub fn init(ch: u32, fg: u32, bg: u32) Cell { }; } -pub fn put(self: Cell, x: usize, y: usize) void { +pub fn put(self: Cell, x: usize, y: usize) !void { if (self.ch == 0) return; - TerminalBuffer.setCell(x, y, self); + try TerminalBuffer.setCell(x, y, self); } diff --git a/ly-ui/src/TerminalBuffer.zig b/ly-ui/src/TerminalBuffer.zig index 1fd9999..4881a2e 100644 --- a/ly-ui/src/TerminalBuffer.zig +++ b/ly-ui/src/TerminalBuffer.zig @@ -103,24 +103,55 @@ pub fn init( random: Random, ) !TerminalBuffer { // Initialize termbox - _ = termbox.tb_init(); - - if (options.full_color) { - _ = termbox.tb_set_output_mode(termbox.TB_OUTPUT_TRUECOLOR); - try log_file.info(io, "tui", "termbox2 set to 24-bit color output mode", .{}); - } else { - try log_file.info(io, "tui", "termbox2 set to eight-color output mode", .{}); + var err = termbox.tb_init(); + if (err != 0) { + try log_file.err( + io, + "tui", + "failed to initialise termbox2: {s}, term: {s}", + .{ termbox.tb_strerror(err), std.c.getenv("TERM").? }, + ); + return error.TermboxInitFailed; } - _ = termbox.tb_clear(); + if (options.full_color) { + err = termbox.tb_set_output_mode(termbox.TB_OUTPUT_TRUECOLOR); + if (err != 0) { + try log_file.err( + io, + "tui", + "failed to set termbox2 output mode to 24-bit color: {s}", + .{termbox.tb_strerror(err)}, + ); + return error.TermboxSetOutputModeFailed; + } + try log_file.info( + io, + "tui", + "termbox2 set to 24-bit color output mode", + .{}, + ); + } else { + try log_file.info( + io, + "tui", + "termbox2 set to eight-color output mode", + .{}, + ); + } // Let's take some precautions here and clear the back buffer as well - try clearBackBuffer(); + try clearScreen(true); - const width: usize = @intCast(termbox.tb_width()); - const height: usize = @intCast(termbox.tb_height()); + const width = getWidth(); + const height = getHeight(); - try log_file.info(io, "tui", "screen resolution is {d}x{d}", .{ width, height }); + try log_file.info( + io, + "tui", + "screen resolution is {d}x{d}", + .{ width, height }, + ); return .{ .log_file = log_file, @@ -163,7 +194,7 @@ pub fn init( pub fn deinit(self: *TerminalBuffer) void { self.keybinds.deinit(); - TerminalBuffer.shutdown(); + TerminalBuffer.shutdown() catch {}; } pub fn runEventLoop( @@ -238,7 +269,8 @@ pub fn runEventLoop( } } - TerminalBuffer.presentBuffer(); + // We don't care about present errors here + TerminalBuffer.presentBuffer() catch {}; } if (inactivity_event_fn) |inactivity_fn| { @@ -338,31 +370,35 @@ pub fn getHeight() usize { return @intCast(termbox.tb_height()); } -pub fn setCursor(x: usize, y: usize) void { - _ = termbox.tb_set_cursor(@intCast(x), @intCast(y)); +pub fn setCursor(x: usize, y: usize) !void { + if (termbox.tb_set_cursor(@intCast(x), @intCast(y)) != 0) { + return error.TermboxSetCursorFailed; + } } pub fn clearScreen(clear_back_buffer: bool) !void { - _ = termbox.tb_clear(); + if (termbox.tb_clear() != 0) return error.TermboxClearFailed; if (clear_back_buffer) try clearBackBuffer(); } -pub fn shutdown() void { - _ = termbox.tb_shutdown(); +pub fn shutdown() !void { + if (termbox.tb_shutdown() != 0) return error.TermboxShutdownFailed; } -pub fn presentBuffer() void { - _ = termbox.tb_present(); +pub fn presentBuffer() !void { + if (termbox.tb_present() != 0) return error.TermboxPresentFailed; } pub fn getCell(x: usize, y: usize) ?Cell { var maybe_cell: ?*termbox.tb_cell = undefined; - _ = termbox.tb_get_cell( + if (termbox.tb_get_cell( @intCast(x), @intCast(y), 1, &maybe_cell, - ); + ) != 0) { + return null; + } if (maybe_cell) |cell| { return Cell.init(cell.ch, cell.fg, cell.bg); @@ -371,29 +407,32 @@ pub fn getCell(x: usize, y: usize) ?Cell { return null; } -pub fn setCell(x: usize, y: usize, cell: Cell) void { - _ = termbox.tb_set_cell( +pub fn setCell(x: usize, y: usize, cell: Cell) !void { + if (termbox.tb_set_cell( @intCast(x), @intCast(y), cell.ch, cell.fg, cell.bg, - ); + ) != 0) { + return error.TermboxSetCellFailed; + } } -pub fn setCellBoundsChecked(self: *TerminalBuffer, x: isize, y: isize, cell: Cell) void { +pub fn setCellBoundsChecked(self: *TerminalBuffer, x: isize, y: isize, cell: Cell) !void { if (0 <= x and x < self.width and 0 <= y and y < self.height) { - cell.put(@intCast(x), @intCast(y)); + try cell.put(@intCast(x), @intCast(y)); } } pub fn reclaim(self: TerminalBuffer) !void { if (self.termios) |termios| { // Take back control of the TTY - _ = termbox.tb_init(); + const err = termbox.tb_init(); + if (err != 0 and err != termbox.TB_ERR_INIT_ALREADY) return error.TermboxReinitFailed; - if (self.full_color) { - _ = termbox.tb_set_output_mode(termbox.TB_OUTPUT_TRUECOLOR); + if (self.full_color and termbox.tb_set_output_mode(termbox.TB_OUTPUT_TRUECOLOR) != 0) { + return error.TermboxSetOutputModeFailed; } try std.posix.tcsetattr(std.posix.STDIN_FILENO, .FLUSH, termios); @@ -464,14 +503,14 @@ pub fn drawText( y: usize, fg: u32, bg: u32, -) void { - const yc: c_int = @intCast(y); +) !void { const utf8view = std.unicode.Utf8View.init(text) catch return; var utf8 = utf8view.iterator(); - var i: c_int = @intCast(x); - while (utf8.nextCodepoint()) |codepoint| : (i += termbox.tb_wcwidth(codepoint)) { - _ = termbox.tb_set_cell(i, yc, codepoint, fg, bg); + var i = x; + while (utf8.nextCodepoint()) |codepoint| : (i += @intCast(termbox.tb_wcwidth(codepoint))) { + const cell = Cell.init(codepoint, fg, bg); + try cell.put(i, y); } } @@ -482,15 +521,16 @@ pub fn drawConfinedText( max_length: usize, fg: u32, bg: u32, -) void { - const yc: c_int = @intCast(y); +) !void { const utf8view = std.unicode.Utf8View.init(text) catch return; var utf8 = utf8view.iterator(); - var i: c_int = @intCast(x); - while (utf8.nextCodepoint()) |codepoint| : (i += termbox.tb_wcwidth(codepoint)) { - if (i - @as(c_int, @intCast(x)) >= max_length) break; - _ = termbox.tb_set_cell(i, yc, codepoint, fg, bg); + var i = x; + while (utf8.nextCodepoint()) |codepoint| : (i += @intCast(termbox.tb_wcwidth(codepoint))) { + if (i - x >= max_length) break; + + const cell = Cell.init(codepoint, fg, bg); + try cell.put(i, y); } } @@ -501,9 +541,9 @@ pub fn drawCharMultiple( length: usize, fg: u32, bg: u32, -) void { +) !void { const cell = Cell.init(char, fg, bg); - for (0..length) |xx| cell.put(x + xx, y); + for (0..length) |xx| try cell.put(x + xx, y); } // Every codepoint is assumed to have a width of 1. @@ -521,6 +561,8 @@ pub fn strWidth(str: []const u8) usize { } fn clearBackBuffer() !void { + if (termbox.global.initialized == 0) return; + // Clear the TTY because termbox2 doesn't seem to do it properly const capability = termbox.global.caps[termbox.TB_CAP_CLEAR_SCREEN]; const capability_slice = std.mem.span(capability); @@ -537,9 +579,9 @@ fn parseKeybind(self: *TerminalBuffer, io: std.Io, keybind: []const u8) !keyboar while (iterator.next()) |item| { var found = false; - inline for (std.meta.fields(keyboard.Key)) |field| { - if (std.ascii.eqlIgnoreCase(field.name, item)) { - @field(key, field.name) = true; + inline for (comptime std.meta.fieldNames(keyboard.Key)) |name| { + if (std.ascii.eqlIgnoreCase(name, item)) { + @field(key, name) = true; found = true; break; } diff --git a/ly-ui/src/components/BigLabel.zig b/ly-ui/src/components/BigLabel.zig index bd9af6e..cb2f6b5 100644 --- a/ly-ui/src/components/BigLabel.zig +++ b/ly-ui/src/components/BigLabel.zig @@ -207,7 +207,7 @@ fn alphaBlit(x: usize, y: usize, tb_width: usize, tb_height: usize, cells: [CHAR for (0..CHAR_HEIGHT) |yy| { for (0..CHAR_WIDTH) |xx| { const cell = cells[yy * CHAR_WIDTH + xx]; - cell.put(x + xx, y + yy); + cell.put(x + xx, y + yy) catch {}; } } } diff --git a/ly-ui/src/components/Box.zig b/ly-ui/src/components/Box.zig index 7c753ae..af3a687 100644 --- a/ly-ui/src/components/Box.zig +++ b/ly-ui/src/components/Box.zig @@ -129,29 +129,29 @@ fn draw(self: *Box) void { self.bg, ); - left_up.put(self.left_pos.x - 1, self.left_pos.y - 1); - right_up.put(self.right_pos.x, self.left_pos.y - 1); - left_down.put(self.left_pos.x - 1, self.right_pos.y); - right_down.put(self.right_pos.x, self.right_pos.y); + left_up.put(self.left_pos.x - 1, self.left_pos.y - 1) catch {}; + right_up.put(self.right_pos.x, self.left_pos.y - 1) catch {}; + left_down.put(self.left_pos.x - 1, self.right_pos.y) catch {}; + right_down.put(self.right_pos.x, self.right_pos.y) catch {}; for (0..self.width) |i| { - top.put(self.left_pos.x + i, self.left_pos.y - 1); - bottom.put(self.left_pos.x + i, self.right_pos.y); + top.put(self.left_pos.x + i, self.left_pos.y - 1) catch {}; + bottom.put(self.left_pos.x + i, self.right_pos.y) catch {}; } top.ch = self.buffer.box_chars.left; bottom.ch = self.buffer.box_chars.right; for (0..self.height) |i| { - top.put(self.left_pos.x - 1, self.left_pos.y + i); - bottom.put(self.right_pos.x, self.left_pos.y + i); + top.put(self.left_pos.x - 1, self.left_pos.y + i) catch {}; + bottom.put(self.right_pos.x, self.left_pos.y + i) catch {}; } } if (self.blank_box) { for (0..self.height) |y| { for (0..self.width) |x| { - self.buffer.blank_cell.put(self.left_pos.x + x, self.left_pos.y + y); + self.buffer.blank_cell.put(self.left_pos.x + x, self.left_pos.y + y) catch {}; } } } @@ -164,7 +164,7 @@ fn draw(self: *Box) void { self.width, self.title_fg, self.bg, - ); + ) catch {}; } if (self.bottom_title) |title| { @@ -175,7 +175,7 @@ fn draw(self: *Box) void { self.width, self.title_fg, self.bg, - ); + ) catch {}; } } diff --git a/ly-ui/src/components/Label.zig b/ly-ui/src/components/Label.zig index 9874fcb..d54cb9c 100644 --- a/ly-ui/src/components/Label.zig +++ b/ly-ui/src/components/Label.zig @@ -117,7 +117,7 @@ fn draw(self: *Label) void { width, self.fg, self.bg, - ); + ) catch {}; return; } @@ -127,7 +127,7 @@ fn draw(self: *Label) void { self.component_pos.y, self.fg, self.bg, - ); + ) catch {}; } fn update(self: *Label, ctx: *anyopaque) !void { diff --git a/ly-ui/src/components/Text.zig b/ly-ui/src/components/Text.zig index 4fc35bf..875021a 100644 --- a/ly-ui/src/components/Text.zig +++ b/ly-ui/src/components/Text.zig @@ -6,7 +6,7 @@ const TerminalBuffer = @import("../TerminalBuffer.zig"); const Position = @import("../Position.zig"); const Widget = @import("../Widget.zig"); -const DynamicString = std.ArrayListUnmanaged(u8); +const DynamicString = std.ArrayList(u8); const Text = @This(); @@ -131,19 +131,23 @@ pub fn handle(self: *Text, maybe_key: ?keyboard.Key) !void { } if (self.masked and self.maybe_mask == null) { - TerminalBuffer.setCursor( + try TerminalBuffer.setCursor( self.component_pos.x, self.component_pos.y, ); return; } - TerminalBuffer.setCursor( + try TerminalBuffer.setCursor( self.component_pos.x + (self.cursor - self.visible_start), self.component_pos.y, ); } +pub fn writeText(self: *Text, str: []const u8) !void { + for (str) |c| try self.write(c); +} + fn draw(self: *Text) void { if (self.masked) { if (self.maybe_mask) |mask| { @@ -159,7 +163,7 @@ fn draw(self: *Text) void { length, self.fg, self.bg, - ); + ) catch {}; } return; } @@ -182,7 +186,7 @@ fn draw(self: *Text) void { self.component_pos.y, self.fg, self.bg, - ); + ) catch {}; } fn goLeft(ptr: *anyopaque) !bool { diff --git a/ly-ui/src/components/generic.zig b/ly-ui/src/components/generic.zig index 0a76c4f..2d0b3c4 100644 --- a/ly-ui/src/components/generic.zig +++ b/ly-ui/src/components/generic.zig @@ -8,7 +8,7 @@ const Position = @import("../Position.zig"); pub fn CyclableLabel(comptime ItemType: type, comptime ChangeItemType: type) type { return struct { const Allocator = std.mem.Allocator; - const ItemList = std.ArrayListUnmanaged(ItemType); + const ItemList = std.ArrayList(ItemType); const DrawItemFn = *const fn (*Self, ItemType, usize, usize, usize) void; const ChangeItemFn = *const fn (ItemType, ?ChangeItemType) void; @@ -105,8 +105,8 @@ pub fn CyclableLabel(comptime ItemType: type, comptime ChangeItemType: type) typ self.current = self.list.items.len - 1; } - pub fn handle(self: *Self, _: ?keyboard.Key) void { - TerminalBuffer.setCursor( + pub fn handle(self: *Self, _: ?keyboard.Key) !void { + try TerminalBuffer.setCursor( self.component_pos.x + self.cursor + 2, self.component_pos.y, ); @@ -119,11 +119,11 @@ pub fn CyclableLabel(comptime ItemType: type, comptime ChangeItemType: type) typ var left_arrow = Cell.init('<', self.fg, self.bg); var right_arrow = Cell.init('>', self.fg, self.bg); - left_arrow.put(self.component_pos.x, self.component_pos.y); + left_arrow.put(self.component_pos.x, self.component_pos.y) catch {}; right_arrow.put( self.component_pos.x + self.width - 1, self.component_pos.y, - ); + ) catch {}; const current_item = self.list.items[self.current]; const x = self.component_pos.x + 2; diff --git a/ly-ui/src/keyboard.zig b/ly-ui/src/keyboard.zig index a90148b..16b9e77 100644 --- a/ly-ui/src/keyboard.zig +++ b/ly-ui/src/keyboard.zig @@ -113,14 +113,14 @@ pub const Key = packed struct { pub fn getEnabledPrintableAscii(self: Key) ?u8 { if (self.ctrl or self.alt) return null; - inline for (std.meta.fields(Key)) |field| { - if (field.name.len == 1 and std.ascii.isPrint(field.name[0]) and @field(self, field.name)) { + inline for (comptime std.meta.fieldNames(Key)) |name| { + if (name.len == 1 and std.ascii.isPrint(name[0]) and @field(self, name)) { if (self.shift) { - if (!std.ascii.isAlphanumeric(field.name[0])) return null; - return std.ascii.toUpper(field.name[0]); + if (!std.ascii.isAlphanumeric(name[0])) return null; + return std.ascii.toUpper(name[0]); } - return field.name[0]; + return name[0]; } } @@ -167,6 +167,12 @@ pub fn getKeyList(allocator: Allocator, tb_event: termbox.tb_event) !KeyList { 21 => key.right = true, else => {}, } + + if (code >= 18 and code <= 21) { + // https://github.com/termbox/termbox2/blob/605398fa79108412976191e062ea14bd4bd30213/termbox2.h#L446 + key.ctrl = false; + key.shift = false; + } } else if (tb_event.ch < 128) { const code = if (tb_event.ch == 0 and tb_event.key < 128) tb_event.key else tb_event.ch; diff --git a/readme.md b/readme.md index aa23db8..2d26c31 100644 --- a/readme.md +++ b/readme.md @@ -2,7 +2,7 @@ ![Ly screenshot](.github/screenshot.png "Ly screenshot") -_Note: the above animation can be found [here](https://codeberg.org/attachments/f336d6ac-8331-4323-91fc-0e4619803401)!_ +_Note: the above animation can be found [here](https://codeberg.org/fairyglade/ly-community/src/branch/main/animations/dur/blackhole-smooth-240x67.dur)!_ Ly is a lightweight TUI (ncurses-like) display manager for Linux and BSD, designed with portability in mind and doesn't require systemd to run. @@ -14,7 +14,7 @@ Join us on Matrix over at [#ly-dm:matrix.org](https://matrix.to/#/#ly-dm:matrix. ## Dependencies - Compile-time: - - zig 0.16.x + - zig 0.16.x (you must use a **release version** of zig; check that `zig version` does not have a `-dev*` suffix) - libc @@ -39,13 +39,38 @@ Join us on Matrix over at [#ly-dm:matrix.org](https://matrix.to/#/#ly-dm:matrix. ### Fedora -> [!WARNING] -> You may encounter issues with SELinux on Fedora. It is recommended to add a rule for Ly as it currently does not ship one. - ``` # dnf install kernel-devel pam-devel libxcb-devel zig xorg-x11-xauth xorg-x11-server brightnessctl ``` +> [!WARNING] +> Distributions using SELinux such as Fedora and openSUSE Tumbleweed may encounter issues. If you encounter such issues, such as session launch failures, proceed with the following steps: +> +> ``` +> # ausearch -m avc -ts recent +> ``` +> +> If SELinux is denying process context transition, you will see this output: +> +> ``` +> denied { transition } for pid=XXXX comm="ly" path="/usr/bin/bash" +> scontext=system_u:system_r:unconfined_service_t:s0 +> tcontext=unconfined_u:unconfined_r:unconfined_t:s0 +> tclass=process permissive=0 +> ``` +> +> Pipe this output into `audit2allow` to generate a security module package. This will persist regardless of changes to filesystem permissions: +> +> ``` +> # ausearch -m avc -ts recent | audit2allow -M ly-local +> ``` +> +> ``` +> # semodule -i ly-local.pp +> ``` +> +> _This fix has been confirmed on Fedora 39 and 44 and openSUSE Tumbleweed. (#494)_ + ### FreeBSD ``` @@ -56,6 +81,10 @@ Join us on Matrix over at [#ly-dm:matrix.org](https://matrix.to/#/#ly-dm:matrix. [![Packaging status](https://repology.org/badge/vertical-allrepos/ly-display-manager.svg?exclude_unsupported=1)](https://repology.org/project/ly-display-manager/versions) +## Custom animations & user scripts + +If you want to pimp your Ly installation even further than what the traditional configuration file allows you to, a [community repository](https://codeberg.org/fairyglade/ly-community) exists containing custom animations & scripts, so go check it out! + ## Support Every environment that works on other login managers also should work on Ly. @@ -95,6 +124,9 @@ $ zig build run > [!IMPORTANT] > While you can run Ly in a terminal emulator as root, it is **not** recommended. If you want to test Ly, please enable its service (as described below) and reboot your machine. +> [!NOTE] +> You can, however, test your configuration file changes like that. Note that you must do Ctrl+C in order to exit Ly. + The next sections will explain how to use Ly with a variety of init systems. Detailed explanation is only given for systemd, but should be applicable for all. > [!NOTE] @@ -130,12 +162,6 @@ Then, similarly to the previous command, you need to enable the Ly service: # systemctl disable getty@tty2.service ``` -On platforms that use systemd-logind to dynamically start `autovt@.service` instances when the switch to a new tty occurs, any ly instances for ttys _except the default tty_ need to be enabled using a different mechanism: To autostart ly on switch to `tty2`, do not enable any `ly` unit directly, instead symlink `autovt@tty2.service` to `ly@tty2.service` within `/usr/lib/systemd/system/` (analogous for every other tty you want to enable ly on). - -The target of the symlink, `ly@ttyN.service`, does not actually exist, but systemd nevertheless recognizes that the instanciation of `autovt@.service` with `%I` equal to `ttyN` now points to an instanciation of `ly@.service` with `%I` set to `ttyN`. - -Compare to `man 5 logind.conf`, especially regarding the `NAutoVTs=` and `ReserveVT=` parameters. - On non-systemd systems, you can change the TTY Ly will run on by editing the corresponding service file for your platform. ### OpenRC @@ -148,7 +174,7 @@ On non-systemd systems, you can change the TTY Ly will run on by editing the cor ``` > [!NOTE] -> On Gentoo specifically, you also **must** comment out the appropriate line for the TTY in /etc/inittab. +> On Gentoo, Alpine and potentially others, you also **must** comment out the appropriate line for the TTY in /etc/inittab. ### runit @@ -214,7 +240,7 @@ ttyv1 "/usr/libexec/getty Ly" xterm on secure ### Updating -You can also install Ly without overrding the current configuration file. This is called **updating**. To update, simply run: +You can also install Ly without overriding the current configuration file. This is called **updating**. To update, simply run: ``` # zig build installnoconf @@ -226,13 +252,19 @@ You can, of course, still select the init system of your choice when using this You can find all the configuration in `/etc/ly/config.ini`. The file is fully commented, and includes the default values. +You may also check the validity of your configuration file (i.e. if there are any errors in it) with the following command: + +``` +$ ly --validate-config /etc/ly/config.ini +``` + ## Controls Use the Up/Down arrow keys to change the current field, and the Left/Right arrow keys to scroll through the different fields (whether it be the info line, the desktop environment, or the username). The info line is where messages and errors are displayed. ## A note on .xinitrc -If your `.xinitrc` file doesn't work ,make sure it is executable and includes a shebang. This file is supposed to be a shell script! Quoting from `xinit`'s man page: +If your `.xinitrc` file doesn't work, make sure it is executable and includes a shebang. This file is supposed to be a shell script! Quoting from `xinit`'s man page: > If no specific client program is given on the command line, xinit will look for a file in the user's home directory called .xinitrc to run as a shell script to start up client programs. @@ -244,7 +276,7 @@ A typical shebang for a shell script looks like this: ## Tips -- The numlock and capslock state is printed in the top-right corner. +- The numlock and capslock states are printed in the top-right corner. - Use the F1 and F2 keys to respectively shutdown and reboot. diff --git a/res/config.ini b/res/config.ini index 86f44b4..2bd2624 100644 --- a/res/config.ini +++ b/res/config.ini @@ -25,6 +25,7 @@ allow_empty_password = true # colormix -> Color mixing shader # gameoflife -> John Conway's Game of Life # dur_file -> .dur file format (https://github.com/cmang/durdraw/tree/master) +# lua -> user-made animation written in LuaJIT animation = none # Delay between each animation frame in milliseconds @@ -46,11 +47,6 @@ asterisk = * # If set to 0, the animation will never be played auth_fails = 10 -# Identifier for battery whose charge to display at top left -# Primary battery is usually BAT0 or BAT1 -# If set to null, battery status won't be shown -battery_id = null - # Automatic login configuration # This feature allows Ly to automatically log in a user without password prompt. # IMPORTANT: Both auto_login_user and auto_login_session must be set for this to work. @@ -75,6 +71,12 @@ auto_login_session = null # If null, automatic login is disabled auto_login_user = null +# Identifier for battery whose charge to display at top left +# Primary battery is usually BAT0 or BAT1 +# If set to null, battery status won't be shown +# Unused on FreeBSD (a sysctl is used there) +battery_id = null + # Background color id bg = 0x00000000 @@ -97,6 +99,14 @@ blank_box = true # Border foreground color id border_fg = 0x00FFFFFF +# Relative horizontal position from the end of the screen +# default: 0.5 +box_position_h = 0.5 + +# Relative vertical position from the bottom of the screen +# default: 0.5 +box_position_v = 0.5 + # Title to show at the top of the main box # If set to null, none will be shown box_title = null @@ -104,13 +114,15 @@ box_title = null # Brightness decrease command brightness_down_cmd = $PREFIX_DIRECTORY/bin/brightnessctl -q -n s 10%- -# Brightness decrease key combination, or null to disable +# Brightness decrease key combination +# If null, the keybind is disabled and isn't shown brightness_down_key = F5 # Brightness increase command brightness_up_cmd = $PREFIX_DIRECTORY/bin/brightnessctl -q -n s +10% -# Brightness increase key combination, or null to disable +# Brightness increase key combination +# If null, the keybind is disabled and isn't shown brightness_up_key = F6 # Erase password input on failure @@ -143,6 +155,43 @@ colormix_col2 = 0x000000FF # Color mixing animation third color id colormix_col3 = 0x20000000 +# Screen corners customization +# Keywords: +# shutdown -> Shutdown key +# restart -> Restart key +# britup -> Brightness up key +# britdown -> Brightness down key +# password -> Toggle password key +# clock -> Clock (format defined by 'clock' option) +# tty -> Active TTY number +# battery -> Battery percentage +# version -> Ly version string +# numlock -> Numlock state +# capslock -> Capslock state +# labels -> All custom info labels (lbl:) +# binds -> All custom keybind hints (cmd:) +# lbl:name -> Specific custom info label +# cmd:key -> Specific custom keybind hint +# +# If using a keyword that groups multiple labels into one (e.g. labels, binds), +# they'll be placed horizontally +# +# Also, the order defines the vertical stack (first item is at the edge) +# If items are separted by commas, they'll be placed horizontally +# It is possible to have both horizontal and vertical items on the same corner + +# Bottom left +corner_bottom_left = version + +# Bottom right +corner_bottom_right = labels + +# Top left +corner_top_left = shutdown,restart,britup,britdown,password battery + +# Top right +corner_top_right = clock numlock,capslock + # For custom binds: the horizontal limit in characters for each # line of custom binds before moving on to the next. # If null, defaults to the width of the terminal instead. @@ -238,24 +287,9 @@ gameoflife_frame_delay = 6 # 0.7+ -> Dense, chaotic patterns gameoflife_initial_density = 0.4 -# Command executed when pressing hibernate key (can be null) -hibernate_cmd = null - -# Specifies the key combination used for hibernate -hibernate_key = F4 - # Remove main box borders hide_borders = false -# Remove power management command hints -hide_key_hints = false - -# Remove keyboard lock states from the top right corner -hide_keyboard_locks = false - -# Remove version number from the top left corner -hide_version_string = false - # Command executed when no input is detected for a certain time # If null, no command will be executed inactivity_cmd = null @@ -290,7 +324,11 @@ login_defs_path = /etc/login.defs # no need to add `exec "$@"` at the end logout_cmd = null +# The file pointing to the Lua file to be used when using the Lua animation option +lua_animation_file = $CONFIG_DIRECTORY/ly/example.lua + # General log file path +# If null, syslog will be used instead ly_log = /var/log/ly.log # Main box horizontal margin @@ -306,14 +344,13 @@ numlock = false # If null, ly doesn't set a path path = /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin -# Command executed when pressing restart_key -restart_cmd = /sbin/shutdown -r now - # Specifies the key combination used for restart +# If null, the keybind is disabled and isn't shown restart_key = F2 -# Save the current desktop and login as defaults, and load them on startup -save = true +# Absolute directory for the save file +# If null, current desktop & login won't be saved nor loaded +save_file_dir = $CONFIG_DIRECTORY/ly # Service name (set to ly to use the provided pam config file) service_name = ly @@ -335,25 +372,13 @@ setup_cmd = $CONFIG_DIRECTORY/ly/setup.sh shell = true # Specifies the key combination used for showing the password +# If null, the keybind is disabled and isn't shown show_password_key = F7 -# Display the active TTY number (e.g. tty3) to the right of the clock in the top right corner -# If the clock is disabled, the TTY label occupies the top right corner on its own -# If false, the TTY number will not be shown -show_tty = false - -# Command executed when pressing shutdown_key -shutdown_cmd = /sbin/shutdown $PLATFORM_SHUTDOWN_ARG now - # Specifies the key combination used for shutdown +# If null, the keybind is disabled and isn't shown shutdown_key = F1 -# Command executed when pressing sleep key (can be null) -sleep_cmd = null - -# Specifies the key combination used for sleep -sleep_key = F3 - # Command executed when starting Ly (before the TTY is taken control of) # See file at path below for an example of changing the default TTY colors start_cmd = $CONFIG_DIRECTORY/ly/startup.sh @@ -361,6 +386,10 @@ start_cmd = $CONFIG_DIRECTORY/ly/startup.sh # Center the session name. text_in_center = false +# If true, user will need to manually type username instead of selecting from the list +# of discovered users +type_username = false + # Default vi mode # normal -> normal mode # insert -> insert mode diff --git a/res/example.lua b/res/example.lua new file mode 100644 index 0000000..81f9bc9 --- /dev/null +++ b/res/example.lua @@ -0,0 +1,119 @@ +-- [[ +-- This is an example of using LuaJIT to create a custom animation in Ly, in this case +-- bouncing squares that change colors. +-- +-- You are given the following `ly` table: +-- { +-- height: number -- The height of the terminal +-- width: number -- The width of the terminal +-- putCell(byte, fg, bg, x, y) -- Draw a cell. +-- All arguments to this function are integers, and +-- must be in the unsigned 32-bit integer range: 0 to 2^32-1. +-- If an argument cannot be converted to this range, it will throw +-- an error. +-- +-- For reference, the XY coordinates (0,0) draw a cell on the top-left +-- of the terminal, where the positive-X axis moves right and the +-- positive-Y axis moves down. +-- +-- For arguments fg and bg: they are colors in the format +-- 0xSSRRGGBB, where SS is for styling. See your +-- config.ini for more details. +-- +-- For the byte argument, you may use string.byte to fill this argument. +-- +-- putRect(byte, fg, bg, x, y, w, h) -- Draw a rectangle. +-- Arguments are the same as putCell except for w and h, which are also +-- unsigned integers. The rectangle will be drawn from the top-left, with +-- argument w extending it to the right and argument h extending downwards. +-- +-- +-- putLabel(str, fg, bg, x, y) -- Draw text in argument str. See putCell() +-- for info on the rest of the arguments. +-- +-- clock() -- The time, in microseconds. +-- } +-- +-- A function named `draw()` must be declared in the script. This is ran every +-- frame. +-- +-- In addition to the base library, you are also given the following standard +-- libraries: +-- bit (A library exclusive to LuaJIT, see https://bitop.luajit.org/api.html) +-- math +-- string +-- table +-- +-- The std libraries io and debug are NOT included. +-- +-- ]] + +-- You should probably copy FPS and FPS_COUNT into any future LuaJIT animations +-- you create. +local FPS_COUNT = 40 +local function FPS() + return (1 / FPS_COUNT) * 1000000 +end + + +local SQUARE_WIDTH = 10 +local SQUARE_HEIGHT = 5 + +local SQUARE_COUNT = 25 + +local squares = {} + +for i = 1, SQUARE_COUNT do + local vx = 1 + local vy = 1 + if math.random(1, 2) == 2 then vx = -vx end + if math.random(1, 2) == 2 then vy = -vy end + squares[#squares + 1] = { + x = math.random(1, ly.width - SQUARE_WIDTH), + y = math.random(1, ly.height - SQUARE_HEIGHT), + vx = vx, + vy = vy, + color = math.random(0xFFFFFF) + } +end + +local timer = ly.clock() +local perf = ly.clock() + +function draw() + -- Rather than progressing the animation by frame, do it based on + -- seconds, via ly.clock(). In this timeframe, you can update the animation + -- state. + -- DO NOT DRAW CELLS IN THIS TIMEFRAME. You will get flickering. + + -- if this check passes, we can update the animation + if timer + FPS() < ly.clock() then + for i, v in ipairs(squares) do + v.x = v.x + v.vx + v.y = v.y + v.vy + if v.x == 0 then + v.vx = 1; v.color = math.random(0xFFFFFF) + end + if v.x + SQUARE_WIDTH >= ly.width - 1 then + v.vx = -1; v.color = math.random(0xFFFFFF) + end + if v.y == 0 then + v.vy = 1; v.color = math.random(0xFFFFFF) + end + if v.y + SQUARE_HEIGHT >= ly.height - 1 then + v.vy = -1; v.color = math.random(0xFFFFFF) + end + end + timer = ly.clock() + end + + + for i, v in ipairs(squares) do + ly.putRect(string.byte(' '), 0, v.color, v.x, v.y, SQUARE_WIDTH, SQUARE_HEIGHT) + end + + local new_perf = ly.clock() + local str = "FT: " .. ((new_perf - perf) / 1000) .. "ms" + ly.putLabel(str, 0x00FFFFFF, 0, (ly.width / 2) - (string.len(str) / 2), ly.height - 1) + perf = new_perf +end diff --git a/res/lang/ar.ini b/res/lang/ar.ini index d8cbecf..fd51b51 100644 --- a/res/lang/ar.ini +++ b/res/lang/ar.ini @@ -2,29 +2,29 @@ authenticating = جاري المصادقة... brightness_down = خفض السطوع brightness_up = رفع السطوع capslock = capslock - - - - +custom = مخصص +custom_info_err_output_long = الإخراج طويل جداً +custom_info_err_no_output = لا يوجد إخراج +custom_info_err_no_output_error = ، خطأ محتمل err_alloc = فشل في تخصيص الذاكرة - - +err_args = تعذر تحليل وسيطات سطر الأوامر +err_autologin_session = لم يتم العثور على جلسة تسجيل الدخول التلقائي err_bounds = out-of-bounds index err_brightness_change = فشل في تغيير سطوع الشاشة err_chdir = فشل في فتح مجلد المنزل - +err_clock_too_long = نص الساعة طويل جداً err_config = فشل في تفسير ملف الإعدادات - +err_crawl = فشل الزحف في أدلة الجلسة err_dgn_oob = رسالة سجل (Log) err_domain = اسم نطاق غير صالح err_empty_password = لا يُسمح بكلمة مرور فارغة err_envlist = فشل في جلب قائمة المتغيرات البيئية - - +err_get_active_tty = فشل الحصول على tty النشط +err_hibernate = فشل تنفيذ أمر الإسبات err_hostname = فشل في جلب اسم المضيف (Hostname) - - - +err_inactivity = فشل تنفيذ أمر عدم النشاط +err_lock_state = فشل الحصول على حالة القفل +err_log = فشل فتح ملف السجل err_mlock = فشل في تأمين ذاكرة كلمة المرور (mlock) err_null = مؤشر فارغ (Null pointer) err_numlock = فشل في ضبط Num Lock @@ -50,12 +50,12 @@ err_perm_group = فشل في تخفيض صلاحيات المجموعة (Group p err_perm_user = فشل في تخفيض صلاحيات المستخدم (User permissions) err_pwnam = فشل في جلب معلومات المستخدم err_sleep = فشل في تنفيذ أمر sleep - - - +err_start = فشل تنفيذ أمر البدء +err_battery = فشل تحميل حالة البطارية +err_switch_tty = فشل تبديل tty err_tty_ctrl = فشل في نقل تحكم الطرفية (TTY) - - +err_no_users = لم يتم العثور على مستخدمين +err_uid_range = فشل الحصول الديناميكي على نطاق uid err_user_gid = فشل في تعيين معرّف المجموعة (GID) للمستخدم err_user_init = فشل في تهيئة بيانات المستخدم err_user_uid = فشل في تعيين معرّف المستخدم (UID) @@ -63,11 +63,11 @@ err_xauth = فشل في تنفيذ أمر xauth err_xcb_conn = فشل في الاتصال بمكتبة XCB err_xsessions_dir = فشل في العثور على مجلد Xsessions err_xsessions_open = فشل في فتح مجلد Xsessions - +hibernate = إسبات insert = ادخال login = تسجيل الدخول logout = تم تسجيل خروجك -no_x11_support = تم تعطيل دعم x11 اثناء وقت الـ compile +no_x11_support = دعم x11 معطّل في وقت الترجمة normal = عادي numlock = numlock other = اخر @@ -76,7 +76,7 @@ restart = اعادة التشغيل shell = shell shutdown = ايقاف التشغيل sleep = وضع السكون - +toggle_password = إظهار/إخفاء كلمة المرور wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/cat.ini b/res/lang/cat.ini index 152cb96..3bf271b 100644 --- a/res/lang/cat.ini +++ b/res/lang/cat.ini @@ -2,29 +2,29 @@ authenticating = autenticant... brightness_down = abaixar brillantor brightness_up = apujar brillantor capslock = Bloq Majús - - - - +custom = personalitzat +custom_info_err_output_long = sortida massa llarga +custom_info_err_no_output = sense sortida +custom_info_err_no_output_error = , possible error err_alloc = assignació de memòria fallida - - +err_args = no s'han pogut analitzar els arguments de la línia d'ordres +err_autologin_session = no s'ha trobat la sessió d'inici de sessió automàtic err_bounds = índex fora de límits err_brightness_change = error en canviar la brillantor err_chdir = error en obrir la carpeta home - - - +err_clock_too_long = la cadena del rellotge és massa llarga +err_config = no s'ha pogut analitzar el fitxer de configuració +err_crawl = no s'han pogut explorar els directoris de sessió err_dgn_oob = missatge de registre err_domain = domini invàlid - +err_empty_password = no es permet la contrasenya buida err_envlist = error en obtenir l'envlist - - +err_get_active_tty = no s'ha pogut obtenir el tty actiu +err_hibernate = no s'ha pogut executar l'ordre d'hibernació err_hostname = error en obtenir el nom de l'amfitrió - - - +err_inactivity = no s'ha pogut executar l'ordre d'inactivitat +err_lock_state = no s'ha pogut obtenir l'estat de bloqueig +err_log = no s'ha pogut obrir el fitxer de registre err_mlock = error en bloquejar la memòria de clau err_null = punter nul err_numlock = error en establir el Bloq num @@ -49,13 +49,13 @@ err_perm_dir = error en canviar el directori actual err_perm_group = error en degradar els permisos de grup err_perm_user = error en degradar els permisos de l'usuari err_pwnam = error en obtenir la informació de l'usuari - - - - - - - +err_sleep = no s'ha pogut executar l'ordre de suspensió +err_start = no s'ha pogut executar l'ordre d'inici +err_battery = no s'ha pogut carregar l'estat de la bateria +err_switch_tty = no s'ha pogut canviar de tty +err_tty_ctrl = ha fallat la transferència del control tty +err_no_users = no s'han trobat usuaris +err_uid_range = no s'ha pogut obtenir dinàmicament el rang d'uid err_user_gid = error en establir el GID de l'usuari err_user_init = error en inicialitzar usuari err_user_uid = error en establir l'UID de l'usuari @@ -63,20 +63,20 @@ err_xauth = error en la comanda xauth err_xcb_conn = error en la connexió xcb err_xsessions_dir = error en trobar la carpeta de sessions err_xsessions_open = error en obrir la carpeta de sessions - +hibernate = hibernar insert = inserir login = iniciar sessió logout = sessió tancada -no_x11_support = el suport per x11 ha estat desactivat en la compilació +no_x11_support = suport x11 desactivat en temps de compilació normal = normal numlock = Bloq Num - +other = altres password = Clau restart = reiniciar shell = shell shutdown = aturar sleep = suspendre - +toggle_password = mostrar/amagar contrasenya wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/cs.ini b/res/lang/cs.ini index da0bce2..4f9456c 100644 --- a/res/lang/cs.ini +++ b/res/lang/cs.ini @@ -1,33 +1,33 @@ - - - +authenticating = ověřování... +brightness_down = snížit jas +brightness_up = zvýšit jas capslock = capslock - - - - +custom = vlastní +custom_info_err_output_long = výstup je příliš dlouhý +custom_info_err_no_output = žádný výstup +custom_info_err_no_output_error = , možná chyba err_alloc = alokace paměti selhala - - +err_args = nelze analyzovat argumenty příkazového řádku +err_autologin_session = relace automatického přihlášení nebyla nalezena err_bounds = index je mimo hranice pole - +err_brightness_change = nepodařilo se změnit jas err_chdir = nelze otevřít domovský adresář - - - +err_clock_too_long = řetězec hodin je příliš dlouhý +err_config = nelze analyzovat konfigurační soubor +err_crawl = nepodařilo se prohledat adresáře relací err_dgn_oob = zpráva protokolu err_domain = neplatná doména - - - - +err_empty_password = prázdné heslo není povoleno +err_envlist = nepodařilo se získat seznam proměnných prostředí +err_get_active_tty = nepodařilo se získat aktivní tty +err_hibernate = nepodařilo se spustit příkaz hibernace err_hostname = nelze získat název hostitele - - - +err_inactivity = nepodařilo se spustit příkaz nečinnosti +err_lock_state = nepodařilo se získat stav zámku +err_log = nepodařilo se otevřít soubor protokolu err_mlock = uzamčení paměti hesel selhalo err_null = nulový ukazatel - +err_numlock = nepodařilo se nastavit numlock err_pam = pam transakce selhala err_pam_abort = pam transakce přerušena err_pam_acct_expired = platnost účtu vypršela @@ -49,34 +49,34 @@ err_perm_dir = nepodařilo se změnit adresář err_perm_group = nepodařilo se snížit skupinová oprávnění err_perm_user = nepodařilo se snížit uživatelská oprávnění err_pwnam = nelze získat informace o uživateli - - - - - - - +err_sleep = nepodařilo se spustit příkaz spánku +err_start = nepodařilo se spustit příkaz spuštění +err_battery = nepodařilo se načíst stav baterie +err_switch_tty = nepodařilo se přepnout tty +err_tty_ctrl = přenos řízení tty selhal +err_no_users = nebyli nalezeni žádní uživatelé +err_uid_range = nepodařilo se dynamicky získat rozsah uid err_user_gid = nastavení GID uživatele selhalo err_user_init = inicializace uživatele selhala err_user_uid = nastavení UID uživateli selhalo - - +err_xauth = příkaz xauth selhal +err_xcb_conn = připojení xcb selhalo err_xsessions_dir = nepodařilo se najít složku relací err_xsessions_open = nepodařilo se otevřít složku relací - - +hibernate = hibernace +insert = vložit login = uživatel logout = odhlášen - - +no_x11_support = podpora x11 zakázána při kompilaci +normal = normální numlock = numlock - +other = jiné password = heslo restart = restartovat shell = příkazový řádek shutdown = vypnout - - +sleep = uspat +toggle_password = zobrazit/skrýt heslo wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/de.ini b/res/lang/de.ini index f869dcb..ca3a0ef 100644 --- a/res/lang/de.ini +++ b/res/lang/de.ini @@ -2,29 +2,29 @@ authenticating = authentifizieren... brightness_down = Helligkeit- brightness_up = Helligkeit+ capslock = Feststelltaste - - - - +custom = benutzerdefiniert +custom_info_err_output_long = Ausgabe zu lang +custom_info_err_no_output = keine Ausgabe +custom_info_err_no_output_error = , möglicher Fehler err_alloc = Speicherzuweisung fehlgeschlagen - - +err_args = Kommandozeilenargumente konnten nicht verarbeitet werden +err_autologin_session = Autologin-Sitzung nicht gefunden err_bounds = Index ausserhalb des Bereichs err_brightness_change = Helligkeitsänderung fehlgeschlagen err_chdir = Fehler beim Oeffnen des Home-Ordners - +err_clock_too_long = Uhrzeitzeichenkette zu lang err_config = Fehler beim Verarbeiten der Konfigurationsdatei - +err_crawl = Sitzungsverzeichnisse konnten nicht durchsucht werden err_dgn_oob = Diagnose-Nachricht err_domain = Ungueltige Domain err_empty_password = Leeres Passwort nicht zugelassen err_envlist = Fehler beim Abrufen der Umgebungs-Variablen - - +err_get_active_tty = Aktives tty konnte nicht ermittelt werden +err_hibernate = Ruhezustand-Befehl konnte nicht ausgeführt werden err_hostname = Abrufen des Hostnames fehlgeschlagen - - - +err_inactivity = Inaktivitätsbefehl konnte nicht ausgeführt werden +err_lock_state = Sperrstatus konnte nicht ermittelt werden +err_log = Protokolldatei konnte nicht geöffnet werden err_mlock = Sperren des Passwortspeichers fehlgeschlagen err_null = Null Pointer err_numlock = Numlock konnte nicht aktiviert werden @@ -50,12 +50,12 @@ err_perm_group = Fehler beim Heruntersetzen der Gruppenberechtigungen err_perm_user = Fehler beim Heruntersetzen der Nutzerberechtigungen err_pwnam = Abrufen der Benutzerinformationen fehlgeschlagen err_sleep = Sleep-Befehl fehlgeschlagen - - - +err_start = Startbefehl konnte nicht ausgeführt werden +err_battery = Akkustand konnte nicht geladen werden +err_switch_tty = tty konnte nicht gewechselt werden err_tty_ctrl = Fehler bei der TTY-Uebergabe - - +err_no_users = Keine Benutzer gefunden +err_uid_range = uid-Bereich konnte nicht dynamisch ermittelt werden err_user_gid = Fehler beim Setzen der Gruppen-ID err_user_init = Nutzer-Initialisierung fehlgeschlagen err_user_uid = Setzen der Benutzer-ID fehlgeschlagen @@ -63,11 +63,11 @@ err_xauth = Xauth-Befehl fehlgeschlagen err_xcb_conn = xcb-Verbindung fehlgeschlagen err_xsessions_dir = Fehler beim Finden des Sitzungsordners err_xsessions_open = Fehler beim Oeffnen des Sitzungsordners - +hibernate = Ruhezustand insert = Einfügen login = Nutzer logout = Abmelden -no_x11_support = X11-Support bei Kompilierung deaktiviert +no_x11_support = x11-Unterstützung zur Kompilierzeit deaktiviert normal = Normal numlock = Numlock other = Andere @@ -76,7 +76,7 @@ restart = Neustarten shell = Shell shutdown = Herunterfahren sleep = Sleep - +toggle_password = Passwort anzeigen/verbergen wayland = wayland -x11 = X11 +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/eo.ini b/res/lang/eo.ini index 8463432..c8cbb96 100644 --- a/res/lang/eo.ini +++ b/res/lang/eo.ini @@ -3,9 +3,9 @@ brightness_down = malpliigi helecon brightness_up = pliigi helecon capslock = majuskla baskulo custom = propra - - - +custom_info_err_output_long = eligo tro longa +custom_info_err_no_output = neniu eligo +custom_info_err_no_output_error = , ebla eraro err_alloc = malsukcesis memorasignon err_args = ne povas analizi argumentojn de komanda linio err_autologin_session = aŭtomatan ensalutan seancon ne trovis @@ -76,7 +76,7 @@ restart = restartigi shell = ŝelo shutdown = malŝalti sleep = memordormi - +toggle_password = montri/kaŝi pasvorton wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/es.ini b/res/lang/es.ini index 38c2b9d..f587fe7 100644 --- a/res/lang/es.ini +++ b/res/lang/es.ini @@ -2,32 +2,32 @@ authenticating = autenticando... brightness_down = bajar brillo brightness_up = subir brillo capslock = Bloq Mayús - - - - +custom = personalizado +custom_info_err_output_long = salida demasiado larga +custom_info_err_no_output = sin salida +custom_info_err_no_output_error = , posible error err_alloc = asignación de memoria fallida - - +err_args = no se pudieron analizar los argumentos de la línea de comandos +err_autologin_session = no se encontró la sesión de inicio de sesión automático err_bounds = índice fuera de límites - +err_brightness_change = no se pudo cambiar el brillo err_chdir = error al abrir la carpeta home - - - +err_clock_too_long = la cadena del reloj es demasiado larga +err_config = no se pudo analizar el archivo de configuración +err_crawl = no se pudieron explorar los directorios de sesión err_dgn_oob = mensaje de registro err_domain = dominio inválido - - - - +err_empty_password = no se permite contraseña vacía +err_envlist = no se pudo obtener la lista de variables de entorno +err_get_active_tty = no se pudo obtener el tty activo +err_hibernate = no se pudo ejecutar el comando de hibernación err_hostname = error al obtener el nombre de host - - - +err_inactivity = no se pudo ejecutar el comando de inactividad +err_lock_state = no se pudo obtener el estado de bloqueo +err_log = no se pudo abrir el archivo de registro err_mlock = error al bloquear la contraseña de memoria err_null = puntero nulo - +err_numlock = no se pudo configurar numlock err_pam = error en la transacción pam err_pam_abort = transacción pam abortada err_pam_acct_expired = cuenta expirada @@ -49,25 +49,25 @@ err_perm_dir = error al cambiar el directorio actual err_perm_group = error al degradar los permisos del grupo err_perm_user = error al degradar los permisos del usuario err_pwnam = error al obtener la información del usuario - - - - - - - +err_sleep = no se pudo ejecutar el comando de suspensión +err_start = no se pudo ejecutar el comando de inicio +err_battery = no se pudo cargar el estado de la batería +err_switch_tty = no se pudo cambiar de tty +err_tty_ctrl = falló la transferencia de control tty +err_no_users = no se encontraron usuarios +err_uid_range = no se pudo obtener dinámicamente el rango de uid err_user_gid = error al establecer el GID del usuario err_user_init = error al inicializar usuario err_user_uid = error al establecer el UID del usuario - - +err_xauth = falló el comando xauth +err_xcb_conn = falló la conexión xcb err_xsessions_dir = error al buscar la carpeta de sesiones err_xsessions_open = error al abrir la carpeta de sesiones - +hibernate = hibernar insert = insertar login = usuario logout = cerrar sesión -no_x11_support = soporte para x11 deshabilitado en tiempo de compilación +no_x11_support = soporte x11 desactivado en tiempo de compilación normal = normal numlock = Bloq Num other = otro @@ -76,7 +76,7 @@ restart = reiniciar shell = shell shutdown = apagar sleep = suspender - +toggle_password = mostrar/ocultar contraseña wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/it.ini b/res/lang/it.ini index e8af2a6..9c9679d 100644 --- a/res/lang/it.ini +++ b/res/lang/it.ini @@ -1,33 +1,33 @@ - - - +authenticating = autenticazione in corso... +brightness_down = diminuisci luminosità +brightness_up = aumenta luminosità capslock = capslock - - - - +custom = personalizzato +custom_info_err_output_long = output troppo lungo +custom_info_err_no_output = nessun output +custom_info_err_no_output_error = , possibile errore err_alloc = impossibile allocare memoria - - +err_args = impossibile analizzare gli argomenti della riga di comando +err_autologin_session = sessione di accesso automatico non trovata err_bounds = indice fuori limite - +err_brightness_change = impossibile modificare la luminosità err_chdir = impossibile aprire home directory - - - +err_clock_too_long = stringa dell'orologio troppo lunga +err_config = impossibile analizzare il file di configurazione +err_crawl = impossibile esplorare le directory delle sessioni err_dgn_oob = messaggio log err_domain = dominio non valido - - - - +err_empty_password = password vuota non consentita +err_envlist = impossibile ottenere la lista delle variabili d'ambiente +err_get_active_tty = impossibile ottenere il tty attivo +err_hibernate = impossibile eseguire il comando di ibernazione err_hostname = impossibile ottenere hostname - - - +err_inactivity = impossibile eseguire il comando di inattività +err_lock_state = impossibile ottenere lo stato di blocco +err_log = impossibile aprire il file di log err_mlock = impossibile ottenere lock per la password in memoria err_null = puntatore nullo - +err_numlock = impossibile impostare il numlock err_pam = transazione PAM fallita err_pam_abort = transazione PAM interrotta err_pam_acct_expired = account scaduto @@ -49,34 +49,34 @@ err_perm_dir = impossibile cambiare directory corrente err_perm_group = impossibile ridurre permessi gruppo err_perm_user = impossibile ridurre permessi utente err_pwnam = impossibile ottenere dati utente - - - - - - - +err_sleep = impossibile eseguire il comando di sospensione +err_start = impossibile eseguire il comando di avvio +err_battery = impossibile caricare lo stato della batteria +err_switch_tty = impossibile cambiare tty +err_tty_ctrl = trasferimento del controllo tty fallito +err_no_users = nessun utente trovato +err_uid_range = impossibile ottenere dinamicamente l'intervallo uid err_user_gid = impossibile impostare GID utente err_user_init = impossibile inizializzare utente err_user_uid = impossible impostare UID utente - - +err_xauth = comando xauth fallito +err_xcb_conn = connessione xcb fallita err_xsessions_dir = impossibile localizzare cartella sessioni err_xsessions_open = impossibile aprire cartella sessioni - - +hibernate = ibernazione +insert = inserisci login = username logout = scollegato - - +no_x11_support = supporto x11 disabilitato in fase di compilazione +normal = normale numlock = numlock - +other = altro password = password restart = riavvio shell = shell shutdown = arresto - - +sleep = sospendi +toggle_password = mostra/nascondi password wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/ja_JP.ini b/res/lang/ja_JP.ini index 309ff39..a14feab 100644 --- a/res/lang/ja_JP.ini +++ b/res/lang/ja_JP.ini @@ -2,29 +2,29 @@ authenticating = 認証中... brightness_down = 明るさを下げる brightness_up = 明るさを上げる capslock = CapsLock - - - - +custom = カスタム +custom_info_err_output_long = 出力が長すぎます +custom_info_err_no_output = 出力なし +custom_info_err_no_output_error = 、エラーの可能性あり err_alloc = メモリ割り当て失敗 - - +err_args = コマンドライン引数を解析できません +err_autologin_session = 自動ログインセッションが見つかりません err_bounds = 境界外インデックス err_brightness_change = 明るさの変更に失敗しました err_chdir = ホームフォルダを開けませんでした - +err_clock_too_long = 時計の文字列が長すぎます err_config = 設定ファイルを解析できません - +err_crawl = セッションディレクトリのクロールに失敗しました err_dgn_oob = ログメッセージ err_domain = 無効なドメイン err_empty_password = 空のパスワードは許可されていません err_envlist = 環境変数リストの取得に失敗しました - - +err_get_active_tty = アクティブなttyの取得に失敗しました +err_hibernate = 休止状態コマンドの実行に失敗しました err_hostname = ホスト名の取得に失敗しました - - - +err_inactivity = 無操作コマンドの実行に失敗しました +err_lock_state = ロック状態の取得に失敗しました +err_log = ログファイルを開けませんでした err_mlock = パスワードメモリのロックに失敗しました err_null = ヌルポインタ err_numlock = NumLockの設定に失敗しました @@ -50,12 +50,12 @@ err_perm_group = グループ権限のダウングレードに失敗しました err_perm_user = ユーザー権限のダウングレードに失敗しました err_pwnam = ユーザー情報の取得に失敗しました err_sleep = スリープコマンドの実行に失敗しました - - - +err_start = 起動コマンドの実行に失敗しました +err_battery = バッテリー状態の読み込みに失敗しました +err_switch_tty = ttyの切り替えに失敗しました err_tty_ctrl = TTY制御の転送に失敗しました - - +err_no_users = ユーザーが見つかりません +err_uid_range = uidの範囲を動的に取得できませんでした err_user_gid = ユーザーGIDの設定に失敗しました err_user_init = ユーザーの初期化に失敗しました err_user_uid = ユーザーUIDの設定に失敗しました @@ -63,11 +63,11 @@ err_xauth = xauthコマンドの実行に失敗しました err_xcb_conn = XCB接続に失敗しました err_xsessions_dir = セッションフォルダが見つかりませんでした err_xsessions_open = セッションフォルダを開けませんでした - +hibernate = 休止状態 insert = 挿入 login = ログイン logout = ログアウト済み -no_x11_support = X11サポートはコンパイル時に無効化されています +no_x11_support = x11サポートはコンパイル時に無効化されています normal = 通常 numlock = NumLock other = その他 @@ -76,7 +76,7 @@ restart = 再起動 shell = シェル shutdown = シャットダウン sleep = スリープ - +toggle_password = パスワードの表示/非表示 wayland = Wayland -x11 = X11 +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/ku.ini b/res/lang/ku.ini index 5775274..0c39030 100644 --- a/res/lang/ku.ini +++ b/res/lang/ku.ini @@ -3,9 +3,9 @@ brightness_down = ronahiyê kêm bike brightness_up = ronahiyê bilind bike capslock = tîpên girdek (capslock) custom = kesane - - - +custom_info_err_output_long = encam pir dirêj e +custom_info_err_no_output = encam tune +custom_info_err_no_output_error = , xeletiya mimkun err_alloc = veqetandina bîrê têk çû err_args = argumanên rêzika fermanê nehatin analîzkirin err_autologin_session = danişîna têketina xweber nehate dîtin @@ -76,7 +76,7 @@ restart = ji nû ve bide destpêkirin shell = shell shutdown = vemirîne sleep = têxîne xewê - +toggle_password = şîfre nîşan bide/veşêre wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/lv.ini b/res/lang/lv.ini index a1a3fa9..8f54d89 100644 --- a/res/lang/lv.ini +++ b/res/lang/lv.ini @@ -3,26 +3,26 @@ brightness_down = samazināt spilgtumu brightness_up = palielināt spilgtumu capslock = caps lock custom = pielāgots - - - +custom_info_err_output_long = izvade pārāk gara +custom_info_err_no_output = nav izvades +custom_info_err_no_output_error = , iespējama kļūda err_alloc = neizdevās atmiņas piešķiršana - - +err_args = nevar parsēt komandrindas argumentus +err_autologin_session = automātiskās pieteikšanās sesija nav atrasta err_bounds = indekss ārpus robežām err_brightness_change = neizdevās mainīt spilgtumu err_chdir = neizdevās atvērt mājas mapi err_clock_too_long = pulksteņa virkne pārāk gara err_config = neizdevās parsēt konfigurācijas failu - +err_crawl = neizdevās pārlūkot sesiju direktorijus err_dgn_oob = žurnāla ziņojums err_domain = nederīgs domēns err_empty_password = tukša parole nav atļauta err_envlist = neizdevās iegūt vides mainīgo sarakstu err_get_active_tty = neizdevās iegūt aktīvo tty - +err_hibernate = neizdevās izpildīt hibernācijas komandu err_hostname = neizdevās iegūt hostname - +err_inactivity = neizdevās izpildīt neaktivitātes komandu err_lock_state = neizdevās iegūt bloķēšanas stāvokli err_log = neizdevās atvērt žurnāla failu err_mlock = neizdevās bloķēt paroles atmiņu @@ -50,12 +50,12 @@ err_perm_group = neizdevās pazemināt grupas atļaujas err_perm_user = neizdevās pazemināt lietotāja atļaujas err_pwnam = neizdevās iegūt lietotāja informāciju err_sleep = neizdevās izpildīt miega komandu - +err_start = neizdevās izpildīt startēšanas komandu err_battery = neizdevās ielādēt akumulatora stāvokli err_switch_tty = neizdevās pārslēgt tty err_tty_ctrl = tty vadības nodošana neizdevās err_no_users = lietotāji nav atrasti - +err_uid_range = neizdevās dinamiski iegūt uid diapazonu err_user_gid = neizdevās iestatīt lietotāja GID err_user_init = neizdevās inicializēt lietotāju err_user_uid = neizdevās iestatīt lietotāja UID @@ -63,7 +63,7 @@ err_xauth = xauth komanda neizdevās err_xcb_conn = xcb savienojums neizdevās err_xsessions_dir = neizdevās atrast sesiju mapi err_xsessions_open = neizdevās atvērt sesiju mapi - +hibernate = hibernācija insert = ievietot login = lietotājs logout = iziet @@ -76,7 +76,7 @@ restart = restartēt shell = terminālis shutdown = izslēgt sleep = snauda - +toggle_password = rādīt/slēpt paroli wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/pl.ini b/res/lang/pl.ini index 4c521e4..536680d 100644 --- a/res/lang/pl.ini +++ b/res/lang/pl.ini @@ -3,26 +3,26 @@ brightness_down = zmniejsz jasność brightness_up = zwiększ jasność capslock = capslock custom = własny - - - +custom_info_err_output_long = wyjście zbyt długie +custom_info_err_no_output = brak wyjścia +custom_info_err_no_output_error = , możliwy błąd err_alloc = nieudana alokacja pamięci - +err_args = nie można przetworzyć argumentów wiersza poleceń err_autologin_session = nie znaleziono sesji autologowania err_bounds = indeks poza zakresem err_brightness_change = nie udało się zmienić jasności err_chdir = nie udało się otworzyć folderu domowego err_clock_too_long = ciąg znaków zegara jest za długi err_config = nie można przetworzyć pliku konfiguracyjnego - +err_crawl = nie udało się przeszukać katalogów sesji err_dgn_oob = wiadomość loga err_domain = niepoprawna domena err_empty_password = puste hasło jest niedozwolone err_envlist = nie udało się pobrać listy zmiennych środowiskowych err_get_active_tty = nie udało się uzyskać aktywnego tty - +err_hibernate = nie udało się wykonać polecenia hibernacji err_hostname = nie udało się uzyskać nazwy hosta - +err_inactivity = nie udało się wykonać polecenia nieaktywności err_lock_state = nie udało się uzyskać stanu blokady err_log = nie udało się otworzyć pliku logu err_mlock = nie udało się zablokować pamięci haseł @@ -50,12 +50,12 @@ err_perm_group = nie udało się obniżyć uprawnień grupy err_perm_user = nie udało się obniżyć uprawnień użytkownika err_pwnam = nie udało się uzyskać informacji o użytkowniku err_sleep = nie udało się wykonać polecenia sleep - +err_start = nie udało się wykonać polecenia startowego err_battery = nie udało się sprawdzić statusu baterii err_switch_tty = nie można przełączyć tty err_tty_ctrl = nie udało się przekazać kontroli tty err_no_users = nie znaleziono żadnego użytkownika - +err_uid_range = nie udało się dynamicznie pobrać zakresu uid err_user_gid = nie udało się ustawić GID użytkownika err_user_init = nie udało się zainicjalizować użytkownika err_user_uid = nie udało się ustawić UID użytkownika @@ -63,11 +63,11 @@ err_xauth = polecenie xauth nie powiodło się err_xcb_conn = połączenie xcb nie powiodło się err_xsessions_dir = nie udało się znaleźć folderu sesji err_xsessions_open = nie udało się otworzyć folderu sesji - +hibernate = hibernuj insert = wstaw login = login logout = wylogowano -no_x11_support = wsparcie X11 wyłączone podczas kompilacji +no_x11_support = obsługa x11 wyłączona podczas kompilacji normal = normalny numlock = numlock other = inny @@ -76,7 +76,7 @@ restart = uruchom ponownie shell = powłoka shutdown = wyłącz sleep = uśpij - +toggle_password = Pokaż/ukryj hasło wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/pt.ini b/res/lang/pt.ini index 0b13276..204a9f1 100644 --- a/res/lang/pt.ini +++ b/res/lang/pt.ini @@ -1,33 +1,33 @@ - - - +authenticating = a autenticar... +brightness_down = diminuir brilho +brightness_up = aumentar brilho capslock = capslock - - - - +custom = personalizado +custom_info_err_output_long = saída demasiado longa +custom_info_err_no_output = sem saída +custom_info_err_no_output_error = , possível erro err_alloc = erro na atribuição de memória - - +err_args = não foi possível analisar os argumentos da linha de comandos +err_autologin_session = sessão de início de sessão automático não encontrada err_bounds = índice fora de limites - +err_brightness_change = não foi possível alterar o brilho err_chdir = erro ao abrir a pasta home - - - +err_clock_too_long = a cadeia de caracteres do relógio é demasiado longa +err_config = não foi possível analisar o ficheiro de configuração +err_crawl = não foi possível explorar os diretórios de sessão err_dgn_oob = mensagem de registo err_domain = domínio inválido - - - - +err_empty_password = palavra-passe vazia não é permitida +err_envlist = não foi possível obter a lista de variáveis de ambiente +err_get_active_tty = não foi possível obter o tty ativo +err_hibernate = não foi possível executar o comando de hibernação err_hostname = erro ao obter o nome do host - - - +err_inactivity = não foi possível executar o comando de inatividade +err_lock_state = não foi possível obter o estado de bloqueio +err_log = não foi possível abrir o ficheiro de registo err_mlock = erro de bloqueio de memória err_null = ponteiro nulo - +err_numlock = não foi possível definir o numlock err_pam = erro na transação pam err_pam_abort = transação pam abortada err_pam_acct_expired = conta expirada @@ -49,34 +49,34 @@ err_perm_dir = erro ao alterar o diretório atual err_perm_group = erro ao reduzir as permissões do grupo err_perm_user = erro ao reduzir as permissões do utilizador err_pwnam = erro ao obter informação do utilizador - - - - - - - +err_sleep = não foi possível executar o comando de suspensão +err_start = não foi possível executar o comando de início +err_battery = não foi possível carregar o estado da bateria +err_switch_tty = não foi possível mudar de tty +err_tty_ctrl = falhou a transferência de controlo do tty +err_no_users = nenhum utilizador encontrado +err_uid_range = não foi possível obter dinamicamente o intervalo de uid err_user_gid = erro ao definir o GID do utilizador err_user_init = erro ao iniciar o utilizador err_user_uid = erro ao definir o UID do utilizador - - +err_xauth = o comando xauth falhou +err_xcb_conn = a ligação xcb falhou err_xsessions_dir = erro ao localizar a pasta das sessões err_xsessions_open = erro ao abrir a pasta das sessões - - +hibernate = hibernar +insert = inserir login = iniciar sessão logout = terminar sessão - - +no_x11_support = suporte a x11 desativado em tempo de compilação +normal = normal numlock = numlock - +other = outro password = palavra-passe restart = reiniciar shell = shell shutdown = encerrar - - +sleep = suspender +toggle_password = mostrar/ocultar palavra-passe wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/pt_BR.ini b/res/lang/pt_BR.ini index ca96a3e..af8c970 100644 --- a/res/lang/pt_BR.ini +++ b/res/lang/pt_BR.ini @@ -1,39 +1,39 @@ - - - +authenticating = autenticando... +brightness_down = diminuir brilho +brightness_up = aumentar brilho capslock = caixa alta - - - - +custom = personalizado +custom_info_err_output_long = saída muito longa +custom_info_err_no_output = sem saída +custom_info_err_no_output_error = , possível erro err_alloc = alocação de memória malsucedida - - +err_args = não foi possível analisar os argumentos da linha de comando +err_autologin_session = sessão de login automático não encontrada err_bounds = índice fora de limites - +err_brightness_change = não foi possível alterar o brilho err_chdir = não foi possível abrir o diretório home - - - +err_clock_too_long = a string do relógio é muito longa +err_config = não foi possível analisar o arquivo de configuração +err_crawl = não foi possível explorar os diretórios de sessão err_dgn_oob = mensagem de log err_domain = domínio inválido - - - - +err_empty_password = senha vazia não é permitida +err_envlist = não foi possível obter a lista de variáveis de ambiente +err_get_active_tty = não foi possível obter o tty ativo +err_hibernate = não foi possível executar o comando de hibernação err_hostname = não foi possível obter o nome do host - - - +err_inactivity = não foi possível executar o comando de inatividade +err_lock_state = não foi possível obter o estado de bloqueio +err_log = não foi possível abrir o arquivo de log err_mlock = bloqueio da memória de senha malsucedido err_null = ponteiro nulo - +err_numlock = não foi possível definir o numlock err_pam = transação pam malsucedida err_pam_abort = transação pam abortada err_pam_acct_expired = conta expirada err_pam_auth = erro de autenticação err_pam_authinfo_unavail = não foi possível obter informações do usuário -err_pam_authok_reqd = token expirada +err_pam_authok_reqd = token expirado err_pam_buf = erro de buffer de memória err_pam_cred_err = erro para definir credenciais err_pam_cred_expired = credenciais expiradas @@ -49,34 +49,34 @@ err_perm_dir = não foi possível alterar o diretório atual err_perm_group = não foi possível reduzir as permissões de grupo err_perm_user = não foi possível reduzir as permissões de usuário err_pwnam = não foi possível obter informações do usuário - - - - - - - +err_sleep = não foi possível executar o comando de suspensão +err_start = não foi possível executar o comando de início +err_battery = não foi possível carregar o status da bateria +err_switch_tty = não foi possível mudar de tty +err_tty_ctrl = a transferência de controle do tty falhou +err_no_users = nenhum usuário encontrado +err_uid_range = não foi possível obter dinamicamente o intervalo de uid err_user_gid = não foi possível definir o GID do usuário err_user_init = não foi possível iniciar o usuário err_user_uid = não foi possível definir o UID do usuário - - +err_xauth = o comando xauth falhou +err_xcb_conn = a conexão xcb falhou err_xsessions_dir = não foi possível encontrar a pasta das sessões err_xsessions_open = não foi possível abrir a pasta das sessões - - +hibernate = hibernar +insert = inserir login = conectar logout = desconectado - - +no_x11_support = suporte a x11 desativado em tempo de compilação +normal = normal numlock = numlock - +other = outro password = senha restart = reiniciar shell = shell shutdown = desligar - - +sleep = suspender +toggle_password = mostrar/ocultar senha wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/ro.ini b/res/lang/ro.ini index 0bf92f2..3b771a8 100644 --- a/res/lang/ro.ini +++ b/res/lang/ro.ini @@ -1,34 +1,34 @@ - - - +authenticating = autentificare... +brightness_down = scade luminozitatea +brightness_up = crește luminozitatea capslock = capslock - - - - - - - - - - - - - - - - - - - - - - - - - - - +custom = personalizat +custom_info_err_output_long = ieșire prea lungă +custom_info_err_no_output = fără ieșire +custom_info_err_no_output_error = , posibil eroare +err_alloc = alocare de memorie eșuată +err_args = imposibil de analizat argumentele liniei de comandă +err_autologin_session = sesiunea de autentificare automată nu a fost găsită +err_bounds = index în afara limitelor +err_brightness_change = imposibil de schimbat luminozitatea +err_chdir = imposibil de deschis folderul de acasă +err_clock_too_long = șirul de ceas este prea lung +err_config = imposibil de analizat fișierul de configurare +err_crawl = imposibil de explorat directoarele de sesiune +err_dgn_oob = mesaj jurnal +err_domain = domeniu invalid +err_empty_password = parola goală nu este permisă +err_envlist = imposibil de obținut lista de variabile de mediu +err_get_active_tty = imposibil de obținut tty-ul activ +err_hibernate = imposibil de executat comanda de hibernare +err_hostname = imposibil de obținut numele gazdei +err_inactivity = imposibil de executat comanda de inactivitate +err_lock_state = imposibil de obținut starea de blocare +err_log = imposibil de deschis fișierul jurnal +err_mlock = imposibil de blocat memoria parolei +err_null = pointer nul +err_numlock = imposibil de setat numlock +err_pam = tranzacție pam eșuată err_pam_abort = tranzacţie pam anulată err_pam_acct_expired = cont expirat err_pam_auth = eroare de autentificare @@ -44,39 +44,39 @@ err_pam_perm_denied = acces interzis err_pam_session = eroare de sesiune err_pam_sys = eroare de sistem err_pam_user_unknown = utilizator necunoscut - +err_path = imposibil de setat calea err_perm_dir = nu s-a putut schimba dosarul (folder-ul) curent err_perm_group = nu s-a putut face downgrade permisiunilor de grup err_perm_user = nu s-a putut face downgrade permisiunilor de utilizator - - - - - - - - - - - - - - - - - +err_pwnam = imposibil de obținut informații despre utilizator +err_sleep = imposibil de executat comanda de repaus +err_start = imposibil de executat comanda de pornire +err_battery = imposibil de încărcat starea bateriei +err_switch_tty = imposibil de comutat tty +err_tty_ctrl = transferul controlului tty a eșuat +err_no_users = niciun utilizator găsit +err_uid_range = imposibil de obținut dinamic intervalul uid +err_user_gid = imposibil de setat GID-ul utilizatorului +err_user_init = imposibil de inițializa utilizatorul +err_user_uid = imposibil de setat UID-ul utilizatorului +err_xauth = comanda xauth a eșuat +err_xcb_conn = conexiunea xcb a eșuat +err_xsessions_dir = imposibil de găsit folderul de sesiuni +err_xsessions_open = imposibil de deschis folderul de sesiuni +hibernate = hibernare +insert = inserare login = utilizator logout = opreşte sesiunea - - +no_x11_support = suportul x11 dezactivat la compilare +normal = normal numlock = numlock - +other = altul password = parolă restart = resetează shell = shell shutdown = opreşte sistemul - - +sleep = repaus +toggle_password = afișare/ascundere parolă wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/ru.ini b/res/lang/ru.ini index 23cec27..014c170 100644 --- a/res/lang/ru.ini +++ b/res/lang/ru.ini @@ -3,26 +3,26 @@ brightness_down = уменьшить яркость brightness_up = увеличить яркость capslock = capslock custom = пользовательский - - - +custom_info_err_output_long = вывод слишком длинный +custom_info_err_no_output = нет вывода +custom_info_err_no_output_error = , возможная ошибка err_alloc = не удалось выделить память - +err_args = не удалось разобрать аргументы командной строки err_autologin_session = не найдена сессия с автологином err_bounds = за пределами индекса err_brightness_change = не удалось изменить яркость err_chdir = не удалось открыть домашнюю папку err_clock_too_long = строка часов слишком длинная err_config = не удалось разобрать файл конфигурации - +err_crawl = не удалось просканировать каталоги сессии err_dgn_oob = отладочное сообщение (log) err_domain = неверный домен err_empty_password = пустой пароль не допустим err_envlist = не удалось получить список переменных среды err_get_active_tty = не удалось получить активный tty - +err_hibernate = не удалось выполнить команду гибернации err_hostname = не удалось получить имя хоста - +err_inactivity = не удалось выполнить команду бездействия err_lock_state = не удалось получить состояние lock err_log = не удалось открыть файл log err_mlock = сбой блокировки памяти @@ -50,12 +50,12 @@ err_perm_group = не удалось понизить права доступа err_perm_user = не удалось понизить права доступа пользователя err_pwnam = не удалось получить информацию о пользователе err_sleep = не удалось выполнить команду sleep - +err_start = не удалось выполнить команду запуска err_battery = не удалось получить статус батареи err_switch_tty = не удалось переключить tty err_tty_ctrl = передача управления tty не удалась err_no_users = пользователи не найдены - +err_uid_range = не удалось динамически получить диапазон uid err_user_gid = не удалось установить GID пользователя err_user_init = не удалось инициализировать пользователя err_user_uid = не удалось установить UID пользователя @@ -63,11 +63,11 @@ err_xauth = команда xauth не выполнена err_xcb_conn = ошибка подключения xcb err_xsessions_dir = не удалось найти сессионную папку err_xsessions_open = не удалось открыть сессионную папку - +hibernate = гибернация insert = вставка login = логин logout = вышел из системы -no_x11_support = поддержка x11 отключена во время компиляции +no_x11_support = поддержка x11 отключена при компиляции normal = обычный numlock = numlock other = прочие @@ -76,7 +76,7 @@ restart = перезагрузить shell = оболочка shutdown = выключить sleep = сон - +toggle_password = показать/скрыть пароль wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/sr.ini b/res/lang/sr.ini index d0ad85a..a2678bf 100644 --- a/res/lang/sr.ini +++ b/res/lang/sr.ini @@ -1,82 +1,82 @@ - - - +authenticating = autentifikacija... +brightness_down = smanji osvetljenost +brightness_up = povećaj osvetljenost capslock = capslock - - - - -err_alloc = neuspijesna alokacija memorije - - +custom = prilagođeno +custom_info_err_output_long = izlaz predugačak +custom_info_err_no_output = nema izlaza +custom_info_err_no_output_error = , moguća greška +err_alloc = neuspješna alokacija memorije +err_args = nije moguće raščlaniti argumente komandne linije +err_autologin_session = sesija automatske prijave nije pronađena err_bounds = izvan granica indeksa - -err_chdir = neuspijesno otvaranje home foldera - - - +err_brightness_change = nije uspela promena osvetljenosti +err_chdir = neuspješno otvaranje home foldera +err_clock_too_long = niska sata je preduga +err_config = nije moguće raščlaniti konfiguracioni fajl +err_crawl = nije uspelo skeniranje direktorijuma sesija err_dgn_oob = log poruka -err_domain = nevazeci domen - - - - -err_hostname = neuspijesno trazenje hostname-a - - - -err_mlock = neuspijesno zakljucavanje memorije lozinke -err_null = null pokazivac - -err_pam = pam transakcija neuspijesna +err_domain = nevažeći domen +err_empty_password = prazna lozinka nije dozvoljena +err_envlist = nije uspelo dobijanje liste promenljivih okruženja +err_get_active_tty = nije uspelo dobijanje aktivnog tty +err_hibernate = nije uspelo izvršavanje komande hibernacije +err_hostname = neuspješno traženje hostname-a +err_inactivity = nije uspelo izvršavanje komande neaktivnosti +err_lock_state = nije uspelo dobijanje stanja zaključavanja +err_log = nije uspelo otvaranje fajla dnevnika +err_mlock = neuspješno zaključavanje memorije lozinke +err_null = null pokazivač +err_numlock = nije uspelo postavljanje numlock +err_pam = pam transakcija neuspješna err_pam_abort = pam transakcija prekinuta err_pam_acct_expired = nalog istekao -err_pam_auth = greska pri autentikaciji -err_pam_authinfo_unavail = neuspjelo uzimanje informacija o korisniku +err_pam_auth = greška pri autentikaciji +err_pam_authinfo_unavail = neuspješno uzimanje informacija o korisniku err_pam_authok_reqd = token istekao -err_pam_buf = greska bafera memorije -err_pam_cred_err = neuspjelo postavljanje kredencijala +err_pam_buf = greška bafera memorije +err_pam_cred_err = neuspješno postavljanje kredencijala err_pam_cred_expired = kredencijali istekli err_pam_cred_insufficient = nedovoljni kredencijali -err_pam_cred_unavail = neuspjelo uzimanje kredencijala -err_pam_maxtries = dostignut maksimalan broj pokusaja -err_pam_perm_denied = nedozovoljeno -err_pam_session = greska sesije -err_pam_sys = greska sistema +err_pam_cred_unavail = neuspješno uzimanje kredencijala +err_pam_maxtries = dostignut maksimalan broj pokušaja +err_pam_perm_denied = nedozvoljeno +err_pam_session = greška sesije +err_pam_sys = greška sistema err_pam_user_unknown = nepoznat korisnik -err_path = neuspjelo postavljanje path-a -err_perm_dir = neuspjelo mijenjanje foldera -err_perm_group = neuspjesno snizavanje dozvola grupe -err_perm_user = neuspijesno snizavanje dozvola korisnika -err_pwnam = neuspijesno skupljanje informacija o korisniku - - - - - - - -err_user_gid = neuspijesno postavljanje korisničkog GID-a -err_user_init = neuspijensa inicijalizacija korisnika -err_user_uid = neuspijesno postavljanje UID-a korisnika - - -err_xsessions_dir = neuspijesno pronalazenje foldera sesija -err_xsessions_open = neuspijesno otvaranje foldera sesija - - +err_path = neuspješno postavljanje path-a +err_perm_dir = neuspješno mijenjanje foldera +err_perm_group = neuspješno snižavanje dozvola grupe +err_perm_user = neuspješno snižavanje dozvola korisnika +err_pwnam = neuspješno skupljanje informacija o korisniku +err_sleep = nije uspelo izvršavanje komande spavanja +err_start = nije uspelo izvršavanje komande pokretanja +err_battery = nije uspelo učitavanje statusa baterije +err_switch_tty = nije uspelo prebacivanje tty +err_tty_ctrl = prenos kontrole tty nije uspeo +err_no_users = nisu pronađeni korisnici +err_uid_range = nije uspelo dinamičko dobijanje opsega uid +err_user_gid = neuspješno postavljanje korisničkog GID-a +err_user_init = neuspješna inicijalizacija korisnika +err_user_uid = neuspješno postavljanje UID-a korisnika +err_xauth = komanda xauth nije uspela +err_xcb_conn = xcb veza nije uspela +err_xsessions_dir = neuspješno pronalaženje foldera sesija +err_xsessions_open = neuspješno otvaranje foldera sesija +hibernate = hibernacija +insert = umetni login = korisnik logout = izlogovan - - +no_x11_support = x11 podrška onemogućena tokom prevođenja +normal = normalno numlock = numlock - +other = ostalo password = lozinka restart = ponovo pokreni shell = shell shutdown = ugasi - - +sleep = uspavaj +toggle_password = prikaži/sakrij lozinku wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/sr_Cyrl.ini b/res/lang/sr_Cyrl.ini new file mode 100644 index 0000000..6222b3d --- /dev/null +++ b/res/lang/sr_Cyrl.ini @@ -0,0 +1,82 @@ +authenticating = аутентификација... +brightness_down = смањи осветљеност +brightness_up = повећај осветљеност +capslock = capslock +custom = прилагођено +custom_info_err_output_long = излаз предугачак +custom_info_err_no_output = нема излаза +custom_info_err_no_output_error = , могућа грешка +err_alloc = неуспешна алокација меморије +err_args = није могуће рашчланити аргументе командне линије +err_autologin_session = сесија аутоматске пријаве није пронађена +err_bounds = изван граница индекса +err_brightness_change = није успела промена осветљености +err_chdir = неуспешно отварање home фолдера +err_clock_too_long = ниска сата је предуга +err_config = није могуће рашчланити конфигурациони фајл +err_crawl = није успело скенирање директоријума сесија +err_dgn_oob = лог порука +err_domain = неважећи домен +err_empty_password = празна лозинка није дозвољена +err_envlist = није успело добијање листе променљивих окружења +err_get_active_tty = није успело добијање активног tty +err_hibernate = није успело извршавање команде хибернације +err_hostname = неуспешно тражење hostname-а +err_inactivity = није успело извршавање команде неактивности +err_lock_state = није успело добијање стања закључавања +err_log = није успело отварање фајла дневника +err_mlock = неуспешно закључавање меморије лозинке +err_null = null показивач +err_numlock = није успело постављање numlock +err_pam = pam трансакција неуспешна +err_pam_abort = pam трансакција прекинута +err_pam_acct_expired = налог истекао +err_pam_auth = грешка при аутентикацији +err_pam_authinfo_unavail = неуспешно узимање информација о кориснику +err_pam_authok_reqd = токен истекао +err_pam_buf = грешка бафера меморије +err_pam_cred_err = неуспешно постављање акредитива +err_pam_cred_expired = акредитиви истекли +err_pam_cred_insufficient = недовољни акредитиви +err_pam_cred_unavail = неуспешно узимање акредитива +err_pam_maxtries = достигнут максималан број покушаја +err_pam_perm_denied = недозвољено +err_pam_session = грешка сесије +err_pam_sys = грешка система +err_pam_user_unknown = непознат корисник +err_path = неуспешно постављање путање +err_perm_dir = неуспешно мењање фолдера +err_perm_group = неуспешно снижавање дозвола групе +err_perm_user = неуспешно снижавање дозвола корисника +err_pwnam = неуспешно прикупљање информација о кориснику +err_sleep = није успело извршавање команде спавања +err_start = није успело извршавање команде покретања +err_battery = није успело учитавање статуса батерије +err_switch_tty = није успело пребацивање tty +err_tty_ctrl = пренос контроле tty није успео +err_no_users = нису пронађени корисници +err_uid_range = није успело динамичко добијање опсега uid +err_user_gid = неуспешно постављање корисничког GID-а +err_user_init = неуспешна иницијализација корисника +err_user_uid = неуспешно постављање UID-а корисника +err_xauth = команда xauth није успела +err_xcb_conn = xcb веза није успела +err_xsessions_dir = неуспешно проналажење фолдера сесија +err_xsessions_open = неуспешно отварање фолдера сесија +hibernate = хибернација +insert = уметни +login = корисник +logout = одјављен +no_x11_support = x11 подршка онемогућена током превођења +normal = нормално +numlock = numlock +other = остало +password = лозинка +restart = поново покрени +shell = shell +shutdown = угаси +sleep = успавај +toggle_password = прикажи/сакриј лозинку +wayland = wayland +x11 = x11 +xinitrc = xinitrc diff --git a/res/lang/sv.ini b/res/lang/sv.ini index adec801..45e36d4 100644 --- a/res/lang/sv.ini +++ b/res/lang/sv.ini @@ -3,9 +3,9 @@ brightness_down = minska ljusstyrka brightness_up = öka ljusstyrka capslock = capslock custom = anpassad - - - +custom_info_err_output_long = utdata för lång +custom_info_err_no_output = ingen utdata +custom_info_err_no_output_error = , möjligt fel err_alloc = minnesallokering misslyckades err_args = tolkning av kommandoargument misslyckades err_autologin_session = autologin-session hittades inte @@ -26,7 +26,7 @@ err_inactivity = inaktivitetslägets kommando misslyckades err_lock_state = hämtning av låsningsstatus misslyckades err_log = öppning av loggfil misslyckades err_mlock = låsning av lösenordsminne misslyckades -err_null = null pointer +err_null = nullpekare err_numlock = inställning av numlock misslyckades err_pam = pam-transaktion misslyckades err_pam_abort = pam-transaktion avbröts @@ -76,7 +76,7 @@ restart = starta om shell = shell shutdown = stäng av sleep = viloläge - +toggle_password = visa/dölj lösenord wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/tr.ini b/res/lang/tr.ini index 4ee5960..414f4d5 100644 --- a/res/lang/tr.ini +++ b/res/lang/tr.ini @@ -1,33 +1,33 @@ - +authenticating = kimlik doğrulanıyor... brightness_down = parlakligi azalt brightness_up = parlakligi arttir capslock = capslock - - - - +custom = özel +custom_info_err_output_long = çıktı çok uzun +custom_info_err_no_output = çıktı yok +custom_info_err_no_output_error = , olası hata err_alloc = basarisiz bellek ayirma - - +err_args = komut satırı argümanları ayrıştırılamıyor +err_autologin_session = otomatik oturum açma oturumu bulunamadı err_bounds = sinirlarin disinda dizin - +err_brightness_change = parlaklık değiştirilemedi err_chdir = ev klasoru acilamadi - - - +err_clock_too_long = saat dizesi çok uzun +err_config = yapılandırma dosyası ayrıştırılamıyor +err_crawl = oturum dizinleri taranamadı err_dgn_oob = log mesaji err_domain = gecersiz etki alani - - - - +err_empty_password = boş parola kullanılamaz +err_envlist = ortam değişkenleri listesi alınamadı +err_get_active_tty = aktif tty alınamadı +err_hibernate = hazırda bekletme komutu çalıştırılamadı err_hostname = ana bilgisayar adi alinamadi - - - +err_inactivity = hareketsizlik komutu çalıştırılamadı +err_lock_state = kilit durumu alınamadı +err_log = günlük dosyası açılamadı err_mlock = parola bellegi kilitlenemedi err_null = bos isaretci hatasi - +err_numlock = numlock ayarlanamadı err_pam = pam islemi basarisiz oldu err_pam_abort = pam islemi durduruldu err_pam_acct_expired = hesabin suresi dolmus @@ -49,26 +49,26 @@ err_perm_dir = gecerli dizin degistirilemedi err_perm_group = grup izinleri dusurulemedi err_perm_user = kullanici izinleri dusurulemedi err_pwnam = kullanici bilgileri alinamadi - - - - - - - +err_sleep = uyku komutu çalıştırılamadı +err_start = başlatma komutu çalıştırılamadı +err_battery = pil durumu yüklenemedi +err_switch_tty = tty değiştirilemedi +err_tty_ctrl = tty kontrol aktarımı başarısız oldu +err_no_users = kullanıcı bulunamadı +err_uid_range = uid aralığı dinamik olarak alınamadı err_user_gid = kullanici icin GID ayarlanamadi err_user_init = kullanici oturumu baslatilamadi err_user_uid = kullanici icin UID ayarlanamadi - - +err_xauth = xauth komutu başarısız oldu +err_xcb_conn = xcb bağlantısı başarısız oldu err_xsessions_dir = oturumlar klasoru bulunamadi err_xsessions_open = oturumlar klasoru acilamadi hibernate = askiya al - +insert = ekle login = kullanici logout = oturumdan cikis yapildi - - +no_x11_support = x11 desteği derleme zamanında devre dışı bırakıldı +normal = normal numlock = numlock other = baska password = sifre @@ -76,7 +76,7 @@ restart = yeniden baslat shell = shell shutdown = makineyi kapat sleep = uykuya al - +toggle_password = parolayı göster/gizle wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/uk.ini b/res/lang/uk.ini index 7b47f8a..6baa469 100644 --- a/res/lang/uk.ini +++ b/res/lang/uk.ini @@ -1,33 +1,33 @@ - - - +authenticating = автентифікація... +brightness_down = зменшити яскравість +brightness_up = збільшити яскравість capslock = capslock - - - - +custom = власний +custom_info_err_output_long = вивід занадто довгий +custom_info_err_no_output = немає виводу +custom_info_err_no_output_error = , можлива помилка err_alloc = невдале виділення пам'яті - - +err_args = не вдалося розібрати аргументи командного рядка +err_autologin_session = сеанс автоматичного входу не знайдено err_bounds = поза межами індексу - +err_brightness_change = не вдалося змінити яскравість err_chdir = не вдалося відкрити домашній каталог - - - +err_clock_too_long = рядок годинника занадто довгий +err_config = не вдалося розібрати файл конфігурації +err_crawl = не вдалося сканувати каталоги сесій err_dgn_oob = повідомлення журналу (log) err_domain = недійсний домен - - - - +err_empty_password = порожній пароль не дозволено +err_envlist = не вдалося отримати список змінних середовища +err_get_active_tty = не вдалося отримати активний tty +err_hibernate = не вдалося виконати команду гібернації err_hostname = не вдалося отримати ім'я хосту - - - +err_inactivity = не вдалося виконати команду неактивності +err_lock_state = не вдалося отримати стан блокування +err_log = не вдалося відкрити файл журналу err_mlock = збій блокування пам'яті err_null = нульовий вказівник - +err_numlock = не вдалося встановити numlock err_pam = невдала pam транзакція err_pam_abort = pam транзакція перервана err_pam_acct_expired = термін дії акаунту вичерпано @@ -49,34 +49,34 @@ err_perm_dir = не вдалося змінити поточний катало err_perm_group = не вдалося понизити права доступу групи err_perm_user = не вдалося понизити права доступу користувача err_pwnam = не вдалося отримати дані користувача - - - - - - - +err_sleep = не вдалося виконати команду сну +err_start = не вдалося виконати команду запуску +err_battery = не вдалося завантажити стан акумулятора +err_switch_tty = не вдалося переключити tty +err_tty_ctrl = передача керування tty не вдалася +err_no_users = користувачів не знайдено +err_uid_range = не вдалося динамічно отримати діапазон uid err_user_gid = не вдалося змінити GID користувача err_user_init = не вдалося ініціалізувати користувача err_user_uid = не вдалося змінити UID користувача - - +err_xauth = команда xauth не вдалася +err_xcb_conn = з'єднання xcb не вдалося err_xsessions_dir = не вдалося знайти каталог сесій err_xsessions_open = не вдалося відкрити каталог сесій - - +hibernate = гібернація +insert = вставити login = логін logout = вийти - - +no_x11_support = підтримку x11 вимкнено під час компіляції +normal = нормальний numlock = numlock - +other = інший password = пароль restart = перезавантажити shell = оболонка shutdown = вимкнути - - +sleep = сплячий режим +toggle_password = показати/приховати пароль wayland = wayland - +x11 = x11 xinitrc = xinitrc diff --git a/res/lang/zh_CN.ini b/res/lang/zh_CN.ini index d2af6c3..4562624 100644 --- a/res/lang/zh_CN.ini +++ b/res/lang/zh_CN.ini @@ -1,33 +1,33 @@ - - - +authenticating = 正在认证... +brightness_down = 降低亮度 +brightness_up = 提高亮度 capslock = 大写锁定 - - - - +custom = 自定义 +custom_info_err_output_long = 输出过长 +custom_info_err_no_output = 无输出 +custom_info_err_no_output_error = ,可能有错误 err_alloc = 内存分配失败 - - +err_args = 无法解析命令行参数 +err_autologin_session = 未找到自动登录会话 err_bounds = 索引越界 - +err_brightness_change = 无法更改亮度 err_chdir = 无法打开home文件夹 - - - +err_clock_too_long = 时钟字符串过长 +err_config = 无法解析配置文件 +err_crawl = 无法扫描会话目录 err_dgn_oob = 日志消息 err_domain = 无效的域 - - - - +err_empty_password = 不允许空密码 +err_envlist = 无法获取环境变量列表 +err_get_active_tty = 无法获取当前活动的tty +err_hibernate = 无法执行休眠命令 err_hostname = 获取主机名失败 - - - +err_inactivity = 无法执行非活动命令 +err_lock_state = 无法获取锁定状态 +err_log = 无法打开日志文件 err_mlock = 锁定密码存储器失败 err_null = 空指针 - +err_numlock = 无法设置numlock err_pam = PAM事件失败 err_pam_abort = PAM事务已中止 err_pam_acct_expired = 帐户已过期 @@ -49,34 +49,34 @@ err_perm_dir = 更改当前目录失败 err_perm_group = 组权限降级失败 err_perm_user = 用户权限降级失败 err_pwnam = 获取用户信息失败 - - - - - - - +err_sleep = 无法执行睡眠命令 +err_start = 无法执行启动命令 +err_battery = 无法加载电池状态 +err_switch_tty = 无法切换tty +err_tty_ctrl = tty控制转移失败 +err_no_users = 未找到用户 +err_uid_range = 无法动态获取uid范围 err_user_gid = 设置用户GID失败 err_user_init = 初始化用户失败 err_user_uid = 设置用户UID失败 - - +err_xauth = xauth命令失败 +err_xcb_conn = xcb连接失败 err_xsessions_dir = 找不到会话文件夹 err_xsessions_open = 无法打开会话文件夹 - - +hibernate = 休眠 +insert = 插入 login = 登录 logout = 注销 - - +no_x11_support = x11支持在编译时被禁用 +normal = 正常 numlock = 数字锁定 - +other = 其他 password = 密码 - +restart = 重启 shell = shell - - - +shutdown = 关机 +sleep = 睡眠 +toggle_password = 显示/隐藏密码 wayland = wayland x11 = x11 xinitrc = xinitrc diff --git a/res/lang/zh_TW.ini b/res/lang/zh_TW.ini new file mode 100644 index 0000000..50d5f68 --- /dev/null +++ b/res/lang/zh_TW.ini @@ -0,0 +1,82 @@ +authenticating = 正在驗證... +brightness_down = 降低亮度 +brightness_up = 提高亮度 +capslock = 大寫鎖定 +custom = 自訂 +custom_info_err_output_long = 輸出過長 +custom_info_err_no_output = 無輸出 +custom_info_err_no_output_error = ,可能有錯誤 +err_alloc = 記憶體配置失敗 +err_args = 無法解析命令列參數 +err_autologin_session = 找不到自動登入工作階段 +err_bounds = 索引超出範圍 +err_brightness_change = 無法變更亮度 +err_chdir = 無法開啟家目錄 +err_clock_too_long = 時鐘字串過長 +err_config = 無法解析設定檔 +err_crawl = 無法掃描工作階段目錄 +err_dgn_oob = 日誌訊息 +err_domain = 無效的網域 +err_empty_password = 不允許空密碼 +err_envlist = 無法取得環境變數清單 +err_get_active_tty = 無法取得目前使用中的 tty +err_hibernate = 無法執行休眠命令 +err_hostname = 取得主機名稱失敗 +err_inactivity = 無法執行閒置命令 +err_lock_state = 無法取得鎖定狀態 +err_log = 無法開啟日誌檔案 +err_mlock = 鎖定密碼記憶體失敗 +err_null = 空指標 +err_numlock = 無法設定 numlock +err_pam = PAM 交易失敗 +err_pam_abort = PAM 交易已中止 +err_pam_acct_expired = 帳號已過期 +err_pam_auth = 驗證錯誤 +err_pam_authinfo_unavail = 取得使用者資訊失敗 +err_pam_authok_reqd = 金鑰已過期 +err_pam_buf = 記憶體緩衝區錯誤 +err_pam_cred_err = 設定憑證失敗 +err_pam_cred_expired = 憑證已過期 +err_pam_cred_insufficient = 憑證不足 +err_pam_cred_unavail = 無法取得憑證 +err_pam_maxtries = 已達到最大嘗試次數限制 +err_pam_perm_denied = 拒絕存取 +err_pam_session = 工作階段錯誤 +err_pam_sys = 系統錯誤 +err_pam_user_unknown = 未知的使用者 +err_path = 無法設定路徑 +err_perm_dir = 變更目前目錄失敗 +err_perm_group = 群組權限降級失敗 +err_perm_user = 使用者權限降級失敗 +err_pwnam = 取得使用者資訊失敗 +err_sleep = 無法執行睡眠命令 +err_start = 無法執行啟動命令 +err_battery = 無法載入電池狀態 +err_switch_tty = 無法切換 tty +err_tty_ctrl = tty 控制權移轉失敗 +err_no_users = 找不到使用者 +err_uid_range = 無法動態取得 uid 範圍 +err_user_gid = 設定使用者 GID 失敗 +err_user_init = 初始化使用者失敗 +err_user_uid = 設定使用者 UID 失敗 +err_xauth = xauth 命令失敗 +err_xcb_conn = xcb 連線失敗 +err_xsessions_dir = 找不到工作階段資料夾 +err_xsessions_open = 無法開啟工作階段資料夾 +hibernate = 休眠 +insert = 插入 +login = 登入 +logout = 登出 +no_x11_support = x11 支援已在編譯時停用 +normal = 正常 +numlock = 數字鎖定 +other = 其他 +password = 密碼 +restart = 重新啟動 +shell = shell +shutdown = 關機 +sleep = 睡眠 +toggle_password = 顯示/隱藏密碼 +wayland = wayland +x11 = x11 +xinitrc = xinitrc diff --git a/res/ly-kmsconvt@.service b/res/ly-kmsconvt@.service index 80eb1da..9384bdf 100644 --- a/res/ly-kmsconvt@.service +++ b/res/ly-kmsconvt@.service @@ -1,17 +1,28 @@ +# Default kmsconvt@.service +# Modified for Ly by AnErrupTion + [Unit] -Description=TUI display manager using KMSCON -After=systemd-user-sessions.service plymouth-quit-wait.service -After=kmsconvt@%i.service -Conflicts=kmsconvt@%i.service +Description=TUI display manager on %I using KMSCON +After=systemd-user-sessions.service plymouth-quit-wait.service rc-local.service kmsconvt@%i.service +Conflicts=getty@%i.service kmsconvt@%i.service ly@%i.service +OnFailure=ly@%i.service [Service] -ExecStart=$PREFIX_DIRECTORY/bin/kmscon --font-engine unifont --vt=%I --seats=seat0 --login -- $PREFIX_DIRECTORY/bin/$EXECUTABLE_NAME --use-kmscon-vt -StandardInput=tty +ExecStart=$PREFIX_DIRECTORY/bin/kmscon --term=linux --font-engine unifont --vt=%I --login -- $PREFIX_DIRECTORY/bin/$EXECUTABLE_NAME --use-kmscon-vt +Type=idle +Restart=always +RestartSec=0 UtmpIdentifier=%I +StandardInput=tty +StandardOutput=tty TTYPath=/dev/%I TTYReset=yes TTYVHangup=yes TTYVTDisallocate=yes +IgnoreSIGPIPE=no +SendSIGHUP=yes [Install] +Alias=autovt@.service WantedBy=multi-user.target +DefaultInstance=tty2 diff --git a/res/ly@.service b/res/ly@.service index 54d8bf6..b2fb5ff 100644 --- a/res/ly@.service +++ b/res/ly@.service @@ -1,16 +1,46 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +# +# This file is part of systemd. +# +# systemd is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation; either version 2.1 of the License, or +# (at your option) any later version. +# +# Modified for Ly by AnErrupTion + [Unit] -Description=TUI display manager -After=systemd-user-sessions.service plymouth-quit-wait.service -After=getty@%i.service -Conflicts=getty@%i.service +Description=TUI display manager on %I +After=systemd-user-sessions.service plymouth-quit-wait.service getty@%i.service +Conflicts=getty@%i.service kmsconvt@%i.service ly-kmsconvt@%i.service [Service] +ExecStart=$PREFIX_DIRECTORY/bin/agetty -nl $PREFIX_DIRECTORY/bin/$EXECUTABLE_NAME %I ${TERM} Type=idle -ExecStart=$PREFIX_DIRECTORY/bin/$EXECUTABLE_NAME +Restart=always +RestartSec=0 +UtmpIdentifier=%I StandardInput=tty +StandardOutput=tty TTYPath=/dev/%I TTYReset=yes TTYVHangup=yes +TTYVTDisallocate=yes +IgnoreSIGPIPE=no +SendSIGHUP=yes + +ImportCredential=tty.virtual.%I.agetty.*:agetty. +ImportCredential=tty.virtual.%I.login.*:login. +ImportCredential=agetty.* +ImportCredential=login.* +ImportCredential=shell.* + +# Unset locale for the console getty since the console has problems +# displaying some internationalized messages. +UnsetEnvironment=LANG LANGUAGE LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT LC_IDENTIFICATION [Install] +Alias=autovt@.service + WantedBy=multi-user.target +DefaultInstance=tty2 diff --git a/res/pam.d/ly-freebsd-autologin b/res/pam.d/ly-freebsd-autologin index e2448ad..b6f56e3 100644 --- a/res/pam.d/ly-freebsd-autologin +++ b/res/pam.d/ly-freebsd-autologin @@ -3,7 +3,6 @@ # OpenPAM (used in FreeBSD) doesn't support prepending "-" for ignoring missing # modules. auth required pam_permit.so -auth include login account include login password include login session include login diff --git a/src/animations/Cascade.zig b/src/animations/Cascade.zig index 587cd37..c9b7769 100644 --- a/src/animations/Cascade.zig +++ b/src/animations/Cascade.zig @@ -71,14 +71,14 @@ fn draw(self: *Cascade) void { if ((self.buffer.random.int(u16) % 10) > 7) continue; - cell.?.put(x, y); + cell.?.put(x, y) catch {}; var space = Cell.init( ' ', cell_under.?.fg, cell_under.?.bg, ); - space.put(x, y - 1); + space.put(x, y - 1) catch {}; } } @@ -87,6 +87,6 @@ fn draw(self: *Cascade) void { self.current_auth_fails.* = 0; } - TerminalBuffer.presentBuffer(); + TerminalBuffer.presentBuffer() catch {}; } } diff --git a/src/animations/ColorMix.zig b/src/animations/ColorMix.zig index 49c6238..e9063a3 100644 --- a/src/animations/ColorMix.zig +++ b/src/animations/ColorMix.zig @@ -114,7 +114,7 @@ fn draw(self: *ColorMix) void { } const cell = self.palette[@as(usize, @trunc(math.floor(length(uv) * 5.0))) % palette_len]; - cell.put(x, y); + cell.put(x, y) catch {}; } } } diff --git a/src/animations/Doom.zig b/src/animations/Doom.zig index 9b0abae..504831a 100644 --- a/src/animations/Doom.zig +++ b/src/animations/Doom.zig @@ -129,13 +129,13 @@ fn draw(self: *Doom) void { // Send known fire levels to terminal buffer const from_cell = self.fire[level_buf_from]; const to_cell = self.fire[level_buf_to]; - from_cell.put(x, y); - to_cell.put(to_x, to_y); + from_cell.put(x, y) catch {}; + to_cell.put(to_x, to_y) catch {}; } // Draw bottom line (fire source) const src_cell = self.fire[STEPS]; - src_cell.put(x, self.terminal_buffer.height - 1); + src_cell.put(x, self.terminal_buffer.height - 1) catch {}; } } diff --git a/src/animations/DurFile.zig b/src/animations/DurFile.zig index 7e56520..95677f8 100644 --- a/src/animations/DurFile.zig +++ b/src/animations/DurFile.zig @@ -19,25 +19,6 @@ const LogFile = ly_core.LogFile; const enums = @import("../enums.zig"); const DurOffsetAlignment = enums.DurOffsetAlignment; -fn read_decompress_file(allocator: Allocator, io: std.Io, file_path: []const u8) ![]u8 { - const file_buffer = std.Io.Dir.cwd().openFile(io, file_path, .{}) catch { - return error.FileNotFound; - }; - defer file_buffer.close(io); - - var file_reader_buffer: [4096]u8 = undefined; - var decompress_buffer: [flate.max_window_len]u8 = undefined; - - var file_reader = file_buffer.reader(io, &file_reader_buffer); - var decompress: flate.Decompress = .init(&file_reader.interface, .gzip, &decompress_buffer); - - const file_decompressed = decompress.reader.allocRemaining(allocator, .unlimited) catch { - return error.NotValidFile; - }; - - return file_decompressed; -} - const Frame = struct { frameNumber: i32, delay: f32, @@ -62,7 +43,7 @@ const Frame = struct { }; // https://github.com/cmang/durdraw/blob/0.29.0/durformat.md -const DurFormat = struct { +const DurFormatRaw = struct { allocator: Allocator, formatVersion: ?i64 = null, colorFormat: ?[]const u8 = null, @@ -72,38 +53,48 @@ const DurFormat = struct { lines: ?i64 = null, frames: std.ArrayList(Frame) = undefined, - pub fn valid(self: *DurFormat) bool { - if (self.formatVersion != null and - self.colorFormat != null and - self.encoding != null and - self.framerate != null and - self.columns != null and - self.lines != null and - self.frames.items.len >= 1) - { - // v8 may have breaking changes like changing the colormap xy direction - // (https://github.com/cmang/durdraw/issues/24) - if (self.formatVersion.? != 7) return false; + // Validate data and return a valid DurFormat + // Consumes `self`, making it unusable after + pub fn validate(self: *DurFormatRaw) !DurFormat { + // v8 may have breaking changes like changing the colormap xy direction + // (https://github.com/cmang/durdraw/issues/24) + const format_version = self.formatVersion orelse return error.MissingFieldVersion; + if (format_version != 7) return error.UnsupportedVersion; - // Code currently only supports 16 and 256 color format only - if (!(eql(u8, "16", self.colorFormat.?) or eql(u8, "256", self.colorFormat.?))) - return false; + const color_format_str = self.colorFormat orelse return error.MissingFieldColorFormat; + // Code currently only supports 16 and 256 color format only + const color_format: DurColorFormat = + if (eql(u8, color_format_str, "16")) .@"16" else if (eql(u8, color_format_str, "256")) .@"256" else return error.UnsupportedColorFormat; - // Code currently supports only utf-8 encoding - if (!eql(u8, self.encoding.?, "utf-8")) return false; + const encoding_str = self.encoding orelse return error.MissingFieldEncoding; + // Code currently supports only utf-8 encoding + const encoding: DurEncoding = if (eql(u8, encoding_str, "utf-8")) .utf_8 else return error.UnsupportedEncoding; - // Sanity check on file - if (self.columns.? <= 0) return false; - if (self.lines.? <= 0) return false; - if (self.framerate.? < 0) return false; + if (self.framerate == null) return error.MissingFieldFramerate; + if (self.framerate.? <= 0) return error.InvalidFramerate; + const framerate: f64 = self.framerate.?; - return true; - } + // Sanity check on file + if (self.columns == null or self.lines == null) return error.MissingDimensions; + const columns = std.math.cast(u32, self.columns.?) orelse return error.InvalidColumnCount; + const lines = std.math.cast(u32, self.lines.?) orelse return error.InvalidLineCount; - return false; + if (self.frames.items.len == 0) return error.NoFrames; + const frames = self.frames; + + return .{ + .allocator = self.allocator, + .formatVersion = format_version, + .colorFormat = color_format, + .encoding = encoding, + .framerate = framerate, + .columns = columns, + .lines = lines, + .frames = frames, + }; } - fn parse_dur_from_json(self: *DurFormat, allocator: Allocator, dur_json_root: Json.Value) !void { + fn parseFromJson(self: *DurFormatRaw, allocator: Allocator, dur_json_root: Json.Value) !void { var dur_movie = if (dur_json_root.object.get("DurMovie")) |dm| dm.object else return error.NotValidFile; // Depending on the version, a dur file can have different json object names (ie: columns vs sizeX) @@ -150,28 +141,53 @@ const DurFormat = struct { } } - pub fn create_from_file(self: *DurFormat, allocator: Allocator, io: std.Io, file_path: []const u8) !void { - const file_decompressed = try read_decompress_file(allocator, io, file_path); - defer allocator.free(file_decompressed); + pub fn createFromFile(self: *DurFormatRaw, allocator: Allocator, io: std.Io, file_path: []const u8) !void { + const file = try std.Io.Dir.cwd().openFile(io, file_path, .{}); + defer file.close(io); - const parsed = try Json.parseFromSlice(Json.Value, allocator, file_decompressed, .{}); - defer parsed.deinit(); + var reader_buffer: [4096]u8 = undefined; + var decompress_buffer: [flate.max_window_len]u8 = undefined; - try parse_dur_from_json(self, allocator, parsed.value); + var file_reader = file.reader(io, &reader_buffer); + var decompress: flate.Decompress = .init(&file_reader.interface, .gzip, &decompress_buffer); - if (!self.valid()) { - return error.NotValidFile; - } + var json_reader = Json.Reader.init(allocator, &decompress.reader); + defer json_reader.deinit(); + + const json = try Json.parseFromTokenSource(Json.Value, allocator, &json_reader, .{}); + defer json.deinit(); + + try parseFromJson(self, allocator, json.value); } - pub fn init(allocator: Allocator) DurFormat { + pub fn init(allocator: Allocator) DurFormatRaw { return .{ .allocator = allocator }; } - pub fn deinit(self: *DurFormat) void { + pub fn deinit(self: *DurFormatRaw) void { if (self.colorFormat) |str| self.allocator.free(str); if (self.encoding) |str| self.allocator.free(str); + } +}; +const DurColorFormat = enum { + @"16", + @"256", +}; + +const DurEncoding = enum { utf_8 }; + +const DurFormat = struct { + allocator: Allocator, + formatVersion: i64, + colorFormat: DurColorFormat, + encoding: DurEncoding, + framerate: f64, + columns: u32, + lines: u32, + frames: std.ArrayList(Frame), + + pub fn deinit(self: *DurFormat) void { for (self.frames.items) |frame| { frame.deinit(self.allocator); } @@ -240,7 +256,7 @@ const durcolor_table_to_color16 = [17]u32{ 15, // 16 bright white }; -fn sixcube_to_channel(sixcube: u32) u32 { +fn sixCubeToChannel(sixcube: u32) u32 { // Although the range top for the extended range is 0xFF, 6 is not divisible into 0xFF, // so we use 0xF0 instead with a scaler const equal_divisions = 0xF0 / 6; @@ -251,7 +267,7 @@ fn sixcube_to_channel(sixcube: u32) u32 { return if (sixcube > 0) (sixcube * equal_divisions) + scaler else 0; } -fn convert_256_to_rgb(color_256: u32) u32 { +fn convert256ToRgb(color_256: u32) u32 { var rgb_color: u32 = 0; // 0 - 15 is the standard color range, map to array table @@ -267,9 +283,9 @@ fn convert_256_to_rgb(color_256: u32) u32 { // divide by 1 gets the height of the cube (divide 1 for clarity for what we are doing) // each channel can be 6 levels of brightness hence remander operation of 6 // finally bitshift to correct rgb channel (16 for red, 8 for green, 0 for blue) - rgb_color |= sixcube_to_channel(((color_256 - 16) / 36) % 6) << 16; - rgb_color |= sixcube_to_channel(((color_256 - 16) / 6) % 6) << 8; - rgb_color |= sixcube_to_channel(((color_256 - 16) / 1) % 6); + rgb_color |= sixCubeToChannel(((color_256 - 16) / 36) % 6) << 16; + rgb_color |= sixCubeToChannel(((color_256 - 16) / 6) % 6) << 8; + rgb_color |= sixCubeToChannel(((color_256 - 16) / 1) % 6); } // 232 - 255 is the grayscale range else { @@ -327,12 +343,12 @@ fn center(v: i64) i64 { return @intCast(@divTrunc(v, 2) + @mod(v, 2)); } -fn calc_start_position(terminal_buffer: *TerminalBuffer, dur_movie: *DurFormat, offset_alignment: DurOffsetAlignment, offset: IVec2) IVec2 { +fn calculateStartPos(terminal_buffer: *TerminalBuffer, dur_movie: *DurFormat, offset_alignment: DurOffsetAlignment, offset: IVec2) IVec2 { const buf_width: i64 = @intCast(terminal_buffer.width); const buf_height: i64 = @intCast(terminal_buffer.height); - const movie_width: i64 = @intCast(dur_movie.columns.?); - const movie_height: i64 = @intCast(dur_movie.lines.?); + const movie_width: i64 = @intCast(dur_movie.columns); + const movie_height: i64 = @intCast(dur_movie.lines); const start_pos: IVec2 = switch (offset_alignment) { DurOffsetAlignment.center => .{ center(buf_width) - center(movie_width), center(buf_height) - center(movie_height) }, @@ -363,9 +379,10 @@ pub fn init( timeout_sec: u12, frame_delay: u16, ) !DurFile { - var dur_movie: DurFormat = .init(allocator); + var dur_movie_raw: DurFormatRaw = .init(allocator); + defer dur_movie_raw.deinit(); - dur_movie.create_from_file(allocator, io, file_path) catch |err| switch (err) { + dur_movie_raw.createFromFile(allocator, io, file_path) catch |err| switch (err) { error.FileNotFound => { try log_file.err(io, "tui", "dur_file was not found at: {s}", .{file_path}); return err; @@ -377,19 +394,70 @@ pub fn init( else => return err, }; + var dur_movie = dur_movie_raw.validate() catch |err| switch (err) { + error.MissingFieldVersion => { + try log_file.err(io, "tui", "dur_file loaded was invalid: missing field formatVersion!", .{}); + return err; + }, + error.UnsupportedVersion => { + try log_file.err(io, "tui", "dur_file loaded was invalid: unsupported version ({d})!", .{dur_movie_raw.formatVersion.?}); + return err; + }, + error.MissingFieldColorFormat => { + try log_file.err(io, "tui", "dur_file loaded was invalid: missing field colorFormat!", .{}); + return err; + }, + error.UnsupportedColorFormat => { + try log_file.err(io, "tui", "dur_file loaded was invalid: unsupported colorFormat ({s})!", .{dur_movie_raw.colorFormat.?}); + return err; + }, + error.MissingFieldEncoding => { + try log_file.err(io, "tui", "dur_file loaded was invalid: missing field encoding!", .{}); + return err; + }, + error.UnsupportedEncoding => { + try log_file.err(io, "tui", "dur_file loaded was invalid: unsupported encoding ({s})!", .{dur_movie_raw.encoding.?}); + return err; + }, + error.MissingFieldFramerate => { + try log_file.err(io, "tui", "dur_file loaded was invalid: missing field framerate!", .{}); + return err; + }, + error.InvalidFramerate => { + try log_file.err(io, "tui", "dur_file loaded was invalid: negative framerate value found!", .{}); + return err; + }, + error.MissingDimensions => { + try log_file.err(io, "tui", "dur_file loaded was invalid: missing field(s) lines and/or columns!", .{}); + return err; + }, + error.InvalidColumnCount => { + try log_file.err(io, "tui", "dur_file loaded was invalid: columns value falls outside of supported range ({d})!", .{dur_movie_raw.columns.?}); + return err; + }, + error.InvalidLineCount => { + try log_file.err(io, "tui", "dur_file loaded was invalid: lines value falls outside of supported range ({d})!", .{dur_movie_raw.lines.?}); + return err; + }, + error.NoFrames => { + try log_file.err(io, "tui", "dur_file loaded was invalid: animation has no frames!", .{}); + return err; + }, + }; + // 4 bit mode with 256 color is unsupported - if (!full_color and eql(u8, dur_movie.colorFormat.?, "256")) { + if (!full_color and dur_movie.colorFormat == .@"256") { try log_file.err(io, "tui", "dur_file can not be 256 color encoded when not using full_color option!", .{}); dur_movie.deinit(); - return error.InvalidColorFormat; + return error.NotFullColor; } const offset: IVec2 = .{ x_offset, y_offset }; - const start_pos = calc_start_position(terminal_buffer, &dur_movie, offset_alignment, offset); + const start_pos = calculateStartPos(terminal_buffer, &dur_movie, offset_alignment, offset); // Convert dur fps to frames per ms - const frame_time: u32 = @trunc(1000 / dur_movie.framerate.?); + const frame_time: u32 = @trunc(1000 / dur_movie.framerate); return .{ .instance = null, @@ -406,7 +474,7 @@ pub fn init( .frame_delay = frame_delay, .dur_movie = dur_movie, .frame_time = frame_time, - .is_color_format_16 = eql(u8, dur_movie.colorFormat.?, "16"), + .is_color_format_16 = dur_movie.colorFormat == .@"16", .offset_alignment = offset_alignment, .offset = offset, }; @@ -434,7 +502,7 @@ fn deinit(self: *DurFile) void { fn realloc(self: *DurFile) !void { // when terminal size changes, we need to recalculate the start_pos based on the new size - self.start_pos = calc_start_position(self.terminal_buffer, &self.dur_movie, self.offset_alignment, self.offset); + self.start_pos = calculateStartPos(self.terminal_buffer, &self.dur_movie, self.offset_alignment, self.offset); } fn draw(self: *DurFile) void { @@ -443,12 +511,12 @@ fn draw(self: *DurFile) void { const current_frame = self.dur_movie.frames.items[self.frames]; // y is used as an iterator in the durformat, while cell_y gives us the correct placement for the cell (same for x) - for (0..@intCast(self.dur_movie.lines.?)) |y| { + for (0..@intCast(self.dur_movie.lines)) |y| { const cell_y = @as(i32, @intCast(y)) + self.start_pos[VEC_Y]; var iter = std.unicode.Utf8View.initUnchecked(current_frame.contents[y]).iterator(); - for (0..@intCast(self.dur_movie.columns.?)) |x| { + for (0..@intCast(self.dur_movie.columns)) |x| { const cell_x = @as(i32, @intCast(x)) + self.start_pos[VEC_X]; const codepoint: u21 = iter.nextCodepoint().?; @@ -462,12 +530,12 @@ fn draw(self: *DurFile) void { color_map_1 = durcolor_table_to_color16[color_map_1 + 1]; // Add 1, dur source stores it like this for some reason } - const fg_color = if (self.full_color) convert_256_to_rgb(color_map_0) else tb_color_16[color_map_0]; - const bg_color = if (self.full_color) convert_256_to_rgb(color_map_1) else tb_color_16[color_map_1]; + const fg_color = if (self.full_color) convert256ToRgb(color_map_0) else tb_color_16[color_map_0]; + const bg_color = if (self.full_color) convert256ToRgb(color_map_1) else tb_color_16[color_map_1]; const cell = Cell{ .ch = @intCast(codepoint), .fg = fg_color, .bg = bg_color }; - self.terminal_buffer.setCellBoundsChecked(cell_x, cell_y, cell); + self.terminal_buffer.setCellBoundsChecked(cell_x, cell_y, cell) catch {}; } } diff --git a/src/animations/GameOfLife.zig b/src/animations/GameOfLife.zig index c100c52..6e9a16c 100644 --- a/src/animations/GameOfLife.zig +++ b/src/animations/GameOfLife.zig @@ -146,7 +146,7 @@ fn draw(self: *GameOfLife) void { const row_offset = y * self.width; for (0..self.width) |x| { const cell = if (self.current_grid[row_offset + x]) alive_cell else self.dead_cell; - cell.put(x, y); + cell.put(x, y) catch {}; } } } diff --git a/src/animations/Lua.zig b/src/animations/Lua.zig new file mode 100644 index 0000000..2d2956f --- /dev/null +++ b/src/animations/Lua.zig @@ -0,0 +1,304 @@ +const std = @import("std"); +const ly_ui = @import("ly-ui"); +const LogFile = ly_ui.ly_core.LogFile; +const Widget = ly_ui.Widget; +const TerminalBuffer = ly_ui.TerminalBuffer; +const Cell = ly_ui.Cell; +const Allocator = std.mem.Allocator; +const InfoLine = @import("../components/InfoLine.zig"); +const Lang = @import("../config/Lang.zig"); + +const zlua = @import("zlua"); + +const ly_lua = @embedFile("ly.lua"); + +const Lua = @This(); + +allocator: Allocator, +instance: ?Widget = null, +lua: *zlua.Lua, +log: *LogFile, +terminal_buffer: *TerminalBuffer, +width: usize, +height: usize, +margin: usize, +io: std.Io, +animation_delay: u16, + +info_line: *InfoLine, +fg: u32, +bg: u32, + +lang: Lang, +full_color: bool, + +lua_error: bool = false, +lua_error_logged: bool = false, +lua_str: ?[:0]const u8 = null, + +pub fn init( + io: std.Io, + alloc: Allocator, + log: *LogFile, + buf: *TerminalBuffer, + file: []const u8, + margin: u8, + animation_delay: u16, + info_line: *InfoLine, + fg: u32, + bg: u32, + lang: Lang, + full_color: bool, +) !Lua { + var self: Lua = .{ + .lua = try zlua.Lua.init(alloc), + .allocator = alloc, + .terminal_buffer = buf, + .instance = null, + .log = log, + .width = 0, + .height = 0, + .margin = margin, + .io = io, + .animation_delay = animation_delay, + .info_line = info_line, + .fg = fg, + .bg = bg, + .lang = lang, + .full_color = full_color, + }; + + // exclude IO and debug libraries + self.lua.openBase(); + self.lua.openBit(); + self.lua.openMath(); + self.lua.openString(); + self.lua.openTable(); + + file_loading: { + const zf = std.mem.concatWithSentinel(alloc, u8, &[1][]const u8{file}, 0) catch |e| { + try self.log.err(self.io, "lua", "failed to allocate file path: {}", .{e}); + self.lua_str = "failed to allocate file path!"; + self.info_line.addMessage(lang.err_alloc, self.bg, self.fg) catch {}; + return e; + }; + defer alloc.free(zf); + + // create the ly table + self.lua.newTable(); + self.lua.setGlobal("ly"); + + // create ly.width and ly.height from TerminalBuffer width/height + self.propagateTerminalBounds(); + + _ = self.lua.getGlobal("ly"); + _ = self.lua.pushString("clock"); + self.lua.pushFunction(luaLyClock); + self.lua.setTable(-3); + _ = self.lua.pushString("putCell"); + self.lua.pushFunction(luaPutCell); + self.lua.setTable(-3); + _ = self.lua.pushString("putLabel"); + self.lua.pushFunction(luaPutLabel); + self.lua.setTable(-3); + _ = self.lua.pushString("putRect"); + self.lua.pushFunction(luaPutRect); + self.lua.setTable(-3); + self.lua.setGlobal("ly"); + + self.lua.doFile(zf) catch { + const errorStr = self.lua.toString(-1) catch unreachable; + self.lua_str = try self.allocator.dupeSentinel(u8, errorStr, 0); + try self.log.err(self.io, "lua", "lua error: {s}", .{errorStr}); + self.lua_error = true; + break :file_loading; + }; + } + + return self; +} + +fn draw(self: *Lua) void { + self.propagateTerminalBounds(); + if (self.lua_error) { + // Ly's Red Screen of Omega-Death:tm: + const RED: u32 = if (self.full_color) TerminalBuffer.Color.TRUE_RED else TerminalBuffer.Color.ECOL_RED; + const cell = Cell.init(0x2588, RED, RED); + for (0..self.terminal_buffer.height) |y| + for (0..self.terminal_buffer.width) |x| + cell.put(x, y) catch {}; + if (self.lua_str) |str| + for (str, 0..) |c, i| { + const dwidth = @divFloor(self.width, 2); + const dlen = @divFloor(str.len, 2); + Cell.init(c, 0x00FFFFFF, 0).put( + (if (dlen > dwidth) 0 else dwidth - dlen) + i, + self.margin + 5, + ) catch {}; + }; + if (!self.lua_error_logged) { + self.info_line.addMessage("lua animation failed", self.bg, self.fg) catch {}; + self.lua_error_logged = true; + } + return; + } + + _ = self.lua.getGlobal("draw"); + self.lua.protectedCall(.{}) catch { + const errorStr = self.lua.toString(-1) catch unreachable; + self.lua_str = std.mem.concatWithSentinel( + self.allocator, + u8, + &.{ "cannot call draw(): ", errorStr }, + 0, + ) catch unreachable; + self.log.err(self.io, "lua", "error (cannot call draw()): {s}", .{errorStr}) catch unreachable; + self.lua_error = true; + }; +} + +fn calculateTimeout(self: *Lua, _: *anyopaque) !?usize { + return self.animation_delay; +} + +fn deinit(self: *Lua) void { + if (self.lua_str) |str| self.allocator.free(str); + self.lua.deinit(); +} + +pub fn widget(self: *Lua) *Widget { + if (self.instance) |*inst| return inst; + self.instance = Widget.init( + "Lua", + null, + self, + deinit, + null, + draw, + null, + null, + calculateTimeout, + ); + return &self.instance.?; +} + +fn propagateTerminalBounds(self: *Lua) void { + if (self.terminal_buffer.height == self.height and + self.terminal_buffer.width == self.width) + return; + self.width = self.terminal_buffer.width; + self.height = self.terminal_buffer.height; + _ = self.lua.getGlobal("ly"); + _ = self.lua.pushString("width"); + self.lua.pushInteger(@intCast(self.terminal_buffer.width)); + self.lua.setTable(-3); + _ = self.lua.pushString("height"); + self.lua.pushInteger(@intCast(self.terminal_buffer.height)); + self.lua.setTable(-3); + self.lua.setGlobal("ly"); +} + +fn luaLyClock(state: ?*zlua.LuaState) callconv(.c) c_int { + var threaded = std.Io.Threaded.init_single_threaded; + const lua: *zlua.Lua = @ptrCast(@alignCast(state orelse unreachable)); + lua.pushInteger(std.Io.Timestamp.now(threaded.io(), .real).toMicroseconds()); + return 1; +} + +fn luaPutCell(state: ?*zlua.LuaState) callconv(.c) c_int { + const lua: *zlua.Lua = @ptrCast(@alignCast(state orelse unreachable)); + const MSG = "ly.putCell: cannot convert %s-typed "; + const byte = lua.toNumeric(u32, 1) catch { + const t = lua.typeName(lua.typeOf(1)); + lua.raiseErrorStr(MSG ++ "byte to u32", .{t.ptr}); + }; + const fg = lua.toNumeric(u32, 2) catch { + const t = lua.typeName(lua.typeOf(2)); + lua.raiseErrorStr(MSG ++ "fg to u32", .{t.ptr}); + }; + const bg = lua.toNumeric(u32, 3) catch { + const t = lua.typeName(lua.typeOf(3)); + lua.raiseErrorStr(MSG ++ "bg to u32", .{t.ptr}); + }; + const x = lua.toNumeric(usize, 4) catch { + const t = lua.typeName(lua.typeOf(4)); + lua.raiseErrorStr(MSG ++ "x to usize", .{t.ptr}); + }; + const y = lua.toNumeric(usize, 5) catch { + const t = lua.typeName(lua.typeOf(5)); + lua.raiseErrorStr(MSG ++ "y to usize", .{t.ptr}); + }; + TerminalBuffer.setCell(x, y, .{ + .fg = fg, + .bg = bg, + .ch = byte, + }) catch {}; + return 0; +} + +fn luaPutRect(state: ?*zlua.LuaState) callconv(.c) c_int { + const lua: *zlua.Lua = @ptrCast(@alignCast(state orelse unreachable)); + const MSG = "ly.putRect: cannot convert %s-typed "; + const byte = lua.toNumeric(u32, 1) catch { + const t = lua.typeName(lua.typeOf(1)); + lua.raiseErrorStr(MSG ++ "byte to u32", .{t.ptr}); + }; + const fg = lua.toNumeric(u32, 2) catch { + const t = lua.typeName(lua.typeOf(2)); + lua.raiseErrorStr(MSG ++ "fg to u32", .{t.ptr}); + }; + const bg = lua.toNumeric(u32, 3) catch { + const t = lua.typeName(lua.typeOf(3)); + lua.raiseErrorStr(MSG ++ "bg to u32", .{t.ptr}); + }; + const x = lua.toNumeric(usize, 4) catch { + const t = lua.typeName(lua.typeOf(4)); + lua.raiseErrorStr(MSG ++ "x to usize", .{t.ptr}); + }; + const y = lua.toNumeric(usize, 5) catch { + const t = lua.typeName(lua.typeOf(5)); + lua.raiseErrorStr(MSG ++ "y to usize", .{t.ptr}); + }; + const w = lua.toNumeric(usize, 6) catch { + const t = lua.typeName(lua.typeOf(5)); + lua.raiseErrorStr(MSG ++ "w to usize", .{t.ptr}); + }; + const h = lua.toNumeric(usize, 7) catch { + const t = lua.typeName(lua.typeOf(5)); + lua.raiseErrorStr(MSG ++ "h to usize", .{t.ptr}); + }; + for (0..w) |wx| for (0..h) |hy| + TerminalBuffer.setCell(x + wx, y + hy, .{ + .fg = fg, + .bg = bg, + .ch = byte, + }) catch {}; + return 0; +} + +fn luaPutLabel(state: ?*zlua.LuaState) callconv(.c) c_int { + const lua: *zlua.Lua = @ptrCast(@alignCast(state orelse unreachable)); + const MSG = "ly.putLabel: cannot convert %s-typed "; + const str = lua.toString(1) catch { + const t = lua.typeName(lua.typeOf(2)); + lua.raiseErrorStr(MSG ++ "str to string", .{t.ptr}); + }; + const fg = lua.toNumeric(u32, 2) catch { + const t = lua.typeName(lua.typeOf(2)); + lua.raiseErrorStr(MSG ++ "fg to u32", .{t.ptr}); + }; + const bg = lua.toNumeric(u32, 3) catch { + const t = lua.typeName(lua.typeOf(3)); + lua.raiseErrorStr(MSG ++ "bg to u32", .{t.ptr}); + }; + const x = lua.toNumeric(usize, 4) catch { + const t = lua.typeName(lua.typeOf(4)); + lua.raiseErrorStr(MSG ++ "x to usize", .{t.ptr}); + }; + const y = lua.toNumeric(usize, 5) catch { + const t = lua.typeName(lua.typeOf(5)); + lua.raiseErrorStr(MSG ++ "y to usize", .{t.ptr}); + }; + TerminalBuffer.drawText(str, x, y, fg, bg) catch {}; + return 0; +} diff --git a/src/animations/Matrix.zig b/src/animations/Matrix.zig index e7af489..3d43118 100644 --- a/src/animations/Matrix.zig +++ b/src/animations/Matrix.zig @@ -200,9 +200,9 @@ fn draw(self: *Matrix) void { .bg = self.terminal_buffer.bg, }; - cell.put(x, y - 1); + cell.put(x, y - 1) catch {}; // Fill background in between columns - self.default_cell.put(x + 1, y - 1); + self.default_cell.put(x + 1, y - 1) catch {}; } } } diff --git a/src/auth.zig b/src/auth.zig index 6a97fff..7d9c66c 100644 --- a/src/auth.zig +++ b/src/auth.zig @@ -105,6 +105,11 @@ pub fn authenticate(allocator: std.mem.Allocator, io: std.Io, log_file: *LogFile try log_file.info(io, "auth/passwd", "setting user shell", .{}); if (user_entry.shell == null) interop.setUserShell(&user_entry); + // chown & chmod stdin (which is the TTY) + // https://github.com/mirror/busybox/blob/371fe9f71d445d18be28c82a2a6d82115c8af19d/loginutils/login.c#L558 + if (interop.isError(std.posix.system.fchown(std.posix.STDIN_FILENO, user_entry.uid, user_entry.gid))) return error.TtyChownFailed; + if (interop.isError(std.posix.system.fchmod(std.posix.STDIN_FILENO, 0o600))) return error.TtyChmodFailed; + var shared_err = try SharedError.init(null, null); defer shared_err.deinit(); @@ -179,17 +184,19 @@ fn startSession( // Reset the XDG environment variables try log_file.info(io, "auth/env", "resetting xdg environment variables", .{}); try setXdgEnv(allocator, tty_str, current_environment); - try setXdgRuntimeDir(allocator); + try setXdgRuntimeDir(allocator, io); // Set the PAM variables const pam_env_vars: ?[*:null]?[*:0]u8 = interop.pam.pam_getenvlist(handle); if (pam_env_vars == null) return error.GetEnvListFailed; const env_list = std.mem.span(pam_env_vars.?); - for (env_list) |env_var| { - if (env_var == null) continue; - try log_file.info(io, "auth/env", "setting pam environment variable: {s}", .{std.mem.span(env_var.?)}); - try interop.putEnvironmentVariable(env_var); + for (env_list) |maybe_env_var| { + if (maybe_env_var) |env_var| { + const env_var_slice = std.mem.span(env_var); + try log_file.info(io, "auth/env", "setting pam environment variable: {s}", .{env_var_slice}); + try interop.putEnvironmentVariable(env_var_slice); + } } const home_z = try allocator.dupeZ(u8, user_entry.home.?); @@ -247,18 +254,20 @@ fn setXdgEnv(allocator: std.mem.Allocator, tty_str: []u8, environment: Environme try interop.setEnvironmentVariable(allocator, "XDG_VTNR", tty_str, false); } -fn setXdgRuntimeDir(allocator: std.mem.Allocator) !void { - // The "/run/user/%d" directory is not available on FreeBSD. It is much - // better to stick to the defaults and let applications using - // XDG_RUNTIME_DIR to fall back to directories inside user's home - // directory. - if (builtin.os.tag != .freebsd) { - const uid = std.posix.system.getuid(); - var uid_buffer: [32]u8 = undefined; // No UID can be larger than this - const uid_str = try std.fmt.bufPrint(&uid_buffer, "/run/user/{d}", .{uid}); +fn setXdgRuntimeDir(allocator: std.mem.Allocator, io: std.Io) !void { + // The "/run/user/%d" directory is not available on some operating systems, + // like FreeBSD and Alpine + const uid = std.posix.system.getuid(); + var uid_buffer: [32]u8 = undefined; // No UID can be larger than this + const uid_str = try std.fmt.bufPrint(&uid_buffer, "/run/user/{d}", .{uid}); - try interop.setEnvironmentVariable(allocator, "XDG_RUNTIME_DIR", uid_str, false); - } + var xdg_dir = std.Io.Dir.openDirAbsolute(io, uid_str, .{}) catch |err| { + if (err == error.FileNotFound) return; + return err; + }; + xdg_dir.close(io); + + try interop.setEnvironmentVariable(allocator, "XDG_RUNTIME_DIR", uid_str, false); } fn loginConv( @@ -390,7 +399,7 @@ fn createXauthFile(log_file: *LogFile, io: std.Io, pwd: []const u8, buffer: []u8 const xauthority: []u8 = try std.fmt.bufPrint(buffer, "{s}/{s}", .{ trimmed_xauth_dir, xauth_file }); - std.Io.Dir.cwd().createDirPath(io, trimmed_xauth_dir) catch {}; + try std.Io.Dir.cwd().createDirPath(io, trimmed_xauth_dir); try log_file.info(io, "auth/x11", "creating xauth file: {s}", .{xauthority}); @@ -565,7 +574,15 @@ fn executeCmd(global_log_file: *LogFile, allocator: std.mem.Allocator, io: std.I fn redirectStandardStreams(global_log_file: *LogFile, io: std.Io, session_log: []const u8, create: bool) !std.Io.File { create_session_log_dir: { const session_log_dir = std.Io.Dir.path.dirname(session_log) orelse break :create_session_log_dir; - std.Io.Dir.cwd().createDirPath(io, session_log_dir) catch |err| { + + var buffer = std.mem.zeroes([std.Io.Dir.max_path_bytes]u8); + const len = std.Io.Dir.cwd().realPathFile(io, session_log_dir, &buffer) catch |err| { + try global_log_file.err(io, "auth/sys", "failed to resolve path for session log file directory: {s}", .{@errorName(err)}); + return err; + }; + const resolved_path = buffer[0..len]; + + std.Io.Dir.cwd().createDirPath(io, resolved_path) catch |err| { try global_log_file.err(io, "auth/sys", "failed to create session log file directory: {s}", .{@errorName(err)}); return err; }; diff --git a/src/components/InfoLine.zig b/src/components/InfoLine.zig index 97a8a73..45b5da3 100644 --- a/src/components/InfoLine.zig +++ b/src/components/InfoLine.zig @@ -84,7 +84,7 @@ pub fn clearRendered(self: InfoLine, allocator: Allocator) !void { @memset(spaces, ' '); - TerminalBuffer.drawText( + try TerminalBuffer.drawText( spaces, self.label.component_pos.x + 2, self.label.component_pos.y, @@ -98,7 +98,7 @@ fn draw(self: *InfoLine) void { } fn handle(self: *InfoLine, maybe_key: ?keyboard.Key) !void { - self.label.handle(maybe_key); + try self.label.handle(maybe_key); } fn drawItem(label: *MessageLabel, message: Message, x: usize, y: usize, width: usize) void { @@ -114,5 +114,5 @@ fn drawItem(label: *MessageLabel, message: Message, x: usize, y: usize, width: u width, message.fg, message.bg, - ); + ) catch {}; } diff --git a/src/components/Session.zig b/src/components/Session.zig index 1e975c6..fe8c498 100644 --- a/src/components/Session.zig +++ b/src/components/Session.zig @@ -14,19 +14,19 @@ const Env = struct { environment: Environment, index: usize, }; -const EnvironmentLabel = CyclableLabel(Env, *UserList); +const EnvironmentLabel = CyclableLabel(Env, *?UserList); const Session = @This(); instance: ?Widget = null, label: *EnvironmentLabel, -user_list: *UserList, +user_list: *?UserList, pub fn init( allocator: Allocator, io: std.Io, buffer: *TerminalBuffer, - user_list: *UserList, + user_list: *?UserList, width: usize, text_in_center: bool, fg: u32, @@ -79,7 +79,7 @@ pub fn addEnvironment(self: *Session, environment: Environment) !void { const env = Env{ .environment = environment, .index = self.label.list.items.len }; try self.label.addItem(env); - addedSession(env, self.user_list); + if (self.user_list.*) |w| addedSession(env, w); } fn draw(self: *Session) void { @@ -87,19 +87,19 @@ fn draw(self: *Session) void { } fn handle(self: *Session, maybe_key: ?keyboard.Key) !void { - self.label.handle(maybe_key); + try self.label.handle(maybe_key); } -fn addedSession(env: Env, user_list: *UserList) void { +fn addedSession(env: Env, user_list: UserList) void { const user = user_list.label.list.items[user_list.label.current]; if (!user.first_run) return; user.session_index.* = env.index; } -fn sessionChanged(env: Env, maybe_user_list: ?*UserList) void { +fn sessionChanged(env: Env, maybe_user_list: ?*?UserList) void { if (maybe_user_list) |user_list| { - user_list.label.list.items[user_list.label.current].session_index.* = env.index; + if (user_list.*) |w| w.label.list.items[w.label.current].session_index.* = env.index; } } @@ -119,5 +119,5 @@ fn drawItem(label: *EnvironmentLabel, env: Env, x: usize, y: usize, width: usize width, label.fg, label.bg, - ); + ) catch {}; } diff --git a/src/components/UserList.zig b/src/components/UserList.zig index c407173..1be513c 100644 --- a/src/components/UserList.zig +++ b/src/components/UserList.zig @@ -10,7 +10,7 @@ const CyclableLabel = ly_ui.CyclableLabel; const Session = @import("Session.zig"); const SavedUsers = @import("../config/SavedUsers.zig"); -const StringList = std.ArrayListUnmanaged([]const u8); +const StringList = std.ArrayList([]const u8); pub const User = struct { name: []const u8, session_index: *usize, @@ -118,7 +118,7 @@ fn draw(self: *UserList) void { } fn handle(self: *UserList, maybe_key: ?keyboard.Key) !void { - self.label.handle(maybe_key); + try self.label.handle(maybe_key); } fn usernameChanged(user: User, maybe_session: ?*Session) void { @@ -143,5 +143,5 @@ fn drawItem(label: *UserLabel, user: User, x: usize, y: usize, width: usize) voi width, label.fg, label.bg, - ); + ) catch {}; } diff --git a/src/config/Config.zig b/src/config/Config.zig index 2233cb4..2ba8444 100644 --- a/src/config/Config.zig +++ b/src/config/Config.zig @@ -13,16 +13,18 @@ animation_frame_delay: u16 = 5, animation_timeout_sec: u12 = 0, asterisk: ?u32 = '*', auth_fails: u64 = 10, -battery_id: ?[]const u8 = null, auto_login_service: [:0]const u8 = "ly-autologin", auto_login_session: ?[]const u8 = null, auto_login_user: ?[]const u8 = null, +battery_id: ?[]const u8 = null, bg: u32 = 0x00000000, bigclock: Bigclock = .none, bigclock_12hr: bool = false, bigclock_seconds: bool = false, blank_box: bool = true, border_fg: u32 = 0x00FFFFFF, +box_position_h: f32 = 0.5, +box_position_v: f32 = 0.5, box_title: ?[]const u8 = null, brightness_down_cmd: [:0]const u8 = build_options.prefix_directory ++ "/bin/brightnessctl -q -n s 10%-", brightness_down_key: ?[]const u8 = "F5", @@ -37,6 +39,10 @@ cmatrix_max_codepoint: u16 = 0x7B, colormix_col1: u32 = 0x00FF0000, colormix_col2: u32 = 0x000000FF, colormix_col3: u32 = 0x20000000, +corner_bottom_left: []const u8 = "version", +corner_bottom_right: []const u8 = "labels", +corner_top_left: []const u8 = "shutdown,restart,britup,britdown,password battery", +corner_top_right: []const u8 = "clock numlock,capslock", custom_bind_width: ?u32 = null, custom_sessions: []const u8 = build_options.config_directory ++ "/ly/custom-sessions", default_input: Input = .login, @@ -58,12 +64,7 @@ gameoflife_fg: u32 = 0x0000FF00, gameoflife_entropy_interval: usize = 10, gameoflife_frame_delay: usize = 6, gameoflife_initial_density: f32 = 0.4, -hibernate_cmd: ?[]const u8 = null, -hibernate_key: []const u8 = "F4", hide_borders: bool = false, -hide_key_hints: bool = false, -hide_keyboard_locks: bool = false, -hide_version_string: bool = false, inactivity_cmd: ?[]const u8 = null, inactivity_delay: u16 = 0, initial_info_text: ?[]const u8 = null, @@ -72,26 +73,23 @@ lang: []const u8 = "en", login_cmd: ?[]const u8 = null, login_defs_path: []const u8 = "/etc/login.defs", logout_cmd: ?[]const u8 = null, -ly_log: []const u8 = "/var/log/ly.log", +lua_animation_file: []const u8 = build_options.config_directory ++ "/ly/example.lua", +ly_log: ?[]const u8 = "/var/log/ly.log", margin_box_h: u8 = 2, margin_box_v: u8 = 1, numlock: bool = false, path: ?[]const u8 = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", -restart_cmd: []const u8 = "/sbin/shutdown -r now", -restart_key: []const u8 = "F2", -save: bool = true, +restart_key: ?[]const u8 = "F2", +save_file_dir: ?[]const u8 = build_options.config_directory ++ "/ly", service_name: [:0]const u8 = "ly", session_log: ?[]const u8 = "ly-session.log", setup_cmd: []const u8 = build_options.config_directory ++ "/ly/setup.sh", shell: bool = true, -show_password_key: []const u8 = "F7", -show_tty: bool = false, -shutdown_cmd: []const u8 = "/sbin/shutdown -a now", -shutdown_key: []const u8 = "F1", -sleep_cmd: ?[]const u8 = null, -sleep_key: []const u8 = "F3", +show_password_key: ?[]const u8 = "F7", +shutdown_key: ?[]const u8 = "F1", start_cmd: ?[]const u8 = null, text_in_center: bool = false, +type_username: bool = false, vi_default_mode: ViMode = .normal, vi_mode: bool = false, waylandsessions: ?[]const u8 = build_options.prefix_directory ++ "/share/wayland-sessions", diff --git a/src/config/migrator.zig b/src/config/migrator.zig index 366bc81..4ed4d2e 100644 --- a/src/config/migrator.zig +++ b/src/config/migrator.zig @@ -2,6 +2,7 @@ // Properties removed or changed since 0.6.0 // Color codes interpreted differently since 1.1.0 +const build_options = @import("build_options"); const std = @import("std"); var temporary_allocator = std.heap.page_allocator; @@ -14,6 +15,7 @@ const IniParser = ly_core.IniParser; const ini = ly_core.ini; const Config = @import("Config.zig"); +const Lang = @import("Lang.zig"); const OldSave = @import("OldSave.zig"); const SavedUsers = @import("SavedUsers.zig"); const custom = @import("custom.zig"); @@ -45,12 +47,23 @@ const removed_properties = [_][]const u8{ "wayland_cmd", "console_dev", "load", + "shutdown_cmd", + "restart_cmd", + // Migrating these isn't worth the effort so just say we removed them + "hide_key_hints", + "hide_keyboard_locks", + "hide_version_string", + "show_tty", }; pub var auto_eight_colors: bool = true; pub var maybe_animate: ?bool = null; pub var maybe_save_file: ?[]const u8 = null; +pub var maybe_sleep_key: ?[]const u8 = null; +pub var maybe_sleep_cmd: ?[]const u8 = null; +pub var maybe_hibernate_key: ?[]const u8 = null; +pub var maybe_hibernate_cmd: ?[]const u8 = null; pub fn configFieldHandler(_: std.mem.Allocator, field: ini.IniField) ?ini.IniField { if (std.mem.eql(u8, field.key, "animate")) { @@ -124,7 +137,6 @@ pub fn configFieldHandler(_: std.mem.Allocator, field: ini.IniField) ?ini.IniFie if (std.mem.eql(u8, field.key, "save_file")) { // The option doesn't exist anymore, but we save its value for migration later on maybe_save_file = temporary_allocator.dupe(u8, field.value) catch return null; - return null; } @@ -163,6 +175,39 @@ pub fn configFieldHandler(_: std.mem.Allocator, field: ini.IniField) ?ini.IniFie return mapped_field; } + if (std.mem.eql(u8, field.key, "sleep_key")) { + maybe_sleep_key = temporary_allocator.dupe(u8, field.value) catch return null; + return null; + } + + if (std.mem.eql(u8, field.key, "sleep_cmd")) { + maybe_sleep_cmd = temporary_allocator.dupe(u8, field.value) catch return null; + return null; + } + + if (std.mem.eql(u8, field.key, "hibernate_key")) { + maybe_hibernate_key = temporary_allocator.dupe(u8, field.value) catch return null; + return null; + } + + if (std.mem.eql(u8, field.key, "hibernate_cmd")) { + maybe_hibernate_cmd = temporary_allocator.dupe(u8, field.value) catch return null; + return null; + } + + if (std.mem.eql(u8, field.key, "save")) { + // The option now uses a string for the file's parent directory + var mapped_field = field; + + if (std.mem.eql(u8, field.value, "true")) { + mapped_field.value = build_options.config_directory ++ "/ly"; + } else if (std.mem.eql(u8, field.value, "false")) { + mapped_field.value = "null"; + } + + return mapped_field; + } + // TODO: Dearest Melpert, // I pray this message finds you well, as daylight dwindles and the witching hour // approaches, I find it more and more imperative as time continues that I place @@ -223,7 +268,7 @@ pub fn configFieldHandler(_: std.mem.Allocator, field: ini.IniField) ?ini.IniFie // This is the stuff we only handle after reading the config. // For example, the "animate" field could come after "animation" -pub fn lateConfigFieldHandler(config: *Config) void { +pub fn lateConfigFieldHandler(config: *Config, lang: Lang) void { if (maybe_animate) |animate| { if (!animate) config.*.animation = .none; } @@ -252,6 +297,24 @@ pub fn lateConfigFieldHandler(config: *Config) void { if (!set_color_properties[7]) config.error_fg = Styling.BOLD | Color.ECOL_RED; if (!set_color_properties[8]) config.fg = Color.ECOL_WHITE; } + + if (maybe_sleep_key) |key| { + if (maybe_sleep_cmd) |cmd| { + custom.binds.put(temporary_allocator, key, .{ + .name = temporary_allocator.dupe(u8, lang.sleep) catch "", + .cmd = cmd, + }) catch {}; + } + } + + if (maybe_hibernate_key) |key| { + if (maybe_hibernate_cmd) |cmd| { + custom.binds.put(temporary_allocator, key, .{ + .name = temporary_allocator.dupe(u8, lang.hibernate) catch "", + .cmd = cmd, + }) catch {}; + } + } } pub fn tryMigrateIniSaveFile(allocator: std.mem.Allocator, io: std.Io, path: []const u8, saved_users: *SavedUsers, usernames: [][]const u8) !?IniParser(OldSave) { @@ -284,8 +347,6 @@ pub fn tryMigrateIniSaveFile(allocator: std.mem.Allocator, io: std.Io, path: []c fn tryMigrateFirstSaveFile(io: std.Io, user_buf: *[32]u8) ?OldSave { if (maybe_save_file) |path| { - defer temporary_allocator.free(path); - var save = OldSave{}; var file = std.Io.Dir.openFileAbsolute(io, path, .{}) catch return null; defer file.close(io); diff --git a/src/enums.zig b/src/enums.zig index 47771da..ff69f84 100644 --- a/src/enums.zig +++ b/src/enums.zig @@ -7,6 +7,7 @@ pub const Animation = enum { colormix, gameoflife, dur_file, + lua, }; pub const DisplayServer = enum { diff --git a/src/main.zig b/src/main.zig index f9f4a51..1d0db99 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,6 +1,6 @@ const std = @import("std"); const Allocator = std.mem.Allocator; -const StringList = std.ArrayListUnmanaged([]const u8); +const StringList = std.ArrayList([]const u8); const temporary_allocator = std.heap.page_allocator; const builtin = @import("builtin"); const build_options = @import("build_options"); @@ -29,6 +29,7 @@ const Doom = @import("animations/Doom.zig"); const DurFile = @import("animations/DurFile.zig"); const GameOfLife = @import("animations/GameOfLife.zig"); const Matrix = @import("animations/Matrix.zig"); +const Lua = @import("animations/Lua.zig"); const auth = @import("auth.zig"); const InfoLine = @import("components/InfoLine.zig"); const Session = @import("components/Session.zig"); @@ -56,12 +57,12 @@ fn signalHandler(sig: std.posix.SIG) callconv(.c) void { _ = std.c.waitpid(session_pid, &status, 0); } - TerminalBuffer.shutdown(); + TerminalBuffer.shutdown() catch {}; std.c.exit(@intCast(@intFromEnum(sig))); } fn ttyControlTransferSignalHandler(_: std.posix.SIG) callconv(.c) void { - TerminalBuffer.shutdown(); + TerminalBuffer.shutdown() catch {}; } const CustomBindLabel = struct { @@ -87,8 +88,6 @@ const UiState = struct { labels_max_length: usize, shutdown_label: Label, restart_label: Label, - sleep_label: Label, - hibernate_label: Label, toggle_password_label: Label, brightness_down_label: Label, brightness_up_label: Label, @@ -106,8 +105,10 @@ const UiState = struct { info_line: InfoLine, animate: bool, session: Session, + saved_username: ?[]const u8, saved_users: SavedUsers, - login: UserList, + login: ?UserList, + login_text: ?*Text, password: *Text, password_widget: *Widget, insert_mode: bool, @@ -131,9 +132,6 @@ var shutdown = false; var restart = false; pub fn main(init: std.process.Init) !void { - var shutdown_cmd: []const u8 = undefined; - var restart_cmd: []const u8 = undefined; - var commands_allocated = false; var state: UiState = undefined; state.io = init.io; @@ -142,28 +140,20 @@ pub fn main(init: std.process.Init) !void { var stderr_writer = std.Io.File.stderr().writer(state.io, &stderr_buffer); var stderr = &stderr_writer.interface; + // If we can't shutdown or restart due to an error, we print it to standard error. If that fails, just bail out defer { - // If we can't shutdown or restart due to an error, we print it to standard error. If that fails, just bail out if (shutdown) { - const shutdown_error = std.process.replace(state.io, .{ .argv = &[_][]const u8{ "/bin/sh", "-c", shutdown_cmd } }); - stderr.print("error: couldn't shutdown: {s}\n", .{@errorName(shutdown_error)}) catch std.process.exit(1); - stderr.flush() catch std.process.exit(1); + interop.shutdownSystem() catch std.log.err("whoopsie doodle, couldn't shutdown system!", .{}); } else if (restart) { - const restart_error = std.process.replace(state.io, .{ .argv = &[_][]const u8{ "/bin/sh", "-c", restart_cmd } }); - stderr.print("error: couldn't restart: {s}\n", .{@errorName(restart_error)}) catch std.process.exit(1); - stderr.flush() catch std.process.exit(1); - } else { - // The user has quit Ly using Ctrl+C - if (commands_allocated) { - // Necessary if we error out before allocating - temporary_allocator.free(shutdown_cmd); - temporary_allocator.free(restart_cmd); - } + interop.rebootSystem() catch std.log.err("whoopsie doodle, couldn't restart system!", .{}); } } - var gpa = std.heap.DebugAllocator(.{}).init; - defer _ = gpa.deinit(); + var gpa: std.heap.DebugAllocator(.{ + .never_unmap = builtin.mode == .Debug, + .retain_metadata = builtin.mode == .Debug, + }) = .init; + defer if (gpa.deinit() == .leak) std.log.err("attention please, memory has been leaked!", .{}); state.allocator = gpa.allocator(); @@ -172,7 +162,8 @@ pub fn main(init: std.process.Init) !void { \\-h, --help Shows all commands. \\-v, --version Shows the version of Ly. \\-c, --config Overrides the default configuration path. Example: --config /usr/share/ly - \\--use-kmscon-vt Use KMSCON instead of kernel VT + \\--use-kmscon-vt Uses KMSCON instead of the kernel VT. + \\--validate-config Validates the given configuration file. ); var diag = clap.Diagnostic{}; @@ -200,25 +191,43 @@ pub fn main(init: std.process.Init) !void { if (res.args.help != 0) { try clap.help(stderr, clap.Help, ¶ms, .{}); - _ = try stderr.write("Note: if you want to configure Ly, please check the config file, which is located at " ++ build_options.config_directory ++ "/ly/config.ini.\n"); - try stderr.flush(); + std.log.info("note: if you want to configure Ly, please check the config file, which is located at " ++ build_options.config_directory ++ "/ly/config.ini.", .{}); std.process.exit(0); } if (res.args.version != 0) { - _ = try stderr.write("Ly version " ++ build_options.version ++ "\n"); - try stderr.flush(); + std.log.info("ly version " ++ build_options.version, .{}); std.process.exit(0); } if (res.args.config) |path| config_parent_path = path; if (res.args.@"use-kmscon-vt" != 0) state.use_kmscon_vt = true; + if (res.args.@"validate-config") |path| { + var parser = try IniParser(Config).init( + state.allocator, + state.io, + path, + migrator.configFieldHandler, + ); + defer parser.deinit(); + + for (parser.errors.items) |err| { + std.log.err( + "failed to convert value '{s}' of option '{s}' to type '{s}': {s}", + .{ err.value, err.key, err.type_name, err.error_name }, + ); + } + + if (parser.maybe_load_error) |err| { + std.log.err("failed to load config file: {s}", .{@errorName(err)}); + std.process.exit(1); + } + + std.log.info("no errors detected!", .{}); + std.process.exit(0); + } } // Load configuration file - var save_path_alloc = false; - - state.save_path = build_options.config_directory ++ "/ly/save.txt"; - state.old_save_path = build_options.config_directory ++ "/ly/save.ini"; - defer if (save_path_alloc) { + defer if (state.config.save_file_dir != null) { state.allocator.free(state.save_path); state.allocator.free(state.old_save_path); }; @@ -260,14 +269,13 @@ pub fn main(init: std.process.Init) !void { state.lang = lang_parser.structure; - if (state.config.save) { - state.save_path = try std.Io.Dir.path.join(state.allocator, &[_][]const u8{ config_parent_path, "save.txt" }); + if (state.config.save_file_dir) |dir| { + state.save_path = try std.Io.Dir.path.join(state.allocator, &[_][]const u8{ dir, "save.txt" }); state.old_save_path = try std.Io.Dir.path.join(state.allocator, &[_][]const u8{ config_parent_path, "save.ini" }); - save_path_alloc = true; } if (config_parser.maybe_load_error == null) { - migrator.lateConfigFieldHandler(&state.config); + migrator.lateConfigFieldHandler(&state.config, state.lang); } var maybe_uid_range_error: ?anyerror = null; @@ -278,8 +286,9 @@ pub fn main(init: std.process.Init) !void { } state.has_old_save = false; + state.saved_username = null; - if (state.config.save) read_save_file: { + if (state.config.save_file_dir != null) read_save_file: { old_save_parser = migrator.tryMigrateIniSaveFile(state.allocator, state.io, state.old_save_path, &state.saved_users, usernames.items) catch break :read_save_file; // Don't read the new save file if the old one still exists @@ -295,8 +304,19 @@ pub fn main(init: std.process.Init) !void { var file_reader = save_file.reader(state.io, &file_buffer); var reader = &file_reader.interface; - const last_username_index_str = reader.takeDelimiterInclusive('\n') catch break :read_save_file; - state.saved_users.last_username_index = std.fmt.parseInt(usize, last_username_index_str[0..(last_username_index_str.len - 1)], 10) catch break :read_save_file; + const username_line = reader.takeDelimiterInclusive('\n') catch break :read_save_file; + + if (std.mem.containsAtLeastScalar2(u8, username_line, '-', 1)) read_username: { + var iterator = std.mem.splitScalar(u8, username_line[0..(username_line.len - 1)], '-'); + if (iterator.next() == null) break :read_username; // Would be index + + const maybe_username = iterator.next(); + if (maybe_username) |username| { + state.saved_username = try state.allocator.dupe(u8, username); + } + } else if (!state.config.type_username) { + state.saved_users.last_username_index = std.fmt.parseInt(usize, username_line[0..(username_line.len - 1)], 10) catch break :read_save_file; + } while (reader.seek < reader.buffer.len) { const line = reader.takeDelimiterInclusive('\n') catch break; @@ -318,7 +338,7 @@ pub fn main(init: std.process.Init) !void { // If no save file previously existed, fill it up with all usernames // TODO: Add new username with existing save file - if (state.config.save and state.saved_users.user_list.items.len == 0) { + if (state.config.save_file_dir != null and state.saved_users.user_list.items.len == 0) { for (usernames.items) |user| { try state.saved_users.user_list.append(state.allocator, .{ .username = user, @@ -336,12 +356,6 @@ pub fn main(init: std.process.Init) !void { try state.log_file.info(state.io, "tui", "using {s} vt", .{if (state.use_kmscon_vt) "kmscon" else "default"}); - // These strings only end up getting freed if the user quits Ly using Ctrl+C, which is fine since in the other cases - // we end up shutting down or restarting the system - shutdown_cmd = try temporary_allocator.dupe(u8, state.config.shutdown_cmd); - restart_cmd = try temporary_allocator.dupe(u8, state.config.restart_cmd); - commands_allocated = true; - if (state.config.start_cmd) |start_cmd| handle_start_cmd: { var process = std.process.spawn(state.io, .{ .argv = &[_][]const u8{ "/bin/sh", "-c", start_cmd }, @@ -423,26 +437,6 @@ pub fn main(init: std.process.Init) !void { ); defer state.restart_label.deinit(); - state.sleep_label = Label.init( - "", - null, - state.buffer.fg, - state.buffer.bg, - null, - null, - ); - defer state.sleep_label.deinit(); - - state.hibernate_label = Label.init( - "", - null, - state.buffer.fg, - state.buffer.bg, - null, - null, - ); - defer state.hibernate_label.deinit(); - state.toggle_password_label = Label.init( "", null, @@ -473,50 +467,40 @@ pub fn main(init: std.process.Init) !void { ); defer state.brightness_up_label.deinit(); - if (!state.config.hide_key_hints) { + if (state.config.shutdown_key) |key| { try state.shutdown_label.setTextAlloc( state.allocator, "{s} {s}", - .{ state.config.shutdown_key, state.lang.shutdown }, + .{ key, state.lang.shutdown }, ); + } + if (state.config.restart_key) |key| { try state.restart_label.setTextAlloc( state.allocator, "{s} {s}", - .{ state.config.restart_key, state.lang.restart }, + .{ key, state.lang.restart }, ); + } + if (state.config.show_password_key) |key| { try state.toggle_password_label.setTextAlloc( state.allocator, "{s} {s}", - .{ state.config.show_password_key, state.lang.toggle_password }, + .{ key, state.lang.toggle_password }, + ); + } + if (state.config.brightness_down_key) |key| { + try state.brightness_down_label.setTextAlloc( + state.allocator, + "{s} {s}", + .{ key, state.lang.brightness_down }, + ); + } + if (state.config.brightness_up_key) |key| { + try state.brightness_up_label.setTextAlloc( + state.allocator, + "{s} {s}", + .{ key, state.lang.brightness_up }, ); - if (state.config.sleep_cmd != null) { - try state.sleep_label.setTextAlloc( - state.allocator, - "{s} {s}", - .{ state.config.sleep_key, state.lang.sleep }, - ); - } - if (state.config.hibernate_cmd != null) { - try state.hibernate_label.setTextAlloc( - state.allocator, - "{s} {s}", - .{ state.config.hibernate_key, state.lang.hibernate }, - ); - } - if (state.config.brightness_down_key) |key| { - try state.brightness_down_label.setTextAlloc( - state.allocator, - "{s} {s}", - .{ key, state.lang.brightness_down }, - ); - } - if (state.config.brightness_up_key) |key| { - try state.brightness_up_label.setTextAlloc( - state.allocator, - "{s} {s}", - .{ key, state.lang.brightness_up }, - ); - } } state.numlock_label = Label.init( @@ -746,22 +730,25 @@ pub fn main(init: std.process.Init) !void { ); defer state.login_label.deinit(); - state.login = try UserList.init( - state.allocator, - state.io, - &state.buffer, - usernames, - &state.saved_users, - &state.session, - state.box.width - 2 * state.box.horizontal_margin - state.labels_max_length - 1, - state.config.text_in_center, - state.buffer.fg, - state.buffer.bg, - ); - defer state.login.deinit(); + state.login = null; + if (!state.config.type_username) { + state.login = try UserList.init( + state.allocator, + state.io, + &state.buffer, + usernames, + &state.saved_users, + &state.session, + state.box.width - 2 * state.box.horizontal_margin - state.labels_max_length - 1, + state.config.text_in_center, + state.buffer.fg, + state.buffer.bg, + ); - try state.buffer.registerKeybind(state.io, &state.login.label.keybinds, "H", &viGoLeft, &state); - try state.buffer.registerKeybind(state.io, &state.login.label.keybinds, "L", &viGoRight, &state); + try state.buffer.registerKeybind(state.io, &state.login.?.label.keybinds, "H", &viGoLeft, &state); + try state.buffer.registerKeybind(state.io, &state.login.?.label.keybinds, "L", &viGoRight, &state); + } + defer if (state.login) |*w| w.deinit(); if (state.config.shell) { addOtherEnvironment(&state.session, state.lang, .shell, null) catch |err| { @@ -870,7 +857,7 @@ pub fn main(init: std.process.Init) !void { // This effectively means you can't login, since there would be no local // accounts *and* no root account...but at this point, if that's the // case, you have bigger problems to deal with in the first place. :D - try state.info_line.addMessage(state.lang.err_no_users, state.config.error_bg, state.config.error_fg); + if (!state.config.type_username) try state.info_line.addMessage(state.lang.err_no_users, state.config.error_bg, state.config.error_fg); try state.log_file.err(state.io, "sys", "no users found", .{}); } @@ -903,6 +890,22 @@ pub fn main(init: std.process.Init) !void { try state.buffer.registerKeybind(state.io, &state.password.keybinds, "L", &viGoRight, &state); state.password_widget = state.password.widget(); + state.login_text = null; + + if (state.config.type_username) { + state.login_text = try Text.init( + state.allocator, + state.io, + &state.buffer, + state.insert_mode, + false, + null, + state.box.width - 2 * state.box.horizontal_margin - state.labels_max_length - 1, + state.buffer.fg, + state.buffer.bg, + ); + } + defer if (state.login_text) |lt| lt.deinit(); state.version_label = Label.init( ly_version_str, @@ -957,13 +960,18 @@ pub fn main(init: std.process.Init) !void { ); state.session.label.current = session_index; - for (state.login.label.list.items, 0..) |username, i| { - if (std.mem.eql(u8, username.name, auto_user)) { - state.login.label.current = i; - break; + state.is_autologin = true; + + if (state.login_text) |box| { + try box.writeText(auto_user); + } else { + for (state.login.?.label.list.items, 0..) |username, i| { + if (std.mem.eql(u8, username.name, auto_user)) { + state.login.?.label.current = i; + break; + } } } - state.is_autologin = true; } // Switch to selected TTY @@ -997,9 +1005,7 @@ pub fn main(init: std.process.Init) !void { }; } - if (state.config.show_tty) { - try state.tty_label.setTextBuf(&state.tty_buf, "tty{d}", .{state.active_tty}); - } + try state.tty_label.setTextBuf(&state.tty_buf, "tty{d}", .{state.active_tty}); // Initialize the animation, if any var animation: ?*Widget = null; @@ -1077,6 +1083,23 @@ pub fn main(init: std.process.Init) !void { ); animation = dur.widget(); }, + .lua => { + var lua = try Lua.init( + state.io, + state.allocator, + &state.log_file, + &state.buffer, + state.config.lua_animation_file, + state.config.edge_margin, + state.config.animation_frame_delay, + &state.info_line, + state.config.error_fg, + state.config.error_bg, + state.lang, + state.config.full_color, + ); + animation = lua.widget(); + }, } defer if (animation) |a| a.deinit(); @@ -1098,8 +1121,23 @@ pub fn main(init: std.process.Init) !void { // Skip if autologin is active to prevent overriding autologin session var default_input = state.config.default_input; - if (state.config.save and !state.is_autologin) { - if (state.saved_users.last_username_index) |index| load_last_user: { + if (state.config.save_file_dir != null and !state.is_autologin) { + if (state.login_text) |box| { + if (state.saved_username) |username| { + defer state.allocator.free(username); + + try box.writeText(username); + + default_input = .password; + + for (state.saved_users.user_list.items) |user| { + if (std.mem.eql(u8, username, user.username)) { + state.session.label.current = @min(user.session_index, state.session.label.list.items.len - 1); + break; + } + } + } + } else if (state.saved_users.last_username_index) |index| load_last_user: { // If the saved index isn't valid, bail out if (index >= state.saved_users.user_list.items.len) break :load_last_user; @@ -1109,7 +1147,7 @@ pub fn main(init: std.process.Init) !void { // If it doesn't exist (anymore), we don't change the value for (usernames.items, 0..) |username, i| { if (std.mem.eql(u8, username, user.username)) { - state.login.label.current = i; + state.login.?.label.current = i; break; } } @@ -1122,7 +1160,7 @@ pub fn main(init: std.process.Init) !void { const info_line_widget = state.info_line.widget(); const session_widget = state.session.widget(); - const login_widget = state.login.widget(); + const login_widget = if (state.config.type_username) state.login_text.?.widget() else state.login.?.widget(); var widgets: std.ArrayList([]*Widget) = .empty; defer widgets.deinit(state.allocator); @@ -1139,9 +1177,15 @@ pub fn main(init: std.process.Init) !void { state.custom_binds = .empty; defer state.custom_binds.deinit(state.allocator); + defer for (state.custom_binds.items) |*i| { + i.lbl.deinit(); + }; state.custom_info = .empty; defer state.custom_info.deinit(state.allocator); + defer for (state.custom_info.items) |*item| { + item.lbl.deinit(); + }; var lblIter = custom.labels.iterator(); // NOTE: Because widgets have a pointer to the underlying Label, we have to ensure @@ -1157,70 +1201,41 @@ pub fn main(init: std.process.Init) !void { latest.info.id = latest.lbl.widget().id; latest.info.counter = 1; } - defer for (state.custom_info.items) |*item| { - item.lbl.deinit(); - }; var iter = custom.binds.iterator(); - defer for (state.custom_binds.items) |*i| { - i.lbl.deinit(); - }; - - if (!state.config.hide_key_hints) { - while (iter.next()) |i| { - var concat = try std.mem.concat(state.allocator, u8, &[_][]const u8{ i.key_ptr.*, " ", i.value_ptr.name }); - inline for (@typeInfo(Lang).@"struct".fields) |lang_key| { - const new = try std.mem.replaceOwned(u8, state.allocator, concat, "$" ++ lang_key.name, @field(state.lang, lang_key.name)); - state.allocator.free(concat); - concat = new; - } - try state.custom_binds.append(state.allocator, .{ - .lbl = .init( - concat, - null, - state.buffer.fg, - state.buffer.bg, - null, - null, - ), - .cmd = i.value_ptr.*, - .key = i.key_ptr.*, - .io = state.io, - }); - state.custom_binds.items[state.custom_binds.items.len - 1].lbl.allocator = state.allocator; - } - try layer2.append(state.allocator, state.shutdown_label.widget()); - try layer2.append(state.allocator, state.restart_label.widget()); - if (state.config.sleep_cmd != null) { - try layer2.append(state.allocator, state.sleep_label.widget()); - } - if (state.config.hibernate_cmd != null) { - try layer2.append(state.allocator, state.hibernate_label.widget()); - } - try layer2.append(state.allocator, state.toggle_password_label.widget()); - if (state.config.brightness_down_key != null) { - try layer2.append(state.allocator, state.brightness_down_label.widget()); - } - if (state.config.brightness_up_key != null) { - try layer2.append(state.allocator, state.brightness_up_label.widget()); + while (iter.next()) |i| { + var concat = try std.mem.concat(state.allocator, u8, &[_][]const u8{ i.key_ptr.*, " ", i.value_ptr.name }); + inline for (@typeInfo(Lang).@"struct".fields) |lang_key| { + const new = try std.mem.replaceOwned(u8, state.allocator, concat, "$" ++ lang_key.name, @field(state.lang, lang_key.name)); + state.allocator.free(concat); + concat = new; } + try state.custom_binds.append(state.allocator, .{ + .lbl = .init( + concat, + null, + state.buffer.fg, + state.buffer.bg, + null, + null, + ), + .cmd = i.value_ptr.*, + .key = i.key_ptr.*, + .io = state.io, + }); + state.custom_binds.items[state.custom_binds.items.len - 1].lbl.allocator = state.allocator; } - if (state.config.battery_id != null) { - try layer2.append(state.allocator, state.battery_label.widget()); - } - if (state.config.clock != null) { - try layer2.append(state.allocator, state.clock_label.widget()); - } - if (state.config.show_tty) { - try layer2.append(state.allocator, state.tty_label.widget()); - } - if (state.config.bigclock != .none) { - try layer2.append(state.allocator, state.bigclock_label.widget()); - } - if (!state.config.hide_keyboard_locks) { - try layer2.append(state.allocator, state.numlock_label.widget()); - try layer2.append(state.allocator, state.capslock_label.widget()); - } + try layer2.append(state.allocator, state.shutdown_label.widget()); + try layer2.append(state.allocator, state.restart_label.widget()); + try layer2.append(state.allocator, state.toggle_password_label.widget()); + try layer2.append(state.allocator, state.brightness_down_label.widget()); + try layer2.append(state.allocator, state.brightness_up_label.widget()); + try layer2.append(state.allocator, state.battery_label.widget()); + try layer2.append(state.allocator, state.clock_label.widget()); + try layer2.append(state.allocator, state.tty_label.widget()); + try layer2.append(state.allocator, state.bigclock_label.widget()); + try layer2.append(state.allocator, state.numlock_label.widget()); + try layer2.append(state.allocator, state.capslock_label.widget()); try layer2.append(state.allocator, state.box.widget()); try layer2.append(state.allocator, info_line_widget); try layer2.append(state.allocator, state.session_specifier_label.widget()); @@ -1229,9 +1244,7 @@ pub fn main(init: std.process.Init) !void { try layer2.append(state.allocator, login_widget); try layer2.append(state.allocator, state.password_label.widget()); try layer2.append(state.allocator, state.password_widget); - if (!state.config.hide_version_string) { - try layer2.append(state.allocator, state.version_label.widget()); - } + try layer2.append(state.allocator, state.version_label.widget()); for (state.custom_binds.items) |*item| { try layer2.append(state.allocator, item.lbl.widget()); @@ -1262,11 +1275,9 @@ pub fn main(init: std.process.Init) !void { try state.buffer.registerGlobalKeybind(state.io, "Enter", &authenticate, &state); - try state.buffer.registerGlobalKeybind(state.io, state.config.shutdown_key, &shutdownCmd, &state); - try state.buffer.registerGlobalKeybind(state.io, state.config.restart_key, &restartCmd, &state); - try state.buffer.registerGlobalKeybind(state.io, state.config.show_password_key, &togglePasswordMask, &state); - if (state.config.sleep_cmd != null) try state.buffer.registerGlobalKeybind(state.io, state.config.sleep_key, &sleepCmd, &state); - if (state.config.hibernate_cmd != null) try state.buffer.registerGlobalKeybind(state.io, state.config.hibernate_key, &hibernateCmd, &state); + if (state.config.shutdown_key) |key| try state.buffer.registerGlobalKeybind(state.io, key, &shutdownCmd, &state); + if (state.config.restart_key) |key| try state.buffer.registerGlobalKeybind(state.io, key, &restartCmd, &state); + if (state.config.show_password_key) |key| try state.buffer.registerGlobalKeybind(state.io, key, &togglePasswordMask, &state); if (state.config.brightness_down_key) |key| try state.buffer.registerGlobalKeybind(state.io, key, &decreaseBrightnessCmd, &state); if (state.config.brightness_up_key) |key| try state.buffer.registerGlobalKeybind(state.io, key, &increaseBrightnessCmd, &state); @@ -1366,6 +1377,7 @@ fn disableInsertMode(ptr: *anyopaque) !bool { if (state.config.vi_mode and state.insert_mode) { state.insert_mode = false; state.password.should_insert = false; + if (state.login_text) |lt| lt.should_insert = false; state.buffer.drawNextFrame(true); } return false; @@ -1377,6 +1389,7 @@ fn enableInsertMode(ptr: *anyopaque) !bool { state.insert_mode = true; state.password.should_insert = true; + if (state.login_text) |lt| lt.should_insert = true; state.buffer.drawNextFrame(true); return false; } @@ -1449,6 +1462,32 @@ fn authenticate(ptr: *anyopaque) !bool { state.config.error_bg, state.config.error_fg, ); + if (!state.is_autologin) { + state.info_line.clearRendered(state.allocator) catch |err| { + try state.info_line.addMessage( + state.lang.err_alloc, + state.config.error_bg, + state.config.error_fg, + ); + try state.log_file.err( + state.io, + "tui", + "failed to clear info line: {s}", + .{@errorName(err)}, + ); + }; + state.info_line.label.draw(); + try TerminalBuffer.presentBuffer(); + } + return false; + } + + try state.info_line.addMessage( + state.lang.authenticating, + state.config.bg, + state.config.fg, + ); + if (!state.is_autologin) { state.info_line.clearRendered(state.allocator) catch |err| { try state.info_line.addMessage( state.lang.err_alloc, @@ -1463,32 +1502,10 @@ fn authenticate(ptr: *anyopaque) !bool { ); }; state.info_line.label.draw(); - TerminalBuffer.presentBuffer(); - return false; + try TerminalBuffer.presentBuffer(); } - try state.info_line.addMessage( - state.lang.authenticating, - state.config.bg, - state.config.fg, - ); - state.info_line.clearRendered(state.allocator) catch |err| { - try state.info_line.addMessage( - state.lang.err_alloc, - state.config.error_bg, - state.config.error_fg, - ); - try state.log_file.err( - state.io, - "tui", - "failed to clear info line: {s}", - .{@errorName(err)}, - ); - }; - state.info_line.label.draw(); - TerminalBuffer.presentBuffer(); - - if (state.config.save) save_last_settings: { + if (state.config.save_file_dir != null) save_last_settings: { // It isn't worth cluttering the code with precise error // handling, so let's just report a generic error message, // that should be good enough for debugging anyway. @@ -1514,7 +1531,11 @@ fn authenticate(ptr: *anyopaque) !bool { var file_writer = file.writer(state.io, &file_buffer); var writer = &file_writer.interface; - try writer.print("{d}\n", .{state.login.label.current}); + if (state.login_text) |box| { + try writer.print("0-{s}\n", .{box.text.items}); + } else { + try writer.print("{d}\n", .{state.login.?.label.current}); + } for (state.saved_users.user_list.items) |user| { try writer.print("{s}:{d}\n", .{ user.username, user.session_index }); } @@ -1522,6 +1543,7 @@ fn authenticate(ptr: *anyopaque) !bool { // Delete previous save file if it exists if (migrator.maybe_save_file) |path| { + defer temporary_allocator.free(path); std.Io.Dir.cwd().deleteFile(state.io, path) catch {}; } else if (state.has_old_save) { std.Io.Dir.cwd().deleteFile(state.io, state.old_save_path) catch {}; @@ -1572,7 +1594,7 @@ fn authenticate(ptr: *anyopaque) !bool { &state.log_file, auth_options, current_environment, - state.login.getCurrentUsername(), + if (state.login_text) |box| box.text.items else state.login.?.getCurrentUsername(), password_text, ) catch |err| { shared_err.writeError(err); @@ -1639,8 +1661,8 @@ fn authenticate(ptr: *anyopaque) !bool { } // Restore the cursor - TerminalBuffer.setCursor(0, 0); - TerminalBuffer.presentBuffer(); + try TerminalBuffer.setCursor(0, 0); + try TerminalBuffer.presentBuffer(); return false; } @@ -1660,62 +1682,6 @@ fn restartCmd(ptr: *anyopaque) !bool { return false; } -fn sleepCmd(ptr: *anyopaque) !bool { - var state: *UiState = @ptrCast(@alignCast(ptr)); - - if (state.config.sleep_cmd) |sleep_cmd| { - var process = std.process.spawn(state.io, .{ - .argv = &[_][]const u8{ "/bin/sh", "-c", sleep_cmd }, - .stdout = .ignore, - .stderr = .ignore, - }) catch return false; - - const process_result = process.wait(state.io) catch return false; - if (process_result.exited != 0) { - try state.info_line.addMessage( - state.lang.err_sleep, - state.config.error_bg, - state.config.error_fg, - ); - try state.log_file.err( - state.io, - "sys", - "failed to execute sleep command: exit code {d}", - .{process_result.exited}, - ); - } - } - return false; -} - -fn hibernateCmd(ptr: *anyopaque) !bool { - var state: *UiState = @ptrCast(@alignCast(ptr)); - - if (state.config.hibernate_cmd) |hibernate_cmd| { - var process = std.process.spawn(state.io, .{ - .argv = &[_][]const u8{ "/bin/sh", "-c", hibernate_cmd }, - .stdout = .ignore, - .stderr = .ignore, - }) catch return false; - - const process_result = process.wait(state.io) catch return false; - if (process_result.exited != 0) { - try state.info_line.addMessage( - state.lang.err_hibernate, - state.config.error_bg, - state.config.error_fg, - ); - try state.log_file.err( - state.io, - "sys", - "failed to execute hibernate command: exit code {d}", - .{process_result.exited}, - ); - } - } - return false; -} - fn decreaseBrightnessCmd(ptr: *anyopaque) !bool { var state: *UiState = @ptrCast(@alignCast(ptr)); @@ -1767,7 +1733,7 @@ fn updateNumlock(self: *Label, ptr: *anyopaque) !void { try state.log_file.err( state.io, "sys", - "failed to get lock state: {s}", + "failed to get lock state for numlock: {s}", .{@errorName(err)}, ); return; @@ -1781,8 +1747,17 @@ fn updateCapslock(self: *Label, ptr: *anyopaque) !void { const lock_state = interop.getLockState() catch |err| { self.update_fn = null; - try state.info_line.addMessage(state.lang.err_lock_state, state.config.error_bg, state.config.error_fg); - try state.log_file.err(state.io, "sys", "failed to get lock state: {s}", .{@errorName(err)}); + try state.info_line.addMessage( + state.lang.err_lock_state, + state.config.error_bg, + state.config.error_fg, + ); + try state.log_file.err( + state.io, + "sys", + "failed to get lock state for capslock: {s}", + .{@errorName(err)}, + ); return; }; @@ -1956,110 +1931,366 @@ fn updateSessionSpecifier(self: *Label, ptr: *anyopaque) !void { self.setText(env.environment.specifier); } -fn positionWidgets(ptr: *anyopaque) !void { - var state: *UiState = @ptrCast(@alignCast(ptr)); +const Corner = enum { + bottomLeft, + bottomRight, + topLeft, + topRight, +}; - // Offsets for custom bind placement. Declared here instead of the - // below if stmt as we need these for `battery_label` positioning. - var x_offset: usize = 0; - // To account for the first row of built-in key hints - var y_offset: usize = 1; - if (!state.config.hide_key_hints) { - state.shutdown_label.positionX(state.edge_margin - .add(TerminalBuffer.START_POSITION)); - var last_label = state.shutdown_label; - state.restart_label.positionX(last_label - .childrenPosition() - .addX(1)); - last_label = state.restart_label; - state.sleep_label.positionX(last_label - .childrenPosition() - .addX(1)); - if (state.config.sleep_cmd != null) { - last_label = state.sleep_label; +const PositionedWidgets = struct { + binds: []bool, + labels: []bool, +}; + +fn positionSingleWidget(state: *UiState, item: []const u8, current_x: *usize, current_y: usize, is_left: bool, is_top: bool, positioned: *PositionedWidgets) !bool { + const base_x = state.edge_margin.x; + + if (std.mem.eql(u8, item, "shutdown")) { + if (state.config.shutdown_key == null) return false; + const width = TerminalBuffer.strWidth(state.shutdown_label.text); + if (is_left) { + state.shutdown_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.shutdown_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; } - state.hibernate_label.positionX(last_label - .childrenPosition() - .addX(1)); - if (state.config.hibernate_cmd != null) { - last_label = state.hibernate_label; + return true; + } else if (std.mem.eql(u8, item, "restart")) { + if (state.config.restart_key == null) return false; + const width = TerminalBuffer.strWidth(state.restart_label.text); + if (is_left) { + state.restart_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.restart_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; } - state.toggle_password_label.positionX(last_label - .childrenPosition() - .addX(1)); - last_label = state.toggle_password_label; - state.brightness_down_label.positionX(last_label - .childrenPosition() - .addX(1)); - if (state.config.brightness_down_key != null) { - last_label = state.brightness_down_label; + return true; + } else if (std.mem.eql(u8, item, "britup")) { + if (state.config.brightness_up_key == null) return false; + const width = TerminalBuffer.strWidth(state.brightness_up_label.text); + if (is_left) { + state.brightness_up_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.brightness_up_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; } - state.brightness_up_label.positionXY(last_label - .childrenPosition() - .addX(1)); - for (state.custom_binds.items) |*item| { - item.lbl.positionXY(state.edge_margin - .addY(y_offset) - .addX(x_offset)); - x_offset += item.lbl.text.len + 1; - if (x_offset + item.lbl.text.len > state.config.custom_bind_width orelse state.buffer.width) { - x_offset = 0; - y_offset += 1; + return true; + } else if (std.mem.eql(u8, item, "britdown")) { + if (state.config.brightness_down_key == null) return false; + const width = TerminalBuffer.strWidth(state.brightness_down_label.text); + if (is_left) { + state.brightness_down_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.brightness_down_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "password")) { + if (state.config.show_password_key == null) return false; + const width = TerminalBuffer.strWidth(state.toggle_password_label.text); + if (is_left) { + state.toggle_password_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.toggle_password_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "clock") or std.mem.eql(u8, item, "time")) { + if (state.config.clock == null) return false; + const width = TerminalBuffer.strWidth(state.clock_label.text); + if (is_left) { + state.clock_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.clock_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "tty")) { + const width = TerminalBuffer.strWidth(state.tty_label.text); + if (is_left) { + state.tty_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.tty_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "battery")) { + if (state.config.battery_id == null) return false; + const width = TerminalBuffer.strWidth(state.battery_label.text); + if (is_left) { + state.battery_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.battery_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "version")) { + const width = TerminalBuffer.strWidth(state.version_label.text); + if (is_left) { + state.version_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.version_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "numlock")) { + const width = TerminalBuffer.strWidth(state.lang.numlock); + if (is_left) { + state.numlock_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.numlock_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "capslock")) { + const width = TerminalBuffer.strWidth(state.lang.capslock); + if (is_left) { + state.capslock_label.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + state.capslock_label.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + return true; + } else if (std.mem.eql(u8, item, "labels")) { + for (state.custom_info.items, 0..) |*info, i| { + if (positioned.labels[i]) continue; + const width = TerminalBuffer.strWidth(info.lbl.text); + if (is_left) { + info.lbl.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + info.lbl.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + positioned.labels[i] = true; + } + return true; + } else if (std.mem.eql(u8, item, "binds")) { + var local_x = current_x.*; + var local_y = current_y; + + for (state.custom_binds.items, 0..) |*bind, i| { + if (positioned.binds[i]) continue; + const width = TerminalBuffer.strWidth(bind.lbl.text); + + if (is_left) { + if (local_x + width > (state.config.custom_bind_width orelse state.buffer.width) - state.edge_margin.x) { + local_x = base_x; + if (is_top) local_y += 1 else local_y -= 1; + } + bind.lbl.positionXY(Position.init(local_x, local_y)); + local_x += width + 1; + } else { + if (width + state.edge_margin.x > local_x) { + local_x = state.buffer.width - state.edge_margin.x; + if (is_top) local_y += 1 else local_y -= 1; + } + const dwidth = if (width > local_x) 0 else local_x - width; + bind.lbl.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= local_x) local_x -= width + 1; + } + positioned.binds[i] = true; + } + current_x.* = local_x; + return true; + } else if (std.mem.startsWith(u8, item, "lbl:")) { + const name = item["lbl:".len..]; + for (state.custom_info.items, 0..) |*info, i| { + if (std.mem.eql(u8, info.info.name, name)) { + if (positioned.labels[i]) return false; + const width = TerminalBuffer.strWidth(info.lbl.text); + if (is_left) { + info.lbl.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + info.lbl.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + positioned.labels[i] = true; + return true; + } + } + } else if (std.mem.startsWith(u8, item, "cmd:")) { + const key = item["cmd:".len..]; + for (state.custom_binds.items, 0..) |*bind, i| { + if (std.mem.eql(u8, bind.key, key)) { + if (positioned.binds[i]) return false; + const width = TerminalBuffer.strWidth(bind.lbl.text); + if (is_left) { + bind.lbl.positionXY(Position.init(current_x.*, current_y)); + current_x.* += width + 1; + } else { + const dwidth = if (width > current_x.*) 0 else current_x.* - width; + bind.lbl.positionXY(Position.init(dwidth, current_y)); + if (width + 1 <= current_x.*) current_x.* -= width + 1; + } + positioned.binds[i] = true; + return true; } } } - for (state.custom_info.items, 0..) |*item, i| { - item.lbl.positionXY(state.edge_margin - .invertX(state.buffer.width) - .removeX(item.lbl.text.len) - .invertY(state.buffer.height) - .removeY(state.custom_info.items.len) - .addY(i)); + return false; +} + +fn positionItem(state: *UiState, item: []const u8, current_x: usize, current_y: usize, is_left: bool, is_top: bool, positioned: *PositionedWidgets) !bool { + // Check if item contains a comma for compound widgets + if (std.mem.indexOf(u8, item, ",") == null) { + var line_x = current_x; + return positionSingleWidget(state, item, &line_x, current_y, is_left, is_top, positioned); } - state.battery_label.positionXY(state.edge_margin - .add(TerminalBuffer.START_POSITION) - .addYFromIf(state.brightness_up_label.childrenPosition(), !state.config.hide_key_hints) - .addYIf(y_offset, !state.config.hide_key_hints) - .removeYFromIf(state.edge_margin, !state.config.hide_key_hints)); + var it = std.mem.tokenizeAny(u8, item, ","); + var success = false; - const tty_label_width = if (state.config.show_tty) TerminalBuffer.strWidth(state.tty_label.text) else 0; - const tty_label_gap = if (state.config.show_tty and state.config.clock != null) @as(usize, 1) else 0; - state.tty_label.positionXY(state.edge_margin - .add(TerminalBuffer.START_POSITION) - .invertX(state.buffer.width) - .removeXIf(tty_label_width, state.buffer.width > tty_label_width + state.edge_margin.x)); - state.clock_label.positionXY(state.edge_margin - .add(TerminalBuffer.START_POSITION) - .invertX(state.buffer.width) - .removeXIf(TerminalBuffer.strWidth(state.clock_label.text) + tty_label_width + tty_label_gap, state.buffer.width > TerminalBuffer.strWidth(state.clock_label.text) + tty_label_width + tty_label_gap + state.edge_margin.x)); + // Check if we need to wrap to next line + var line_x = current_x; - state.numlock_label.positionX(state.edge_margin - .add(TerminalBuffer.START_POSITION) - .addYFromIf(state.clock_label.childrenPosition(), state.config.clock != null) - .removeYFromIf(state.edge_margin, state.config.clock != null) - .invertX(state.buffer.width) - .removeXIf(TerminalBuffer.strWidth(state.lang.numlock), state.buffer.width > TerminalBuffer.strWidth(state.lang.numlock) + state.edge_margin.x)); - state.capslock_label.positionX(state.numlock_label - .childrenPosition() - .removeX(TerminalBuffer.strWidth(state.lang.numlock) + TerminalBuffer.strWidth(state.lang.capslock) + 1)); + // Now position each subitem + while (it.next()) |subitem| { + const trimmed = std.mem.trim(u8, subitem, " "); - state.box.positionXY(TerminalBuffer.START_POSITION - .addX((state.buffer.width - @min(state.buffer.width - 2, state.box.width)) / 2) - .addY((state.buffer.height - @min(state.buffer.height - 2, state.box.height)) / 2)); + if (try positionSingleWidget(state, trimmed, &line_x, current_y, is_left, is_top, positioned)) { + success = true; + } + } + + return success; +} + +fn positionCorner(state: *UiState, config_str: []const u8, corner: Corner, positioned: *PositionedWidgets) !void { + const is_left = corner == .topLeft or corner == .bottomLeft; + const is_top = corner == .topLeft or corner == .topRight; + + var y_offset: usize = 0; + var i: usize = 0; + const len = config_str.len; + + while (i < len) { + // Skip whitespace and brackets + while (i < len and (config_str[i] == ' ' or config_str[i] == '\t' or config_str[i] == '[' or config_str[i] == ']')) { + i += 1; + } + if (i >= len) break; + + const start = i; + while (i < len and config_str[i] != ' ' and config_str[i] != '\t' and config_str[i] != '[' and config_str[i] != ']') { + i += 1; + } + const token = config_str[start..i]; + + const current_x = if (is_left) state.edge_margin.x else state.buffer.width - state.edge_margin.x; + const current_y = if (is_top) state.edge_margin.y + y_offset else state.buffer.height - 1 - state.edge_margin.y - y_offset; + + if (try positionItem(state, token, current_x, current_y, is_left, is_top, positioned)) { + y_offset += 1; + } + } +} + +fn positionWidgets(ptr: *anyopaque) !void { + var state: *UiState = @ptrCast(@alignCast(ptr)); + + const offscreen = Position.init(state.buffer.width + 1, state.buffer.height + 1); + + // Reset all potential corner widgets to offscreen + state.shutdown_label.positionXY(offscreen); + state.restart_label.positionXY(offscreen); + state.toggle_password_label.positionXY(offscreen); + state.brightness_down_label.positionXY(offscreen); + state.brightness_up_label.positionXY(offscreen); + state.clock_label.positionXY(offscreen); + state.bigclock_label.positionXY(offscreen); + state.tty_label.positionXY(offscreen); + state.battery_label.positionXY(offscreen); + state.version_label.positionXY(offscreen); + state.numlock_label.positionXY(offscreen); + state.capslock_label.positionXY(offscreen); + + for (state.custom_binds.items) |*bind| { + bind.lbl.positionXY(offscreen); + } + for (state.custom_info.items) |*info| { + info.lbl.positionXY(offscreen); + } + + var positioned = PositionedWidgets{ + .binds = try state.allocator.alloc(bool, state.custom_binds.items.len), + .labels = try state.allocator.alloc(bool, state.custom_info.items.len), + }; + defer state.allocator.free(positioned.binds); + defer state.allocator.free(positioned.labels); + + @memset(positioned.binds, false); + @memset(positioned.labels, false); + + try positionCorner(state, state.config.corner_top_left, .topLeft, &positioned); + try positionCorner(state, state.config.corner_top_right, .topRight, &positioned); + try positionCorner(state, state.config.corner_bottom_left, .bottomLeft, &positioned); + try positionCorner(state, state.config.corner_bottom_right, .bottomRight, &positioned); + + var bb_height = state.box.height; + var bb_width = state.box.width; + const clock_text_len = TerminalBuffer.strWidth(state.bigclock_label.text) * (BigLabel.CHAR_WIDTH + 1); if (state.config.bigclock != .none) { - const half_width = state.buffer.width / 2; - const half_label_width = (TerminalBuffer.strWidth(state.bigclock_label.text) * (BigLabel.CHAR_WIDTH + 1)) / 2; - const half_height = (if (state.buffer.height > state.box.height) state.buffer.height - state.box.height else state.buffer.height) / 2; + bb_height += BigLabel.CHAR_HEIGHT + 2; + bb_width = @max(bb_width, clock_text_len); + } + + const dheight = if (bb_height + 1 > state.buffer.height) 1 else state.buffer.height - bb_height - 1; + const dwidth = if (bb_width + 1 > state.buffer.width) 1 else state.buffer.width - bb_width - 1; + + const max_v_position: f32 = @floatFromInt(dheight); + const max_h_position: f32 = @floatFromInt(dwidth); + + bb_height = @min(bb_height, state.buffer.height - 2); + bb_width = @min(bb_width, state.buffer.width - 2); + + const v_space: f32 = @floatFromInt(state.buffer.height - bb_height); + const v_position: usize = @intFromFloat(if (max_v_position < 1.0) 1.0 else std.math.clamp(v_space * state.config.box_position_v, 1.0, max_v_position)); + const h_space: f32 = @floatFromInt(state.buffer.width - bb_width); + const h_position: usize = @intFromFloat(if (max_h_position < 1.0) 1.0 else std.math.clamp(h_space * state.config.box_position_h, 1.0, max_h_position)); + + if (state.config.bigclock != .none) { + const cwidth = if (clock_text_len > bb_width) 0 else bb_width - clock_text_len; state.bigclock_label.positionXY(TerminalBuffer.START_POSITION - .addX(half_width) - .removeXIf(half_label_width, half_width > half_label_width) - .addY(half_height) - .removeYIf(BigLabel.CHAR_HEIGHT + 2, half_height > BigLabel.CHAR_HEIGHT + 2)); + .addX(h_position + cwidth / 2) + .addY(v_position)); } + const bwidth = if (state.box.width > bb_width) 0 else bb_width - state.box.width; + const bheight = if (state.box.height > bb_height) 0 else bb_height - state.box.height; + + state.box.positionXY(TerminalBuffer.START_POSITION + .addX(h_position + bwidth / 2) + .addY(v_position + bheight)); + state.info_line.label.positionY(state.box .childrenPosition()); @@ -2074,21 +2305,27 @@ fn positionWidgets(ptr: *anyopaque) !void { .childrenPosition() .resetXFrom(state.info_line.label.childrenPosition()) .addY(1)); - state.login.label.positionY(state.login_label - .childrenPosition() - .addX(state.labels_max_length - TerminalBuffer.strWidth(state.login_label.text) + 1)); + if (state.login_text) |box| { + box.positionY(state.login_label + .childrenPosition() + .addX(state.labels_max_length - TerminalBuffer.strWidth(state.login_label.text) + 1)); + } else { + state.login.?.label.positionY(state.login_label + .childrenPosition() + .addX(state.labels_max_length - TerminalBuffer.strWidth(state.login_label.text) + 1)); + } - state.password_label.positionX(state.login.label - .childrenPosition() + const login_children_pos = if (state.login_text) |box| + box.childrenPosition() + else + state.login.?.label.childrenPosition(); + + state.password_label.positionX(login_children_pos .resetXFrom(state.info_line.label.childrenPosition()) .addY(1)); state.password.positionY(state.password_label .childrenPosition() .addX(state.labels_max_length - TerminalBuffer.strWidth(state.password_label.text) + 1)); - - state.version_label.positionXY(state.edge_margin - .add(TerminalBuffer.START_POSITION) - .invertY(state.buffer.height - 1)); } fn handleInactivity(ptr: *anyopaque) !void { @@ -2279,19 +2516,34 @@ fn adjustBrightness(io: std.Io, cmd: []const u8) !void { } fn getBatteryPercentage(io: std.Io, battery_id: []const u8) !u8 { - const path = try std.fmt.allocPrint(temporary_allocator, "/sys/class/power_supply/{s}/capacity", .{battery_id}); - defer temporary_allocator.free(path); + if (builtin.os.tag == .freebsd) { + // battery_id is unused on FreeBSD; sysctl exposes a single aggregate value. + // For multi-battery systems the MIB would be hw.acpi.battery.N.life, + // but hw.acpi.battery.life is the standard single-battery interface. + var capacity: c_int = -1; + var size: usize = @sizeOf(c_int); - const battery_file = try std.Io.Dir.cwd().openFile(io, path, .{}); - defer battery_file.close(io); + const ret = interop.sysctl.sysctlbyname("hw.acpi.battery.life", &capacity, &size, null, 0); - var buffer: [8]u8 = undefined; - const bytes_read = try battery_file.readStreaming(io, &.{&buffer}); - const capacity_str = buffer[0..bytes_read]; + if (ret != 0) return error.SysctlFailed; + if (capacity < 0 or capacity > 100) return error.InvalidBatteryCapacity; - const trimmed = std.mem.trimEnd(u8, capacity_str, "\n\r"); + return @intCast(capacity); + } else { + const path = try std.fmt.allocPrint(temporary_allocator, "/sys/class/power_supply/{s}/capacity", .{battery_id}); + defer temporary_allocator.free(path); - return try std.fmt.parseInt(u8, trimmed, 10); + const battery_file = try std.Io.Dir.cwd().openFile(io, path, .{}); + defer battery_file.close(io); + + var buffer: [8]u8 = undefined; + const bytes_read = try battery_file.readStreaming(io, &.{&buffer}); + const capacity_str = buffer[0..bytes_read]; + + const trimmed = std.mem.trimEnd(u8, capacity_str, "\n\r"); + + return try std.fmt.parseInt(u8, trimmed, 10); + } } fn getAuthErrorMsg(err: anyerror, lang: Lang) []const u8 {