| 1 | // Copyright 2009-2024 Chris Spiegel. |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include <algorithm> |
| 6 | #include <bitset> |
| 7 | #include <cctype> |
| 8 | #include <cerrno> |
| 9 | #include <climits> |
| 10 | #include <cmath> |
| 11 | #include <cstdint> |
| 12 | #include <cstdlib> |
| 13 | #include <cstring> |
| 14 | #include <fstream> |
| 15 | #include <functional> |
| 16 | #include <iomanip> |
| 17 | #include <iostream> |
| 18 | #include <sstream> |
| 19 | #include <stdexcept> |
| 20 | #include <unordered_map> |
| 21 | #include <utility> |
| 22 | |
| 23 | #ifdef ZTERP_GLK_UNIX |
| 24 | extern "C" { |
| 25 | #include <glk.h> |
| 26 | #include <glkstart.h> |
| 27 | } |
| 28 | #endif |
| 29 | |
| 30 | #include "meta.h" |
| 31 | #include "options.h" |
| 32 | #include "osdep.h" |
| 33 | #include "patches.h" |
| 34 | #include "screen.h" |
| 35 | #include "util.h" |
| 36 | #include "zterp.h" |
| 37 | |
| 38 | using namespace std::literals; |
| 39 | |
| 40 | Options options; |
| 41 | std::bitset<3> arg_status; |
| 42 | |
| 43 | #ifndef ZTERP_NO_OPTIONS |
| 44 | struct ParseError : public std::runtime_error { |
| 45 | using std::runtime_error::runtime_error; |
| 46 | }; |
| 47 | |
| 48 | struct Range { |
| 49 | Range() = default; |
| 50 | |
| 51 | Range(unsigned long min_, unsigned long max_) : |
| 52 | min(min_), |
| 53 | max(max_) |
| 54 | { |
| 55 | } |
| 56 | |
| 57 | // The default max is the largest 32-bit power of 10 (1 billion). |
| 58 | // This looks a bit nicer to the end-user than a power of two, and |
| 59 | // is large enough that it will never be a hindrance. In addition, |
| 60 | // it’s predictable: ULONG_MAX can differ across platforms, so it’s |
| 61 | // better to avoid it as the max. |
| 62 | unsigned long min = 0; |
| 63 | unsigned long max = 1000000000UL; |
| 64 | }; |
| 65 | |
| 66 | static Options::Parser bool_helper(bool &target) |
| 67 | { |
| 68 | return [&target](const std::string &val) { |
| 69 | if (val == "0") { |
| 70 | target = false; |
| 71 | } else if (val == "1") { |
| 72 | target = true; |
| 73 | } else { |
| 74 | throw ParseError("must be 0 or 1"); |
| 75 | } |
| 76 | }; |
| 77 | } |
| 78 | |
| 79 | template <typename T> |
| 80 | static Options::Parser number_helper(Range range, T &target, std::function<T(unsigned long)> wrapper) |
| 81 | { |
| 82 | return [range, &target, wrapper = std::move(wrapper)](const std::string &val) { |
| 83 | char *endptr; |
| 84 | errno = 0; |
| 85 | auto n = std::strtoul(val.c_str(), &endptr, 10); |
| 86 | if (val[0] == '-' || *endptr != 0) { |
| 87 | throw ParseError("must be a non-negative integral number"); |
| 88 | } else if ((n == ULONG_MAX && errno == ERANGE) || n < range.min || n > range.max) { |
| 89 | const std::string msg = "must be an integral number between " + std::to_string(range.min) + " and " + std::to_string(range.max) + " inclusive"; |
| 90 | throw ParseError(msg); |
| 91 | } else { |
| 92 | target = wrapper(n); |
| 93 | } |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | static Options::Parser float_helper(double &target) |
| 98 | { |
| 99 | return [&target](const std::string &val) { |
| 100 | char *endptr; |
| 101 | errno = 0; |
| 102 | auto n = std::strtod(val.c_str(), &endptr); |
| 103 | if (val.find_first_of("eE") != std::string::npos || val[0] == '-' || *endptr != 0) { |
| 104 | throw ParseError("must be a non-negative number"); |
| 105 | } else if (errno == ERANGE) { |
| 106 | throw ParseError("floating point value out of range"); |
| 107 | } else { |
| 108 | switch (std::fpclassify(n)) { |
| 109 | case FP_NORMAL: case FP_ZERO: |
| 110 | target = n; |
| 111 | break; |
| 112 | case FP_NAN: |
| 113 | throw ParseError("not a number"); |
| 114 | case FP_INFINITE: |
| 115 | throw ParseError("is infinite"); |
| 116 | case FP_SUBNORMAL: |
| 117 | throw ParseError("is subnormal"); |
| 118 | default: |
| 119 | throw ParseError("unknown classification"); |
| 120 | } |
| 121 | } |
| 122 | }; |
| 123 | } |
| 124 | |
| 125 | static Options::Parser char_helper(unsigned char &target) |
| 126 | { |
| 127 | return [&target](const std::string &val) { |
| 128 | if (val.size() != 1) { |
| 129 | throw ParseError("must be a single character"); |
| 130 | } else { |
| 131 | target = val[0]; |
| 132 | } |
| 133 | }; |
| 134 | } |
| 135 | |
| 136 | #ifdef GLK_MODULE_GARGLKTEXT |
| 137 | static Options::Parser color_helper(int num) |
| 138 | { |
| 139 | return [num](const std::string &val) { |
| 140 | char *endptr; |
| 141 | auto color = std::strtoul(val.c_str(), &endptr, 16); |
| 142 | if (val[0] == '-' || *endptr != 0 || color > 0xffffff) { |
| 143 | throw ParseError("must be a hexadecimal number ranging from 0x000000 to 0xffffff"); |
| 144 | } else { |
| 145 | update_color(num, color); |
| 146 | } |
| 147 | }; |
| 148 | } |
| 149 | #endif |
| 150 | |
| 151 | // Define options that can be set from the command-line or the config file. |
| 152 | #define BOOL(opt, desc, from_config, name) add_parser(opt, desc, from_config, #name, bool_helper(name), OptValue::Type::Flag) |
| 153 | #define NUMBER(opt, desc, from_config, name, range) add_parser(opt, desc, from_config, #name, number_helper<unsigned long>(range, name, [](unsigned long n) { return n; }), OptValue::Type::Number) |
| 154 | #define OPTNUM(opt, desc, from_config, name, range) add_parser(opt, desc, from_config, #name, number_helper<std::unique_ptr<unsigned long>>(range, name, [](unsigned long n) { return std::make_unique<unsigned long>(n); }), OptValue::Type::Number) |
| 155 | #define FLOAT(opt, desc, from_config, name) add_parser(opt, desc, from_config, #name, float_helper(name), OptValue::Type::Value) |
| 156 | #define STRING(opt, desc, from_config, name) add_parser(opt, desc, from_config, #name, [this](const std::string &val) { name = std::make_unique<std::string>(val); }, OptValue::Type::Value) |
| 157 | #define CHAR(opt, desc, from_config, name) add_parser(opt, desc, from_config, #name, char_helper(name), OptValue::Type::Value) |
| 158 | |
| 159 | // Define options that can be set from the config file only. |
| 160 | #define CONFIG_BOOL(name) BOOL(0, "", true, name) |
| 161 | #define CONFIG_STRING(name) STRING(0, "", true, name) |
| 162 | #define CONFIG_FLOAT(name) FLOAT(0, "", true, name) |
| 163 | |
| 164 | #ifdef GLK_MODULE_GARGLKTEXT |
| 165 | #define COLOR(name, num) add_parser(0, "", true, "color_" #name, color_helper(num), OptValue::Type::Value) |
| 166 | #else |
| 167 | #define COLOR(name, num) |
| 168 | #endif |
| 169 | |
| 170 | // Some configuration options are available only in certain compile-time |
| 171 | // configurations. For those options, silently ignore them in |
| 172 | // configurations where they are not valid. This allows configuration |
| 173 | // files to be shared between such builds without dispaying diagnostics |
| 174 | // for options which are valid in some builds but not others. |
| 175 | |
| 176 | Options::Options() { |
| 177 | if (m_initialized) { |
| 178 | throw std::runtime_error("internal error: Options created multiple times"); |
| 179 | } |
| 180 | |
| 181 | m_initialized = true; |
| 182 | |
| 183 | NUMBER('a', "Set the evaluation stack size", true, eval_stack_size, Range()); |
| 184 | NUMBER('A', "Set the call stack size", true, call_stack_size, Range(0, 65535)); |
| 185 | BOOL ('c', "Disable colors", true, disable_color); |
| 186 | BOOL ('C', "Ignore the configuration file", false, disable_config); |
| 187 | BOOL ('d', "Disable timed input", true, disable_timed); |
| 188 | BOOL ('D', "Disable sound effects", true, disable_sound); |
| 189 | BOOL ('e', "Enable ANSI escape sequences in the transcript", true, enable_escape); |
| 190 | STRING('E', "Set the escape string used to decorate transcripts (via -e)", true, escape_string); |
| 191 | BOOL ('f', "Disable fixed-width fonts", true, disable_fixed); |
| 192 | BOOL ('F', "Assume the default font is fixed-width", true, assume_fixed); |
| 193 | BOOL ('g', "Disable the character graphics font", true, disable_graphics_font); |
| 194 | BOOL ('G', "Select alternate box-drawing characters", true, enable_alt_graphics); |
| 195 | BOOL ('h', "Display this help message then exit", false, show_help); |
| 196 | BOOL ('H', "Disable history playback on restore", true, disable_history_playback); |
| 197 | BOOL ('i', "Print the ID of the specified game then exit", false, show_id); |
| 198 | BOOL ('k', "Disable terminating keys", true, disable_term_keys); |
| 199 | STRING('l', "Set the username", true, username); |
| 200 | BOOL ('m', "Disable meta commands", true, disable_meta_commands); |
| 201 | NUMBER('n', "Set the interpreter number (see 11.1.3 in The Z-machine Standards Document 1.1)", true, int_number, Range(1, 11)); |
| 202 | CHAR ('N', "Set the interpreter version to the single-character version (see 11.1.3.1 in The Z-machine Standards Document 1.1)", true, int_version); |
| 203 | BOOL ('p', "Disable the application of patches", true, disable_patches); |
| 204 | BOOL ('r', "Play back a command record", true, replay_on); |
| 205 | STRING('R', "Specify the filename for the command record replay", true, replay_name); |
| 206 | BOOL ('s', "Turn on command recording", true, record_on); |
| 207 | STRING('S', "Specify the filename for the command record", true, record_name); |
| 208 | BOOL ('t', "Turn on transcripting", true, transcript_on); |
| 209 | STRING('T', "Specify the filename for the transcript", true, transcript_name); |
| 210 | NUMBER('u', "Set the maximum number of UNDO slots", true, undo_slots, Range()); |
| 211 | BOOL ('v', "Display version and configuration information then exit", false, show_version); |
| 212 | BOOL ('x', "Disable abbreviations (x, g, z, o) provided by Bocfel for old Infocom games", true, disable_abbreviations); |
| 213 | BOOL ('X', "Turn on the Tandy/censorship flag", true, enable_censorship); |
| 214 | BOOL ('y', "Overwrite transcripts rather than appending to them", true, overwrite_transcript); |
| 215 | BOOL ('Y', "Use internal UNDO handling code only", true, override_undo); |
| 216 | OPTNUM('z', "Provide a seed for the PRNG", true, random_seed, Range(0, UINT32_MAX)); |
| 217 | STRING('Z', "Provide a file/device from which 32 bits will be read as a seed", true, random_device); |
| 218 | |
| 219 | CONFIG_BOOL (autosave); |
| 220 | CONFIG_BOOL (skip_autorestore); |
| 221 | CONFIG_STRING(autosave_directory); |
| 222 | CONFIG_BOOL (autosave_librarystate); |
| 223 | CONFIG_BOOL (persistent_transcript); |
| 224 | CONFIG_STRING(editor); |
| 225 | CONFIG_BOOL (warn_on_v6); |
| 226 | CONFIG_BOOL (redirect_v6_windows); |
| 227 | CONFIG_BOOL (disable_v6_hacks); |
| 228 | CONFIG_FLOAT (v6_hack_max_scale); |
| 229 | CONFIG_BOOL (v6_borders); |
| 230 | CONFIG_BOOL (aspect_correction); |
| 231 | |
| 232 | COLOR(black, 2); |
| 233 | COLOR(red, 3); |
| 234 | COLOR(green, 4); |
| 235 | COLOR(yellow, 5); |
| 236 | COLOR(blue, 6); |
| 237 | COLOR(magenta, 7); |
| 238 | COLOR(cyan, 8); |
| 239 | COLOR(white, 9); |
| 240 | |
| 241 | m_from_config.emplace("cheat", [](const std::string &val) { |
| 242 | #ifndef ZTERP_NO_CHEAT |
| 243 | if (!cheat_add(val, false)) { |
| 244 | throw ParseError("syntax error"); |
| 245 | } |
| 246 | #endif |
| 247 | }); |
| 248 | |
| 249 | m_from_config.emplace("patch", [](const std::string &val) { |
| 250 | try { |
| 251 | apply_user_patch(val); |
| 252 | } catch (const PatchStatus::SyntaxError &e) { |
| 253 | throw ParseError("syntax error: "s + e.what()); |
| 254 | } catch (const PatchStatus::NotFound &) { |
| 255 | throw ParseError("does not apply to this story"); |
| 256 | } |
| 257 | |
| 258 | return false; |
| 259 | }); |
| 260 | |
| 261 | #ifdef ZTERP_GLK_UNIX |
| 262 | int i = 0; |
| 263 | |
| 264 | // glkunix_argumentlist_t is “meant” to be filled with string |
| 265 | // literals, whose lifetime is that of the program. But here the |
| 266 | // descriptions are part of the Options object, and the options |
| 267 | // themselves need to be generated here, so lifetime issues must be |
| 268 | // taken into account. This is ugly, but just allocate space with |
| 269 | // “new”. |
| 270 | for (const auto &opt : options.opts()) { |
| 271 | glkunix_argumentlist_t arg{new char[3], glkunix_arg_NoValue, new char[opt.second.desc.size() + 1]}; |
| 272 | |
| 273 | arg.name[0] = '-'; |
| 274 | arg.name[1] = opt.first; |
| 275 | arg.name[2] = 0; |
| 276 | |
| 277 | if (opt.second.type == OptValue::Type::Number) { |
| 278 | arg.argtype = glkunix_arg_NumberValue; |
| 279 | } else if (opt.second.type == OptValue::Type::Value) { |
| 280 | arg.argtype = glkunix_arg_ValueFollows; |
| 281 | } |
| 282 | |
| 283 | std::memcpy(arg.desc, opt.second.desc.data(), opt.second.desc.size() + 1); |
| 284 | |
| 285 | glkunix_arguments[i++] = arg; |
| 286 | } |
| 287 | |
| 288 | glkunix_arguments[i++] = glkunix_argumentlist_t{const_cast<char *>(""), glkunix_arg_ValueFollows, const_cast<char *>("file to load")}; |
| 289 | glkunix_arguments[i++] = glkunix_argumentlist_t{nullptr, glkunix_arg_End, nullptr}; |
| 290 | #endif |
| 291 | } |
| 292 | |
| 293 | #undef NUMBER |
| 294 | #undef OPTNUM |
| 295 | #undef BOOL |
| 296 | #undef STRING |
| 297 | #undef CHAR |
| 298 | #undef COLOR |
| 299 | |
| 300 | bool Options::m_initialized = false; |
| 301 | |
| 302 | void Options::add_parser(char opt, std::string desc, bool use_config, std::string name, const Parser &parser, OptValue::Type type) { |
| 303 | if (opt != 0) { |
| 304 | m_opts.insert({opt, {type, std::move(desc), parser}}); |
| 305 | } |
| 306 | |
| 307 | if (use_config) { |
| 308 | m_from_config.emplace(std::move(name), parser); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | void Options::read_config() |
| 313 | { |
| 314 | auto file = zterp_os_rcfile(false); |
| 315 | if (file == nullptr) { |
| 316 | return; |
| 317 | } |
| 318 | |
| 319 | std::ifstream f(*file); |
| 320 | if (!f.is_open()) { |
| 321 | return; |
| 322 | } |
| 323 | |
| 324 | parse_grouped_file(f, [&file, this](const std::string &line, int lineno) { |
| 325 | auto errmsg = [&file, lineno](const std::string &msg) { |
| 326 | std::cerr << *file << ":" << lineno << ": " << msg << std::endl; |
| 327 | }; |
| 328 | |
| 329 | auto equal = line.find('='); |
| 330 | if (equal == std::string::npos) { |
| 331 | errmsg("expected '='"); |
| 332 | return; |
| 333 | } |
| 334 | |
| 335 | auto key = rtrim(line.substr(0, equal)); |
| 336 | if (key.empty()) { |
| 337 | errmsg("no key"); |
| 338 | return; |
| 339 | } |
| 340 | |
| 341 | auto val = ltrim(line.substr(equal + 1)); |
| 342 | if (val.empty()) { |
| 343 | errmsg("no value"); |
| 344 | return; |
| 345 | } |
| 346 | |
| 347 | try { |
| 348 | static const std::unordered_map<std::string, std::string> legacy_names = { |
| 349 | {"notes_editor", "editor"}, |
| 350 | {"max_saves", "undo_slots"}, |
| 351 | }; |
| 352 | |
| 353 | const auto &newkey = legacy_names.at(key); |
| 354 | if (newkey.empty()) { |
| 355 | errmsg("warning: configuration option " + key + " no longer exists"); |
| 356 | return; |
| 357 | } else { |
| 358 | errmsg("warning: configuration option " + key + " is deprecated; it has been renamed " + newkey); |
| 359 | key = newkey; |
| 360 | } |
| 361 | } catch (const std::out_of_range &) { |
| 362 | } |
| 363 | |
| 364 | try { |
| 365 | auto parser = m_from_config.at(key); |
| 366 | parser(val); |
| 367 | } catch (const std::out_of_range &) { |
| 368 | errmsg("unknown configuration option: " + key); |
| 369 | } catch (const ParseError &e) { |
| 370 | errmsg("invalid value for " + key + ": " + e.what()); |
| 371 | } |
| 372 | }); |
| 373 | } |
| 374 | |
| 375 | void Options::read_envvars() |
| 376 | { |
| 377 | for (const auto &pair : m_from_config) { |
| 378 | std::ostringstream ss; |
| 379 | ss << "BOCFEL_"; |
| 380 | for (unsigned char ch : pair.first) { |
| 381 | ss << static_cast<char>(std::toupper(ch)); |
| 382 | } |
| 383 | |
| 384 | auto val = zterp_getenv(ss.str()); |
| 385 | if (val != nullptr) { |
| 386 | pair.second(*val); |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | int Options::getopt(int argc, char *const argv[]) |
| 392 | { |
| 393 | int optind = 0; |
| 394 | const char *p = ""; |
| 395 | |
| 396 | while (true) { |
| 397 | if (*p == 0) { |
| 398 | // No more arguments. |
| 399 | if (++optind >= argc) { |
| 400 | return optind; |
| 401 | } |
| 402 | |
| 403 | p = argv[optind]; |
| 404 | |
| 405 | // No more options. |
| 406 | if (p[0] != '-' || p[1] == 0) { |
| 407 | return optind; |
| 408 | } |
| 409 | |
| 410 | // Handle “--” |
| 411 | if (*++p == '-' && p[1] == 0) { |
| 412 | return optind + 1; |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | char c = *p++; |
| 417 | try { |
| 418 | const auto &optvalue = m_opts.at(c); |
| 419 | const char *optarg = nullptr; |
| 420 | |
| 421 | if (optvalue.type == OptValue::Type::Flag) { |
| 422 | optvalue.parser("1"); |
| 423 | } else { |
| 424 | if (*p != 0) { |
| 425 | optarg = p; |
| 426 | p = ""; |
| 427 | } else { |
| 428 | optarg = argv[++optind]; |
| 429 | if (optarg == nullptr) { |
| 430 | arg_status.set(ArgStatus::BadOption); |
| 431 | std::string error = "missing argument for -"s + c; |
| 432 | m_errors.push_back(error); |
| 433 | return optind; |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | optvalue.parser(optarg); |
| 438 | } |
| 439 | } catch (const std::out_of_range &) { |
| 440 | arg_status.set(ArgStatus::BadOption); |
| 441 | } catch (const ParseError &e) { |
| 442 | arg_status.set(ArgStatus::BadValue); |
| 443 | std::string error = "invalid argument for -"s + c + ": " + e.what(); |
| 444 | m_errors.push_back(error); |
| 445 | } |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | void Options::process_arguments(int argc, char **argv) |
| 450 | { |
| 451 | int optind = getopt(argc, argv); |
| 452 | |
| 453 | // Just ignore excess stories for now. |
| 454 | if (optind < argc) { |
| 455 | game_file = argv[optind]; |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | void Options::help() |
| 460 | { |
| 461 | #ifdef ZTERP_GLK |
| 462 | glk_set_style(style_Preformatted); |
| 463 | #endif |
| 464 | |
| 465 | screen_puts("Usage: bocfel [args] filename"); |
| 466 | for (const auto &opt : options.opts()) { |
| 467 | std::string typestr; |
| 468 | |
| 469 | if (opt.second.type == OptValue::Type::Number) { |
| 470 | typestr = "number"; |
| 471 | } else if (opt.second.type == OptValue::Type::Value) { |
| 472 | typestr = "string"; |
| 473 | } |
| 474 | |
| 475 | std::ostringstream ss; |
| 476 | ss << "-" << opt.first << " " << std::setw(12) << std::left << typestr << opt.second.desc; |
| 477 | screen_puts(ss.str()); |
| 478 | } |
| 479 | } |
| 480 | #else |
| 481 | void Options::process_arguments(int argc, char **argv) |
| 482 | { |
| 483 | if (argc > 1) { |
| 484 | game_file = argv[1]; |
| 485 | } |
| 486 | } |
| 487 | #endif |