summaryrefslogtreecommitdiffstats
path: root/dom/xul/XULMenuParentElement.cpp
blob: f2e4d1e5721fd2735eb4c698415ca5020a37b754 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */

#include "XULMenuParentElement.h"
#include "XULButtonElement.h"
#include "XULMenuBarElement.h"
#include "XULPopupElement.h"
#include "mozilla/LookAndFeel.h"
#include "mozilla/StaticAnalysisFunctions.h"
#include "mozilla/TextEvents.h"
#include "mozilla/dom/DocumentInlines.h"
#include "mozilla/dom/KeyboardEvent.h"
#include "mozilla/EventDispatcher.h"
#include "nsDebug.h"
#include "nsMenuPopupFrame.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsUTF8Utils.h"
#include "nsXULElement.h"
#include "nsXULPopupManager.h"

namespace mozilla::dom {

NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED_0(XULMenuParentElement,
                                               nsXULElement)
NS_IMPL_CYCLE_COLLECTION_INHERITED(XULMenuParentElement, nsXULElement,
                                   mActiveItem)

XULMenuParentElement::XULMenuParentElement(
    already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo)
    : nsXULElement(std::move(aNodeInfo)) {}

XULMenuParentElement::~XULMenuParentElement() = default;

class MenuActivateEvent final : public Runnable {
 public:
  MenuActivateEvent(Element* aMenu, bool aIsActivate)
      : Runnable("MenuActivateEvent"), mMenu(aMenu), mIsActivate(aIsActivate) {}

  // TODO: Convert this to MOZ_CAN_RUN_SCRIPT (bug 1415230, bug 1535398)
  MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override {
    nsAutoString domEventToFire;
    if (mIsActivate) {
      // Highlight the menu.
      mMenu->SetAttr(kNameSpaceID_None, nsGkAtoms::menuactive, u"true"_ns,
                     true);
      // The menuactivated event is used by accessibility to track the user's
      // movements through menus
      domEventToFire.AssignLiteral("DOMMenuItemActive");
    } else {
      // Unhighlight the menu.
      mMenu->UnsetAttr(kNameSpaceID_None, nsGkAtoms::menuactive, true);
      domEventToFire.AssignLiteral("DOMMenuItemInactive");
    }

    RefPtr<nsPresContext> pc = mMenu->OwnerDoc()->GetPresContext();
    RefPtr<dom::Event> event = NS_NewDOMEvent(mMenu, pc, nullptr);
    event->InitEvent(domEventToFire, true, true);

    event->SetTrusted(true);

    EventDispatcher::DispatchDOMEvent(mMenu, nullptr, event, pc, nullptr);
    return NS_OK;
  }

 private:
  const RefPtr<Element> mMenu;
  bool mIsActivate;
};

static void ActivateOrDeactivate(XULButtonElement& aButton, bool aActivate) {
  if (!aButton.IsMenu()) {
    return;
  }

  if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
    if (aActivate) {
      // Cancel the close timer if selecting a menu within the popup to be
      // closed.
      pm->CancelMenuTimer(aButton.GetContainingPopupWithoutFlushing());
    } else if (auto* popup = aButton.GetMenuPopupWithoutFlushing()) {
      if (popup->IsOpen()) {
        // Set up the close timer if deselecting an open sub-menu.
        pm->HidePopupAfterDelay(popup, aButton.MenuOpenCloseDelay());
      }
    }
  }

  nsCOMPtr<nsIRunnable> event = new MenuActivateEvent(&aButton, aActivate);
  aButton.OwnerDoc()->Dispatch(TaskCategory::Other, event.forget());
}

XULButtonElement* XULMenuParentElement::GetContainingMenu() const {
  if (IsMenuBar()) {
    return nullptr;
  }
  auto* button = XULButtonElement::FromNodeOrNull(GetParent());
  if (!button || !button->IsMenu()) {
    return nullptr;
  }
  return button;
}

void XULMenuParentElement::LockMenuUntilClosed(bool aLock) {
  if (IsMenuBar()) {
    return;
  }
  mLocked = aLock;
  // Lock/Unlock the parent menu too.
  if (XULButtonElement* menu = GetContainingMenu()) {
    if (XULMenuParentElement* parent = menu->GetMenuParent()) {
      parent->LockMenuUntilClosed(aLock);
    }
  }
}

