Debian Codegraph @

terps/bocfel/osdep.cpp

raw symbols SCIP
1 // Copyright 2010-2025 Chris Spiegel.
2 //
3 // SPDX-License-Identifier: MIT
4
5 #include <climits>
6 #include <cstdio>
7 #include <cstdlib>
8 #include <cstring>
9 #include <exception>
10 #include <iomanip>
11 #include <iostream>
12 #include <memory>
13 #include <random>
14 #include <sstream>
15 #include <stdexcept>
16 #include <thread>
17 #include <utility>
18 #include <vector>
19
20 #ifdef ZTERP_GLK
21 extern "C" {
22 #include <glk.h>
23 }
24 #endif
25
26 #include "io.h"
27 #include "options.h"
28 #include "osdep.h"
29 #include "screen.h"
30 #include "types.h"
31 #include "util.h"
32 #include "zterp.h"
33
34 #if defined(ZTERP_UNIX) || defined(ZTERP_WIN32) || defined(ZTERP_DOS)
35 #error The operating system macros have been renamed to have a ZTERP_OS prefix.
36 #endif
37
38 using namespace std::literals;
39
40 // OS-specific functions should all be collected in this file for
41 // convenience. A sort of poor-man’s “reverse” inheritance is used: for
42 // each function that a particular operating system provides, it should
43 // #define a macro of the same name. At the end of the file, a generic
44 // function is provided for each function that has no associated macro
45 // definition.
46 //
47 // The functions required are as follows:
48 //
49 // long zterp_os_filesize(std::FILE *fp)
50 //
51 // Return the size of the file referred to by fp. It is safe to assume
52 // that the file is opened in binary mode. The file position indicator
53 // need not be maintained. If the size of the file is larger than
54 // LONG_MAX, -1 should be returned.
55 //
56 // std::unique_ptr<std::string> zterp_os_rcfile(bool create_parent)
57 //
58 // Different operating systems have different ideas about where
59 // configuration data should be stored; this function will return a
60 // suitable value for the bocfel configuration file. If a configuration
61 // file location cannot be determined, return a null pointer. If
62 // “create_parent” is true, attempt to create the containing directory,
63 // failing if this isn’t possible.
64 //
65 // std::unique_ptr<std::string> zterp_os_autosave_name()
66 //
67 // Return a suitable filename for autosaving. If there is some problem,
68 // a null pointer is returned. For example, the Unix implementation
69 // returns null if it can’t create all directory components in the
70 // filename. This should not verify that the file exists, because the
71 // first time an autosave is created, it necessarily won’t exist
72 // beforehand.
73 //
74 // std::unique_ptr<std::string> zterp_os_aux_file(const std::string &filename);
75 //
76 // The Z-machine allow games to save and load arbitrary files. Bocfel
77 // confines these files to a single (per-game) directory to avoid games
78 // overwriting unrelated files. This function, given a filename, returns
79 // a pointer to a string containing a full path to a file which
80 // represents the passed-in filename. The file need not exist, but its
81 // containing directory must. A null pointer is returned on failure. The
82 // file must not escape its containing directory, which may require
83 // platform-specific methods, but at the very least means that a file
84 // containing directory separators (e.g. '/' on Unix) must be rejected
85 // or sanitized. The incoming filename is guaranteed to consist of ASCII
86 // printable characters, i.e. in the range 32-126, but may need to be
87 // further sanitized depending on the needs of the target platform.
88 //
89 // void zterp_os_edit_file(const std::string &filename)
90 //
91 // Open the specified file in a text editor. On failure,
92 // std::runtime_error is thrown.
93 //
94 // std::vector<char> zterp_os_edit_notes(const std::vector<char> &notes)
95 //
96 // Given player notes in “notes”, open a text editor editing a file
97 // which contains those notes. When the editor successfully exits,
98 // return the contents of the saved file. On failure, std::runtime_error
99 // is thrown.
100 //
101 // void zterp_os_show_transcript(const std::vector<char> &transcript)
102 //
103 // Identical to zterp_os_edit_notes, except nothing is returned. This is
104 // meant to show the persistent transcript in the user’s editor, so it
105 // can be easily read, searched, etc.
106 //
107 // The following functions are useful for non-Glk builds only. They
108 // provide for some handling of screen functions that is normally taken
109 // care of by Glk.
110 //
111 // std::pair<unsigned int, unsigned int> zterp_os_get_screen_size()
112 //
113 // The size of the terminal, if known, is returned as a pair of (width,
114 // height). If terminal size is unavailable, (0, 0) should be returned.
115 //
116 // void zterp_os_init_term()
117 //
118 // If something special needs to be done to prepare the terminal for
119 // output, it should be done here. This function is called once at
120 // program startup.
121 //
122 // bool zterp_os_have_style(StyleBit style)
123 //
124 // This should return true if the provided individual style is
125 // available.
126 //
127 // bool zterp_os_have_colors()
128 //
129 // Returns true if the terminal supports colors.
130 //
131 // void zterp_os_set_style(const Style &style, const Color &fg, const Color &bg)
132 //
133 // Set both a style and foreground/background color. Any previous
134 // settings should be ignored; for example, if the last call to
135 // zterp_os_set_style() turned on italics and the current call sets
136 // bold, the result should be bold, not bold italic.
137 // The colors are references to “Color”: see screen.h.
138 // This function will be called unconditionally, so implementations must
139 // ignore requests if they cannot be fulfilled.
140
141 // ╔══════════════════════════════════════════════════════════════════════════════╗
142 // ║ Shared functions ║
143 // ╚══════════════════════════════════════════════════════════════════════════════╝
144 #if (defined(ZTERP_OS_WIN32) || defined(ZTERP_OS_DOS)) && !defined(ZTERP_GLK)
145 static void ansi_set_style(const Style &style, const Color &fg, const Color &bg)
146 {
147 std::cout << "\33[0";
148
149 if (style.test(STYLE_ITALIC)) {
150 std::cout << ";4";
151 }
152 if (style.test(STYLE_REVERSE)) {
153 std::cout << ";7";
154 }
155 if (style.test(STYLE_BOLD)) {
156 std::cout << ";1";
157 }
158
159 if (fg.mode == Color::Mode::ANSI) {
160 std::cout << ";" << (28 + fg.value);
161 }
162 if (bg.mode == Color::Mode::ANSI) {
163 std::cout << ";" << (38 + bg.value);
164 }
165
166 std::cout << "m";
167 }
168 #endif
169
170 #if defined(ZTERP_OS_UNIX) || defined(ZTERP_OS_WIN32)
171 static std::vector<char> read_file(const std::string &filename)
172 {
173 std::vector<char> new_file;
174
175 try {
176 IO io(&filename, IO::Mode::ReadOnly, IO::Purpose::Data);
177
178 long size = io.filesize();
179 if (size == -1) {
180 throw std::exception();
181 }
182
183 io.seek(0, IO::SeekFrom::Start);
184
185 if (size != 0) {
186 new_file.resize(size);
187 io.read_exact(new_file.data(), size);
188 }
189 } catch (...) {
190 throw std::runtime_error("unable to read file");
191 }
192
193 return new_file;
194 }
195 #endif
196
197 // ╔══════════════════════════════════════════════════════════════════════════════╗
198 // ║ Unix functions ║
199 // ╚══════════════════════════════════════════════════════════════════════════════╝
200 #ifdef ZTERP_OS_UNIX
201 #include <spawn.h>
202 #include <sys/stat.h>
203 #include <sys/types.h>
204 #include <sys/wait.h>
205 #include <unistd.h>
206
207 #ifdef __HAIKU__
208 #include <FindDirectory.h>
209 #endif
210
211 static std::string unique_name()
212 {
213 auto slash = game_file.rfind('/');
214 std::string basename;
215
216 if (slash != std::string::npos) {
217 basename = game_file.substr(slash + 1);
218 } else {
219 basename = game_file;
220 }
221
222 return basename + "-" + get_story_id();
223 }
224
225 // Given a filename (or a directory name ending in a slash), create all
226 // components of all directories, returning false in case of error.
227 static bool mkdir_p(const std::string &file)
228 {
229 for (auto slash = file.find('/'); slash != std::string::npos; slash = file.find('/', slash + 1)) {
230 auto component = file.substr(0, slash);
231 if (!component.empty()) {
232 struct stat st;
233 mkdir(component.c_str(), 0755);
234 if (stat(component.c_str(), &st) == -1 || !S_ISDIR(st.st_mode)) {
235 return false;
236 }
237 }
238 }
239
240 return true;
241 }
242
243 long zterp_os_filesize(std::FILE *fp)
244 {
245 struct stat st;
246 int fd = fileno(fp);
247
248 if (fd == -1 || fstat(fd, &st) == -1 || !S_ISREG(st.st_mode) || st.st_size > LONG_MAX) {
249 return -1;
250 }
251
252 return st.st_size;
253 }
254 #define have_zterp_os_filesize
255
256 std::unique_ptr<std::string> zterp_os_rcfile(bool create_parent)
257 {
258 std::unique_ptr<std::string> config_file;
259 #ifdef __HAIKU__
260 char settings_dir[4096];
261
262 if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, settings_dir, sizeof settings_dir) != B_OK) {
263 return nullptr;
264 }
265
266 config_file = std::make_unique<std::string>(std::string(settings_dir) + "/bocfel/bocfelrc");
267 #else
268 auto home = zterp_getenv("HOME");
269 if (home != nullptr) {
270 // This is the legacy location of the config file.
271 auto s = *home + "/.bocfelrc";
272 if (access(s.c_str(), R_OK) == 0) {
273 return std::make_unique<std::string>(s);
274 }
275 }
276
277 auto config_home = zterp_getenv("XDG_CONFIG_HOME");
278 if (config_home != nullptr && config_home->find('/') == 0) {
279 config_file = std::make_unique<std::string>(*config_home + "/bocfel/bocfelrc");
280 } else if (home != nullptr) {
281 config_file = std::make_unique<std::string>(*home + "/.config/bocfel/bocfelrc");
282 } else {
283 return nullptr;
284 }
285 #endif
286
287 if (create_parent && !mkdir_p(*config_file)) {
288 return nullptr;
289 }
290
291 return config_file;
292 }
293 #define have_zterp_os_rcfile
294
295 static std::unique_ptr<std::string> data_file(const std::string &filename)
296 {
297 #ifdef __HAIKU__
298 char settings_dir[4096];
299
300 if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, true, settings_dir, sizeof settings_dir) != B_OK) {
301 return nullptr;
302 }
303
304 auto name = std::make_unique<std::string>(std::string(settings_dir) + "/bocfel/" + filename);
305 #else
306 std::unique_ptr<std::string> name;
307
308 auto data_home = zterp_getenv("XDG_DATA_HOME");
309 if (data_home != nullptr && (*data_home)[0] == '/') {
310 name = std::make_unique<std::string>(*data_home + "/bocfel/" + filename);
311 } else {
312 auto home = zterp_getenv("HOME");
313 if (home == nullptr) {
314 return nullptr;
315 }
316 name = std::make_unique<std::string>(*home + "/.local/share/bocfel/" + filename);
317 }
318 #endif
319
320 if (!mkdir_p(*name)) {
321 return nullptr;
322 }
323
324 return name;
325 }
326
327 std::unique_ptr<std::string> zterp_os_autosave_name()
328 {
329 if (options.autosave_directory != nullptr) {
330 std::string filename = *options.autosave_directory + "/"s + unique_name();
331 if (!mkdir_p(filename)) {
332 return nullptr;
333 }
334 return std::make_unique<std::string>(filename);
335 } else {
336 std::string filename = "autosave/"s + unique_name();
337 return data_file(filename);
338 }
339 }
340 #define have_zterp_os_autosave_name
341
342 std::unique_ptr<std::string> zterp_os_aux_file(const std::string &filename_)
343 {
344 std::string filename = filename_;
345 for (auto &c : filename) {
346 if (c == '/') {
347 c = '_';
348 }
349 }
350
351 return data_file("auxiliary/"s + unique_name() + "/" + filename);
352 }
353 #define have_zterp_os_aux_file
354
355 static pid_t launch_editor(const std::string &filename)
356 {
357 // A list of possible text editors. The user can specify a text
358 // editor using the config file. If he doesn’t, or if it doesn’t
359 // exist, keep trying various possible editors in hopes that one
360 // exists and works. This really should use XDG to query the user’s
361 // preferred text editor, but for now, it doesn’t.
362 const std::vector<const char *> editors = {
363 #if defined(__HAIKU__)
364 "StyledEdit",
365 #elif defined(__serenity__)
366 "TextEditor",
367 #elif defined(__APPLE__)
368 "open -Wnt",
369 #else
370 "kwrite",
371 "kate",
372 "nedit-ng",
373 "nedit",
374 "gedit",
375 #endif
376 };
377
378 auto edit_with = [&filename](const std::string &editor) {
379 std::istringstream ss(editor);
380 std::vector<std::string> args;
381 std::string token;
382
383 while (ss >> std::quoted(token)) {
384 args.push_back(token);
385 }
386 args.push_back(filename);
387
388 std::vector<char *> c_args;
389 for (const auto &arg : args) {
390 c_args.push_back(const_cast<char *>(arg.c_str()));
391 }
392 c_args.push_back(nullptr);
393
394 pid_t pid;
395 extern char **environ;
396 int rval = posix_spawnp(&pid, c_args[0], nullptr, nullptr, c_args.data(), environ);
397 if (rval != 0) {
398 throw rval;
399 }
400
401 return pid;
402 };
403
404 // Try the user’s editor explicitly instead of prepending it to the
405 // list of defaults so a diagnostic message can easily be displayed.
406 if (options.editor != nullptr) {
407 try {
408 return edit_with(*options.editor);
409 } catch (int err) {
410 std::cerr << "Unable to execute " << *options.editor << ": " << std::strerror(err) << std::endl;
411 }
412 }
413
414 for (const auto &editor : editors) {
415 try {
416 return edit_with(editor);
417 } catch (int) {
418 }
419 }
420
421 return 0;
422 }
423
424 void zterp_os_edit_file(const std::string &filename)
425 {
426 pid_t pid = launch_editor(filename);
427 if (pid == 0) {
428 throw std::runtime_error("unable to find a text editor");
429 }
430
431 int status;
432
433 #ifdef ZTERP_GLK_TICK
434 while (waitpid(pid, &status, WNOHANG) != pid) {
435 std::this_thread::sleep_for(10ms);
436 glk_tick();
437 }
438 #else
439 waitpid(pid, &status, 0);
440 #endif
441
442 if (!WIFEXITED(status)) {
443 throw std::runtime_error("editor process terminated abnormally");
444 }
445
446 #ifndef __APPLE__
447 if (WEXITSTATUS(status) == 127) {
448 throw std::runtime_error("unable to find a text editor");
449 }
450 #endif
451
452 if (WEXITSTATUS(status) != 0) {
453 throw std::runtime_error("editor had exit status " + std::to_string(WEXITSTATUS(status)));
454 }
455 }
456 #define have_zterp_os_edit_file
457
458 class TempFile {
459 public:
460 explicit TempFile(const std::string &tmpl)
461 {
462 auto tmpdir = zterp_getenv("TMPDIR");
463 if (tmpdir == nullptr) {
464 tmpdir = std::make_unique<std::string>("/tmp");
465 }
466
467 m_path = *tmpdir + "/" + tmpl + ".XXXXXX";
468
469 m_fd = mkstemp(&m_path[0]);
470 if (m_fd == -1) {
471 throw std::runtime_error("unable to create temporary file");
472 }
473 }
474
475 TempFile(const TempFile &) = delete;
476 TempFile &operator=(const TempFile &) = delete;
477
478 void write(const std::vector<char> &data) const {
479 size_t bytes = 0;
480 while (bytes < data.size()) {
481 ssize_t n = ::write(m_fd, &data[bytes], data.size() - bytes);
482 if (n == -1) {
483 throw std::runtime_error("unable to write to temporary file");
484 }
485 bytes += n;
486 }
487 }
488
489 ~TempFile() {
490 close(m_fd);
491 std::remove(m_path.c_str());
492 }
493
494 const std::string &path() const {
495 return m_path;
496 }
497
498 private:
499 std::string m_path;
500 int m_fd;
501 };
502
503 std::vector<char> zterp_os_edit_notes(const std::vector<char> &notes)
504 {
505 TempFile tempfile("bocfel.notes");
506
507 tempfile.write(notes);
508 zterp_os_edit_file(tempfile.path());
509
510 return read_file(tempfile.path());
511 }
512 #define have_zterp_os_edit_notes
513
514 void zterp_os_show_transcript(const std::vector<char> &transcript)
515 {
516 TempFile tempfile("bocfel.transcript");
517
518 tempfile.write(transcript);
519 zterp_os_edit_file(tempfile.path());
520 }
521 #define have_zterp_os_show_transcript
522
523 #ifndef ZTERP_GLK
524
525 #ifndef ZTERP_NO_CURSES
526 #include <curses.h>
527 #include <sys/ioctl.h>
528 #include <term.h>
529 #ifdef TIOCGWINSZ
530 std::pair<unsigned int, unsigned int> zterp_os_get_screen_size()
531 {
532 struct winsize winsize;
533
534 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) == 0) {
535 return {winsize.ws_col, winsize.ws_row};
536 }
537
538 return {0, 0};
539 }
540 #define have_zterp_os_get_screen_size
541 #endif
542
543 static const char *capstr(const char *cap)
544 {
545 char *ret = tigetstr(const_cast<char *>(cap));
546 if (ret == nullptr || ret == reinterpret_cast<char *>(-1)) {
547 return nullptr;
548 }
549
550 return ret;
551 }
552
553 static const char *ital = nullptr, *rev = nullptr, *bold = nullptr, *none = nullptr;
554 static const char *fg_string = nullptr, *bg_string = nullptr;
555 static bool have_colors = false;
556 static bool have_24bit_rgb = false;
557 void zterp_os_init_term()
558 {
559 if (setupterm(nullptr, STDOUT_FILENO, nullptr) != OK) {
560 return;
561 }
562
563 // prefer italics over underline for emphasized text
564 ital = capstr("sitm");
565 if (ital == nullptr) {
566 ital = capstr("smul");
567 }
568 rev = capstr("rev");
569 bold = capstr("bold");
570 none = capstr("sgr0");
571
572 fg_string = capstr("setaf");
573 bg_string = capstr("setab");
574
575 have_colors = none != nullptr && fg_string != nullptr && bg_string != nullptr;
576
577 have_24bit_rgb = tigetflag(const_cast<char *>("RGB")) > 0 && tigetnum(const_cast<char *>("colors")) == 1U << 24;
578 }
579 #define have_zterp_os_init_term
580
581 bool zterp_os_have_style(StyleBit style)
582 {
583 if (none == nullptr) {
584 return false;
585 }
586
587 switch (style) {
588 case STYLE_ITALIC:
589 return ital != nullptr;
590 case STYLE_REVERSE:
591 return rev != nullptr;
592 case STYLE_BOLD:
593 return bold != nullptr;
594 default:
595 return false;
596 }
597 }
598 #define have_zterp_os_have_style
599
600 bool zterp_os_have_colors()
601 {
602 return have_colors;
603 }
604 #define have_zterp_os_have_colors
605
606 static void set_color(const char *string, const Color &color)
607 {
608 // Cast the first argument to tparm() below to char*, for unfortunate
609 // historical purposes: X/Open defines tparm() as taking a char*, and
610 // while most modern Unixes have a Curses implementation that takes
611 // const char*, at least macOS still takes a char*. No reasonable Curses
612 // implementation will modify the argument, so it’s safe enough to just
613 // cast here.
614
615 switch (color.mode) {
616 case Color::Mode::ANSI:
617 if (color.value >= 2 && color.value <= 9) {
618 putp(tparm(const_cast<char *>(string), color.value - 2, 0, 0, 0, 0, 0, 0, 0, 0));
619 }
620 break;
621 case Color::Mode::True:
622 if (have_24bit_rgb) {
623 // Presumably for compatibility, even on terminals capable of
624 // direct color, the values 0 to 7 are still treated as if on a
625 // 16-color terminal (1 is red, 2 is green, and so on). Any
626 // other value is treated as a 24-bit color in the expected
627 // fashion. If a value between 1 and 7 is chosen, round to 0
628 // (which is still black) or 8.
629 uint16_t transformed = color.value < 4 ? 0 :
630 color.value < 8 ? 8 :
631 color.value;
632 putp(tparm(const_cast<char *>(string), screen_convert_color(transformed), 0, 0, 0, 0, 0, 0, 0, 0));
633 }
634 break;
635 }
636 }
637
638 void zterp_os_set_style(const Style &style, const Color &fg, const Color &bg)
639 {
640 // If the terminal cannot be reset, nothing can be used.
641 if (none == nullptr) {
642 return;
643 }
644
645 putp(none);
646
647 if (style.test(STYLE_ITALIC) && ital != nullptr) {
648 putp(ital);
649 }
650 if (style.test(STYLE_REVERSE) && rev != nullptr) {
651 putp(rev);
652 }
653 if (style.test(STYLE_BOLD) && bold != nullptr) {
654 putp(bold);
655 }
656
657 if (have_colors) {
658 set_color(fg_string, fg);
659 set_color(bg_string, bg);
660 }
661 }
662 #define have_zterp_os_set_style
663 #endif
664
665 #endif
666
667 // ╔══════════════════════════════════════════════════════════════════════════════╗
668 // ║ Windows functions ║
669 // ╚══════════════════════════════════════════════════════════════════════════════╝
670 #elif defined(ZTERP_OS_WIN32)
671 #include <direct.h>
672 #include <sys/stat.h>
673 #include <sys/types.h>
674 #include <windows.h>
675
676 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
677 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
678 #endif
679
680 #ifdef _MSC_VER
681 #pragma comment(lib, "shell32.lib")
682 #endif
683
684 long zterp_os_filesize(std::FILE *fp)
685 {
686 struct _stat st;
687 int fd = _fileno(fp);
688
689 if (fd == -1 || _fstat(_fileno(fp), &st) == -1 || (st.st_mode & _S_IFREG) == 0 || st.st_size > LONG_MAX) {
690 return -1;
691 }
692
693 return st.st_size;
694 }
695 #define have_zterp_os_filesize
696
697 static bool mkdir_p(const std::string &filename)
698 {
699 char drive[MAX_PATH], path[MAX_PATH];
700
701 if (_splitpath_s(filename.c_str(), drive, sizeof drive, path, sizeof path, nullptr, 0, nullptr, 0) != 0) {
702 return false;
703 }
704
705 for (char *p = path; *p != 0; p++) {
706 if ((*p == '/' || *p == '\\') && p != path) {
707 char slash = *p;
708 struct _stat st;
709 *p = 0;
710 std::string component = std::string(drive) + path;
711 _mkdir(component.c_str());
712 if (_stat(component.c_str(), &st) == -1 || (st.st_mode & S_IFDIR) != S_IFDIR) {
713 return false;
714 }
715 *p = slash;
716 }
717 }
718
719 return true;
720 }
721
722 std::unique_ptr<std::string> zterp_os_rcfile(bool create_parent)
723 {
724 auto appdata = zterp_getenv("APPDATA");
725 if (appdata == nullptr) {
726 return nullptr;
727 }
728
729 auto config = std::make_unique<std::string>(*appdata + "\\Bocfel\\bocfel.ini");
730
731 if (create_parent && !mkdir_p(*config)) {
732 return nullptr;
733 }
734
735 return config;
736 }
737 #define have_zterp_os_rcfile
738
739 std::unique_ptr<std::string> unique_name()
740 {
741 char fname[MAX_PATH], ext[MAX_PATH];
742
743 if (_splitpath_s(game_file.c_str(), nullptr, 0, nullptr, 0, fname, sizeof fname, ext, sizeof ext) != 0) {
744 return nullptr;
745 }
746
747 return std::make_unique<std::string>(std::string(fname) + ext + "-" + get_story_id());
748 }
749
750 static std::unique_ptr<std::string> data_file(const std::string &filename)
751 {
752 auto appdata = zterp_getenv("APPDATA");
753 if (appdata == nullptr) {
754 return nullptr;
755 }
756
757 auto name = std::make_unique<std::string>(*appdata + "\\Bocfel\\" + filename);
758
759 if (!mkdir_p(*name)) {
760 return nullptr;
761 }
762
763 return name;
764 }
765
766 std::unique_ptr<std::string> zterp_os_autosave_name()
767 {
768 auto filename = unique_name();
769
770 if (filename == nullptr) {
771 return nullptr;
772 }
773
774 return data_file("autosave\\"s + *filename);
775 }
776 #define have_zterp_os_autosave_name
777
778 static std::string ascii_toupper(std::string s)
779 {
780 for (auto &c : s) {
781 if (c >= 97 && c <= 122) {
782 c -= 32;
783 }
784 }
785
786 return s;
787 }
788
789 std::unique_ptr<std::string> zterp_os_aux_file(const std::string &filename_)
790 {
791 std::string filename = filename_;
792 std::string upper = ascii_toupper(filename);
793
794 static const std::vector<std::string> reserved_names = {
795 "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
796 "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2",
797 "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
798 };
799
800 for (const auto &reserved_name : reserved_names) {
801 if (upper == reserved_name || upper.find(reserved_name + ".") == 0) {
802 return nullptr;
803 }
804 }
805
806 static const std::string invalid_characters = "<>:\"/\\|?*";
807 for (auto &c : filename) {
808 if (invalid_characters.find(c) != std::string::npos) {
809 c = '_';
810 }
811 }
812
813 auto basename = unique_name();
814 if (basename == nullptr) {
815 return nullptr;
816 }
817
818 return data_file("auxiliary\\"s + *basename + "\\" + filename);
819 }
820 #define have_zterp_os_aux_file
821
822 void zterp_os_edit_file(const std::string &filename)
823 {
824 SHELLEXECUTEINFO si;
825 si.cbSize = sizeof(SHELLEXECUTEINFO);
826 si.fMask = SEE_MASK_NOCLOSEPROCESS;
827 si.hwnd = nullptr;
828 si.lpVerb = "open";
829 si.lpFile = filename.c_str();
830 si.lpParameters = nullptr;
831 si.lpDirectory = nullptr;
832 si.nShow = SW_SHOW;
833 si.hInstApp = nullptr;
834
835 if (!ShellExecuteEx(&si)) {
836 throw std::runtime_error("unable to launch text editor");
837 }
838
839 #ifdef ZTERP_GLK_TICK
840 while (WaitForSingleObject(si.hProcess, 10) != 0) {
841 glk_tick();
842 }
843 #else
844 WaitForSingleObject(si.hProcess, INFINITE);
845 #endif
846
847 CloseHandle(si.hProcess);
848 }
849 #define have_zterp_os_edit_file
850
851 class Remover {
852 public:
853 explicit Remover(const std::string &filename) : m_filename(filename) {
854 }
855
856 Remover(const Remover &) = delete;
857 Remover &operator=(const Remover &) = delete;
858
859 Remover(Remover &&other) noexcept : m_filename(std::move(other.m_filename)) {
860 other.m_filename.clear();
861 }
862
863 ~Remover() {
864 if (!m_filename.empty()) {
865 std::remove(m_filename.c_str());
866 }
867 }
868
869 const std::string &filename() {
870 return m_filename;
871 }
872
873 private:
874 std::string m_filename;
875 };
876
877 static std::string generate_random_prefix()
878 {
879 const char charset[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
880 std::default_random_engine rng(std::random_device{}());
881 std::uniform_int_distribution<> dist(0, sizeof(charset) - 2);
882 std::string prefix;
883 for (size_t i = 0; i < 12; ++i) {
884 prefix += charset[dist(rng)];
885 }
886 return prefix;
887 }
888
889 static Remover create_temp_file(const std::string &filename, const std::vector<char> &data)
890 {
891 char tempdir[300];
892
893 DWORD ret = GetTempPath(sizeof tempdir, tempdir);
894 if (ret == 0 || ret > sizeof tempdir) {
895 throw std::runtime_error("unable to find temporary directory");
896 }
897
898 Remover remover(std::string(tempdir) + "\\" + generate_random_prefix() + "-" + filename);
899 try {
900 IO io(&remover.filename(), IO::Mode::WriteOnly, IO::Purpose::Data);
901 io.write_exact(data.data(), data.size());
902 } catch (const IO::OpenError &) {
903 throw std::runtime_error("unable to create temporary file");
904 } catch (const IO::IOError &) {
905 throw std::runtime_error("unable to write to temporary file");
906 }
907
908 return remover;
909 }
910
911 std::vector<char> zterp_os_edit_notes(const std::vector<char> &notes)
912 {
913 auto notes_name = create_temp_file("bocfel_notes.txt", notes);
914
915 zterp_os_edit_file(notes_name.filename());
916
917 return read_file(notes_name.filename());
918 }
919 #define have_zterp_os_edit_notes
920
921 void zterp_os_show_transcript(const std::vector<char> &transcript)
922 {
923 auto transcript_name = create_temp_file("bocfel_transcript.txt", transcript);
924 zterp_os_edit_file(transcript_name.filename());
925 }
926 #define have_zterp_os_show_transcript
927
928 #ifndef ZTERP_GLK
929 std::pair<unsigned int, unsigned int> zterp_os_get_screen_size()
930 {
931 HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
932 if (handle != INVALID_HANDLE_VALUE) {
933 CONSOLE_SCREEN_BUFFER_INFO screen;
934 GetConsoleScreenBufferInfo(handle, &screen);
935
936 return {screen.srWindow.Right - screen.srWindow.Left + 1,
937 screen.srWindow.Bottom - screen.srWindow.Top + 1};
938 }
939
940 return {0, 0};
941 }
942 #define have_zterp_os_get_screen_size
943
944 static bool terminal_processing_enabled = false;
945 void zterp_os_init_term()
946 {
947 HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
948 if (handle != INVALID_HANDLE_VALUE) {
949 DWORD mode;
950 if (GetConsoleMode(handle, &mode)) {
951 mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
952 terminal_processing_enabled = SetConsoleMode(handle, mode);
953 }
954 }
955 }
956 #define have_zterp_os_init_term
957
958 bool zterp_os_have_style(StyleBit)
959 {
960 return terminal_processing_enabled;
961 }
962 #define have_zterp_os_have_style
963
964 bool zterp_os_have_colors()
965 {
966 return terminal_processing_enabled;
967 }
968 #define have_zterp_os_have_colors
969
970 void zterp_os_set_style(const Style &style, const Color &fg, const Color &bg)
971 {
972 if (!terminal_processing_enabled) {
973 return;
974 }
975
976 ansi_set_style(style, fg, bg);
977 }
978 #define have_zterp_os_set_style
979 #endif
980
981 // ╔══════════════════════════════════════════════════════════════════════════════╗
982 // ║ DOS functions ║
983 // ╚══════════════════════════════════════════════════════════════════════════════╝
984 #elif defined(ZTERP_OS_DOS)
985 #ifndef ZTERP_GLK
986 // This assumes ANSI.SYS (or equivalent) is loaded.
987 bool zterp_os_have_style(StyleBit)
988 {
989 return true;
990 }
991 #define have_zterp_os_have_style
992
993 bool zterp_os_have_colors()
994 {
995 return true;
996 }
997 #define have_zterp_os_have_colors
998
999 void zterp_os_set_style(const Style &style, const Color &fg, const Color &bg)
1000 {
1001 ansi_set_style(style, fg, bg);
1002 }
1003 #define have_zterp_os_set_style
1004 #endif
1005
1006 #endif
1007
1008 // ╔══════════════════════════════════════════════════════════════════════════════╗
1009 // ║ Generic functions ║
1010 // ╚══════════════════════════════════════════════════════════════════════════════╝
1011 #ifndef have_zterp_os_filesize
1012 long zterp_os_filesize(std::FILE *fp)
1013 {
1014 // Assume fseek() can seek to the end of binary streams.
1015 if (std::fseek(fp, 0, SEEK_END) == -1) {
1016 return -1;
1017 }
1018
1019 return std::ftell(fp);
1020 }
1021 #endif
1022
1023 #ifndef have_zterp_os_edit_file
1024 void zterp_os_edit_file(const std::string &)
1025 {
1026 throw std::runtime_error("editing unimplemented on this platform");
1027 }
1028 #endif
1029
1030 #ifndef have_zterp_os_rcfile
1031 std::unique_ptr<std::string> zterp_os_rcfile(bool)
1032 {
1033 return std::make_unique<std::string>("bocfelrc");
1034 }
1035 #endif
1036
1037 #ifndef have_zterp_os_autosave_name
1038 std::unique_ptr<std::string> zterp_os_autosave_name()
1039 {
1040 return nullptr;
1041 }
1042 #endif
1043
1044 #ifndef have_zterp_os_aux_file
1045
1046 #ifdef ZTERP_GLK_UNIX
1047 extern "C" {
1048 #include <glkstart.h>
1049 }
1050 #endif
1051
1052 std::unique_ptr<std::string> zterp_os_aux_file(const std::string &filename)
1053 {
1054 #if defined(ZTERP_GLK_UNIX) && defined(GLKUNIX_FILEREF_GET_FILENAME)
1055 frefid_t fref = glk_fileref_create_by_name(fileusage_Data | fileusage_BinaryMode, const_cast<char *>(filename.c_str()), 0);
1056 if (fref != nullptr) {
1057 auto result = std::make_unique<std::string>(glkunix_fileref_get_filename(fref));
1058 glk_fileref_destroy(fref);
1059 return result;
1060 }
1061 #endif
1062 return nullptr;
1063 }
1064 #endif
1065
1066 #ifndef have_zterp_os_edit_notes
1067 std::vector<char> zterp_os_edit_notes(const std::vector<char> &)
1068 {
1069 throw std::runtime_error("notes unimplemented on this platform");
1070 }
1071 #endif
1072
1073 #ifndef have_zterp_os_show_transcript
1074 void zterp_os_show_transcript(const std::vector<char> &transcript)
1075 {
1076 throw std::runtime_error("transcript display unimplemented on this platform");
1077 }
1078 #endif
1079
1080 #ifndef ZTERP_GLK
1081 #ifndef have_zterp_os_get_screen_size
1082 std::pair<unsigned int, unsigned int> zterp_os_get_screen_size()
1083 {
1084 return {0, 0};
1085 }
1086 #endif
1087
1088 #ifndef have_zterp_os_init_term
1089 void zterp_os_init_term()
1090 {
1091 }
1092 #endif
1093
1094 #ifndef have_zterp_os_have_style
1095 bool zterp_os_have_style(StyleBit)
1096 {
1097 return false;
1098 }
1099 #endif
1100
1101 #ifndef have_zterp_os_have_colors
1102 bool zterp_os_have_colors()
1103 {
1104 return false;
1105 }
1106 #endif
1107
1108 #ifndef have_zterp_os_set_style
1109 void zterp_os_set_style(const Style &, const Color &, const Color &)
1110 {
1111 }
1112 #endif
1113 #endif