9653ec0d12bff69b53526cabbe68a9bcc5eafee6
[feisty_meow.git] / huffware / huffotronic_scripts / card_configurator_v8.1.txt
1 
2 // huffware script: card configurator, by fred huffhines.
3 //
4 // processes a notecard with configuration info, then sends the information as packages of
5 // configuration nuggest to a consuming script.  this is one level above the noteworthy script,
6 // which simply reads the notecard.  this script keeps the config parsing out of higher-level
7 // scripts.
8 //
9 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
10 // do not use it in objects without fully realizing you are implicitly accepting that license.
11 //
12
13 // global constants...
14
15 integer MAXIMUM_ITEMS_PER_BURST = 6;
16     // try this out as a good limit for the size of the sends.
17
18 // global variables...
19
20 string signature_required;
21     // sent to us when the request for configuration info is made.
22
23 list good_prefixes;
24     // similarly, a set of prefixes for notecard lines that the calling script
25     // cares about.  if this is empty, then anything will match.
26
27 string global_notecard_name;  // name of our notecard in the object's inventory.
28 integer response_code;  // set to uniquely identify the notecard read in progress.
29 list global_config_list;  // a collection of configuration parameters from our notecard.
30 list global_responses;  // the items we want to send back to the requestor.
31
32 // card configurator link message API:
33 //////////////
34 // do not redefine these constants.
35 integer CARD_CONFIGURATOR_HUFFWARE_ID = 10042;
36     // the unique id within the huffware system for the card configurator script to
37     // accept commands on.  this is used in llMessageLinked as the num parameter.
38 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
39     // this pattern is an uncommon thing to see in text, so we use it to separate
40     // our commands in link messages.
41 string HUFFWARE_ITEM_SEPARATOR = "{|||}";
42     // used to separate lists of items from each other when stored inside a parameter.
43     // this allows lists to be passed as single string parameters if needed.
44 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
45 //////////////
46 string BAD_NOTECARD_TEXT = "*badcrd*";
47     // the sign that we hated the notecards we found, or there were none.
48 string FINISHED_READING_NOTECARDS = "**finished**";
49     // the sign that we are done plowing through the card we found.
50 string BEGIN_READING_NOTECARD_COMMAND = "#read-cfg#";
51     // requests that the configurator find a good notecard and read its contents.
52     // it should send the contents via the alert below.  first parm is the signature and
53     // second is the wrapped list of valid item prefixes.
54 string READ_PARTICULAR_NOTECARD_COMMAND = "#read-note#";
55     // requests that the configurator find a good notecard and read its contents.
56     // it should send the contents via the alert below.  first two parms are the same as
57     // begin reading notecard, and the third parameter is the name of the specific notecard.
58 string CARD_CONFIG_RECEIVED_ALERT = "#cfg-event-upd#";
59     // this message is sent when the configurator has found some data updates or has finished
60     // reading the configuration file.
61 //////////////
62
63 // imported interfaces below...
64
65 // requires noteworthy library v8.5 or better.
66 //////////////
67 // do not redefine these constants.
68 integer NOTEWORTHY_HUFFWARE_ID = 10010;
69     // the unique id within the huffware system for the noteworthy script to
70     // accept commands on.  this is used in llMessageLinked as the num parameter.
71 // commands available via the noteworthy library:
72 string BUSY_READING_INDICATOR = "busy_already";
73     // this return value indicates that the script is already in use by some other script.
74     // the calling script should try again later.
75 string NOTECARD_READ_CONTINUATION = "continue!";
76     // returned as first parameter if there is still more data to handle.
77 // commands available via the noteworthy library:
78 string READ_NOTECARD_COMMAND = "#read_note#";
79     // command used to tell the script to read notecards.  needs a signature to find
80     // in the card as the first parameter, and a randomly generated response code for
81     // the second parameter.  the response code is used to uniquely identify a set of
82     // pending notecard readings (hopefully).  the signature can be blank.
83     // the results will be fired back as the string value returned, which will have
84     // as first element the notecard's name (or BAD_NOTECARD_INDICATOR if none was
85     // found) and as subsequent elements an embedded list that was read from the
86     // notecard.  this necessarily limits the size of the notecards that we can read
87     // and return.
88 string READ_SPECIFIC_NOTECARD_COMMAND = "#read_thisun#";
89     // like the read notecard command, but specifies the notecard name to use.  only that
90     // specific notecard file will be consulted.  first and second parm are still signature
91     // and response code, third parm is the notecard name.
92 //
93 //////////////
94 // joins a list of parameters using the parameter sentinel for the library.
95 string wrap_parameters(list to_flatten)
96 { return llDumpList2String(to_flatten, HUFFWARE_PARM_SEPARATOR); }
97 //////////////
98
99 // this function fires off a request to the noteworthy library via a link message.
100 // noteworthy will look for a notecard with our particular signature in it and
101 // if it finds one, it will read the configuration therein.  an empty string is
102 // returned if noteworthy couldn't find anything.
103 request_configuration()
104 {
105     global_notecard_name = "";  // reset any previous card.
106     // try to find a notecard with our configuration.
107     response_code = -1 * (integer)randomize_within_range(23, 80000, FALSE);
108     string parms_sent = wrap_parameters([signature_required, response_code]);
109     llMessageLinked(LINK_THIS, NOTEWORTHY_HUFFWARE_ID, READ_NOTECARD_COMMAND,
110          parms_sent);
111 }
112
113 request_specific_configuration()
114 {
115     // try to find a notecard with our configuration.
116     response_code = -1 * (integer)randomize_within_range(23, 80000, FALSE);
117     string parms_sent = wrap_parameters([signature_required, response_code, global_notecard_name]);
118     llMessageLinked(LINK_THIS, NOTEWORTHY_HUFFWARE_ID, READ_SPECIFIC_NOTECARD_COMMAND,
119          parms_sent);
120 }
121
122 // processes link messages received from the noteworthy library.
123 process_notecard(integer which, integer num, string msg, key id)
124 {
125     if (msg != READ_NOTECARD_COMMAND) return;  // not for us.
126     // process the result of reading the notecard.
127     list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
128     string notecard_name = llList2String(parms, 0);
129     integer response_for = llList2Integer(parms, 1);
130     if (response_for != response_code) return;  // oops, this isn't for us.
131     if (notecard_name != BAD_NOTECARD_TEXT) {
132         // a valid notecard has been found.
133         global_notecard_name = notecard_name;  // record its name for later use.
134         // snag all but the first two elements for our config now.
135         global_config_list = llList2List(parms, 2, -1);
136         parms = [];  // toss the old copy.
137         // and process the file as a set of definitions.
138         process_ini_config();
139         send_data_burst();  // send any pending configs out.
140         if (notecard_name != NOTECARD_READ_CONTINUATION) {
141 //log_it("sending final sentinel at end of card.");
142             // blast out a fake data burst that means we're done reading.
143             global_notecard_name = FINISHED_READING_NOTECARDS;
144             global_responses += [ FINISHED_READING_NOTECARDS ];
145             send_data_burst();
146         }
147 //log_it("after config read, memory left=" + (string)llGetFreeMemory());
148     } else {
149         // we hated the notecards we found, or there were none.
150         // send a failure response.
151         llMessageLinked(LINK_THIS, CARD_CONFIGURATOR_HUFFWARE_ID + REPLY_DISTANCE,
152             CARD_CONFIG_RECEIVED_ALERT, wrap_parameters([BAD_NOTECARD_TEXT]));
153     }
154 }
155
156 ///////////////
157
158 // sends the currently held data out to whoever requested it.
159 send_data_burst()
160 {
161     if (!llGetListLength(global_responses)) return;  // nothing to send.
162 //log_it("sending " + (string)llGetListLength(global_responses) + " items");
163     llMessageLinked(LINK_THIS, CARD_CONFIGURATOR_HUFFWARE_ID + REPLY_DISTANCE, CARD_CONFIG_RECEIVED_ALERT,
164         wrap_parameters([global_notecard_name] + global_responses));
165     global_responses = [];  // reset any items held.
166 }
167
168 // consumes the notecard in a very application specific way to retrieve our configuration items.
169 // the example script only looks for two variables: name and description.  if those are found in
170 // the sample card, then they are proudly shown.
171 parse_variable_definition(string to_parse)
172 {
173     string content;  // filled after finding a variable name.
174     list x_y = separate_variable_definition(to_parse);
175     string x = llList2String(x_y, 0);
176     if (!llGetListLength(good_prefixes)) {
177         global_responses += x_y;
178     } else {
179         integer indy;
180         for (indy = 0; indy < llGetListLength(good_prefixes); indy++) {
181             // if it's one of our desired prefixes, then we add it.
182             if (is_prefix(x, llList2String(good_prefixes, indy))) {
183                 global_responses += x_y;
184                 indy = llGetListLength(good_prefixes) + 5;  // skip rest of loop.
185             }
186         }
187     }
188     
189     if (llGetListLength(global_responses) > MAXIMUM_ITEMS_PER_BURST) {
190         send_data_burst();
191     }
192 }
193
194 // examines all entries that we got from the notecard to see if any contain definitions.
195 // this is basically an INI file reader, but it uses a list instead of a file.
196 // ini files provide a format with multiple sections of config information, like so:
197 //    [section_1]
198 //    name1=value1
199 //    name2=value2 ...etc...
200 //    [section_2]
201 //    name1=value1 ...etc...
202 process_ini_config()
203 {
204 //    log_it("scanning notecard for variable definitions...");
205     integer indy;
206     integer count = llGetListLength(global_config_list);
207     // iterate across the items in our configuration to look for ones that are not done yet.
208     for (indy = 0; indy < count; indy++) {
209         string line = llList2String(global_config_list, indy);
210 //log_it("ini proc: " + line);
211         // search for a section beginning.
212         if (llGetSubString(line, 0, 0) == "[") {
213             // we found the start of a section name.  now read the contents.
214 //            log_it("reading section: " + llGetSubString(line, 1, -2));
215 //            global_responses += [ line, "e" ];
216             indy++;  // skip the section line.
217         }
218         integer sec_indy;
219         for (sec_indy = indy; sec_indy < count; sec_indy++) {
220             // read the lines in the section.
221             line = llList2String(global_config_list, sec_indy);
222             if (llGetSubString(line, 0, 0) != "[") {
223                 // try to interpret this line as a variable setting.  this is just
224                 // one example of a way to handle the config file; one might instead
225                 // want to do something below once a whole section is read.
226                 parse_variable_definition(line);
227             } else {
228                 // we're at the beginning of a new section now, so start processing its
229                 // configuration in the outer loop.
230                 indy = sec_indy - 1;  // set indy to proper beginning of section.
231                 sec_indy = count + 3;  // skip remainder of inner loop.
232             }
233         }
234         if (sec_indy == count) indy = count + 3;  // skip out of loop now.
235     }
236     global_config_list = [];  // we ate it!
237 }
238
239 initialize_specific(string specific_card)
240 {
241     // reset our relevant variables.
242     global_notecard_name = specific_card;
243     global_config_list = [];
244     global_responses = [];
245
246     // request that the noteworthy library start looking for our notecard.
247     request_specific_configuration();
248 }
249
250 initialize()
251 {
252     // reset our relevant variables.
253     global_notecard_name = "";
254     global_config_list = [];
255     global_responses = [];
256
257     // request that the noteworthy library start looking for our notecard.
258     request_configuration();
259 }
260
261 //////////////
262 // from hufflets...
263 //
264 integer debug_num = 0;
265
266 // a debugging output method.  can be disabled entirely in one place.
267 log_it(string to_say)
268 {
269     debug_num++;
270     // tell this to the owner.    
271     llOwnerSay(llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
272     // say this on open chat, but use an unusual channel.
273 //    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
274 }
275
276 integer find_substring(string full_string, string pattern)
277 {
278     string full_lower = llToLower(full_string);
279     return llSubStringIndex(full_lower, pattern);
280 }
281
282 //////////////
283
284 // locates the string "text" in the list to "search_in".
285 integer find_in_list(list search_in, string text)
286
287     integer len = llGetListLength(search_in);
288     integer i; 
289     for (i = 0; i < len; i++) { 
290         if (llList2String(search_in, i) == text) 
291             return i; 
292     } 
293     return -1;
294 }
295
296 // returns TRUE if the "prefix" string is the first part of "compare_with".
297 integer is_prefix(string compare_with, string prefix)
298 { return (llSubStringIndex(compare_with, prefix) == 0); }
299
300 // returns a number at most "maximum" and at least "minimum".
301 // if "allow_negative" is TRUE, then the return may be positive or negative.
302 float randomize_within_range(float minimum, float maximum, integer allow_negative)
303 {
304     if (minimum > maximum) {
305         // flip the two if they are reversed.
306         float temp = minimum; minimum = maximum; maximum = temp;
307     }
308     float to_return = minimum + llFrand(maximum - minimum);
309     if (allow_negative) {
310         if (llFrand(1.0) < 0.5) to_return *= -1.0;
311     }
312     return to_return;
313 }
314
315 // strips the spaces off of the beginning and end of a string.
316 string strip_spaces(string to_strip)
317 {
318     // clean out initial spaces.
319     while (llGetSubString(to_strip, 0, 0) == " ")
320         to_strip = llDeleteSubString(to_strip, 0, 0);
321     // clean out ending spaces.
322     while (llGetSubString(to_strip, -1, -1) == " ")
323         to_strip = llDeleteSubString(to_strip, -1, -1);
324     return to_strip;
325 }
326
327 // parses a variable definition to find the name of the variable and its value.
328 // this returns two strings [X, Y], if "to_split" is in the form X=Y.
329 list separate_variable_definition(string to_split)
330 {
331     integer equals_indy = llSubStringIndex(to_split, "=");
332     // we don't support missing an equals sign, and we don't support it as the first character.
333     if (equals_indy <= 0) return [];  // no match.
334     string x = llGetSubString(to_split, 0, equals_indy - 1);
335     string y = llGetSubString(to_split, equals_indy + 1, -1);
336     to_split = "";  // save space.
337 ///log_it("got x = " + x + " and y = " + y);
338     return [ strip_spaces(x), strip_spaces(y) ];
339 }
340 //
341 // end hufflets
342 //////////////
343
344 //////////////
345 // huffware script: auto-retire, by fred huffhines, version 2.5.
346 // distributed under BSD-like license.
347 //   !!  keep in mind that this code must be *copied* into another
348 //   !!  script that you wish to add auto-retirement capability to.
349 // when a script has auto_retire in it, it can be dropped into an
350 // object and the most recent version of the script will destroy
351 // all older versions.
352 //
353 // the version numbers are embedded into the script names themselves.
354 // the notation for versions uses a letter 'v', followed by two numbers
355 // in the form "major.minor".
356 // major and minor versions are implicitly considered as a floating point
357 // number that increases with each newer version of the script.  thus,
358 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
359 // and "hazmap v3.2" is a more recent version.
360 //
361 // example usage of the auto-retirement script:
362 //     default {
363 //         state_entry() {
364 //            auto_retire();  // make sure newest addition is only version of script.
365 //        }
366 //     }
367 // this script is partly based on the self-upgrading scripts from markov brodsky
368 // and jippen faddoul.
369 //////////////
370 auto_retire() {
371     string self = llGetScriptName();  // the name of this script.
372     list split = compute_basename_and_version(self);
373     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
374     string basename = llList2String(split, 0);  // script name with no version attached.
375     string version_string = llList2String(split, 1);  // the version found.
376     integer posn;
377     // find any scripts that match the basename.  they are variants of this script.
378     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
379 //log_it("invpo=" + (string)posn);
380         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
381         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
382             // found a basic match at least.
383             list inv_split = compute_basename_and_version(curr_script);
384             if (llGetListLength(inv_split) == 2) {
385                 // see if this script is more ancient.
386                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
387                 // must make sure that the retiring script is completely the identical basename;
388                 // just matching in the front doesn't make it a relative.
389                 if ( (llList2String(inv_split, 0) == basename)
390                     && ((float)inv_version_string < (float)version_string) ) {
391                     // remove script with same name from inventory that has inferior version.
392                     llRemoveInventory(curr_script);
393                 }
394             }
395         }
396     }
397 }
398 //
399 // separates the base script name and version number.  used by auto_retire.
400 list compute_basename_and_version(string to_chop_up)
401 {
402     // minimum script name is 2 characters plus a version.
403     integer space_v_posn;
404     // find the last useful space and 'v' combo.
405     for (space_v_posn = llStringLength(to_chop_up) - 3;
406         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
407         space_v_posn--) {
408         // look for space and v but do nothing else.
409 //log_it("pos=" + (string)space_v_posn);
410     }
411     if (space_v_posn < 2) return [];  // no space found.
412 //log_it("space v@" + (string)space_v_posn);
413     // now we zoom through the stuff after our beloved v character and find any evil
414     // space characters, which are most likely from SL having found a duplicate item
415     // name and not so helpfully renamed it for us.
416     integer indy;
417     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
418 //log_it("indy=" + (string)space_v_posn);
419         if (llGetSubString(to_chop_up, indy, indy) == " ") {
420             // found one; zap it.  since we're going backwards we don't need to
421             // adjust the loop at all.
422             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
423 //log_it("saw case of previously redundant item, aieee.  flattened: " + to_chop_up);
424         }
425     }
426     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
427     // ditch the space character for our numerical check.
428     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
429     // strip out a 'v' if there is one.
430     if (llGetSubString(chop_suffix, 0, 0) == "v")
431         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
432     // if valid floating point number and greater than zero, that works for our version.
433     string basename = to_chop_up;  // script name with no version attached.
434     if ((float)chop_suffix > 0.0) {
435         // this is a big success right here.
436         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
437         return [ basename, chop_suffix ];
438     }
439     // seems like we found nothing useful.
440     return [];
441 }
442 //
443 //////////////
444
445 default
446 {
447     state_entry() { if (llSubStringIndex(llGetObjectName(),  "huffotronic") < 0) state real_default; }
448     on_rez(integer parm) { state rerun; }
449 }
450 state rerun { state_entry() { state default; } }
451
452 state real_default
453 {
454     state_entry()
455     {
456         auto_retire();  // make sure newest addition is only version of script.
457     }
458
459     on_rez(integer parm) { state rerun; }
460
461     link_message(integer sender, integer num, string msg, key id) {
462         if (num == NOTEWORTHY_HUFFWARE_ID + REPLY_DISTANCE) {
463             if (msg == READ_NOTECARD_COMMAND) {
464                 process_notecard(sender, num, msg, id);
465             }
466             return;
467         }
468         
469         if (num != CARD_CONFIGURATOR_HUFFWARE_ID) return;  // not even slightly for us.
470         
471         if (msg == BEGIN_READING_NOTECARD_COMMAND) {
472             list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
473             signature_required = llList2String(parms, 0);
474             string prefixes_wrap = llList2String(parms, 1);
475 //log_it("pref raw is: " + prefixes_wrap);
476             good_prefixes = llParseString2List(prefixes_wrap, [HUFFWARE_ITEM_SEPARATOR], []);
477 //log_it("signature to find: " + signature_required);
478             initialize();
479 //log_it("prefixes are: " + (string)good_prefixes);
480 //log_it("began reading, memory left=" + (string)llGetFreeMemory());
481             return;
482         }
483         if (msg == READ_PARTICULAR_NOTECARD_COMMAND) {
484             list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
485             signature_required = llList2String(parms, 0);
486             string prefixes_wrap = llList2String(parms, 1);
487             string specific_card = llList2String(parms, 2);
488 //log_it("pref raw is: " + prefixes_wrap);
489             good_prefixes = llParseString2List(prefixes_wrap, [HUFFWARE_ITEM_SEPARATOR], []);
490 //log_it("signature to find: " + signature_required);
491             initialize_specific(specific_card);
492 //log_it("prefixes are: " + (string)good_prefixes);
493 //log_it("notecard is: " + specific_card);
494 //log_it("began reading, memory left=" + (string)llGetFreeMemory());
495             return;
496         }
497     }
498 }
499