void XULMenuParentElement::SetActiveMenuChild(XULButtonElement* aChild,
                                              ByKey aByKey) {
  if (aChild == mActiveItem) {
    return;
  }

  if (mActiveItem) {
    ActivateOrDeactivate(*mActiveItem, false);
  }
  mActiveItem = nullptr;

  if (auto* menuBar = XULMenuBarElement::FromNode(*this)) {
    // KnownLive because `this` is known-live by definition.
    MOZ_KnownLive(menuBar)->SetActive(!!aChild);
  }

  if (!aChild) {
    return;
  }

  // When a menu opens a submenu, the mouse will often be moved onto a sibling
  // before moving onto an item within the submenu, causing the parent to become
  // deselected. We need to ensure that the parent menu is reselected when an
  // item in the submenu is selected.
  if (RefPtr menu = GetContainingMenu()) {
    if (RefPtr parent = menu->GetMenuParent()) {
      parent->SetActiveMenuChild(menu, aByKey);
    }
  }

  mActiveItem = aChild;
  ActivateOrDeactivate(*mActiveItem, true);

  if (IsInMenuList()) {
    if (nsMenuPopupFrame* f = do_QueryFrame(GetPrimaryFrame())) {
      f->EnsureActiveMenuListItemIsVisible();
#ifdef XP_WIN
      // On Windows, a menulist should update its value whenever navigation was
      // done by the keyboard.
      //
      // NOTE(emilio): This is a rather odd per-platform behavior difference,
      // but other browsers also do this.
      if (aByKey == ByKey::Yes && f->IsOpen()) {
        // Fire a command event as the new item, but we don't want to close the
        // menu, blink it, or update any other state of the menuitem. The
        // command event will cause the item to be selected.
        RefPtr<mozilla::PresShell> presShell = OwnerDoc()->GetPresShell();
        nsContentUtils::DispatchXULCommand(aChild, /* aTrusted = */ true,
                                           nullptr, presShell, false, false,
                                           false, false);
      }
#endif
    }
  }
}

static bool IsValidMenuItem(const XULMenuParentElement& aMenuParent,
                            const nsIContent& aContent) {
  const auto* button = XULButtonElement::FromNode(aContent);
  if (!button || !button->IsMenu()) {
    return false;
  }
  if (!button->GetPrimaryFrame()) {
    // Hidden buttons are not focusable/activatable.
    return false;
  }
  if (!button->IsDisabled()) {
    return true;
  }
  // In the menubar or a menulist disabled items are always skipped.
  const bool skipDisabled =
      LookAndFeel::GetInt(LookAndFeel::IntID::SkipNavigatingDisabledMenuItem) ||
      aMenuParent.IsMenuBar() || aMenuParent.IsInMenuList();
  return !skipDisabled;
}

enum class StartKind { Parent, Item };

template <bool aForward>
static XULButtonElement* DoGetNextMenuItem(
    const XULMenuParentElement& aMenuParent, const nsIContent& aStart,
    StartKind aStartKind) {
  nsIContent* start =
      aStartKind == StartKind::Item
          ? (aForward ? aStart.GetNextSibling() : aStart.GetPreviousSibling())
          : (aForward ? aStart.GetFirstChild() : aStart.GetLastChild());
  for (nsIContent* node = start; node;
       node = aForward ? node->GetNextSibling() : node->GetPreviousSibling()) {
    if (IsValidMenuItem(aMenuParent, *node)) {
      return static_cast<XULButtonElement*>(node);
    }
    if (node->IsXULElement(nsGkAtoms::menugroup)) {
      if (XULButtonElement* child = DoGetNextMenuItem<aForward>(
              aMenuParent, *node, StartKind::Parent)) {
        return child;
      }
    }
  }
  if (aStartKind == StartKind::Item && aStart.GetParent() &&
      aStart.GetParent()->IsXULElement(nsGkAtoms::menugroup)) {
    // We haven't found anything in aStart's sibling list, but if we're in a
    // group we need to keep looking.
    return DoGetNextMenuItem<aForward>(aMenuParent, *aStart.GetParent(),
                                       StartKind::Item);
  }
  return nullptr;
}

XULButtonElement* XULMenuParentElement::GetFirstMenuItem() const {
  return DoGetNextMenuItem<true>(*this, *this, StartKind::Parent);
}

XULButtonElement* XULMenuParentElement::GetLastMenuItem() const {
  return DoGetNextMenuItem<false>(*this, *this, StartKind::Parent);
}

XULButtonElement* XULMenuParentElement::GetNextMenuItemFrom(
    const XULButtonElement& aStartingItem) const {
  return DoGetNextMenuItem<true>(*this, aStartingItem, StartKind::Item);
}

XULButtonElement* XULMenuParentElement::GetPrevMenuItemFrom(
    const XULButtonElement& aStartingItem) const {
  return DoGetNextMenuItem<false>(*this, aStartingItem, StartKind::Item);
}

XULButtonElement* XULMenuParentElement::GetNextMenuItem(Wrap aWrap) const {
  if (mActiveItem) {
    if (auto* next = GetNextMenuItemFrom(*mActiveItem)) {
      return next;
    }
    if (aWrap == Wrap::No) {
      return nullptr;
    }
  }
  return GetFirstMenuItem();
}

XULButtonElement* XULMenuParentElement::GetPrevMenuItem(Wrap aWrap) const {
  if (mActiveItem) {
    if (auto* prev = GetPrevMenuItemFrom(*mActiveItem)) {
      return prev;
    }
    if (aWrap == Wrap::No) {
      return nullptr;
    }
  }
  return GetLastMenuItem();
}

