347d259047f44d5665f4d0ff3191734e1499cf2b
[feisty_meow.git] / huffware / huffotronic_scripts / menutini_library_v6.1.txt
1 
2 // huffware script: menutini library, by fred huffhines.
3 //
4 // this is a library script for menuing that provides a way to remote control the
5 // menu, somewhat.  another script can zing link messages at this script and a menu
6 // will be shown based on the specified description and buttons.  when the user
7 // selects an answer, that result is sent back in a link message reply.
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 // useful constants you might want to change:
14
15 integer TIMEOUT_FOR_MENU = 42;
16     // timeout for the menu in seconds.
17 //hmmm: may want this to be selectable from menu request.
18 //      or may even want to never time out!
19 //      if we managed a list of ongoing menus, that would work.
20 //      currently it cannot.
21
22 integer DEBUGGING = FALSE;
23     // if this is true, then extra info will be printed when handling a menu.
24
25 string NEXT_MENU_TEXT = "Next >>";
26     // what the next item will say for showing next menu page.
27
28 // menutini link message API...
29 //////////////
30 // do not redefine these constants.
31 integer MENUTINI_HUFFWARE_ID = 10009;
32     // the unique id within the huffware system for the jaunt script to
33     // accept commands on.  this is used in llMessageLinked as the num parameter.
34 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
35     // this pattern is an uncommon thing to see in text, so we use it to separate
36     // our commands in link messages.
37 string HUFFWARE_ITEM_SEPARATOR = "{|||}";
38     // used to separate lists of items from each other when stored inside a parameter.
39     // this allows lists to be passed as single string parameters if needed.
40 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
41 string SHOW_MENU_COMMAND = "#menu#";
42     // the command that tells menutini to show a menu defined by parameters
43     // that are passed along.  these must be: the menu name, the menu's title
44     // (which is really the info to show as content in the main box of the menu),
45     // the wrapped list of commands to show as menu buttons, the menu system
46     // channel's for listening, and the key to listen to.
47     // the reply will include: the menu name, the choice made and the key for
48     // the avatar.
49 //
50 //////////////
51 // joins a list of sub-items using the item sentinel for the library.
52 string wrap_item_list(list to_wrap)
53 { return llDumpList2String(to_wrap, HUFFWARE_ITEM_SEPARATOR); }
54 //
55 //////////////
56
57 // global variables...
58
59 list _private_global_buttons;  // holds onto the active set of menu options.
60 string _private_global_av_key;  // the key for the avatar who clicks the menu.
61 string _private_global_title;  // holds onto current title text.
62
63 integer _menu_base_start = 0;  // position in the items of the current menu.
64
65 integer listening_id = 0;
66     // the current id of our listening for the menu.  it's an id returned by LSL
67     // that we need to track so we can cancel the listen.
68
69 integer menu_system_channel = 0;
70     // messages come back to us from this channel when user clicks the dialog.
71     // this is set later and the default is meaningless.
72
73 string global_menu_name = "";
74     // hangs onto the current menu's name.
75
76 //hmmm: note; to manage multiple concurrent menus on different channels,
77 //      we must make these into lists.  then the timeouts should apply
78 //      individually to these instead of overall (if we even do timeouts;
79 //      it's nicer if menus never stop being active).
80
81
82 // displays the menu requested.  it's "menu_name" is an internal name that is
83 // not displayed to the user.  the "title" is the content shown in the main area
84 // of the menu.  "commands_in" is the list of menu items to show as buttons.
85 // the "menu_channel" is where the user's clicked response will be sent.  the
86 // "listen_to" key is the avatar expected to click the menu, which is needed to
87 // listen to his response.
88 show_menu(string menu_name, string title, list buttons,
89     integer menu_channel, key listen_to)
90 {
91     // save our new parms.
92     global_menu_name = menu_name;
93     _private_global_title = title;
94     _private_global_buttons = buttons;
95     menu_system_channel = menu_channel;
96     _private_global_av_key = listen_to;
97 //log_it("showing menu to " + llKey2Name(listen_to) + " with key " + (string)listen_to);
98     if (DEBUGGING) {
99         log_it("menu name: " + global_menu_name);
100         log_it("title: " + _private_global_title);
101         log_it("buttons: " + (string)buttons);
102         log_it("channel: " + (string)menu_system_channel);
103         log_it("listen key: " + (string)listen_to);
104     }
105
106     integer add_next = FALSE;  // true if we should add a next menu item.
107
108     // the math here incorporates current button position.
109     integer current = _menu_base_start;
110     integer max_buttons = llGetListLength(buttons) - current;
111
112     if (max_buttons > 12) {
113         // limitation of SL: menus have a max of 12 buttons.
114         max_buttons = 12;
115         add_next = TRUE;
116     } else if (llGetListLength(buttons) > 12) {
117         // we already have been adding next.  let's make sure this gets
118         // a wrap-around next button.
119         add_next = TRUE;
120     }
121     // chop out what we can use in a menu.
122     list trunc_buttons = llList2List(buttons, current, current + max_buttons - 1);
123     if (add_next) {
124         // we were asked to add a menu item for the next screen.
125         trunc_buttons = llList2List(trunc_buttons, 0, 10) + NEXT_MENU_TEXT;
126     }
127
128     listening_id = llListen(menu_channel, "", listen_to, "");
129     list commands;
130     integer i;
131     // take only the prefix of the string, to avoid getting a length complaint.
132     for (i = 0; i < llGetListLength(trunc_buttons); i++) {
133         string curr = llList2String(trunc_buttons, i);
134         integer last_pos = 23;  // default maximum, highest possible is 24.
135         if (llStringLength(curr) - 1 < last_pos) last_pos = llStringLength(curr) - 1;
136         curr = llGetSubString(curr, 0, last_pos);
137         commands += curr;
138     }
139     llDialog(listen_to, title, commands, menu_channel);
140     llSetTimerEvent(TIMEOUT_FOR_MENU);
141 }
142
143 // shuts down any connection we might have had with any active menu.  we will not
144 // send any responses after this point (although we might already have responded when
145 // the user clicked the menu).
146 clear_menu()
147 {
148     llListenRemove(listening_id);
149     llSetTimerEvent(0.0);
150 }
151
152 // a simple version of a reply for a command that has been executed.  the parameters
153 // might contain an outcome or result of the operation that was requested.
154 // ours do differ from normal in that we send back the channel as the number parameter
155 // instead of enforcing that being MENU_HUFFWARE_ID.
156 send_reply(integer destination, integer channel, list parms, string command)
157 {
158     llMessageLinked(destination, channel, command,
159         llDumpList2String(parms, HUFFWARE_PARM_SEPARATOR));
160 }
161
162 // processes the menu requests.
163 handle_link_message(integer sender, integer huff_id, string msg, key id)
164 {
165     if (huff_id != MENUTINI_HUFFWARE_ID) return;  // not for us.
166
167     if (msg == SHOW_MENU_COMMAND) {
168         _menu_base_start = 0;  // reset the position in the menus.
169         // separate the list out.
170 //log_it("id showing: " + (string)id);
171         list parms = llParseStringKeepNulls(id, [HUFFWARE_PARM_SEPARATOR], []);
172 //log_it("parm len " + (string)llGetListLength(parms) + ", parms are: " + (string)parms);
173         // toss any existing menu info.
174         clear_menu();
175 //log_it("key here early: " + llList2String(parms, 4));
176         show_menu(llList2String(parms, 0), llList2String(parms, 1),
177             llParseStringKeepNulls(llList2String(parms, 2),
178                 [HUFFWARE_ITEM_SEPARATOR], []),
179             (integer)llList2String(parms, 3),
180             (key)llList2String(parms, 4));
181     }
182 }
183
184 // process the response when the user chooses a menu item.  this causes our
185 // caller to be told what was selected.
186 process_menu_response(integer channel, string name, key id, string message)
187 {
188     if (channel != menu_system_channel) return;  // not for us.
189
190     if (message == NEXT_MENU_TEXT) {
191         // this is the special choice, so we need to go to the next page.
192         _menu_base_start += 11;
193         if (_menu_base_start > llGetListLength(_private_global_buttons)) {
194             // we have wrapped around the list.  go to the start again.
195             _menu_base_start = 0;
196         }
197         show_menu(global_menu_name, _private_global_title,
198             _private_global_buttons, menu_system_channel,
199             _private_global_av_key);
200         return;  // handled by opening a new menu.
201     }
202     
203     string calculated_name;
204     integer indy;
205     // first try for an exact match.
206     for (indy = 0; indy < llGetListLength(_private_global_buttons); indy++) {
207         string curr = llList2String(_private_global_buttons, indy);
208         if (curr == message) {
209             // correct the answer based on the full button string.
210             calculated_name = curr;
211         }
212     }
213     if (calculated_name == "") {
214         // try an imprecise match if the exact matching didn't work.
215         for (indy = 0; indy < llGetListLength(_private_global_buttons); indy++) {
216             string curr = llList2String(_private_global_buttons, indy);
217             if (is_prefix(curr, message)) {
218                 // correct the answer based on the full button string.
219                 calculated_name = curr;
220             }
221         }
222     }
223     if (calculated_name != "") {
224         // only send a response if that menu choice made sense to us.
225         send_reply(LINK_THIS, MENUTINI_HUFFWARE_ID + REPLY_DISTANCE,
226             [ global_menu_name, calculated_name, _private_global_av_key ],
227             SHOW_MENU_COMMAND);
228     }
229 }
230
231 //////////////
232 // from hufflets...
233
234 integer debug_num = 0;
235
236 // a debugging output method.  can be disabled entirely in one place.
237 log_it(string to_say)
238 {
239     debug_num++;
240     // tell this to the owner.    
241     llOwnerSay(llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
242     // say this on open chat, but use an unusual channel.
243 //    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
244 }
245
246 //////////////
247
248 // returns TRUE if the "prefix" string is the first part of "compare_with".
249 integer is_prefix(string compare_with, string prefix)
250 { return (llSubStringIndex(compare_with, prefix) == 0); }
251
252 //////////////
253
254 //////////////
255 // huffware script: auto-retire, by fred huffhines, version 2.8.
256 // distributed under BSD-like license.
257 //   !!  keep in mind that this code must be *copied* into another
258 //   !!  script that you wish to add auto-retirement capability to.
259 // when a script has auto_retire in it, it can be dropped into an
260 // object and the most recent version of the script will destroy
261 // all older versions.
262 //
263 // the version numbers are embedded into the script names themselves.
264 // the notation for versions uses a letter 'v', followed by two numbers
265 // in the form "major.minor".
266 // major and minor versions are implicitly considered as a floating point
267 // number that increases with each newer version of the script.  thus,
268 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
269 // and "hazmap v3.2" is a more recent version.
270 //
271 // example usage of the auto-retirement script:
272 //     default {
273 //         state_entry() {
274 //            auto_retire();  // make sure newest addition is only version of script.
275 //        }
276 //     }
277 // this script is partly based on the self-upgrading scripts from markov brodsky
278 // and jippen faddoul.
279 //////////////
280 auto_retire() {
281     string self = llGetScriptName();  // the name of this script.
282     list split = compute_basename_and_version(self);
283     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
284     string basename = llList2String(split, 0);  // script name with no version attached.
285     string version_string = llList2String(split, 1);  // the version found.
286     integer posn;
287     // find any scripts that match the basename.  they are variants of this script.
288     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
289         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
290         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
291             // found a basic match at least.
292             list inv_split = compute_basename_and_version(curr_script);
293             if (llGetListLength(inv_split) == 2) {
294                 // see if this script is more ancient.
295                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
296                 // must make sure that the retiring script is completely the identical basename;
297                 // just matching in the front doesn't make it a relative.
298                 if ( (llList2String(inv_split, 0) == basename)
299                     && ((float)inv_version_string < (float)version_string) ) {
300                     // remove script with same name from inventory that has inferior version.
301                     llRemoveInventory(curr_script);
302                 }
303             }
304         }
305     }
306 }
307 //
308 // separates the base script name and version number.  used by auto_retire.
309 list compute_basename_and_version(string to_chop_up)
310 {
311     // minimum script name is 2 characters plus a version.
312     integer space_v_posn;
313     // find the last useful space and 'v' combo.
314     for (space_v_posn = llStringLength(to_chop_up) - 3;
315         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
316         space_v_posn--) {
317         // look for space and v but do nothing else.
318     }
319     if (space_v_posn < 2) return [];  // no space found.
320     // now we zoom through the stuff after our beloved v character and find any evil
321     // space characters, which are most likely from SL having found a duplicate item
322     // name and not so helpfully renamed it for us.
323     integer indy;
324     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
325         if (llGetSubString(to_chop_up, indy, indy) == " ") {
326             // found one; zap it.  since we're going backwards we don't need to
327             // adjust the loop at all.
328             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
329         }
330     }
331     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
332     // ditch the space character for our numerical check.
333     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
334     // strip out a 'v' if there is one.
335     if (llGetSubString(chop_suffix, 0, 0) == "v")
336         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
337     // if valid floating point number and greater than zero, that works for our version.
338     string basename = to_chop_up;  // script name with no version attached.
339     if ((float)chop_suffix > 0.0) {
340         // this is a big success right here.
341         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
342         return [ basename, chop_suffix ];
343     }
344     // seems like we found nothing useful.
345     return [];
346 }
347 //
348 //////////////
349
350 //hmmm: extract this code to a menutini example!
351
352 //////////////
353 // how to invoke a menu (assuming menutini is in same prim as calling script):
354 //
355 list buttons;  // holds onto the set of menu options.
356 //
357 integer random_channel() { return -(integer)(llFrand(40000) + 20000); }
358 //
359 example_invocation()
360 {
361     string menu_name = "grumfazoid";
362     string title = "These united colors of ben's futon have unfortunately run.";
363     buttons = [ "garp out", "sklonar", "fuzzlenog" ];
364     integer menu_channel = random_channel();
365     key listen_to = llGetOwner();
366     llMessageLinked(LINK_THIS, MENUTINI_HUFFWARE_ID, SHOW_MENU_COMMAND,
367         menu_name + HUFFWARE_PARM_SEPARATOR
368         + title + HUFFWARE_PARM_SEPARATOR
369         + wrap_item_list(buttons) + HUFFWARE_PARM_SEPARATOR
370         + (string)menu_channel + HUFFWARE_PARM_SEPARATOR
371         + (string)listen_to);
372 }
373 //
374 // how to handle the response message when the user chooses a button.
375 //
376 react_to_menu(string menu_name, string which_choice)
377 {
378     // one might use the menu_name when dealing with multiple different menus.
379
380     integer indy = 0;
381     // find the specified item and process it.
382     while (indy < llGetListLength(buttons)) {
383         // see if the current destination matches.
384         if (llSubStringIndex(llList2String(buttons, indy), which_choice) == 0) {
385             // this is the chosen item.
386 //            process_menu_item(indy);  // using numerical numbering.
387 // this function must be implemented in your own code; it is what handles the
388 // user picking a particular button on the menu.
389             return;            
390         }
391         indy++;
392     }
393     llSay(0, "did not find menu option");
394 }
395
396 // an example for menu handling.  this gets the response from menutini library
397 // and calls the menu processing method "react_to_menu".
398 example_handle_link_message(integer sender, integer num, string msg, key id)
399 {
400     if (num != MENUTINI_HUFFWARE_ID + REPLY_DISTANCE) return;  // not for us.
401     if (msg != SHOW_MENU_COMMAND) return;  // also not for us.
402     list parms = llParseStringKeepNulls(id, [HUFFWARE_PARM_SEPARATOR], []);
403     string menu_name = llList2String(parms, 0);
404     string which_choice = llList2String(parms, 1);
405     react_to_menu(menu_name, which_choice);
406 }
407
408 // then inside a state, you need an event handler like so:
409 //
410 // link_message(integer sender, integer num, string msg, key id)
411 // { example_handle_link_message(sender, num, msg, id); }
412
413 //
414 // end invocation sample code...
415 //////////////
416
417 default
418 {
419     state_entry() { if (llSubStringIndex(llGetObjectName(),  "huffotronic") < 0) state real_default; }
420     on_rez(integer parm) { state rerun; }
421 }
422 state rerun { state_entry() { state default; } }
423
424 state real_default
425 {
426     state_entry() { auto_retire(); }
427
428     link_message(integer sender, integer huff_id, string msg, key id)
429     { handle_link_message(sender, huff_id, msg, id); }
430
431     listen(integer channel, string name, key id, string message)
432     { process_menu_response(channel, name, id, message); }
433     
434     // if the timer goes off, then the user has ignored the menu for longer than the
435     // timeout.  we need to turn off our listen and ignore that menu.
436     timer() { clear_menu(); }
437 }
438