Debian Codegraph @

terps/tads/tads3/include/file.h

raw symbols SCIP
1 #charset "us-ascii"
2 #pragma once
3
4 /*
5 * Copyright (c) 2001, 2006 Michael J. Roberts
6 *
7 * This file is part of TADS 3.
8 *
9 * This header defines the File intrinsic class.
10 */
11
12
13 /* include our base class definition */
14 #include "systype.h"
15
16 /*
17 * File methods use the CharacterSet and ByteArray intrinsic
18 * classes, so include their headers to make sure they're available to
19 * File users.
20 */
21 #include "charset.h"
22 #include "bytearr.h"
23
24 /* if we're using File objects, we probably want FileName objects as well */
25 #include "filename.h"
26
27 /* ------------------------------------------------------------------------ */
28 /*
29 * File access modes. These are used when calling the file open methods
30 * to specify how the file is to be accessed.
31 */
32
33 /*
34 * Read mode - the file is opened for reading (writing is not allowed).
35 * When opened in this mode, the file must exist, or a
36 * FileNotFoundException is thrown from the open method.
37 */
38 #define FileAccessRead 0x0001
39
40 /*
41 * Write mode - the file is opened for writing (reading is not allowed).
42 * When opened in this mode, if the file doesn't already exist, a new file
43 * is created; if the file does already exist, the existing data in the
44 * file are discarded (i.e., the file is truncated to zero length) on
45 * open.
46 */
47 #define FileAccessWrite 0x0002
48
49 /*
50 * Read/write mode, keeping existing contents - the file is opened for
51 * both reading and writing. If the file does not exist, a new file is
52 * created. If the file does already exist, the existing contents of the
53 * file are kept intact on open.
54 */
55 #define FileAccessReadWriteKeep 0x0003
56
57 /*
58 * Read/write mode, truncating existing contents - the file is opened for
59 * both reading and writing. If the file does not exist, a new file is
60 * created. If the file does already exist, the existing contents of the
61 * file are discarded (i.e., the file is truncated to zero length) on
62 * open.
63 */
64 #define FileAccessReadWriteTrunc 0x0004
65
66
67 /* ------------------------------------------------------------------------ */
68 /*
69 * File mode constants. These are returned from getFileMode() to indicate
70 * the mode used to open the file.
71 */
72
73 /* text mode */
74 #define FileModeText 1
75
76 /* "data" mode */
77 #define FileModeData 2
78
79 /* "raw" mode */
80 #define FileModeRaw 3
81
82
83 /* ------------------------------------------------------------------------ */
84 /*
85 * Special file identifiers. These identifiers can be passed to the 'open'
86 * routines in place of the filename string argument.
87 *
88 * The actual name and location of a special file is determined by the
89 * interpreter. Since games use these internal identifiers rather than the
90 * actual system filenames when accessing special files, different
91 * interpreters can adapt to different local conventions without bothering
92 * the game code with the details. The game code simply refers to the file
93 * it wants using the virtual identifier, and the interpreter takes care of
94 * the rest.
95 *
96 * Note that special files generally bypass the interpreter "file safety"
97 * settings. This is important because it allows the library and games a
98 * degree of controlled access to the file system, even when the file
99 * safety settings wouldn't normally allow similar access for arbitrary
100 * file operations. Even though this special file access can bypass the
101 * file safety level, it doesn't compromise security, because the
102 * interpreter has exclusive control over the names and locations of the
103 * special files - thus a game can only access the particular files that
104 * the interpreter designates as special, and can't use special files to
105 * access arbitrary file system entities.
106 */
107
108 /*
109 * The library defaults file. This is the special file where the library
110 * stores user-controlled start-up default settings.
111 */
112 #define LibraryDefaultsFile 0x0001
113
114 /*
115 * Web UI preference settings file. This is the special file where we
116 * store display style settings for the Web UI.
117 */
118 #define WebUIPrefsFile 0x0002
119
120
121 /* ------------------------------------------------------------------------ */
122 /*
123 * The File intrinsic class provides access to files in the external file
124 * system. This lets you create, read, and write files. The class
125 * supports text files (with translations to and from local character
126 * sets), "data" files (using the special TADS 2 binary file format), and
127 * "raw" files (this mode lets you manipulate files in arbitrary text or
128 * binary formats by giving you direct access to the raw bytes in the
129 * file).
130 */
131 intrinsic class File 'file/030003': Object
132 {
133 /*
134 * File has no constructors. Instead of using 'new', you create a File
135 * object by opening a file through one of the openXxxFile methods:
136 *
137 * f = File.openTextFile()
138 *
139 * All of the open methods have a 'filename' argument giving the name
140 * of the file to open. This is usually a string giving a file name in
141 * the local file system. You can also use a TemporaryFile object in
142 * place of a filename, to open a temporary file.
143 *
144 * All of the open methods throw exceptions if the open fails:
145 *
146 * FileNotFoundException - indicates that the requested file doesn't
147 * exist. This is thrown when the access mode requires an existing
148 * file but the named file does not exist.
149 *
150 * FileCreationException - indicates that the requested file couldn't
151 * be created. This is thrown when the access mode requires creating a
152 * new file but the named file cannot be created.
153 *
154 * FileOpenException - indicates that the requested file couldn't be
155 * opened. This is thrown when the access mode allows either an
156 * existing file to be opened or a new file to be created, but neither
157 * could be accomplished.
158 *
159 * FileSafetyException - the requested access mode isn't allowed for
160 * the given file due to the current file safety level set by the user.
161 * Users can set the file safety level (through command-line switches
162 * or other preference mechanisms which vary by interpreter) to
163 * restrict the types of file operations that applications are allowed
164 * to perform, in order to protect their systems from malicious
165 * programs. This exception indicates that the user has set a safety
166 * level that is too restrictive for the requested operation.
167 */
168
169 /*
170 * Static creator method: open a text file. Returns a File object that
171 * can be used to read or write the file.
172 *
173 * 'filename' is the name of the file to open. This is a string giving
174 * the name of a file in the local file system. It can alternatively
175 * be a TemporaryFile object, to open a temporary file.
176 *
177 * 'access' is the read/write mode, and must be one of FileAccessRead
178 * or FileAccessWrite.
179 *
180 * 'charset' is a CharacterSet object, or can optionally be a string
181 * naming a character set, in which case a CharacterSet object for the
182 * named character set will automatically be created. If 'charset' is
183 * omitted, the local system's default character set for file contents
184 * is used.
185 *
186 * When a file is opened in text mode for reading, each call to
187 * readFile() reads and returns a line of text from the file. When a
188 * file is opened in text mode for writing, any existing file is
189 * discarded and replaced with the new data. Each read and write to a
190 * text file is mapped through the CharacterSet in effect at the time
191 * of the read or write.
192 */
193 static openTextFile(filename, access, charset?);
194
195 /*
196 * Static creator method: open a file in 'data' mode. Returns a File
197 * object that can be used to read or write the file.
198 *
199 * 'filename' is a string giving the file name in the local file
200 * system, or a TemporaryFile object.
201 *
202 * 'access' indicates the desired read/write access and the disposition
203 * of any existing file; any of the FileAccessXxx modes can be used.
204 *
205 * When a file is opened in data mode, you can read and write integers,
206 * strings, and 'true' values to the file, and the values in the file
207 * are marked with their datatype in a private data format. Because
208 * the file uses a tads-specific format, this mode cannot be used to
209 * read files created by other applications or write files for use by
210 * other applications; however, this storage format is convenient for
211 * storing simple data values because the File object takes care of
212 * converting to and from a portable binary format.
213 */
214 static openDataFile(filename, access);
215
216 /*
217 * Static creator method: open a file in 'raw' mode. Returns a File
218 * object that can be used to read or write the file.
219 *
220 * 'filename' is a string giving the name of the file in the local file
221 * system, or a TemporaryFile object.
222 *
223 * 'access' indicates the desired read/write access mode and the
224 * disposition of any existing file; any of the FileAccessXxx modes can
225 * be used.
226 *
227 * When a file is opened in raw mode, only ByteArray values can be read
228 * and written. The File object performs no translations of the bytes
229 * read or written. This mode requires the calling program itself to
230 * perform all data conversions to and from a raw byte format, but the
231 * benefit of this extra work is that this mode can be used to read and
232 * write files in arbitrary data formats, including formats defined by
233 * other applications.
234 */
235 static openRawFile(filename, access);
236
237 /*
238 * get the CharacterSet object the File is currently using; returns
239 * nil for a non-text file
240 */
241 getCharacterSet();
242
243 /*
244 * Set the CharacterSet object the File is to use from now on. This
245 * isn't meaningful except for text files. 'charset' can be a
246 * CharacterSet object, a string giving the name of a character mapping
247 * (in which case a CharacterSet object is automatically created based
248 * on the name), or nil (in which case the local system's default
249 * character set for text files is used).
250 */
251 setCharacterSet(charset);
252
253 /*
254 * Close the file. Flushes any buffered information to the underlying
255 * system file and releases any system resources (such as share locks
256 * or system buffers) associated with the file. After this routine is
257 * called, no further operations on the file can be performed (a
258 * FileClosedException will be thrown if any subsequent operations are
259 * attempted).
260 *
261 * If the game is running in web server mode, the file might be on a
262 * remote storage server. In this case, if the file was opened with
263 * write access, closing it will send the file to the storage server.
264 *
265 * Note that this method can throw an error, so you shouldn't consider
266 * updates to the file to be "safe" until this method returns
267 * successfully. On many systems, writes are buffered in memory, so
268 * closing the file can involve flushing buffers, which can trigger the
269 * same sorts of errors that can happen with ordinary writes (running
270 * out of disk space, physical media defects, etc). In addition, when
271 * the file is on a remote network storage server, closing a file
272 * opened with write access transmits the file to the storage server,
273 * which can encounter network errors.
274 *
275 * You should always explicitly close files when done with them. This
276 * is especially important when writing to a file, because many systems
277 * buffer written data in memory and don't write changes to the
278 * physical media until the file is closed. This means that updates
279 * can be lost if the program crashes (or the computer loses power,
280 * etc) while the file is still open. Closing the file as soon as
281 * you're done with it reduces the chances of this kind of data loss.
282 * It also helps overall system performance to release resources back
283 * to the operating system as soon as you're done with them.
284 *
285 * If you *don't* close a file, though, the system will close it
286 * automatically when the File object becomes unreachable and is
287 * deleted by the garbage collector. It's considered bad form to
288 * depend on this for the reasons above, and it's also problematic
289 * because you won't have any way of finding out if an error should
290 * happen on close.
291 */
292 closeFile();
293
294 /*
295 * Read from the file. Returns a data value that depends on the file
296 * mode, as described below, or nil at end of file.
297 *
298 * If the file is open in text mode, this reads a line of text from the
299 * file and returns a string with the text of the line read. A line of
300 * text is a sequence of characters terminated with a line-ending
301 * sequence, which is a carriage return, line feed, CR/LF pair, LF/CR
302 * pair, or a Unicode line terminator character (0x2028) if the file is
303 * being read with one of the Unicode encodings. If the line read ends
304 * in a line-ending sequence, the returned text will end in a '\n'
305 * character, regardless of which of the possible line-ending sequences
306 * is actually in the file, so the caller need not worry about the
307 * details of the external file's format. Every line read from the
308 * file will end in a '\n' except possibly the last line - if the file
309 * doesn't end with a line-ending sequence, then the last line read
310 * from the file won't end in a '\n' character. All bytes read from
311 * the file will be mapped to characters through the CharacterSet
312 * object currently in effect in the file, so the returned string will
313 * always be a standard Unicode string, regardless of the byte encoding
314 * of the file.
315 *
316 * If the file is open in 'data' mode, this reads one data element
317 * using the private tads-specific data format. The result is a value
318 * of one of the types writable with writeFile() in 'data' mode. In
319 * order to read a 'data' file, the file must have been previously
320 * written in 'data' mode.
321 */
322 readFile();
323
324 /*
325 * Write to the file. Writes the given value to the file in a format
326 * that depends on the file mode, as described below. No return
327 * value; if an error occurs writing the data, this throws a
328 * FileIOException.
329 *
330 * If the file is open in text mode, this writes text to the file,
331 * converting the given value to a string if necessary (and throwing
332 * an error if such a conversion isn't possible), and translating the
333 * string to be written to bytes by mapping the string through the
334 * CharacterSet object currently in effect for the file. Note that no
335 * line-ending characters are automatically added to the output, so if
336 * the caller wishes to write line terminators, it should simply
337 * include a '\n' character at the end of each line.
338 *
339 * If the file is open in 'data' mode, this writes the value, which
340 * must be a string, integer, enum, or 'true' value, in a private
341 * tads-specific data format that can later be read using the same
342 * format. The values are converted to the private binary format,
343 * which is portable across platforms: a file written in 'data' mode
344 * on one machine can be copied (byte-for-byte) to another machine,
345 * even one that uses different hardware and a different operating
346 * system, and read back in 'data' mode on the new machine to yield
347 * the original values written.
348 */
349 writeFile(val);
350
351 /*
352 * Read bytes from the file into the given ByteArray object. This can
353 * only be used for a file opened in 'raw' mode. If 'start' and 'cnt'
354 * are given, they give the starting index in the byte array at which
355 * the bytes read are to be stored, and the number of bytes to read,
356 * respectively; if these are omitted, one byte is read from the file
357 * for each byte in the byte array.
358 *
359 * Returns the number of bytes actually read into the byte array,
360 * which will be less than or equal to the number requested. If the
361 * number read is less than the number requested, it means that the
362 * end of the file was encountered, and only the returned number of
363 * bytes were available.
364 */
365 readBytes(byteArr, start?, cnt?);
366
367 /*
368 * Write bytes from the given source object into the file. This can
369 * only be used for a file opened in 'raw' mode.
370 *
371 * The source object must be one of the following object types:
372 *
373 * File: the contents of the given source file are copied to 'self'.
374 * 'start' is the starting seek position in the source file; if
375 * omitted, the current seek position is the default. 'cnt' is the
376 * number of bytes to copy; if omitted, the file is copied from the
377 * given starting position to the end of the file.
378 *
379 * ByteArray: the bytes of the byte array are copied to the file.
380 * 'start' is the starting index in the byte array; if omitted, the
381 * default is the first byte (index 1). 'cnt' is the number of bytes
382 * to copy; if omitted, bytes are copied from the start position to the
383 * end of the array.
384 *
385 * No return value; if an error occurs writing the data, a
386 * FileIOException is thrown.
387 */
388 writeBytes(source, start?, cnt?);
389
390 /*
391 * Get the current read/write position in the file. Returns the byte
392 * offset in the file of the next byte to be read or written. Note
393 * that this value is an offset, so 0 is the offset of the first byte
394 * in the file.
395 */
396 getPos();
397
398 /*
399 * Set the current read/write position in the file. 'pos' is a byte
400 * offset in the file; 0 is the offset of the first byte.
401 *
402 * For files in 'text' and 'data' modes, a caller should NEVER set the
403 * file position to any value other than a value previously returned
404 * by getPos(), because other positions might violate the format
405 * constraints. For example, if you move the file position to a byte
406 * in the middle of a line-ending sequence in a text file, subsequent
407 * reading from the file might misinterpret the sequence as something
408 * other than a line ending, or as an extra line ending. If you move
409 * the position in a 'data' file to a byte in the middle of an integer
410 * value, reading from the file would misinterpret as a data type tag
411 * a byte that is part of the integer value instead. So it is never
412 * meaningful or safe to set an arbitrary byte offset in these file
413 * formats; only values known to be valid by virtue of having been
414 * returned from getPos() can be used here in these modes.
415 */
416 setPos(pos);
417
418 /*
419 * Set the current read/write position to the end of the file. This
420 * can be used, for example, to open a 'data' mode file for
421 * read/write/keep access (keeping the contents of an existing file)
422 * and then adding more data after all of the existing data in the
423 * file.
424 */
425 setPosEnd();
426
427 /*
428 * Static creator method: open a resource in 'text' mode. This acts
429 * like openTextFile(), but rather than opening an ordinary file, this
430 * method opens a resource. Resources differ from ordinary files in
431 * two important respects. First, a resource is named with a
432 * URL-style path rather than a local file system name. Second, a
433 * resource can be embedded in the program's executable (.t3) file, or
434 * can be embedded in an external resource bundle (.3r0, etc) file.
435 *
436 * Resources are read-only, so the access mode is implicitly
437 * FileAccessRead.
438 */
439 static openTextResource(resname, charset?);
440
441 /*
442 * Static creator method: open a resource in 'raw' mode. This acts
443 * like openRawFile(), but opens a resource rather than an ordinary
444 * file.
445 *
446 * Resources are read-only, so the access mode is implicitly
447 * FileAccessRead.
448 */
449 static openRawResource(resname);
450
451 /* get the size in bytes of the file */
452 getFileSize();
453
454 /*
455 * Get the file mode. This returns one of the FileModeXxx constants,
456 * indicating the mode used to open the file (text, data, raw).
457 */
458 getFileMode();
459
460 /*
461 * Extract the file's "root name" from the given filename string. This
462 * returns a new string giving the portion of the filename excluding
463 * any directory path. This parses the filename according to the local
464 * file system's syntax rules. For example, given the filename
465 * 'a/b/c.txt', if you're running on a Unix or Linux machine, the
466 * function returns 'c.txt'.
467 *
468 * Note that this function doesn't attempt to open the file or check
469 * for its existence or validity; it simply parses the name according
470 * to the local syntax conventions.
471 *
472 * (It's recommended that you use the newer FileName.getBaseName() in
473 * place of this function.)
474 */
475 static getRootName(filename);
476
477 /*
478 * Delete the file with the given name. This erases the file from
479 * disk. 'filename' is a string giving the name of the file to delete,
480 * or one of the special file identifier values.
481 *
482 * The file can only be deleted if the file safety level would allow
483 * you to write to the file; if not, a file safety exception is thrown.
484 *
485 * (It's recommended that you use the newer FileName.deleteFile() in
486 * place of this function.)
487 */
488 static deleteFile(filename);
489
490 /*
491 * Change the file mode. 'mode' is a FileModeXxx value giving the
492 * desired new file mode.
493 *
494 * If the mode is FileModeText, 'charset' is the character set mapping
495 * to use for the file; this can be given as a CharacterSet object, or
496 * as a string giving the name of a character set. If the value is nil
497 * or the argument is omitted, the local system's default character for
498 * file contents is used. The 'charset' parameter is ignored for other
499 * modes.
500 */
501 setFileMode(mode, charset?);
502
503 /*
504 * Pack the given data values into bytes according to a format
505 * definition string, and write the packed bytes to the file. This
506 * function is designed to simplify writing files that use structured
507 * binary formats defined by third parties, such as JPEG or PDF. The
508 * function translates native TADS data values into selected binary
509 * formats, and writes the resulting bytes to the file, all in a single
510 * operation.
511 *
512 * 'format' is the format string, and the remaining arguments are the
513 * values to be packed.
514 *
515 * Returns the number of bytes written to the file. (More precisely,
516 * returns the final file position as a byte offset from the starting
517 * file pointer. If a positioning code like @ or X is used in the
518 * string, it's possible that more bytes were actually written.)
519 *
520 * See Byte Packing in the System Manual for details.
521 */
522 packBytes(format, ...);
523
524 /*
525 * Read bytes and unpack into a data structure, according to the format
526 * description string 'desc'.
527 *
528 * 'format' is the format string. The function reads bytes from the
529 * current location in the file and translates them into data values
530 * according to the format string, returning a list of the unpacked
531 * values.
532 *
533 * Refer to Byte Packing in the System Manual for details.
534 */
535 unpackBytes(format);
536
537 /*
538 * Calculate the 256-bit SHA-2 hash of bytes read from the file,
539 * starting at the current seek location and continuing for the given
540 * number of bytes. If the length is omitted, the whole rest of the
541 * file is hashed. This has the side effect of reading the given
542 * number of bytes from the file, so it leaves the seek position set to
543 * the next byte after the bytes hashed.
544 *
545 * Returns a string of 64 hex digits giving the hash result.
546 *
547 * This can only be used on files opened in raw mode with read access.
548 */
549 sha256(length?);
550
551 /*
552 * Calculate the MD5 digest of bytes read from the file, starting at
553 * the current seek location and continuing for the given number of
554 * bytes. If the length is omitted, the whole rest of the file is
555 * digested. This has the side effect of reading the given number of
556 * bytes from the file, so it leaves the seek position set to the next
557 * byte after the bytes digested.
558 *
559 * Returns a string of 32 hex digits giving the digest result.
560 *
561 * This can only be used on files opened in raw mode with read access.
562 */
563 digestMD5(length?);
564 }
565
566
567 /* ------------------------------------------------------------------------ */
568 /*
569 * The TemporaryFile intrinsic class represents a temporary file name in
570 * the local file system. Temporary files can be used to store data too
571 * large to conveniently store in memory.
572 *
573 * You create a temporary file with 'new TemporaryFile()'. This
574 * automatically assigns the object a unique filename in the local file
575 * system, typically in a system directory reserved for temporary files.
576 * The local file can then be opened, read, written, and otherwise
577 * manipulated via the File class, just like any other file. Simply pass
578 * the TemporaryFile object in place of a filename to the File.openXxx
579 * methods.
580 *
581 * The underlying file system file will be deleted automatically when the
582 * TemporaryFile object is collected by the garbage collector (or when the
583 * program terminates). This means that you don't have to worry about
584 * cleaning up the file system space used by the file; it'll be released
585 * automatically when the file is no longer needed. However, you can call
586 * the deleteFile() method to explicitly release the file when you're done
587 * with it, if you want to ensure that the resource is returned to the
588 * operating system as soon as possible.
589 *
590 * TemporaryFile objects are inherently transient - they're only valid for
591 * the current session on the current local system, so they can't be saved
592 * or restored.
593 *
594 * Temporary files are exempt from the file safety level settings, because
595 * the inherent restrictions on temporary files provide the same system
596 * protections that the safety level settings provide for ordinary files.
597 */
598 intrinsic class TemporaryFile 'tempfile/030000': Object
599 {
600 /*
601 * Get the name of the underlying file system object. This returns a
602 * string with the local filename. This is mostly for debugging
603 * purposes or for displaying to the user. You can't necessarily use
604 * this filename in a call to File.openXxxFile, because the file path
605 * is usually in a system directory reserved for temporary files, and
606 * the file safety level settings often prohibit opening files outside
607 * of the program's own home directory. To open the temp file, you
608 * should always pass the TemporaryFile object itself in place of the
609 * filename.
610 */
611 getFilename();
612
613 /*
614 * Delete the underlying file system object. This deletes the
615 * temporary file and marks the TemporaryFile object as invalid. After
616 * calling this, you can no longer open the file via the
617 * File.openXxxFile methods.
618 *
619 * This method allows you to release the underlying file system
620 * resources as soon as you're done with the temp file. It's never
621 * necessary to do this. TADS automatically deletes the underlying
622 * file system resources when the TemporaryFile object is deleted by
623 * the garbage collector (or when the program terminates), so the
624 * operating system file will be deleted eventually whether you call
625 * this method or not. The point of this method is to let you tell the
626 * system *exactly* when you're done with the file, so that the
627 * resources can be released earlier than if we waited for garbage
628 * collection to take care of it. This should make little difference
629 * in most situations, but in a program that will run for a long time
630 * and use a lot of temporary files, it might be worthwhile to release
631 * resources manually as soon as possible.
632 */
633 deleteFile();
634 }
635
636
637 /* ------------------------------------------------------------------------ */
638 /*
639 * The filename passed to the File "open" methods, as well as to most
640 * system functions that accept filename arguments, can be a TadsObject
641 * object in lieu of a string. Such an object must implement the following
642 * methods:
643 *
644 * getFilename() - return the actual filename to use, which must be a
645 * string or TemporaryFile object.
646 *
647 * closeFile() - optional. This is called just after the underlying system
648 * file is closed, allowing the program to perform any desired
649 * post-processing on the file.
650 */
651 export getFilename 'FileSpec.getFilename';
652 export closeFile 'FileSpec.closeFile';
653