void XULMenuParentElement::SelectFirstItem() {
  if (RefPtr firstItem = GetFirstMenuItem()) {
    SetActiveMenuChild(firstItem);
  }
}

XULButtonElement* XULMenuParentElement::FindMenuWithShortcut(
    KeyboardEvent& aKeyEvent) const {
  using AccessKeyArray = AutoTArray<uint32_t, 10>;
  AccessKeyArray accessKeys;
  WidgetKeyboardEvent* nativeKeyEvent =
      aKeyEvent.WidgetEventPtr()->AsKeyboardEvent();
  if (nativeKeyEvent) {
    nativeKeyEvent->GetAccessKeyCandidates(accessKeys);
  }
  const uint32_t charCode = aKeyEvent.CharCode();
  if (accessKeys.IsEmpty() && charCode) {
    accessKeys.AppendElement(charCode);
  }
  if (accessKeys.IsEmpty()) {
    return nullptr;  // no character was pressed so just return
  }
  XULButtonElement* foundMenu = nullptr;
  size_t foundIndex = AccessKeyArray::NoIndex;
  for (auto* item = GetFirstMenuItem(); item;
       item = GetNextMenuItemFrom(*item)) {
    nsAutoString shortcutKey;
    item->GetAttr(nsGkAtoms::accesskey, shortcutKey);
    if (shortcutKey.IsEmpty()) {
      continue;
    }

    ToLowerCase(shortcutKey);
    const char16_t* start = shortcutKey.BeginReading();
    const char16_t* end = shortcutKey.EndReading();
    uint32_t ch = UTF16CharEnumerator::NextChar(&start, end);
    size_t index = accessKeys.IndexOf(ch);
    if (index == AccessKeyArray::NoIndex) {
      continue;
    }
    if (foundIndex == AccessKeyArray::NoIndex || index < foundIndex) {
      foundMenu = item;
      foundIndex = index;
    }
  }
  return foundMenu;
}

XULButtonElement* XULMenuParentElement::FindMenuWithShortcut(
    const nsAString& aString, bool& aDoAction) const {
  aDoAction = false;
  uint32_t accessKeyMatchCount = 0;
  uint32_t matchCount = 0;

  XULButtonElement* foundAccessKeyMenu = nullptr;
  XULButtonElement* foundMenuBeforeCurrent = nullptr;
  XULButtonElement* foundMenuAfterCurrent = nullptr;

  bool foundActive = false;
  for (auto* item = GetFirstMenuItem(); item;
       item = GetNextMenuItemFrom(*item)) {
    nsAutoString textKey;
    // Get the shortcut attribute.
    item->GetAttr(nsGkAtoms::accesskey, textKey);
    const bool isAccessKey = !textKey.IsEmpty();
    if (textKey.IsEmpty()) {  // No shortcut, try first letter
      item->GetAttr(nsGkAtoms::label, textKey);
      if (textKey.IsEmpty()) {  // No label, try another attribute (value)
        item->GetAttr(nsGkAtoms::value, textKey);
      }
    }

    const bool isActive = item == GetActiveMenuChild();
    foundActive |= isActive;

    if (!StringBeginsWith(
            nsContentUtils::TrimWhitespace<
                nsContentUtils::IsHTMLWhitespaceOrNBSP>(textKey, false),
            aString, nsCaseInsensitiveStringComparator)) {
      continue;
    }
    // There is one match
    matchCount++;
    if (isAccessKey) {
      // There is one shortcut-key match
      accessKeyMatchCount++;
      // Record the matched item. If there is only one matched shortcut
      // item, do it
      foundAccessKeyMenu = item;
    }
    // Get the active status
    if (isActive && aString.Length() > 1 && !foundMenuBeforeCurrent) {
      // If there is more than one char typed and the current item matches, the
      // current item has highest priority, otherwise the item next to current
      // has highest priority.
      return item;
    }
    if (!foundActive || isActive) {
      // It's a first candidate item located before/on the current item
      if (!foundMenuBeforeCurrent) {
        foundMenuBeforeCurrent = item;
      }
    } else {
      if (!foundMenuAfterCurrent) {
        foundMenuAfterCurrent = item;
      }
    }
  }

  aDoAction = !IsInMenuList() && (matchCount == 1 || accessKeyMatchCount == 1);

  if (accessKeyMatchCount == 1) {
    // We have one matched accesskey item
    return foundAccessKeyMenu;
  }
  // If we have matched an item after the current, use it.
  if (foundMenuAfterCurrent) {
    return foundMenuAfterCurrent;
  }
  // If we haven't, use the item before the current, if any.
  return foundMenuBeforeCurrent;
}

void XULMenuParentElement::HandleEnterKeyPress(WidgetEvent& aEvent) {
  if (RefPtr child = GetActiveMenuChild()) {
    child->HandleEnterKeyPress(aEvent);
  }
}

}  // namespace mozilla::dom