media: scrapers are now independent of page-modes
[conkeror/arlinius.git] / modules / minibuffer-read.js
blob1849f70555c7b1f8ff3951c3f79b83dc5ed550f9
1 /**
2  * (C) Copyright 2007-2009 John J. Foerch
3  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
4  *
5  * Use, modification, and distribution are subject to the terms specified in the
6  * COPYING file.
7 **/
9 define_variable("default_minibuffer_auto_complete_delay", 150,
10     "Delay (in milliseconds) after the most recent key-stroke "+
11     "before auto-completing.");
13 define_variable("minibuffer_auto_complete_preferences", {});
15 define_variable("minibuffer_auto_complete_default", false,
16     "Boolean specifying whether to auto-complete by default. "+
17     "The user variable `minibuffer_auto_complete_preferences' "+
18     "overrides this.");
20 var minibuffer_history_data = new string_hashmap();
22 /* FIXME: These should possibly be saved to disk somewhere */
23 define_variable("minibuffer_history_max_items", 100,
24     "Maximum number of minibuffer history entries stored. Older "+
25     "history entries are truncated after this limit is reached.");
28 /* The parameter `args' specifies the arguments.  In addition, the
29  * arguments for basic_minibuffer_state are also allowed.
30  *
31  * history:           [optional] specifies a string to identify the history list to use
32  *
33  * completer
34  *
35  * match_required
36  *
37  * default_completion  only used if match_required is set to true
38  *
39  * $valiator          [optional]
40  *          specifies a function
41  */
42 define_keywords("$keymap", "$history", "$validator",
43                 "$completer", "$match_required", "$default_completion",
44                 "$auto_complete", "$auto_complete_initial", "$auto_complete_conservative",
45                 "$auto_complete_delay",
46                 "$space_completes");
47 /* FIXME: support completing in another thread */
48 function text_entry_minibuffer_state (window, continuation) {
49     keywords(arguments, $keymap = minibuffer_keymap);
51     basic_minibuffer_state.call(this, window, forward_keywords(arguments));
53     this.continuation = continuation;
54     if (arguments.$history) {
55         this.history = minibuffer_history_data.get_put_default(arguments.$history, []);
56         this.history_index = -1;
57         this.saved_last_history_entry = null;
58     }
60     this.validator = arguments.$validator;
62     if (arguments.$completer != null) {
63         this.completer = arguments.$completer;
64         let auto = arguments.$auto_complete;
65         while (typeof(auto) == "string")
66             auto = minibuffer_auto_complete_preferences[auto];
67         if (auto == null)
68             auto = minibuffer_auto_complete_default;
69         this.auto_complete = auto;
70         this.auto_complete_initial = !!arguments.$auto_complete_initial;
71         this.auto_complete_conservative = !!arguments.$auto_complete_conservative;
72         let delay = arguments.$auto_complete_delay;
73         if (delay == null)
74             delay = default_minibuffer_auto_complete_delay;
75         this.auto_complete_delay = delay;
76         this.completions = null;
77         this.completions_valid = false;
78         this.space_completes = !!arguments.$space_completes;
79         this.completions_timer_ID = null;
80         this.completions_display_element = null;
81         this.selected_completion_index = -1;
82         this.match_required  = !!arguments.$match_required;
83         if (this.match_required)
84             this.default_completion = arguments.$default_completion;
85     }
88 function completions_tree_view (minibuffer_state) {
89     this.minibuffer_state = minibuffer_state;
92 var atom_service = Cc["@mozilla.org/atom-service;1"].getService(Ci.nsIAtomService);
94 completions_tree_view.prototype = {
95     get rowCount () {
96         var c = this.minibuffer_state.completions;
97         if (!c)
98             return 0;
99         return c.count;
100     },
101     getCellText : function (row,column) {
102         var c = this.minibuffer_state.completions;
103         if (row >= c.count)
104             return null;
105         if (column.index == 0)
106             return c.get_string(row);
107         if (c.get_description)
108             return c.get_description(row);
109         return "";
110     },
111     setTree : function (treebox) { this.treebox = treebox; },
112     isContainer: function (row) { return false; },
113     isSeparator: function (row) { return false; },
114     isSorted: function () { return false; },
115     getLevel: function (row) { return 0; },
116     getImageSrc: function (row, col) { return null; },
117     getRowProperties: function (row, props) {},
118     getCellProperties: function (row, col, props) {
119         if (col.index == 0)
120             props.AppendElement(atom_service.getAtom("completion-string"));
121         else
122             props.AppendElement(atom_service.getAtom("completion-description"));
123     },
124     getColumnProperties: function (colid, col, props) {}
127 // inherit from basic_minibuffer_state
128 text_entry_minibuffer_state.prototype = {
129     __proto__: basic_minibuffer_state.prototype,
130     load : function (window) {
131         basic_minibuffer_state.prototype.load.call(this, window);
132         this.window = window;
133         if (this.completer) {
134             // Create completion display element if needed
135             if (!this.completion_element) {
136                 /* FIXME: maybe use the dom_generator */
137                 var tree = create_XUL(window, "tree");
138                 var s = this;
139                 tree.addEventListener("select", function () {
140                         s.selected_completion_index = s.completions_display_element.currentIndex;
141                         s.handle_completion_selected();
142                     }, true);
143                 tree.setAttribute("class", "completions");
145                 tree.setAttribute("rows", "8");
147                 tree.setAttribute("collapsed", "true");
149                 tree.setAttribute("hidecolumnpicker", "true");
150                 tree.setAttribute("hideheader", "true");
152                 var treecols = create_XUL(window, "treecols");
153                 tree.appendChild(treecols);
154                 var treecol = create_XUL(window, "treecol");
155                 treecol.setAttribute("flex", "1");
156                 treecols.appendChild(treecol);
157                 treecol = create_XUL(window, "treecol");
158                 treecol.setAttribute("flex", "1");
159                 treecols.appendChild(treecol);
160                 tree.appendChild(create_XUL(window, "treechildren"));
162                 window.minibuffer.insert_before(tree);
163                 tree.view = new completions_tree_view(this);
164                 this.completions_display_element = tree;
166                 /* This is the initial loading of this minibuffer
167                  * state.  If this.complete_initial is true, generate
168                  * completions. */
169                 if (this.auto_complete_initial)
170                     this.handle_input();
171             }
173             this.update_completions_display();
174         }
175     },
177     unload : function (window) {
178         if (this.completions_display_element)
179             this.completions_display_element.setAttribute("collapsed", "true");
180         basic_minibuffer_state.prototype.unload.call(this, window);
181     },
183     destroy : function (window) {
184         if (this.completions != null && this.completions.destroy)
185             this.completions.destroy();
186         delete this.completions;
187         if (this.completions_cont)
188             this.completions_cont.throw(abort());
189         delete this.completions_cont;
191         var el = this.completions_display_element;
192         if (el) {
193             el.parentNode.removeChild(el);
194             this.completions_display_element = null;
195         }
196         if (this.continuation)
197             this.continuation.throw(abort());
198         basic_minibuffer_state.prototype.destroy.call(this, window);
199     },
201     handle_input : function () {
202         if (!this.completer) return;
204         this.completions_valid = false;
206         if (!this.auto_complete) return;
208         var s = this;
210         if (this.auto_complete_delay > 0) {
211             if (this.completions_timer_ID != null)
212                 this.window.clearTimeout(this.completions_timer_ID);
213             this.completions_timer_ID = this.window.setTimeout(
214                 function () {
215                     s.completions_timer_ID = null;
216                     s.update_completions(true /* auto */, true /* update completions display */);
217                 }, this.auto_complete_delay);
218             return;
219         }
221         s.update_completions(true /* auto */, true /* update completions display */);
222     },
224     ran_minibuffer_command : function () {
225         this.handle_input();
226     },
228     update_completions_display : function () {
230         var m = this.window.minibuffer;
232         if (m.current_state == this) {
233             if (this.completions && this.completions.count > 0) {
234                 this.completions_display_element.view = this.completions_display_element.view;
235                 this.completions_display_element.setAttribute("collapsed", "false");
237                 this.completions_display_element.currentIndex = this.selected_completion_index;
238                 this.completions_display_element.treeBoxObject.scrollToRow(this.selected_completion_index);
239             } else {
240                 this.completions_display_element.setAttribute("collapsed", "true");
241             }
242         }
243     },
245     /* If auto is true, this update is due to auto completion, rather
246      * than specifically requested. */
247     update_completions : function (auto, update_display) {
249         if (this.completions_timer_ID != null) {
250             this.window.clearTimeout(this.completions_timer_ID);
251             this.completions_timer_ID = null;
252         }
254         let m = this.window.minibuffer;
256         if (this.completions_cont) {
257             this.completions_cont.throw(abort());
258             this.completions_cont = null;
259         }
261         let c = this.completer(m._input_text, m._selection_start,
262                                auto && this.auto_complete_conservative);
264         if (is_coroutine(c)) {
265             let s = this;
266             let already_done = false;
267             this.completions_cont = co_call(function () {
268                 var x;
269                 try {
270                     x = yield c;
271                 } finally {
272                     s.completions_cont = null;
273                     already_done = true;
274                 }
275                 s.update_completions_done(x, update_display);
276             }());
278             // In case the completer actually already finished
279             if (already_done)
280                 this.completions_cont = null;
281             return;
282         } else
283             this.update_completions_done(c, update_display);
284     },
286     update_completions_done : function update_completions_done (c, update_display) {
288         /* The completer should return undefined if completion was not
289          * attempted due to auto being true.  Otherwise, it can return
290          * null to indicate no completions. */
291         if (this.completions != null && this.completions.destroy)
292             this.completions.destroy();
294         this.completions = c;
295         this.completions_valid = true;
296         this.applied_common_prefix = false;
298         let i = -1;
299         if (c && c.count > 0) {
300             if (this.match_required) {
301                 if (c.count == 1)
302                     i = 0;
303                 else if (c.default_completion != null)
304                     i = c.default_completion;
305                 else if (this.default_completion && this.completions.index_of)
306                     i = this.completions.index_of(this.default_completion);
307             }
308             this.selected_completion_index = i;
309         }
311         if (update_display)
312             this.update_completions_display();
313     },
315     select_completion : function (i) {
316         this.selected_completion_index = i;
317         this.completions_display_element.currentIndex = i;
318         if (i >= 0)
319             this.completions_display_element.treeBoxObject.ensureRowIsVisible(i);
320         this.handle_completion_selected();
321     },
323     handle_completion_selected : function () {
324         /**
325          * When a completion is selected, apply it to the input text
326          * if a match is not "required"; otherwise, the completion is
327          * only displayed.
328          */
329         var i = this.selected_completion_index;
330         var m = this.window.minibuffer;
331         var c = this.completions;
333         if (this.completions_valid && c && !this.match_required && i >= 0 && i < c.count)
334         {
335             m.set_input_state(c.get_input_state(i));
336         }
337     }
340 function minibuffer_complete (window, count) {
341     var m = window.minibuffer;
342     var s = m.current_state;
343     if (!(s instanceof text_entry_minibuffer_state))
344         throw new Error("Invalid minibuffer state");
345     if (!s.completer)
346         return;
347     var just_completed_manually = false;
348     if (!s.completions_valid || s.completions === undefined) {
349         if (s.completions_timer_ID == null)
350             just_completed_manually = true;
351         s.update_completions(false /* not auto */, true /* update completions display */);
353         // If the completer is a coroutine, nothing we can do here
354         if (!s.completions_valid)
355             return;
356     }
358     var c = s.completions;
360     if (!c || c.count == 0)
361         return;
363     var e = s.completions_display_element;
364     var new_index = -1;
366     let common_prefix;
368     if (count == 1 && !s.applied_common_prefix && (common_prefix = c.common_prefix_input_state)) {
369         m.set_input_state(common_prefix);
370         s.applied_common_prefix = true;
371     } else if (!just_completed_manually) {
372         if (e.currentIndex != -1) {
373             new_index = (e.currentIndex + count) % c.count;
374             if (new_index < 0)
375                 new_index += c.count;
376         } else {
377             new_index = (count - 1) % c.count;
378             if (new_index < 0)
379                 new_index += c.count;
380         }
381     }
383     if (new_index != -1)
384         s.select_completion(new_index);
386 interactive("minibuffer-complete", null,
387     function (I) { minibuffer_complete(I.window, I.p); });
388 interactive("minibuffer-complete-previous", null,
389     function (I) { minibuffer_complete(I.window, -I.p); });
391 function exit_minibuffer (window) {
392     var m = window.minibuffer;
393     var s = m.current_state;
394     if (!(s instanceof text_entry_minibuffer_state))
395         throw new Error("Invalid minibuffer state");
397     var val = m._input_text;
399     if (s.validator != null && !s.validator(val, m))
400         return;
402     var match = null;
404     if (s.completer && s.match_required) {
405         if (!s.completions_valid || s.completions === undefined)
406             s.update_completions(false /* not conservative */, false /* don't update */);
408         let c = s.completions;
409         let i = s.selected_completion_index;
410         if (c != null && i >= 0 && i < c.count) {
411             if (c.get_value != null)
412                 match = c.get_value(i);
413             else
414                 match = c.get_string(i);
415         } else {
416             m.message("No match");
417             return;
418         }
419     }
421     if (s.history) {
422         s.history.push(val);
423         if (s.history.length > minibuffer_history_max_items)
424             s.history.splice(0, s.history.length - minibuffer_history_max_items);
425     }
426     var cont = s.continuation;
427     delete s.continuation;
428     m.pop_state();
429     if (cont) {
430         if (s.match_required)
431             cont(match);
432         else
433             cont(val);
434     }
436 interactive("exit-minibuffer", null,
437     function (I) { exit_minibuffer(I.window); });
439 function minibuffer_history_next (window, count) {
440     var m = window.minibuffer;
441     var s = m.current_state;
442     if (!(s instanceof text_entry_minibuffer_state))
443         throw new Error("Invalid minibuffer state");
444     if (!s.history || s.history.length == 0)
445         throw interactive_error("No history available.");
446     if (count == 0)
447         return;
448     var index = s.history_index;
449     if (count > 0 && index == -1)
450         throw interactive_error("End of history; no next item");
451     else if (count < 0 && index == 0) {
452         throw interactive_error("Beginning of history; no preceding item");
453     }
454     if (index == -1) {
455         s.saved_last_history_entry = m._input_text;
456         index = s.history.length + count;
457     } else
458         index = index + count;
460     if (index < 0)
461         index = 0;
463     m._restore_normal_state();
464     if (index >= s.history.length) {
465         index = -1;
466         m._input_text = s.saved_last_history_entry;
467     } else {
468         m._input_text = s.history[index];
469     }
470     s.history_index = index;
471     m._set_selection();
472     s.handle_input();
474 interactive("minibuffer-history-next", null,
475     function (I) { minibuffer_history_next(I.window, I.p); });
476 interactive("minibuffer-history-previous", null,
477     function (I) { minibuffer_history_next(I.window, -I.p); });
479 // Define the asynchronous minibuffer.read function
480 minibuffer.prototype.read = function () {
481     var s = new text_entry_minibuffer_state(this.window, (yield CONTINUATION), forward_keywords(arguments));
482     this.push_state(s);
483     var result = yield SUSPEND;
484     yield co_return(result);
487 minibuffer.prototype.read_command = function () {
488     keywords(
489         arguments,
490         $prompt = "Command", $history = "command",
491         $completer = prefix_completer(
492             $completions = function (visitor) interactive_commands.for_each_value(visitor),
493             $get_string = function (x) x.name,
494             $get_description = function (x) x.shortdoc || "",
495             $get_value = function (x) x.name),
496         $match_required = true);
497     var result = yield this.read(forward_keywords(arguments));
498     yield co_return(result);
501 minibuffer.prototype.read_user_variable = function () {
502     keywords(
503         arguments,
504         $prompt = "User variable", $history = "user_variable",
505         $completer = prefix_completer(
506             $completions = function (visitor) {
507                 for (var i in user_variables) visitor(i);
508             },
509             $get_string = function (x) x,
510             $get_description = function (x) user_variables[x].shortdoc || "",
511             $get_value = function (x) x),
512         $match_required = true);
513     var result = yield this.read(forward_keywords(arguments));
514     yield co_return(result);
517 minibuffer.prototype.read_preference = function minibuffer__read_preference () {
518     keywords(arguments,
519              $prompt = "Preference:", $history = "preference",
520              $completer = prefix_completer(
521                  $completions = preferences.getBranch(null).getChildList("", {}),
522                  $get_description = function (pref) {
523                      let default_value = get_default_pref(pref);
524                      let value = get_pref(pref);
525                      if (value == default_value)
526                          value = null;
527                      let type;
528                      switch (preferences.getBranch(null).getPrefType(pref)) {
529                      case Ci.nsIPrefBranch.PREF_STRING:
530                          type = "string";
531                          break;
532                      case Ci.nsIPrefBranch.PREF_INT:
533                          type = "int";
534                          break;
535                      case Ci.nsIPrefBranch.PREF_BOOL:
536                          type = "boolean";
537                          break;
538                      }
539                      let out = type + ":";
540                      if (value != null)
541                          out += " " + pretty_print_value(value);
542                      if (default_value != null)
543                          out += " (" + pretty_print_value(default_value) + ")";
544                      return out;
545                  }),
546              $match_required = true);
547     var result = yield this.read(forward_keywords(arguments));
548     yield co_return(result);