Debian Codegraph @

garglk/cheapglk/cgfref.cpp

raw symbols SCIP
1 /******************************************************************************
2 * *
3 * Copyright (C) 2006-2009 by Tor Andersson, Andrew Plotkin. *
4 * *
5 * This file is part of Gargoyle. *
6 * *
7 * Gargoyle is free software; you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation; either version 2 of the License, or *
10 * (at your option) any later version. *
11 * *
12 * Gargoyle is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have received a copy of the GNU General Public License *
18 * along with Gargoyle; if not, write to the Free Software *
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA *
20 * *
21 *****************************************************************************/
22
23 /* cgfref.c: Fileref functions for Glk API.
24 Designed by Andrew Plotkin <[email protected]>
25 http://www.eblong.com/zarf/glk/index.html
26
27 Portions of this file are copyright 1998-2004 by Andrew Plotkin.
28 It is distributed under the MIT license; see the "LICENSE" file.
29 */
30
31 #include <algorithm>
32 #include <string>
33
34 #if __cplusplus >= 201703L
35 #include <filesystem>
36 #endif
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h> /* for unlink() */
42 #include <sys/stat.h> /* for stat() */
43
44 #ifdef _WIN32
45 #define _CRT_INTERNAL_NONSTDC_NAMES 1
46 #define WIN32_LEAN_AND_MEAN
47 #ifndef NOMINMAX
48 #define NOMINMAX
49 #endif
50 #include <windows.h>
51 #endif
52 #if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
53 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
54 #endif
55 #if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
56 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
57 #endif
58
59 #include "glk.h"
60 #include "garglk.h"
61 #include "glkstart.h"
62
63 #include "format.h"
64 #include "optional.hpp"
65
66 #ifdef GARGLK
67 std::string gli_workdir = ".";
68 nonstd::optional<std::string> gli_workfile;
69
70 const char *garglk_fileref_get_name(fileref_t *fref)
71 {
72 return fref->filename;
73 }
74 #endif
75
76 /* This file implements filerefs as they work in a stdio system: a
77 fileref contains a pathname, a text/binary flag, and a file
78 type.
79 */
80
81 /* Linked list of all filerefs */
82 static fileref_t *gli_filereflist = NULL;
83
84 #ifndef GARGLK
85 #define BUFLEN (256)
86 static char workingdir[BUFLEN] = ".";
87 #endif
88
89 static fileref_t *gli_new_fileref(const char *filename, glui32 usage, glui32 rock)
90 {
91 fileref_t *fref = (fileref_t *)malloc(sizeof(fileref_t));
92 if (!fref)
93 return NULL;
94
95 fref->magicnum = MAGIC_FILEREF_NUM;
96 fref->rock = rock;
97
98 #ifdef GARGLK
99 fref->filename = new char[strlen(filename) + 1];
100 #else
101 fref->filename = malloc(1 + strlen(filename));
102 #endif
103 strcpy(fref->filename, filename);
104
105 fref->textmode = ((usage & fileusage_TextMode) != 0);
106 fref->filetype = (usage & fileusage_TypeMask);
107
108 fref->prev = NULL;
109 fref->next = gli_filereflist;
110 gli_filereflist = fref;
111 if (fref->next) {
112 fref->next->prev = fref;
113 }
114
115 if (gli_register_obj)
116 fref->disprock = (*gli_register_obj)(fref, gidisp_Class_Fileref);
117 else
118 fref->disprock.ptr = NULL;
119
120 return fref;
121 }
122
123 static void gli_delete_fileref(fileref_t *fref)
124 {
125 fileref_t *prev, *next;
126
127 if (gli_unregister_obj) {
128 (*gli_unregister_obj)(fref, gidisp_Class_Fileref, fref->disprock);
129 fref->disprock.ptr = NULL;
130 }
131
132 fref->magicnum = 0;
133
134 #ifdef GARGLK
135 delete [] fref->filename;
136 fref->filename = nullptr;
137 #else
138 if (fref->filename) {
139 free(fref->filename);
140 fref->filename = NULL;
141 }
142 #endif
143
144 prev = fref->prev;
145 next = fref->next;
146 fref->prev = NULL;
147 fref->next = NULL;
148
149 if (prev)
150 prev->next = next;
151 else
152 gli_filereflist = next;
153 if (next)
154 next->prev = prev;
155
156 free(fref);
157 }
158
159 void glk_fileref_destroy(fileref_t *fref)
160 {
161 if (!fref) {
162 gli_strict_warning("fileref_destroy: invalid ref");
163 return;
164 }
165 gli_delete_fileref(fref);
166 }
167
168 static std::string gli_suffix_for_usage(glui32 usage)
169 {
170 switch (usage & fileusage_TypeMask) {
171 case fileusage_Data:
172 return ".glkdata";
173 case fileusage_SavedGame:
174 return ".glksave";
175 case fileusage_Transcript:
176 case fileusage_InputRecord:
177 return ".txt";
178 default:
179 return "";
180 }
181 }
182
183 frefid_t glk_fileref_create_temp(glui32 usage, glui32 rock)
184 {
185 #ifdef GARGLK
186 fileref_t *fref;
187 #ifdef _WIN32
188 char tempdir[MAX_PATH];
189 char filename[MAX_PATH];
190 GetTempPathA(MAX_PATH, tempdir);
191 if(GetTempPathA(MAX_PATH, tempdir) == 0 ||
192 GetTempFileNameA(tempdir, "glk", 0, filename) == 0)
193 {
194 gli_strict_warning("fileref_create_temp: unable to create temporary file");
195 return NULL;
196 }
197 #else
198 char filename[4096];
199 const char *tempdir = getenv("TMPDIR");
200 int fd;
201 if (tempdir == NULL)
202 tempdir = "/tmp";
203 snprintf(filename, sizeof filename, "%s/garglkXXXXXX", tempdir);
204 fd = mkstemp(filename);
205 if (fd == -1)
206 {
207 gli_strict_warning("fileref_create_temp: unable to create temporary file");
208 return NULL;
209 }
210 close(fd);
211 #endif
212 #else
213 char filename[BUFLEN];
214 fileref_t *fref;
215
216 sprintf(filename, "/tmp/glktempfref-XXXXXX");
217 close(mkstemp(filename));
218
219 #endif
220
221 fref = gli_new_fileref(filename, usage, rock);
222 if (!fref) {
223 gli_strict_warning("fileref_create_temp: unable to create fileref.");
224 return NULL;
225 }
226
227 return fref;
228 }
229
230 frefid_t glk_fileref_create_from_fileref(glui32 usage, frefid_t oldfref,
231 glui32 rock)
232 {
233 fileref_t *fref;
234
235 if (!oldfref) {
236 gli_strict_warning("fileref_create_from_fileref: invalid ref");
237 return NULL;
238 }
239
240 fref = gli_new_fileref(oldfref->filename, usage, rock);
241 if (!fref) {
242 gli_strict_warning("fileref_create_from_fileref: unable to create fileref.");
243 return NULL;
244 }
245
246 return fref;
247 }
248
249 frefid_t glk_fileref_create_by_name(glui32 usage, char *name,
250 glui32 rock)
251 {
252 fileref_t *fref;
253 #ifdef GARGLK
254 /* The new spec recommendations: delete all characters in the
255 string "/\<>:|?*" (including quotes). Truncate at the first
256 period. Change to "null" if there's nothing left. Then append
257 an appropriate suffix: ".glkdata", ".glksave", ".txt".
258 */
259 const std::string to_remove = "\"\\/><:|?*";
260 std::string buf = name;
261
262 buf.erase(
263 std::remove_if(buf.begin(),
264 buf.end(),
265 [&to_remove](const char &c) { return to_remove.find(c) != std::string::npos; }),
266 buf.end());
267
268 auto dot = buf.find('.');
269 if (dot != std::string::npos) {
270 buf = buf.substr(0, dot);
271 }
272
273 if (buf.empty()) {
274 buf = "null";
275 }
276
277 buf = Format("{}/{}{}", gli_workdir, buf, gli_suffix_for_usage(usage));
278
279 fref = gli_new_fileref(buf.c_str(), usage, rock);
280 #else
281 char buf[BUFLEN];
282 char buf2[2*BUFLEN+10];
283 int len;
284 char *cx;
285 char *suffix;
286
287 /* The new spec recommendations: delete all characters in the
288 string "/\<>:|?*" (including quotes). Truncate at the first
289 period. Change to "null" if there's nothing left. Then append
290 an appropriate suffix: ".glkdata", ".glksave", ".txt".
291 */
292
293 for (cx=name, len=0; (*cx && *cx!='.' && len<BUFLEN-1); cx++) {
294 switch (*cx) {
295 case '"':
296 case '\\':
297 case '/':
298 case '>':
299 case '<':
300 case ':':
301 case '|':
302 case '?':
303 case '*':
304 break;
305 default:
306 buf[len++] = *cx;
307 }
308 }
309 buf[len] = '\0';
310
311 if (len == 0) {
312 strcpy(buf, "null");
313 len = strlen(buf);
314 }
315
316 suffix = gli_suffix_for_usage(usage);
317 sprintf(buf2, "%s/%s%s", workingdir, buf, suffix);
318
319 fref = gli_new_fileref(buf2, usage, rock);
320 #endif
321 if (!fref) {
322 gli_strict_warning("fileref_create_by_name: unable to create fileref.");
323 return NULL;
324 }
325
326 return fref;
327 }
328
329 frefid_t glk_fileref_create_by_prompt(glui32 usage, glui32 fmode,
330 glui32 rock)
331 {
332 fileref_t *fref;
333 #ifdef GARGLK
334 std::string buf;
335 FileFilter filter;
336 const char *prompt;
337
338 switch (usage & fileusage_TypeMask) {
339 case fileusage_SavedGame:
340 prompt = "Saved game";
341 filter = FileFilter::Save;
342 break;
343 case fileusage_Transcript:
344 prompt = "Transcript file";
345 filter = FileFilter::Text;
346 break;
347 case fileusage_InputRecord:
348 prompt = "Command record file";
349 filter = FileFilter::Text;
350 break;
351 case fileusage_Data:
352 default:
353 prompt = "Data file";
354 filter = FileFilter::Data;
355 break;
356 }
357
358 if (fmode == filemode_Read) {
359 buf = garglk::winopenfile(prompt, filter);
360 } else {
361 buf = garglk::winsavefile(prompt, filter);
362 }
363
364 if (buf.empty()) {
365 /* The player just hit return. It would be nice to provide a
366 default value, but this implementation is too cheap. */
367 return nullptr;
368 }
369
370 if (fmode == filemode_Read) {
371 /* According to recent spec discussion, we must silently return NULL if no such file exists. */
372 if (access(buf.c_str(), R_OK) == -1) {
373 return nullptr;
374 }
375 }
376
377 fref = gli_new_fileref(buf.c_str(), usage, rock);
378 #else
379 char buf[BUFLEN];
380 char newbuf[2*BUFLEN+10];
381 char *res;
382 char *cx;
383 int val, gotdot;
384 char *prompt, *prompt2;
385
386 switch (usage & fileusage_TypeMask) {
387 case fileusage_SavedGame:
388 prompt = "Enter saved game";
389 break;
390 case fileusage_Transcript:
391 prompt = "Enter transcript file";
392 break;
393 case fileusage_InputRecord:
394 prompt = "Enter command record file";
395 break;
396 case fileusage_Data:
397 default:
398 prompt = "Enter data file";
399 break;
400 }
401
402 if (fmode == filemode_Read)
403 prompt2 = "to load";
404 else
405 prompt2 = "to store";
406
407 printf("%s %s: ", prompt, prompt2);
408
409 res = fgets(buf, BUFLEN-1, stdin);
410 if (!res) {
411 printf("\n<end of input>\n");
412 glk_exit();
413 }
414
415 /* Trim whitespace from end and beginning. */
416
417 val = strlen(buf);
418 while (val
419 && (buf[val-1] == '\n'
420 || buf[val-1] == '\r'
421 || buf[val-1] == ' '))
422 val--;
423 buf[val] = '\0';
424
425 for (cx = buf; *cx == ' '; cx++) { }
426
427 val = strlen(cx);
428 if (!val) {
429 /* The player just hit return. It would be nice to provide a
430 default value, but this implementation is too cheap. */
431 return NULL;
432 }
433
434 if (cx[0] == '/')
435 strcpy(newbuf, cx);
436 else
437 sprintf(newbuf, "%s/%s", workingdir, cx);
438
439 /* If there is no dot-suffix, add a standard one. */
440 val = strlen(newbuf);
441 gotdot = FALSE;
442 while (val && (buf[val-1] != '/')) {
443 if (buf[val-1] == '.') {
444 gotdot = TRUE;
445 break;
446 }
447 val--;
448 }
449 if (!gotdot) {
450 char *suffix = gli_suffix_for_usage(usage);
451 strcat(newbuf, suffix);
452 }
453
454 if (fmode == filemode_Read) {
455 /* According to recent spec discussion, we must silently return NULL if no such file exists. */
456 if (access(newbuf, R_OK)) {
457 return NULL;
458 }
459 }
460
461 fref = gli_new_fileref(newbuf, usage, rock);
462 #endif
463 if (!fref) {
464 gli_strict_warning("fileref_create_by_prompt: unable to create fileref.");
465 return NULL;
466 }
467
468 return fref;
469 }
470
471 frefid_t glk_fileref_iterate(fileref_t *fref, glui32 *rock)
472 {
473 if (!fref) {
474 fref = gli_filereflist;
475 }
476 else {
477 fref = fref->next;
478 }
479
480 if (fref) {
481 if (rock)
482 *rock = fref->rock;
483 return fref;
484 }
485
486 if (rock)
487 *rock = 0;
488 return NULL;
489 }
490
491 glui32 glk_fileref_get_rock(fileref_t *fref)
492 {
493 if (!fref) {
494 gli_strict_warning("fileref_get_rock: invalid ref.");
495 return 0;
496 }
497
498 return fref->rock;
499 }
500
501 glui32 glk_fileref_does_file_exist(fileref_t *fref)
502 {
503 struct stat buf;
504
505 if (!fref) {
506 gli_strict_warning("fileref_does_file_exist: invalid ref");
507 return FALSE;
508 }
509
510 /* This is sort of Unix-specific, but probably any stdio library
511 will implement at least this much of stat(). */
512
513 if (stat(fref->filename, &buf))
514 return 0;
515
516 if (S_ISREG(buf.st_mode))
517 return 1;
518 else
519 return 0;
520 }
521
522 void glk_fileref_delete_file(fileref_t *fref)
523 {
524 if (!fref) {
525 gli_strict_warning("fileref_delete_file: invalid ref");
526 return;
527 }
528
529 /* If you don't have the unlink() function, obviously, change it
530 to whatever file-deletion function you do have. */
531
532 unlink(fref->filename);
533 }
534
535 /* This should only be called from startup code. */
536 void glkunix_set_base_file(char *filename)
537 {
538 #ifdef GARGLK
539 #if __cplusplus >= 201703L
540 auto parent = std::filesystem::path(filename).parent_path();
541 if (parent.empty()) {
542 parent = ".";
543 }
544
545 gli_workdir = parent.string();
546 #else
547 gli_workdir = filename;
548 auto slash = gli_workdir.find_last_of('/');
549 if (slash == std::string::npos) {
550 slash = gli_workdir.find_last_of('\\');
551 }
552
553 if (slash != std::string::npos) {
554 gli_workdir.erase(slash);
555 } else {
556 gli_workdir = ".";
557 }
558 #endif
559
560 gli_workfile = filename;
561 #else
562 int ix;
563
564 for (ix=strlen(filename)-1; ix >= 0; ix--)
565 if (filename[ix] == '/')
566 break;
567
568 if (ix >= 0) {
569 /* There is a slash. */
570 strncpy(workingdir, filename, ix);
571 workingdir[ix] = '\0';
572 ix++;
573 }
574 else {
575 /* No slash, just a filename. */
576 ix = 0;
577 }
578 #endif
579 }
580
581 const char *glkunix_fileref_get_filename(fileref_t *fref)
582 {
583 return fref->filename;
584 }