/// Configuration management.
///
/// Copyright: dd86k
/// License: MIT
/// Authors: $(LINK2 https://github.com/dd86k, dd86k)
module configuration; // "config" would conflict with std.getopt.config
import std.conv : text, to;
import std.system : Endian;
import ddhx.formatting;
import ddhx.charset : Charset, ASCII, EBCDIC037, findCharset;
import os.terminal : terminalKeybind;
import colors;
import messages;
import utils : arguments, Argument;
import view : bindkey, setcolor, initdefaults, binded;
/// Special value for RC.find_bookmark_limit, for no limit at all.
enum BOOKMARK_LIMIT_NONE = -1;
/// Editor configuration
struct RC
{
/// Address formatting (hex, dec, oct).
AddressType address_type = AddressType.hex;
/// Data formatting (x8, etc.)
DataType data_type = DataType(BaseType.u8, Format.hex);
/// Character set used for transcoding.
immutable(Charset)* charset = &ASCII;
/// Writing mode.
///
/// Opening document as read-only automatically sets this as readonly too.
WritingMode writemode = WritingMode.overwrite;
/// If set, editing is restricted for the whole session (-R/--restrict).
///
/// Unlike the readonly writing mode, which is only the current mode and
/// can be changed back, this cannot be lifted once the session started.
bool restricted;
/// Number of columns
int columns = 16;
/// If set, columns are refit to the terminal width on resize.
bool columns_auto;
/// Number of characters to fill when printing row address.
int address_spacing = 11;
/// If set, hide header.
bool header = true;
/// If set, hide status bar.
bool status = true;
/// If set, sets the cursor mirror.
bool mirror_cursor; // could be paired with "mirror-color" later
/// Highlight zero data values.
bool highlight_zeros = true;
/// Enable coalescing
bool coalescing = true;
/// Show the inspector panel below the data view.
bool inspector;
/// Endian used by the inspector for multi-byte interpretations.
Endian endian = Endian.littleEndian;
/// Maximum number of bookmarks the find-bookmark command adds in one run,
/// or BOOKMARK_LIMIT_NONE for no limit.
///
/// A search reports as many matches as the document holds, and every
/// bookmark costs memory and view rendering time, so a one-byte needle
/// over a large file is capped rather than left to bring the editor
/// down. The command says when it stops early.
int find_bookmark_limit = 4096;
/// Format string for the normal status bar.
string status_fmt_normal = "%e %m | %t | %c | %8p";
/// Format string for the selection status bar.
string status_fmt_selection = "SEL: %V (%v Bytes)";
/// Format string for the report bar (report command).
string status_fmt_report = "%d / %s B (%q%%)";
private:
// Fixes when RC file has config and CLI already set a field.
bool address_type_set;
bool data_type_set;
bool charset_set;
bool writemode_set;
bool columns_set;
bool address_spacing_set;
bool header_set;
bool status_set;
bool mirror_cursor_set;
bool highlight_zeros_set;
bool coalescing_set;
bool inspector_set;
bool endian_set;
bool find_bookmark_limit_set;
bool status_fmt_normal_set;
bool status_fmt_selection_set;
bool status_fmt_report_set;
}
/// Return true/false given sting input.
///
/// Values like "on"/"off" are accepted.
///
/// More values could be accepted in the future, such as "true"/"false",
/// "yes"/"no", "enabled"/"disabled", but for the sake of consistency
/// and simplicity, it's better to just stick to one pair.
/// Params: input = String value input.
/// Returns: true for "on", false for "off"
/// Throws: Exception if neither.
private
bool boolean(string input)
{
switch (input) {
case "on": return true;
case "off": return false;
default: throw new Exception(MSG_ON_OR_OFF_ACCEPTED);
}
}
unittest
{
assert(boolean("on") == true);
assert(boolean("off") == false);
try
{
cast(void)boolean(null);
assert(false);
}
catch (Exception) {}
}
/// Load a configuration from text.
/// Params:
/// rc = RC instance reference.
/// text = Configuration text.
void loadRC(ref RC rc, string text) // @suppress(dscanner.style.doc_missing_throw)
{
// NOTE: The strategy is to only update value in RC if they're default.
// Otherwise, if the value is different than default, then it was set
// at the command-line, and thus should not be changed.
import std.string : lineSplitter;
foreach (ref string line; lineSplitter(text))
{
if (line.length == 0 || line[0] == '#')
continue;
Argument[] args = arguments(line);
if (args.length < 2)
throw new Exception(MSG_MISSING_VALUE);
// Special
switch (args[0].text) {
case "bind": // bind KEY COMMAND [ARGS...]
if (args.length < 3)
throw new Exception(MSG_MISSING_COMMAND);
bindkey(
terminalKeybind( args[1].text ),
args[2].text,
args.length > 3 ? args[3..$] : null);
continue;
case "color": // color SCHEME COLOR
if (args.length < 3)
throw new Exception(MSG_MISSING_COLOR);
setcolor(
getScheme(args[1].text),
ColorMap.parse(args[2].text)
);
continue;
default:
configRC(rc, args[0].text, args[1].text, true);
}
}
}
unittest
{
initdefaults(); // bindkey depends on g_commands (command names)
// Check defaults
RC rc;
int key = terminalKeybind("j");
assert(rc.columns == 16);
assert(binded(key) == null);
// Emulate CLI change, before config
configure_columns(rc, "6");
configure_charset(rc, "ascii");
// Load and check
loadRC(rc,
`columns 20
charset ebcdic037
bind j left`);
assert(rc.columns == 6); // Untouched by config file
assert(rc.charset == &ASCII);
assert(binded(key));
}
/// Describes a configuration.
struct Config
{
string name; /// Short name
string description; /// Configuration description
string availvalues; /// Available values or expected type
string defaultval; /// Default value
void function(ref RC, string val, bool rc) impl; /// Implementation function
}
/// Available configurations.
immutable Config[] configurations = [ // Try keeping this ascending by name!
{
"address-spacing", "Address spacing in characters",
"Number", "11",
&configure_address_spacing
},
{
"address", "Address representation format",
`"h[exadecimal]", "o[ctal]", "d[ecimal]"`, `"hexadecimal"`,
&configure_address
},
{
"data", "Data representation format",
`"x8", "x16", "x32", "d8", "d16", "d32", "o8", "o16", "o32"`, `"x8"`,
&configure_data
},
{
"charset", "Character set",
`"ascii", "cp437", "ebcdic037", "macroman", "latin1", "win1252"`, `"ascii"`,
&configure_charset
},
{
// NOTE: "autoresize" was too ambiguous and moved into columns
"columns", "Number of elements to show on a row, 'auto' to fit screen",
`Number, or "auto"`, "16",
&configure_columns
},
{
"header", "If enabled, show the header bar",
"Boolean", `"on"`,
&configure_header
},
{
"status", "If enabled, show the status bar",
"Boolean", `"on"`,
&configure_status
},
{
"mirror-cursor", "If set, mirrors the cursor for both columns",
"Boolean", `"off"`,
&configure_mirror_cursor
},
{
"highlight-zeros", "If set, zero data values are colored",
"Boolean", `"on"`,
&configure_highlight_zeros
},
{
"coalesce", "If set, edits are coalescing",
"Boolean", `"on"`,
&configure_coalescing
},
{
"inspector", "If set, show the data inspector panel below the view",
"Boolean", `"off"`,
&configure_inspector
},
{
"endian", "Endian used for multi-byte values (inspector, scalar patterns)",
`"little" or "big" (aliases: "le", "be")`, `"little"`, // TODO: native option
&configure_endian
},
{
"find-bookmark-limit", "Maximum matches the find-bookmark command bookmarks in one run",
`Number, or "none" for no limit`, "4096",
&configure_find_bookmark_limit
},
{
"status-format", "Normal status bar format string",
"Format string", `"%e %m | %t | %c | %p"`,
&configure_status_fmt_normal
},
{
"status-report", "Report status bar format string",
"Format string", `"%d / %s B"`,
&configure_status_fmt_report
},
{
"status-selection", "Selection status bar format string",
"Format string", `"SEL: %V (%v Bytes)"`,
&configure_status_fmt_selection
},
{
"writemode", "Writing mode used when entering data",
`"readonly", "overwrite", "insert", "digit"`, `"overwrite"`,
&configure_writemode
},
];
unittest
{
foreach (config; configurations)
{
// Must have name
assert(config.name, "No name");
// Must have description
assert(config.description, "No description: "~config.name);
// Must have values
assert(config.availvalues, "No values: "~config.name);
// Must have default
assert(config.defaultval, "No default: "~config.name);
// Must have implementation
assert(config.impl, "No impl: "~config.name);
}
}
// Used when configurating runtime config and parsing command values.
/// Set a runtime configuration setting to a value.
/// Params:
/// rc = RC instance reference.
/// field = Setting name.
/// value = New value.
/// conf = Loading from RC. If set, do not change if already set.
/// Throws: Exception when a setting or value is invalid.
void configRC(ref RC rc, string field, string value, bool conf = false)
{
foreach (config; configurations)
{
if (config.name == field)
{
config.impl(rc, value, conf);
return;
}
}
throw new Exception(text(MSG_UNKNOWN_FIELD, field));
}
unittest
{
RC rc;
configRC(rc, "columns", "10");
assert(rc.columns == 10);
configRC(rc, "address", "dec");
assert(rc.address_type == AddressType.dec);
configRC(rc, "address-spacing", "5");
assert(rc.address_spacing == 5);
configRC(rc, "charset", "ebcdic037");
assert(rc.charset == &EBCDIC037);
configRC(rc, "writemode", "insert");
assert(rc.writemode == WritingMode.insert);
}
unittest
{
// Restricted (-R) can't be lifted, by config file or at runtime
RC rc;
restrictRC(rc);
assert(rc.writemode == WritingMode.readonly);
loadRC(rc, "writemode overwrite");
assert(rc.writemode == WritingMode.readonly);
try
{
configRC(rc, "writemode", "overwrite");
assert(false);
}
catch (Exception) {}
assert(rc.writemode == WritingMode.readonly);
}
unittest
{
// Without -R, the readonly mode is just a mode, and can be changed back
RC rc;
loadRC(rc, "writemode readonly");
assert(rc.writemode == WritingMode.readonly);
configRC(rc, "writemode", "overwrite");
assert(rc.writemode == WritingMode.overwrite);
}
unittest
{
// -W lifts -R (last option wins) and configuration files can't restrict
RC rc;
restrictRC(rc);
unrestrictRC(rc);
assert(rc.restricted == false);
assert(rc.writemode == WritingMode.overwrite);
loadRC(rc, "writemode readonly");
assert(rc.writemode == WritingMode.overwrite);
// And editing can still be restricted afterward, at runtime
configRC(rc, "writemode", "readonly");
assert(rc.writemode == WritingMode.readonly);
}
void configure_columns(ref RC rc, string value, bool conf = false)
{
if (conf && rc.columns_set)
return;
// Aliases
switch (value) {
case "auto", "autoresize":
rc.columns_auto = true;
rc.columns_set = true;
return;
default:
}
int cols = to!int(value);
if (cols <= 0)
throw new Exception(MSG_NO_COLUMNS);
rc.columns = cols;
rc.columns_auto = false;
rc.columns_set = true;
}
void configure_find_bookmark_limit(ref RC rc, string value, bool conf = false)
{
if (conf && rc.find_bookmark_limit_set)
return;
// Alias, because "-1" reads like a typo in a configuration file
if (value == "none")
{
rc.find_bookmark_limit = BOOKMARK_LIMIT_NONE;
rc.find_bookmark_limit_set = true;
return;
}
int limit = to!int(value);
// Zero means bookmarking nothing, which is not something to ask of a
// command that exists to add bookmarks
if (limit == 0)
throw new Exception(MSG_BOOKMARK_LIMIT_INVALID);
if (limit < 0) // any negative reads as "no limit"
limit = BOOKMARK_LIMIT_NONE;
rc.find_bookmark_limit = limit;
rc.find_bookmark_limit_set = true;
}
unittest
{
RC rc;
assert(rc.find_bookmark_limit == 4096); // default
configRC(rc, "find-bookmark-limit", "10");
assert(rc.find_bookmark_limit == 10);
configRC(rc, "find-bookmark-limit", "none");
assert(rc.find_bookmark_limit == BOOKMARK_LIMIT_NONE);
configRC(rc, "find-bookmark-limit", "-1");
assert(rc.find_bookmark_limit == BOOKMARK_LIMIT_NONE);
// Zero, and anything that is not a number, are refused
try
{
configRC(rc, "find-bookmark-limit", "0");
assert(false);
}
catch (Exception ex) {}
try
{
configRC(rc, "find-bookmark-limit", "many");
assert(false);
}
catch (Exception ex) {}
assert(rc.find_bookmark_limit == BOOKMARK_LIMIT_NONE); // untouched
}
void configure_address(ref RC rc, string value, bool conf = false)
{
if (conf && rc.address_type_set)
return;
if (value is null || value.length == 0)
Lerror:
throw new Exception(text(MSG_UNKNOWN_ADDRESS_TYPE, value));
switch (value[0]) { // cheap "startsWith"
case 'h': rc.address_type = AddressType.hex; break;
case 'd': rc.address_type = AddressType.dec; break;
case 'o': rc.address_type = AddressType.oct; break;
default: goto Lerror;
}
rc.address_type_set = true;
}
void configure_data(ref RC rc, string value, bool conf = false)
{
if (conf && rc.data_type_set)
return;
rc.data_type = selectDataType(value);
rc.data_type_set = true;
}
void configure_address_spacing(ref RC rc, string value, bool conf = false)
{
if (conf && rc.address_spacing_set)
return;
int spacing = to!int(value);
if (spacing < 3 && spacing > -3) // due to offset indicator ("hex",etc.)
throw new Exception(MSG_ADDRESS_SPACING_TOO_LOW);
rc.address_spacing = spacing;
rc.address_spacing_set = true;
}
void configure_charset(ref RC rc, string value, bool conf = false)
{
if (conf && rc.charset_set)
return;
immutable(Charset)* set = findCharset(value);
if (set == null)
throw new Exception(text(MSG_INVALID_CHARSET, value));
rc.charset = set;
rc.charset_set = true;
}
void configure_header(ref RC rc, string value, bool conf = false)
{
if (conf && rc.header_set)
return;
rc.header = boolean(value);
rc.header_set = true;
}
void configure_status(ref RC rc, string value, bool conf = false)
{
if (conf && rc.status_set)
return;
rc.status = boolean(value);
rc.status_set = true;
}
void configure_mirror_cursor(ref RC rc, string value, bool conf = false)
{
if (conf && rc.mirror_cursor_set)
return;
rc.mirror_cursor = boolean(value);
rc.mirror_cursor_set = true;
}
void configure_highlight_zeros(ref RC rc, string value, bool conf = false)
{
if (conf && rc.highlight_zeros_set)
return;
// Eventually could just set the color mapping directly
rc.highlight_zeros = boolean(value);
rc.highlight_zeros_set = true;
}
void configure_coalescing(ref RC rc, string value, bool conf = false)
{
if (conf && rc.coalescing_set)
return;
rc.coalescing = boolean(value);
rc.coalescing_set = true;
}
void configure_inspector(ref RC rc, string value, bool conf = false)
{
if (conf && rc.inspector_set)
return;
rc.inspector = boolean(value);
rc.inspector_set = true;
}
void configure_endian(ref RC rc, string value, bool conf = false)
{
if (conf && rc.endian_set)
return;
switch (value) {
case "little", "le": rc.endian = Endian.littleEndian; break;
case "big", "be": rc.endian = Endian.bigEndian; break;
default: throw new Exception(text(MSG_UNKNOWN_ENDIAN, value));
}
rc.endian_set = true;
}
void configure_status_fmt_normal(ref RC rc, string value, bool conf = false)
{
if (conf && rc.status_fmt_normal_set)
return;
rc.status_fmt_normal = value;
rc.status_fmt_normal_set = true;
}
void configure_status_fmt_selection(ref RC rc, string value, bool conf = false)
{
if (conf && rc.status_fmt_selection_set)
return;
rc.status_fmt_selection = value;
rc.status_fmt_selection_set = true;
}
void configure_writemode(ref RC rc, string value, bool conf = false)
{
if (conf && rc.writemode_set)
return;
WritingMode mode = selectWritingMode(value);
// Restricted sessions (-R/--restrict) stay read-only, like the
// change-mode command refuses to switch out of it
if (rc.restricted && mode != WritingMode.readonly)
throw new Exception(MSG_CANT_EDIT_READONLY);
rc.writemode = mode;
rc.writemode_set = true;
}
/// Restrict document editing for the session (-R/--restrict).
///
/// A restricted session starts read-only and cannot be switched to another
/// writing mode, neither by configuration file nor at runtime.
/// Params: rc = RC instance reference.
void restrictRC(ref RC rc)
{
rc.restricted = true;
rc.writemode = WritingMode.readonly;
rc.writemode_set = true;
}
/// Allow document editing for the session (-W/--writable).
///
/// Lifts a restriction set earlier at the command-line, and keeps
/// configuration files from starting the session read-only.
/// Params: rc = RC instance reference.
void unrestrictRC(ref RC rc)
{
rc.restricted = false;
rc.writemode = WritingMode.overwrite;
rc.writemode_set = true;
}
void configure_status_fmt_report(ref RC rc, string value, bool conf = false)
{
if (conf && rc.status_fmt_report_set)
return;
rc.status_fmt_report = value;
rc.status_fmt_report_set = true;
}