Source code

Revision control

Line Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<?xml version="1.0"?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
   - License, v. 2.0. If a copy of the MPL was not distributed with this
   - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->

<!-- XULCommandEvent is a specialised global. -->
<!-- global XULCommandEvent -->

<!DOCTYPE bindings [
<!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd">
%browserDTD;
]>

<bindings id="SearchBindings"
          xmlns="http://www.mozilla.org/xbl"
          xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
          xmlns:xbl="http://www.mozilla.org/xbl">

  <binding id="searchbar-textbox"
      extends="chrome://global/content/bindings/autocomplete.xml#autocomplete">
    <implementation>
      <constructor><![CDATA[
        if (this.closest("searchbar").parentNode.parentNode.localName ==
            "toolbarpaletteitem")
          return;

        if (Services.prefs.getBoolPref("browser.urlbar.clickSelectsAll"))
          this.setAttribute("clickSelectsAll", true);

        let textBox = document.getAnonymousElementByAttribute(this,
                                              "anonid", "moz-input-box");

        // Force the Custom Element to upgrade until Bug 1470242 handles this:
        customElements.upgrade(textBox);
        let cxmenu = textBox.menupopup;
        cxmenu.addEventListener("popupshowing",
                                () => { this.initContextMenu(cxmenu); },
                                {capture: true, once: true});

        this.setAttribute("aria-owns", this.popup.id);
        this.closest("searchbar")._textboxInitialized = true;
      ]]></constructor>

      <destructor><![CDATA[
        // If the context menu has never been opened, there won't be anything
        // to remove here.
        // Also, XBL and the customize toolbar code sometimes interact poorly.
        try {
          this.controllers.removeController(this.searchbarController);
        } catch (ex) { }
      ]]></destructor>

      // Add items to context menu and attach controller to handle them the
      // first time the context menu is opened.
      <method name="initContextMenu">
        <parameter name="aMenu"/>
        <body><![CDATA[
          let stringBundle = this.closest("searchbar")._stringBundle;

          let pasteAndSearch, suggestMenuItem;
          let element, label, akey;

          element = document.createXULElement("menuseparator");
          aMenu.appendChild(element);

          let insertLocation = aMenu.firstElementChild;
          while (insertLocation.nextElementSibling &&
                 insertLocation.getAttribute("cmd") != "cmd_paste")
            insertLocation = insertLocation.nextElementSibling;
          if (insertLocation) {
            element = document.createXULElement("menuitem");
            label = stringBundle.getString("cmd_pasteAndSearch");
            element.setAttribute("label", label);
            element.setAttribute("anonid", "paste-and-search");
            element.setAttribute("oncommand", "BrowserSearch.pasteAndSearch(event)");
            aMenu.insertBefore(element, insertLocation.nextElementSibling);
            pasteAndSearch = element;
          }

          element = document.createXULElement("menuitem");
          label = stringBundle.getString("cmd_clearHistory");
          akey = stringBundle.getString("cmd_clearHistory_accesskey");
          element.setAttribute("label", label);
          element.setAttribute("accesskey", akey);
          element.setAttribute("cmd", "cmd_clearhistory");
          aMenu.appendChild(element);

          element = document.createXULElement("menuitem");
          label = stringBundle.getString("cmd_showSuggestions");
          akey = stringBundle.getString("cmd_showSuggestions_accesskey");
          element.setAttribute("anonid", "toggle-suggest-item");
          element.setAttribute("label", label);
          element.setAttribute("accesskey", akey);
          element.setAttribute("cmd", "cmd_togglesuggest");
          element.setAttribute("type", "checkbox");
          element.setAttribute("autocheck", "false");
          suggestMenuItem = element;
          aMenu.appendChild(element);

          if (AppConstants.platform == "macosx") {
            this.addEventListener("keypress", aEvent => {
              if (aEvent.keyCode == KeyEvent.DOM_VK_F4)
                this.openSearch();
            }, true);
          }

          this.controllers.appendController(this.searchbarController);

          let onpopupshowing = function() {
            BrowserSearch.searchBar._textbox.closePopup();
            if (suggestMenuItem) {
              let enabled =
                Services.prefs.getBoolPref("browser.search.suggest.enabled");
              suggestMenuItem.setAttribute("checked", enabled);
            }

            if (!pasteAndSearch)
              return;
            let controller = document.commandDispatcher.getControllerForCommand("cmd_paste");
            let enabled = controller.isCommandEnabled("cmd_paste");
            if (enabled)
              pasteAndSearch.removeAttribute("disabled");
            else
              pasteAndSearch.setAttribute("disabled", "true");
          };
          aMenu.addEventListener("popupshowing", onpopupshowing);
          onpopupshowing();
        ]]></body>
      </method>

      <!--
        This overrides the searchParam property in autocomplete.xml.  We're
        hijacking this property as a vehicle for delivering the privacy
        information about the window into the guts of nsSearchSuggestions.

        Note that the setter is the same as the parent.  We were not sure whether
        we can override just the getter.  If that proves to be the case, the setter
        can be removed.
      -->
      <property name="searchParam"
                onget="return this.getAttribute('autocompletesearchparam') +
                       (PrivateBrowsingUtils.isWindowPrivate(window) ? '|private' : '');"
                onset="this.setAttribute('autocompletesearchparam', val); return val;"/>

      <!-- This is implemented so that when textbox.value is set directly (e.g.,
           by tests), the one-off query is updated. -->
      <method name="onBeforeValueSet">
        <parameter name="aValue"/>
        <body><![CDATA[
          this.popup.oneOffButtons.query = aValue;
          return aValue;
        ]]></body>
      </method>

      <!--
        This method overrides the autocomplete binding's openPopup (essentially
        duplicating the logic from the autocomplete popup binding's
        openAutocompletePopup method), modifying it so that the popup is aligned with
        the inner textbox, but sized to not extend beyond the search bar border.
      -->
      <method name="openPopup">
        <body><![CDATA[
          // Entering customization mode after the search bar had focus causes
          // the popup to appear again, due to focus returning after the
          // hamburger panel closes. Don't open in that spurious event.
          if (document.documentElement.getAttribute("customizing") == "true") {
            return;
          }

          let popup = this.popup;
          if (!popup.mPopupOpen) {
            // Initially the panel used for the searchbar (PopupSearchAutoComplete
            // in browser.xul) is hidden to avoid impacting startup / new
            // window performance. The base binding's openPopup would normally
            // call the overriden openAutocompletePopup in
            // browser-search-autocomplete-result-popup binding to unhide the popup,
            // but since we're overriding openPopup we need to unhide the panel
            // ourselves.
            popup.hidden = false;

            // Don't roll up on mouse click in the anchor for the search UI.
            if (popup.id == "PopupSearchAutoComplete") {
              popup.setAttribute("norolluponanchor", "true");
            }

            popup.mInput = this;
            // clear any previous selection, see bugs 400671 and 488357
            popup.selectedIndex = -1;

            document.popupNode = null;

            let outerRect = this.getBoundingClientRect();
            let innerRect = this.inputField.getBoundingClientRect();
            let width = RTL_UI ?
                        innerRect.right - outerRect.left :
                        outerRect.right - innerRect.left;
            popup.setAttribute("width", width > 100 ? width : 100);

            // invalidate() depends on the width attribute
            popup._invalidate();

            let yOffset = outerRect.bottom - innerRect.bottom;
            popup.openPopup(this.inputField, "after_start", 0, yOffset, false, false);
          }
        ]]></body>
      </method>

      <method name="openSearch">
        <body>
          <![CDATA[
            if (!this.popupOpen) {
              this.closest("searchbar").openSuggestionsPanel();
              return false;
            }
            return true;
          ]]>
        </body>
      </method>

      <method name="handleEnter">
        <parameter name="event"/>
        <body><![CDATA[
          // Toggle the open state of the add-engine menu button if it's
          // selected.  We're using handleEnter for this instead of listening
          // for the command event because a command event isn't fired.
          if (this.selectedButton &&
              this.selectedButton.getAttribute("anonid") ==
                "addengine-menu-button") {
            this.selectedButton.open = !this.selectedButton.open;
            return true;
          }
          // Otherwise, "call super": do what the autocomplete binding's
          // handleEnter implementation does.
          return this.mController.handleEnter(false, event || null);
        ]]></body>
      </method>

      <!-- override |onTextEntered| in autocomplete.xml -->
      <method name="onTextEntered">
        <parameter name="aEvent"/>
        <body><![CDATA[
          let engine;
          let oneOff = this.selectedButton;
          if (oneOff) {
            if (!oneOff.engine) {
              oneOff.doCommand();
              return;
            }
            engine = oneOff.engine;
          }
          if (this._selectionDetails) {
            BrowserSearch.searchBar.telemetrySearchDetails = this._selectionDetails;
            this._selectionDetails = null;
          }
          this.closest("searchbar").handleSearchCommand(aEvent, engine);
        ]]></body>
      </method>

      <property name="selectedButton">
        <getter><![CDATA[
          return this.popup.oneOffButtons.selectedButton;
        ]]></getter>
        <setter><![CDATA[
          return this.popup.oneOffButtons.selectedButton = val;
        ]]></setter>
      </property>

      <method name="handleKeyboardNavigation">
        <parameter name="aEvent"/>
        <body><![CDATA[
          let popup = this.popup;
          if (!popup.popupOpen)
            return;

          // accel + up/down changes the default engine and shouldn't affect
          // the selection on the one-off buttons.
          if (aEvent.getModifierState("Accel"))
            return;

          let suggestionsHidden =
            popup.richlistbox.getAttribute("collapsed") == "true";
          let numItems = suggestionsHidden ? 0 : this.popup.matchCount;
          this.popup.oneOffButtons.handleKeyPress(aEvent, numItems, true);
        ]]></body>
      </method>

      <!-- nsIController -->
      <field name="searchbarController" readonly="true"><![CDATA[({
        _self: this,
        supportsCommand(aCommand) {
          return aCommand == "cmd_clearhistory" ||
                 aCommand == "cmd_togglesuggest";
        },

        isCommandEnabled(aCommand) {
          return true;
        },

        doCommand(aCommand) {
          switch (aCommand) {
            case "cmd_clearhistory":
              let param = this._self.getAttribute("autocompletesearchparam");

              BrowserSearch.searchBar.FormHistory.update({ op: "remove", fieldname: param }, null);
              this._self.value = "";
              break;
            case "cmd_togglesuggest":
              let enabled =
                Services.prefs.getBoolPref("browser.search.suggest.enabled");
              Services.prefs.setBoolPref("browser.search.suggest.enabled",
                                         !enabled);
              break;
            default:
              // do nothing with unrecognized command
          }
        },
      })]]></field>
    </implementation>

    <handlers>
      <handler event="input"><![CDATA[
        this.popup.removeAttribute("showonlysettings");
      ]]></handler>

      <handler event="keypress" phase="capturing"
               action="return this.handleKeyboardNavigation(event);"/>

      <handler event="keypress" keycode="VK_UP" modifiers="accel"
               phase="capturing"
               action='this.closest("searchbar").selectEngine(event, false);'/>

      <handler event="keypress" keycode="VK_DOWN" modifiers="accel"
               phase="capturing"
               action='this.closest("searchbar").selectEngine(event, true);'/>

      <handler event="keypress" keycode="VK_DOWN" modifiers="alt"
               phase="capturing"
               action="return this.openSearch();"/>

      <handler event="keypress" keycode="VK_UP" modifiers="alt"
               phase="capturing"
               action="return this.openSearch();"/>

      <handler event="dragover">
      <![CDATA[
        let types = event.dataTransfer.types;
        if (types.includes("text/plain") || types.includes("text/x-moz-text-internal"))
          event.preventDefault();
      ]]>
      </handler>

      <handler event="drop">
      <![CDATA[
        let dataTransfer = event.dataTransfer;
        let data = dataTransfer.getData("text/plain");
        if (!data)
          data = dataTransfer.getData("text/x-moz-text-internal");
        if (data) {
          event.preventDefault();
          this.value = data;
          this.closest("searchbar").openSuggestionsPanel();
        }
      ]]>
      </handler>

    </handlers>
  </binding>

  <binding id="browser-search-autocomplete-result-popup" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete-rich-result-popup">
    <content ignorekeys="true" level="top" consumeoutsideclicks="never">
      <xul:hbox anonid="searchbar-engine" xbl:inherits="showonlysettings"
                class="search-panel-header search-panel-current-engine">
        <xul:image class="searchbar-engine-image" xbl:inherits="src"/>
        <xul:label anonid="searchbar-engine-name" flex="1" crop="end"
                   role="presentation"/>
      </xul:hbox>
      <xul:richlistbox anonid="richlistbox" class="autocomplete-richlistbox search-panel-tree" flex="1"/>
      <xul:hbox anonid="search-one-off-buttons" class="search-one-offs"/>
    </content>
    <implementation>
      <method name="openAutocompletePopup">
        <parameter name="aInput"/>
        <parameter name="aElement"/>
        <body><![CDATA[
          // initially the panel is hidden
          // to avoid impacting startup / new window performance
          aInput.popup.hidden = false;

          // this method is defined on the base binding
          this._openAutocompletePopup(aInput, aElement);
        ]]></body>
      </method>

      <method name="onPopupClick">
        <parameter name="aEvent"/>
        <body><![CDATA[
          // Ignore all right-clicks
          if (aEvent.button == 2)
            return;

          let searchBar = BrowserSearch.searchBar;
          let popupForSearchBar = searchBar && searchBar.textbox == this.mInput;
          if (popupForSearchBar) {
            searchBar.telemetrySearchDetails = {
              index: this.selectedIndex,
              kind: "mouse",
            };
          }

          // Check for unmodified left-click, and use default behavior
          if (aEvent.button == 0 && !aEvent.shiftKey && !aEvent.ctrlKey &&
              !aEvent.altKey && !aEvent.metaKey) {
            this.input.controller.handleEnter(true, aEvent);
            return;
          }

          // Check for middle-click or modified clicks on the search bar
          if (popupForSearchBar) {
            BrowserUsageTelemetry.recordSearchbarSelectedResultMethod(
              aEvent,
              this.selectedIndex
            );

            // Handle search bar popup clicks
            let search = this.input.controller.getValueAt(this.selectedIndex);

            // open the search results according to the clicking subtlety
            let where = whereToOpenLink(aEvent, false, true);
            let params = {};

            // But open ctrl/cmd clicks on autocomplete items in a new background tab.
            let modifier = AppConstants.platform == "macosx" ?
                           aEvent.metaKey :
                           aEvent.ctrlKey;
            if (where == "tab" && (aEvent instanceof MouseEvent) &&
                (aEvent.button == 1 || modifier))
              params.inBackground = true;

            // leave the popup open for background tab loads
            if (!(where == "tab" && params.inBackground)) {
              // close the autocomplete popup and revert the entered search term
              this.closePopup();
              this.input.controller.handleEscape();
            }

            searchBar.doSearch(search, where, null, params);
            if (where == "tab" && params.inBackground)
              searchBar.focus();
            else
              searchBar.value = search;
          }
        ]]></body>
      </method>

      <!-- Popup rollup is triggered by native events before the mousedown event
           reaches the DOM. The will be set to true by the popuphiding event and
           false after the mousedown event has been triggered to detect what
           caused rollup. -->
      <field name="_isHiding">false</field>
      <field name="_bundle">null</field>
      <property name="bundle" readonly="true">
        <getter>
          <![CDATA[
            if (!this._bundle) {
              const kBundleURI = "chrome://browser/locale/search.properties";
              this._bundle = Services.strings.createBundle(kBundleURI);
            }
            return this._bundle;
          ]]>
        </getter>
      </property>

      <field name="oneOffButtons" readonly="true">
        new SearchOneOffs(
          document.getAnonymousElementByAttribute(this, "anonid",
                                                  "search-one-off-buttons"));
      </field>

      <method name="updateHeader">
        <body><![CDATA[
          let currentEngine = Services.search.defaultEngine;
          let uri = currentEngine.iconURI;
          if (uri) {
            this.setAttribute("src", uri.spec);
          } else {
            // If the default has just been changed to a provider without icon,
            // avoid showing the icon of the previous default provider.
            this.removeAttribute("src");
          }

          let headerText = this.bundle.formatStringFromName("searchHeader",
                                                            [currentEngine.name], 1);
          document.getAnonymousElementByAttribute(this, "anonid", "searchbar-engine-name")
                  .setAttribute("value", headerText);
          document.getAnonymousElementByAttribute(this, "anonid", "searchbar-engine")
                  .engine = currentEngine;
        ]]></body>
      </method>

      <!-- This is called when a one-off is clicked and when "search in new tab"
           is selected from a one-off context menu. -->
      <method name="handleOneOffSearch">
        <parameter name="event"/>
        <parameter name="engine"/>
        <parameter name="where"/>
        <parameter name="params"/>
        <body><![CDATA[
          let searchbar = document.getElementById("searchbar");
          searchbar.handleSearchCommandWhere(event, engine, where, params);
        ]]></body>
      </method>
    </implementation>

    <handlers>
      <handler event="popupshowing"><![CDATA[
        // Force the panel to have the width of the searchbar rather than
        // the width of the textfield.
        let DOMUtils = window.windowUtils;
        let textboxRect = DOMUtils.getBoundsWithoutFlushing(this.mInput);
        let inputRect = DOMUtils.getBoundsWithoutFlushing(this.mInput.inputField);

        // Ensure the panel is wide enough to fit at least 3 engines.
        let minWidth = Math.max(textboxRect.width,
                                this.oneOffButtons.buttonWidth * 3);
        this.style.minWidth = Math.round(minWidth) + "px";
        // Alignment of the panel with the searchbar is obtained with negative
        // margins.
        this.style.marginLeft = (textboxRect.left - inputRect.left) + "px";
        // This second margin is needed when the direction is reversed,
        // eg. when using command+shift+X.
        this.style.marginRight = (inputRect.right - textboxRect.right) + "px";

        // First handle deciding if we are showing the reduced version of the
        // popup containing only the preferences button. We do this if the
        // glass icon has been clicked if the text field is empty.
        let searchbar = document.getElementById("searchbar");
        if (searchbar.hasAttribute("showonlysettings")) {
          searchbar.removeAttribute("showonlysettings");
          this.setAttribute("showonlysettings", "true");

          // Setting this with an xbl-inherited attribute gets overridden the
          // second time the user clicks the glass icon for some reason...
          this.richlistbox.collapsed = true;
        } else {
          this.removeAttribute("showonlysettings");
          // Uncollapse as long as we have a view which has >= 1 row.
          // The autocomplete binding itself will take care of uncollapsing later,
          // if we currently have no rows but end up having some in the future
          // when the search string changes
          this.richlistbox.collapsed = (this.matchCount == 0);
        }

        // Show the current default engine in the top header of the panel.
        this.updateHeader();
      ]]></handler>

      <handler event="popuphiding"><![CDATA[
        this._isHiding = true;
        Services.tm.dispatchToMainThread(() => {
          this._isHiding = false;
        });
      ]]></handler>

      <!-- This handles clicks on the topmost "Foo Search" header in the
           popup (hbox[anonid="searchbar-engine"]). -->
      <handler event="click"><![CDATA[
        if (event.button == 2) {
          // Ignore right clicks.
          return;
        }
        let button = event.originalTarget;
        let engine = button.parentNode.engine;
        if (!engine) {
          return;
        }
        this.oneOffButtons.handleSearchCommand(event, engine);
      ]]></handler>
    </handlers>

  </binding>

</bindings>