Debian Codegraph @

terps/bocfel/glkautosave.cpp

raw symbols SCIP
1 // Copyright 2025 Andrew Plotkin.
2 //
3 // SPDX-License-Identifier: MIT
4
5 #include <string>
6
7 #include "glkautosave.h"
8 #include "osdep.h"
9 #include "screen.h"
10
11 #ifdef ZTERP_GLK_UNIX
12 extern "C" {
13 #include <glk.h>
14 #include <gi_blorb.h>
15 #include <glkstart.h>
16 }
17 #endif
18
19 #ifdef GLKUNIX_AUTOSAVE_FEATURES
20 static strid_t open_autosave(bool writemode)
21 {
22 auto autosavepath = zterp_os_autosave_name();
23 if (autosavepath == nullptr) {
24 return nullptr;
25 }
26 std::string pathname = *autosavepath + ".json";
27
28 return glkunix_stream_open_pathname_gen(const_cast<char *>(pathname.c_str()), writemode, FALSE, 1);
29 }
30 #endif
31
32 bool glkautosave_library_autosave()
33 {
34 #ifdef GLKUNIX_AUTOSAVE_FEATURES
35 strid_t jsavefile = open_autosave(true);
36 if (jsavefile == nullptr) {
37 return false;
38 }
39
40 glkunix_save_library_state(jsavefile, jsavefile, nullptr, nullptr);
41
42 glk_stream_close(jsavefile, nullptr);
43 jsavefile = nullptr;
44 #endif // GLKUNIX_AUTOSAVE_FEATURES
45
46 return true;
47 }
48
49 bool glkautosave_library_autorestore()
50 {
51 #ifdef GLKUNIX_AUTOSAVE_FEATURES
52 strid_t jsavefile = open_autosave(false);
53 if (jsavefile == nullptr) {
54 return false;
55 }
56
57 glkunix_library_state_t library_state = glkunix_load_library_state(jsavefile, nullptr, nullptr);
58
59 glk_stream_close(jsavefile, nullptr);
60 jsavefile = nullptr;
61
62 if (library_state == nullptr) {
63 return false;
64 }
65
66 // The interpreter has already opened its windows. This will close
67 // them and open new ones, which is clunky but that’s the sequence
68 // we’re working with.
69 if (!glkunix_update_from_library_state(library_state)) {
70 glkunix_library_state_free(library_state);
71 return false;
72 }
73
74 // We’re done with the library state object.
75 glkunix_library_state_free(library_state);
76 library_state = nullptr;
77
78 // Recover the blorb stream ID, if we have one open.
79 if (giblorb_get_resource_map() != nullptr) {
80 // It’s inefficient to throw away the blorb chunk map, which we
81 // just loaded, and then recreate it. Oh well.
82 if (giblorb_unset_resource_map() != giblorb_err_None) {
83 return false;
84 }
85
86 glui32 rock = 0;
87 for (auto str = glk_stream_iterate(nullptr, &rock); str != nullptr; str = glk_stream_iterate(str, &rock)) {
88 if (rock == static_cast<glui32>(StreamRock::BlorbStream)) {
89 if (giblorb_set_resource_map(str) != giblorb_err_None) {
90 return false;
91 }
92 break;
93 }
94 }
95 }
96
97 // Let the interpreter recover window IDs.
98 screen_recover_glk_windows();
99 screen_recover_glk_streams();
100 #endif // GLKUNIX_AUTOSAVE_FEATURES
101
102 return true;
103 }