Debian Codegraph @

terps/tads/tads3/lib/adv3/settings.t

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2000, 2006 Michael J. Roberts. All Rights Reserved.
5 *
6 * TADS 3 Library - settings file management
7 *
8 * This is a framework that the library uses to keep track of certain
9 * preference settings - things like the NOTIFY, FOOTNOTES, and EXITS
10 * settings.
11 *
12 * The point of this framework is "global" settings - settings that apply
13 * not just to a particular game, but to all games that have a particular
14 * feature. Things like NOTIFY, FOOTNOTES, and some other such features
15 * are part of the standard library, so they tend to be available in most
16 * games. Furthermore, they tend to work more or less the same way in
17 * most games. As a result, a given player will probably prefer to set
18 * the options a particular way for most or all games. If a player
19 * doesn't like score notification, she'll probably dislike it across the
20 * board, not just in certain games.
21 *
22 * This module provides the internal, programmatic core for managing
23 * global preferences. There's no UI in this part of the implementation;
24 * the adv3 library layers the UI on top via the settingsUI object, but
25 * other alternative UIs could be built using the API provided here.
26 *
27 * The framework is extensible - there's an easy, structured way for
28 * library extensions and games to add their own configuration variables
29 * that will be automatically managed by the framework. All you have to
30 * do to create a new configuration variable is to create a SettingsItem
31 * object to represent it. Once you've created the object, the library
32 * will automatically find it and manage it for you.
33 *
34 * This module is designed to be separable from the adv3 library, so that
35 * alternative libraries or stand-alone (non-library-based) games can
36 * reuse it. This file has no dependencies on anything in adv3 (at
37 * least, it shouldn't).
38 */
39
40 #include <tads.h>
41 #include <file.h>
42
43
44 /* ------------------------------------------------------------------------ */
45 /*
46 * A settings item. This encapsulates a single setting variable. When
47 * we're saving or restoring default settings, we'll simply loop over all
48 * objects of this class to get or set the current settings.
49 *
50 * Note that we don't make any assumptions in this base class about the
51 * type of the value associated with this setting, how it's stored, or
52 * how it's represented in the external configuration file. This means
53 * that each subclass has to provide the property or properties that
54 * store the item's value, and must also define the methods that operate
55 * on the value.
56 *
57 * If you want to force a particular default setting for a particular
58 * preference item, overriding the setting stored in the global
59 * preferences file, you can override that SettingsItem's
60 * settingFromText() method. This is the method that interprets the
61 * information in the preferences file, so if you want to ignore the
62 * preferences file setting, override this method to set the hard-coded
63 * value of your choosing.
64 */
65 class SettingsItem: object
66 /*
67 * The setting's identifier string. This is the ID of the setting as
68 * it appears in the external configuration file.
69 *
70 * The ID should be chosen to ensure uniqueness. To reduce the
71 * chances of name collisions, we suggest a convention of using a two
72 * part name: a prefix identifying the source of the name (an
73 * abbreviated version of the name of the library, library extension,
74 * or game), followed by a period as a separator, followed by a short
75 * descriptive name for the variable. The library follows this
76 * convention by using names of the form "adv3.xxx" - the "adv3"
77 * prefix indicates the standard library.
78 *
79 * The ID should contain only letters, numbers, and periods. Don't
80 * use spaces or punctuation marks (other than periods).
81 *
82 * Note that the ID string is for the program's use, not the
83 * player's, so this isn't something we translate to different
84 * languages. Note, though, that the configuration file is a simple
85 * text file, so it wouldn't hurt to use a reasonably meaningful
86 * name, in case the user takes it upon herself to look at the
87 * contents of the file.
88 */
89 settingID = ''
90
91 /*
92 * Display a message fragment that shows the current setting value.
93 * We use this to show the player exactly what we're saving or
94 * restoring in response to a SAVE DEFAULTS or RESTORE DEFAULTS
95 * command, so that there's no confusion about which settings are
96 * included. In most cases, the best thing to show here is the
97 * command that selects the current setting: "NOTIFY ON," for
98 * example. This is for the UI's convenience; it's not used by the
99 * settings manager itself.
100 */
101 settingDesc = ""
102
103 /*
104 * Should this item be included in listings shown to the user? If
105 * this is true, the UI will include this setting in a display list
106 * of current settings shown to the user on request, by calling our
107 * settingDesc method.
108 */
109 includeInListing = true
110
111 /*
112 * Get the textual representation of the setting - returns a string
113 * representing the setting as it should appear in the external
114 * configuration file. We use this to write the setting to the file.
115 *
116 * Note that this is only needed if the default saveItem() method is
117 * used.
118 */
119 settingToText() { /* subclasses must override */ }
120
121 /*
122 * Set the current value to the contents of the given string. The
123 * string contains a textual representation of a setting value, as
124 * previously generated with settingToText().
125 *
126 * This is only needed if the default restoreItem() method is used.
127 */
128 settingFromText(str) { /* subclasses must override */ }
129
130 /*
131 * Load from a settings file. By default, this simply calls the
132 * setting file object to load the data.
133 *
134 * This implementation is suitable for any scalar type, so this won't
135 * need to be overwritten for subclasses that only need to load a
136 * single string value from the file. Subclasses that implement
137 * complex (non-scalar) datatypes can override this as needed to read
138 * multiple line items from the file.
139 */
140 restoreItem(s)
141 {
142 /* look up the file item by ID */
143 local fileItem = s.getItem(settingID);
144
145 /*
146 * if this item appears in the file, retrieve its value; if not,
147 * restore my factory default setting
148 */
149 settingFromText(fileItem != nil ? fileItem.val_ : factoryDefault);
150 }
151
152 /*
153 * Save to a settings file. By default, this makes a string out of
154 * our value and updates or adds our corresponding entry in the file.
155 *
156 * This implementation is suitable for any scalar type, so this won't
157 * need to be overwritten for subclasses that only need to store a
158 * single string value in the file. Subclasses that implement
159 * complex (non-scalar) datatypes can override this as needed to
160 * manipulate multiple line items in the file.
161 */
162 saveItem(s)
163 {
164 /* get the string representation of my value */
165 local val = settingToText();
166
167 /* add or replace it in the file */
168 s.setItem(settingID, val);
169 }
170
171 /*
172 * My "factory default" setting. At pre-init time, before we've
173 * loaded the settings file for the first time, we'll run through all
174 * SettingsItems and store their pre-defined source-code settings
175 * here, as though we were saving the values to a file. Later, when
176 * we load a file, if we find the file lacks an entry for this
177 * setting item, we'll simply re-load the factory default from this
178 * property.
179 */
180 factoryDefault = nil
181 ;
182
183 /*
184 * A binary settings item - this is for variables that have simple
185 * true/nil values.
186 */
187 class BinarySettingsItem: SettingsItem
188 /* convert to text - use ON or OFF as the representation */
189 settingToText() { return isOn ? 'on' : 'off'; }
190
191 /* parse text */
192 settingFromText(str)
193 {
194 /* convert to lower-case and strip off spaces */
195 if (rexMatch('<space>*(<alpha>+)', str.toLower()) != nil)
196 str = rexGroup(1)[3];
197
198 /* get the new setting */
199 isOn = (str.toLower() == 'on');
200 }
201
202 /* our value is true (on) or nil (off) */
203 isOn = nil
204 ;
205
206 /*
207 * A string settings item. This is for variables that have scalar string
208 * values. Value strings can contain anything except newlines.
209 */
210 class StringSettingsItem: SettingsItem
211 /* convert to text */
212 settingToText()
213 {
214 /* quote the value if necessary */
215 return quoteValue(val);
216 }
217
218 /* parse text */
219 settingFromText(str)
220 {
221 /*
222 * If the value isn't quoted, use the value as-is, trimming off
223 * leading and trailing spaces. If it at least starts with a
224 * quote, remove the leading and trailing quote (if present) and
225 * translate backslash sequences.
226 */
227 if (rexMatch('^<space>*"', str))
228 {
229 /* it's quoted - remove the quotes and translate backslashes */
230 val = rexReplace(
231 [leadTrailSpPat, '\\"', '\\\\', '\\n', '\\r'], str,
232 ['', '"', '\\', '\n', '\r']);
233 }
234 else
235 {
236 /* no leading quote; just trim spaces */
237 rexMatch(trimSpPat, str);
238 val = rexGroup(1)[3];
239 }
240 }
241
242 leadTrailSpPat = static new RexPattern('^<space>+|<space>+$')
243 trimSpPat = static new RexPattern('^<space>*(.*?)<space>*$')
244
245 /*
246 * Class method: quote a string value for storing in the file. If
247 * the string has any leading or trailing spaces, starts with a
248 * double quote, or contains any newlines, we'll quote it; otherwise
249 * we'll return it as-is.
250 */
251 quoteValue(str)
252 {
253 /*
254 * if the value needs quoting, quote it, otherwise just return it
255 * unchanged
256 */
257 if (rexSearch(needQuotePat, str))
258 {
259 /*
260 * add quotes around the string, and backslash-escape any
261 * quotes, backslashes, or newlines within the string
262 */
263 return '"' + val.findReplace(
264 ['"', '\\', '\n', '\r'], ['\\"', '\\\\', '\\n', '\\r'])
265 + '"';
266 }
267 else
268 {
269 /* quotes aren't needed*/
270 return str;
271 }
272 }
273
274 needQuotePat = static new RexPattern('^<space>+|^"|[\r\n]')
275
276 /* our current value string */
277 val = ''
278 ;
279
280
281
282
283 /* ------------------------------------------------------------------------ */
284 /*
285 * The settings manager. This object gathers up some global methods for
286 * managing the saved settings. This base class provides only a
287 * programmatic interface - it doesn't have a user interface.
288 */
289 settingsManager: object
290 /*
291 * Save the current settings. This writes out the current settings
292 * to the global settings file.
293 *
294 * On any error, the method throws an exception. Possible errors
295 * include:
296 *
297 * - FileCreationException indicates that the settings file couldn't
298 * be opened for writing.
299 */
300 saveSettings()
301 {
302 /* retrieve the current settings */
303 local s = retrieveSettings();
304
305 /* if that failed, there's nothing more we can do */
306 if (s == nil)
307 return;
308
309 /*
310 * Update the file's contents with all of the current in-memory
311 * settings objects (applying the filter condition, if provided).
312 */
313 forEachInstance(SettingsItem, { item: item.saveItem(s) });
314
315 /* write out the settings */
316 storeSettings(s);
317 }
318
319 /*
320 * Restore all of the settings. If an error occurs, we'll throw an
321 * exception:
322 *
323 * - SettingsNotSupportedException - this is an older interpreter
324 * that doesn't support the "special files" feature, so we can't save
325 * or restore the default settings.
326 */
327 restoreSettings()
328 {
329 /* retrieve the current settings */
330 local s = retrieveSettings();
331
332 /*
333 * update all of the in-memory settings objects with the values
334 * from the file
335 */
336 forEachInstance(SettingsItem, {item: item.restoreItem(s)});
337 }
338
339 /*
340 * Retrieve the settings from the global settings file. This returns
341 * a SettingsFileData object that describes the file's contents.
342 * Note that if there simply isn't an existing settings file, we'll
343 * successfully return a SettingsFileData object with no data - the
344 * absence of a settings file isn't an error, but is merely
345 * equivalent to an empty settings file.
346 */
347 retrieveSettings()
348 {
349 local f;
350 local s = new SettingsFileData();
351 local linePat = new RexPattern(
352 '<space>*(<alphanum|-|_|$|lsquare|rsquare|percent|dot>+)'
353 + '<space>*=<space>*([^\n]*)\n?$');
354
355 /*
356 * Try opening the settings file. Older interpreters don't
357 * support the "special files" feature; if the interpreter
358 * predates special file support, it'll throw a "string value
359 * required," since it won't recognize the special file ID value
360 * as a valid filename.
361 */
362 try
363 {
364 /* open the "library defaults" special file */
365 f = File.openTextFile(LibraryDefaultsFile, FileAccessRead);
366 }
367 catch (FileNotFoundException fnf)
368 {
369 /*
370 * The interpreter supports the special file, but the file
371 * doesn't seem to exist. Simply return the empty file
372 * contents object.
373 */
374 return s;
375 }
376 catch (RuntimeError rte)
377 {
378 /*
379 * if the error is "string value required," then we have an
380 * older interpreter that doesn't support special files -
381 * indicate this by returning nil
382 */
383 if (rte.errno_ == 2019)
384 {
385 /* re-throw this as a SettingsNotSupportedException */
386 throw new SettingsNotSupportedException();
387 }
388
389 /* other exceptions are unexpected, so re-throw them */
390 throw rte;
391 }
392
393 /* read the file */
394 for (;;)
395 {
396 local l;
397
398 /* read the next line */
399 l = f.readFile();
400
401 /* stop if we've reached end of file */
402 if (l == nil)
403 break;
404
405 /* parse the line */
406 if (rexMatch(linePat, l) != nil)
407 {
408 /*
409 * it parsed - add the variable and its value to the
410 * contents object
411 */
412 s.addItem(rexGroup(1)[3], rexGroup(2)[3]);
413 }
414 else
415 {
416 /* it doesn't parse, so just keep the line as a comment */
417 s.addComment(l);
418 }
419 }
420
421 /* done with the file - close it */
422 f.closeFile();
423
424 /* return the populated file contents object */
425 return s;
426 }
427
428 /* store the given SettingsFileData to the global settings file */
429 storeSettings(s)
430 {
431 /*
432 * Open the "library defaults" file. Note that we don't have to
433 * worry here about the old-interpreter situation that we handle
434 * in retrieveSettings() - if the interpreter doesn't support
435 * special files, we won't ever get this far, because we always
436 * have to retrieve the current file's contents before we can
437 * store the new contents.
438 */
439 local f = File.openTextFile(LibraryDefaultsFile, FileAccessWrite);
440
441 /* write each line of the file's contents */
442 foreach (local item in s.lst_)
443 item.writeToFile(f);
444
445 /* done with the file - close it */
446 f.closeFile();
447 }
448 ;
449
450 /* ------------------------------------------------------------------------ */
451 /*
452 * Exception: the settings file mechanism isn't supported on this
453 * interpreter. This indicates that this is an older interpreter that
454 * doesn't support the "special files" feature, so we can't save or load
455 * the global settings file.
456 */
457 class SettingsNotSupportedException: Exception
458 ;
459
460 /* ------------------------------------------------------------------------ */
461 /*
462 * SettingsFileData - this is an object we use to represent the contents
463 * of the configuration file.
464 */
465 class SettingsFileData: object
466 construct()
467 {
468 /*
469 * We store the contents of the file in two ways: as a list, in
470 * the same order in which the contents appear in the file; and
471 * as a lookup table keyed by variable name. The list lets us
472 * preserve the parts of the file's contents that we don't need
473 * to change when we read it in and write it back out. The
474 * lookup table makes it easy to look up particular variable
475 * values.
476 */
477 tab_ = new LookupTable(16, 32);
478 lst_ = new Vector(16);
479 }
480
481 /*
482 * find an item - returns a SettinsFileItem for the key, or nil if
483 * there's no existing item
484 */
485 getItem(id)
486 {
487 /* return the entry from our ID-keyed table */
488 return tab_[id];
489 }
490
491 /* iterate over all data (non-comment) items in the file */
492 forEach(func)
493 {
494 /* scan the list */
495 foreach (local s in lst_)
496 {
497 /* if this is a data item, pass it to the callback */
498 if (s.ofKind(SettingsFileItem))
499 func(s.id_, s.val_);
500 }
501 }
502
503 /* add a variable */
504 addItem(id, val)
505 {
506 local item;
507
508 /* create the item descriptor object */
509 item = new SettingsFileItem(id, val);
510
511 /* append it to our file-contents-ordered list */
512 lst_.append(item);
513
514 /* add it to the lookup table, keyed by the variable ID */
515 tab_[id] = item;
516 }
517
518 /* set a variable, adding a new variable if it doesn't already exist */
519 setItem(id, val)
520 {
521 /* look for an existing SettingsFileItem entry for my ID */
522 local fileItem = getItem(id);
523
524 /* update the item if it exists, otherwise add a new one */
525 if (fileItem != nil)
526 fileItem.val_ = val;
527 else
528 addItem(id, val);
529 }
530
531 /* add a comment line */
532 addComment(str)
533 {
534 /* append a comment descriptor to the contents list */
535 lst_.append(new SettingsFileComment(str));
536 }
537
538 /* delete an item */
539 delItem(id)
540 {
541 /* if it's in our table, delete it */
542 local item = tab_[id];
543 if (item != nil)
544 {
545 /* delete it from the lookup table */
546 tab_.removeElement(id);
547
548 /* delete it from the file source list */
549 lst_.removeElement(item);
550 }
551 }
552
553 /* lookup table of values, keyed by variable name */
554 tab_ = nil
555
556 /* a list of SettingsFileItem objects giving the contents of the file */
557 lst_ = nil
558 ;
559
560 /*
561 * SettingsFileItem - this object describes a single item within an
562 * external settings file.
563 */
564 class SettingsFileItem: object
565 construct(id, val)
566 {
567 id_ = id;
568 val_ = val;
569 }
570
571 /* write this value to a file */
572 writeToFile(f) { f.writeFile(id_ + ' = ' + val_ + '\n'); }
573
574 /* the variable's ID */
575 id_ = nil
576
577 /* the string representation of the value */
578 val_ = nil
579 ;
580
581 /*
582 * SettingsFileComment - this object describes an unparsed line in the
583 * settings file. We treat lines that don't match our parsing rules as
584 * comments. We preserve the contents and order of these lines, but we
585 * don't otherwise try to interpret them.
586 */
587 class SettingsFileComment: object
588 construct(str)
589 {
590 /* if it doesn't end in a newline, add a newline */
591 if (!str.endsWith('\n'))
592 str += '\n';
593
594 /* remember the string */
595 str_ = str;
596 }
597
598 /* write the comment line to a file */
599 writeToFile(f) { f.writeFile(str_); }
600
601 /* the text from the file */
602 str_ = nil
603 ;
604
605