Something went wrong. Try again.
🪄 dd's hex editor
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364/// CLI entry point.////// Copyright: dd86k <dd@dax.moe>/// 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 valuevoid 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); }}