/// CLI entry point. /// /// Copyright: dd86k /// License: MIT /// Authors: $(LINK2 https://github.com/dd86k, dd86k) module main; // NOTE: Avoid putting putting editor behavior and tests in this module. // Apart from collecting CLI options, main module should // not have unittests, since DUB will actively omit this // module (and package modules) when running 'dub test'. import std.process : environment; import std.stdio, std.getopt; import core.stdc.stdlib : exit, EXIT_SUCCESS, EXIT_FAILURE; import ddhx.editor; import ddhx.logger; import configuration; import messages; import view; private: template DVER(uint ver) { enum DVER = cast(char)((ver / 1000) + '0') ~ "." ~ cast(char)(((ver % 1000) / 100) + '0') ~ cast(char)(((ver % 100) / 10) + '0') ~ cast(char)((ver % 10) + '0'); } immutable string SECRET = q"SECRET +----------------------------+ __ | Heard you need help. | / \ | Can I help you with that? | _ _ | [ Yes ] [ No ] [ Go away ] | O O +-. .------------------------+ || |/ |/ | V | \_/ SECRET"; // Opening the target fails before there is a session to report into, so // both it and the session itself end here rather than escaping main(). void fatal(Exception ex) { writeln(); // if cursor was at some weird place, start at newline debug stderr.writeln("fatal: ", ex); else stderr.writeln("fatal: ", ex.msg); log("%s", ex); exit(2); } // print a line with spaces for field and value void printfield(string field, string line, int spacing = -12) { // Thought of adding periods between fields, but there are other ways // to read fields (like more.1/less.1). Best we can do is at least // make that spacing distance shorter for now (for each pages) writefln("%*s%s", spacing, field ? field : "", line); } void printpage(string opt) { final switch (opt) { case "assistant": writeln(SECRET); break; case "version": import ddhx.platform : TARGET_TRIPLE; import os.mem : syspagesize; import std.conv : text; printfield("ddhx", DDHX_VERSION); printfield(null, DDHX_BUILDINFO); printfield("License", "MIT"); printfield(null, DDHX_COPYRIGHT); printfield("Homepage", "https://github.com/dd86k/ddhx"); printfield("Compiler", __VENDOR__~" "~DVER!__VERSION__); printfield("Target", TARGET_TRIPLE); printfield("Pagesize", text(syspagesize())); break; case "ver": writeln(DDHX_VERSION); break; case "help-keys": enum SPACING = -20; printfield("KEYS", "COMMANDS", SPACING); foreach (command; default_commands) { if (command.key == 0) // no keys set for command continue; // Keys (ascii utf-8 range is 1 byte, 1 cell...) // First column, used as a lookup import os.terminal : Key, Mod; static immutable string Ctrl = "Ctrl+"; static immutable string Alt = "Alt+"; static immutable string Shift = "Shift+"; int spacing = SPACING; if (command.key & Mod.ctrl) { spacing += Ctrl.length; write(Ctrl); } if (command.key & Mod.alt) { spacing += Alt.length; write(Alt); } if (command.key & Mod.shift) { spacing += Shift.length; write(Shift); } writef("%*s", spacing, cast(Key)(command.key & 0xff_ffff)); // Command writeln(command.name); } break; case "help-commands": enum SPACING = -25; printfield("COMMAND", "DESCRIPTION", SPACING); foreach (command; default_commands) { printfield(command.name, command.description, SPACING); } break; case "help-config": import std.path : buildPath; import os.path : findConfig, getHomeFolder, getUserConfigFolder, getSystemFolder; enum SPACING0 = -10; static immutable string ACTIVE = "(active)"; static immutable string INACTIVE = " "; string confpath = findConfig("ddhx", ".ddhxrc"); // Bastardized way of printing Type, State, and Path // The state is actively checked against path, null is allowed there writeln("Paths"); string homedir = getHomeFolder(); if (homedir) // available { string homepath = buildPath(homedir, ".ddhxrc"); bool active = homepath == confpath; writefln("%*s %s %s", SPACING0, " User", active ? ACTIVE : INACTIVE, homepath); } string appdir = getUserConfigFolder(); if (appdir) // available { string apppath = buildPath(appdir, "ddhx", ".ddhxrc"); bool active = apppath == confpath; writefln("%*s %s %s", SPACING0, " App", active ? ACTIVE : INACTIVE, apppath); } string sysdir = getSystemFolder(); if (sysdir) { string syspath = buildPath(sysdir, "ddhx", ".ddhxrc"); bool active = syspath == confpath; writefln("%*s %s %s", SPACING0, " System", active ? ACTIVE : INACTIVE, syspath); } writeln; // Print config fields/values enum SPACING1 = -20; foreach (conf; configurations) { writefln("%*s%s", SPACING1, conf.name, conf.description); writefln("%*sValues: %s", SPACING1, "", conf.availvalues); writefln("%*sDefault: %s", SPACING1, "", conf.defaultval); writeln; } break; case "help-charsets": import ddhx.charset : Charset, charsets; enum SPACING = -12; printfield("CHARSET", "NAME", SPACING); foreach (immutable(Charset)* set; charsets) { printfield(set.id, set.name, SPACING); } break; } exit(EXIT_SUCCESS); } void main(string[] args) { enum SECRETCOUNT = 1; RC rc; string orc; /// Use this rc file instead bool onorc; /// Do not use rc file if it exists, force defaults string bookmarks_file; /// Bookmarks file to load on startup string diff_file; /// File to diff against on startup GetoptResult res = void; try { // NOTE: Keep this in ascending order! (except for info switches) // TODO: --color/--no-color: Force color option (overrides rc) res = getopt(args, config.caseSensitive, // Secret options "assistant", "", &printpage, // // Configuration // "A|address", `Set address mode ("hex"/"dec"/"oct", default: "hex")`, (string _, string val) { configure_address(rc, val); }, "address-spacing", "Set address spacing in characters (default: 11)", (string _, string val) { configure_address_spacing(rc, val); }, "autoresize", "Automatically resize columns on dimension change", () { // I've decided this switch can stay because whatever configure_columns(rc, "auto"); }, "B|bookmarks", "Load bookmarks from a file on startup", &bookmarks_file, "C|charset", `Set character translation (default="ascii")`, (string _, string val) { configure_charset(rc, val); }, "c|columns", "Set columns per row (default: 16)", (string _, string val) { configure_columns(rc, val); }, "D|data", `Set data mode ("x8","x16",etc., default: "x8")`, (string _, string val) { configure_data(rc, val); }, "d|diff-file", "Diff the document against a file on startup", &diff_file, "I|norc", "Use defaults and ignore user configuration files", &onorc, "f|rcfile", "Use supplied file for options", &orc, "R|restrict", `Restrict document editing (same as "writemode readonly")`, () { restrictRC(rc); }, "W|writable", `Allow document editing, ignoring "writemode" configurations`, () { unrestrictRC(rc); }, // // Informational pages // "help-commands","Print commands page and exit", &printpage, "help-config", "Print configuration page and exit", &printpage, "help-keys", "Print default shortcuts and exit", &printpage, "help-charsets","Print available character sets and exit", &printpage, "ver", "Print only the version and exit", &printpage, "version", "Print the version page and exit", &printpage, ); } catch (Exception ex) { stderr.writeln("error: ", ex.msg); exit(EXIT_FAILURE); } // -h|--help, artifact of std.getopt. if (res.helpWanted) { // Replace default help line res.options[$-1].help = "Print this help page and exit"; // Usage and options writeln("Hex editor\n"~ "USAGE\n"~ " ddhx [FILE|-] [OPTIONS]\n"~ " ddhx {-h|--help|--version|--ver}\n"~ "\n"~ "OPTIONS"); foreach (opt; res.options[SECRETCOUNT..$]) with (opt) { if (optShort) write(' ', optShort, ','); else write(" "); writefln(" %*s %s", -20, optLong, help); } exit(EXIT_SUCCESS); } if (string logpath = environment.get("DDHX_LOG")) if (logpath.length) { import std.process : thisProcessID; logStart(logpath); log("PID=%d", thisProcessID()); } // Load config file after defaults when able. Spouting an error here is // more important to have a functioning editor, before loading document. import std.file : readText; initdefaults(); if (orc) // Load specified RC by path { Lrc: log(`config_file="%s"`, orc); loadRC(rc, readText(orc)); } else if (onorc == false) // norc==true means to NOT load user configs { import os.path : findConfig; orc = findConfig("ddhx", ".ddhxrc"); if (orc) // we got config path, load it goto Lrc; } // Select editor backend, this allows transitioning between multiple // backends (implementations) easier. IDocumentEditor editor = spawnEditor( environment.get("DDHX_BACKEND") ); log("backend=%s", editor); string target = args.length >= 2 ? args[1] : null; // Create a session here. // Messy, but needed to start tracking files... Session *session = create_session(editor, rc, target); // Open buffer or file where (imitating GNU nano): // - No args: New empty buffer // - "-": Read from stdin // - FILENAME: Attempt to open FILE log(`target="%s"`, target); string initmsg; switch (target) { case null: // no filename import os.terminal : terminalInputIsPipe; if (terminalInputIsPipe()) goto case "-"; initmsg = MSG_NEW_BUFFER; break; case "-": // In-memory buffer from stdin import ddhx.document.memory : MemoryDocument; target = null; // unset target (no name) MemoryDocument doc = new MemoryDocument(); foreach (const(ubyte)[] chk; stdin.byChunk(4096)) { doc.append(chk); } editor.open(doc); session.ogdoc = doc; initmsg = MSG_NEW_BUFFER; break; default: // target is set, to either: file, disk (todo), or PID (todo) try initmsg = open_document(session, target); catch (Exception ex) fatal(ex); } log(`initmsg="%s"`, initmsg); assert(initmsg, "Forgot initmsg?"); try start_session(session, initmsg, bookmarks_file, diff_file); catch (Exception ex) { fatal(ex); } }