Source code

Revision control

Other Tools

1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
* License, v. 2.0. If a copy of the MPL was not distributed with this
5
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "nscore.h"
8
#include "nsCOMPtr.h"
9
#include "nsUnicharUtils.h"
10
#include "nsListControlFrame.h"
11
#include "nsCheckboxRadioFrame.h" // for COMPARE macro
12
#include "nsGkAtoms.h"
13
#include "nsComboboxControlFrame.h"
14
#include "nsIXULRuntime.h"
15
#include "nsFontMetrics.h"
16
#include "nsIScrollableFrame.h"
17
#include "nsCSSRendering.h"
18
#include "nsIDOMEventListener.h"
19
#include "nsLayoutUtils.h"
20
#include "nsDisplayList.h"
21
#include "nsContentUtils.h"
22
#include "mozilla/Attributes.h"
23
#include "mozilla/dom/Event.h"
24
#include "mozilla/dom/HTMLOptGroupElement.h"
25
#include "mozilla/dom/HTMLOptionsCollection.h"
26
#include "mozilla/dom/HTMLSelectElement.h"
27
#include "mozilla/dom/MouseEvent.h"
28
#include "mozilla/dom/MouseEventBinding.h"
29
#include "mozilla/EventStateManager.h"
30
#include "mozilla/EventStates.h"
31
#include "mozilla/LookAndFeel.h"
32
#include "mozilla/MouseEvents.h"
33
#include "mozilla/Preferences.h"
34
#include "mozilla/PresShell.h"
35
#include "mozilla/TextEvents.h"
36
#include <algorithm>
37
38
using namespace mozilla;
39
using namespace mozilla::dom;
40
41
// Constants
42
const uint32_t kMaxDropDownRows = 20; // matches the setting for 4.x browsers
43
const int32_t kNothingSelected = -1;
44
45
// Static members
46
nsListControlFrame* nsListControlFrame::mFocused = nullptr;
47
nsString* nsListControlFrame::sIncrementalString = nullptr;
48
49
// Using for incremental typing navigation
50
#define INCREMENTAL_SEARCH_KEYPRESS_TIME 1000
51
// XXX, kyle.yuan@sun.com, there are 4 definitions for the same purpose:
52
// nsMenuPopupFrame.h, nsListControlFrame.cpp, listbox.xml, tree.xml
53
// need to find a good place to put them together.
54
// if someone changes one, please also change the other.
55
56
DOMTimeStamp nsListControlFrame::gLastKeyTime = 0;
57
58
/******************************************************************************
59
* nsListEventListener
60
* This class is responsible for propagating events to the nsListControlFrame.
61
* Frames are not refcounted so they can't be used as event listeners.
62
*****************************************************************************/
63
64
class nsListEventListener final : public nsIDOMEventListener {
65
public:
66
explicit nsListEventListener(nsListControlFrame* aFrame) : mFrame(aFrame) {}
67
68
void SetFrame(nsListControlFrame* aFrame) { mFrame = aFrame; }
69
70
NS_DECL_ISUPPORTS
71
72
// nsIDOMEventListener
73
MOZ_CAN_RUN_SCRIPT_BOUNDARY
74
NS_IMETHOD HandleEvent(Event* aEvent) override;
75
76
private:
77
~nsListEventListener() {}
78
79
nsListControlFrame* mFrame;
80
};
81
82
//---------------------------------------------------------
83
nsContainerFrame* NS_NewListControlFrame(PresShell* aPresShell,
84
ComputedStyle* aStyle) {
85
nsListControlFrame* it =
86
new (aPresShell) nsListControlFrame(aStyle, aPresShell->GetPresContext());
87
88
it->AddStateBits(NS_FRAME_INDEPENDENT_SELECTION);
89
90
return it;
91
}
92
93
NS_IMPL_FRAMEARENA_HELPERS(nsListControlFrame)
94
95
//---------------------------------------------------------
96
nsListControlFrame::nsListControlFrame(ComputedStyle* aStyle,
97
nsPresContext* aPresContext)
98
: nsHTMLScrollFrame(aStyle, aPresContext, kClassID, false),
99
mView(nullptr),
100
mMightNeedSecondPass(false),
101
mHasPendingInterruptAtStartOfReflow(false),
102
mDropdownCanGrow(false),
103
mForceSelection(false),
104
mLastDropdownComputedBSize(NS_UNCONSTRAINEDSIZE) {
105
mComboboxFrame = nullptr;
106
mChangesSinceDragStart = false;
107
mButtonDown = false;
108
109
mIsAllContentHere = false;
110
mIsAllFramesHere = false;
111
mHasBeenInitialized = false;
112
mNeedToReset = true;
113
mPostChildrenLoadedReset = false;
114
115
mControlSelectMode = false;
116
}
117
118
//---------------------------------------------------------
119
nsListControlFrame::~nsListControlFrame() { mComboboxFrame = nullptr; }
120
121
static bool ShouldFireDropDownEvent() {
122
return (XRE_IsContentProcess() &&
123
Preferences::GetBool("browser.tabs.remote.desktopbehavior", false)) ||
124
Preferences::GetBool("dom.select_popup_in_parent.enabled", false);
125
}
126
127
// for Bug 47302 (remove this comment later)
128
void nsListControlFrame::DestroyFrom(nsIFrame* aDestructRoot,
129
PostDestroyData& aPostDestroyData) {
130
// get the receiver interface from the browser button's content node
131
NS_ENSURE_TRUE_VOID(mContent);
132
133
// Clear the frame pointer on our event listener, just in case the
134
// event listener can outlive the frame.
135
136
mEventListener->SetFrame(nullptr);
137
138
mContent->RemoveSystemEventListener(NS_LITERAL_STRING("keydown"),
139
mEventListener, false);
140
mContent->RemoveSystemEventListener(NS_LITERAL_STRING("keypress"),
141
mEventListener, false);
142
mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mousedown"),
143
mEventListener, false);
144
mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mouseup"),
145
mEventListener, false);
146
mContent->RemoveSystemEventListener(NS_LITERAL_STRING("mousemove"),
147
mEventListener, false);
148
149
if (ShouldFireDropDownEvent()) {
150
nsContentUtils::AddScriptRunner(
151
new AsyncEventDispatcher(mContent, NS_LITERAL_STRING("mozhidedropdown"),
152
CanBubble::eYes, ChromeOnlyDispatch::eYes));
153
}
154
155
nsCheckboxRadioFrame::RegUnRegAccessKey(static_cast<nsIFrame*>(this), false);
156
nsHTMLScrollFrame::DestroyFrom(aDestructRoot, aPostDestroyData);
157
}
158
159
void nsListControlFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
160
const nsDisplayListSet& aLists) {
161
// We allow visibility:hidden <select>s to contain visible options.
162
163
// Don't allow painting of list controls when painting is suppressed.
164
// XXX why do we need this here? we should never reach this. Maybe
165
// because these can have widgets? Hmm
166
if (aBuilder->IsBackgroundOnly()) return;
167
168
DO_GLOBAL_REFLOW_COUNT_DSP("nsListControlFrame");
169
170
if (IsInDropDownMode()) {
171
NS_ASSERTION(NS_GET_A(mLastDropdownBackstopColor) == 255,
172
"need an opaque backstop color");
173
// XXX Because we have an opaque widget and we get called to paint with
174
// this frame as the root of a stacking context we need make sure to draw
175
// some opaque color over the whole widget. (Bug 511323)
176
aLists.BorderBackground()->AppendNewToBottom<nsDisplaySolidColor>(
177
aBuilder, this, nsRect(aBuilder->ToReferenceFrame(this), GetSize()),
178
mLastDropdownBackstopColor);
179
}
180
181
nsHTMLScrollFrame::BuildDisplayList(aBuilder, aLists);
182
}
183
184
/**
185
* This is called by the SelectsAreaFrame, which is the same
186
* as the frame returned by GetOptionsContainer. It's the frame which is
187
* scrolled by us.
188
* @param aPt the offset of this frame, relative to the rendering reference
189
* frame
190
*/
191
void nsListControlFrame::PaintFocus(DrawTarget* aDrawTarget, nsPoint aPt) {
192
if (mFocused != this) return;
193
194
nsPresContext* presContext = PresContext();
195
196
nsIFrame* containerFrame = GetOptionsContainer();
197
if (!containerFrame) return;
198
199
nsIFrame* childframe = nullptr;
200
nsCOMPtr<nsIContent> focusedContent = GetCurrentOption();
201
if (focusedContent) {
202
childframe = focusedContent->GetPrimaryFrame();
203
}
204
205
nsRect fRect;
206
if (childframe) {
207
// get the child rect
208
fRect = childframe->GetRect();
209
// get it into our coordinates
210
fRect.MoveBy(childframe->GetParent()->GetOffsetTo(this));
211
} else {
212
float inflation = nsLayoutUtils::FontSizeInflationFor(this);
213
fRect.x = fRect.y = 0;
214
if (GetWritingMode().IsVertical()) {
215
fRect.width = GetScrollPortRect().width;
216
fRect.height = CalcFallbackRowBSize(inflation);
217
} else {
218
fRect.width = CalcFallbackRowBSize(inflation);
219
fRect.height = GetScrollPortRect().height;
220
}
221
fRect.MoveBy(containerFrame->GetOffsetTo(this));
222
}
223
fRect += aPt;
224
225
bool lastItemIsSelected = false;
226
HTMLOptionElement* domOpt = HTMLOptionElement::FromNodeOrNull(focusedContent);
227
if (domOpt) {
228
lastItemIsSelected = domOpt->Selected();
229
}
230
231
// set up back stop colors and then ask L&F service for the real colors
232
nscolor color = LookAndFeel::GetColor(
233
lastItemIsSelected ? LookAndFeel::ColorID::WidgetSelectForeground
234
: LookAndFeel::ColorID::WidgetSelectBackground);
235
236
nsCSSRendering::PaintFocus(presContext, aDrawTarget, fRect, color);
237
}
238
239
void nsListControlFrame::InvalidateFocus() {
240
if (mFocused != this) return;
241
242
nsIFrame* containerFrame = GetOptionsContainer();
243
if (containerFrame) {
244
containerFrame->InvalidateFrame();
245
}
246
}
247
248
NS_QUERYFRAME_HEAD(nsListControlFrame)
249
NS_QUERYFRAME_ENTRY(nsIFormControlFrame)
250
NS_QUERYFRAME_ENTRY(nsISelectControlFrame)
251
NS_QUERYFRAME_ENTRY(nsListControlFrame)
252
NS_QUERYFRAME_TAIL_INHERITING(nsHTMLScrollFrame)
253
254
#ifdef ACCESSIBILITY
255
a11y::AccType nsListControlFrame::AccessibleType() {
256
return a11y::eHTMLSelectListType;
257
}
258
#endif
259
260
// Return true if we found at least one <option> or non-empty <optgroup> label
261
// that has a frame. aResult will be the maximum BSize of those.
262
static bool GetMaxRowBSize(nsIFrame* aContainer, WritingMode aWM,
263
nscoord* aResult) {
264
bool found = false;
265
for (nsIFrame* child : aContainer->PrincipalChildList()) {
266
if (child->GetContent()->IsHTMLElement(nsGkAtoms::optgroup)) {
267
// An optgroup; drill through any scroll frame and recurse. |inner| might
268
// be null here though if |inner| is an anonymous leaf frame of some sort.
269
auto inner = child->GetContentInsertionFrame();
270
if (inner && GetMaxRowBSize(inner, aWM, aResult)) {
271
found = true;
272
}
273
} else {
274
// an option or optgroup label
275
bool isOptGroupLabel =
276
child->Style()->IsPseudoElement() &&
277
aContainer->GetContent()->IsHTMLElement(nsGkAtoms::optgroup);
278
nscoord childBSize = child->BSize(aWM);
279
// XXX bug 1499176: skip empty <optgroup> labels (zero bsize) for now
280
if (!isOptGroupLabel || childBSize > nscoord(0)) {
281
found = true;
282
*aResult = std::max(childBSize, *aResult);
283
}
284
}
285
}
286
return found;
287
}
288
289
//-----------------------------------------------------------------
290
// Main Reflow for ListBox/Dropdown
291
//-----------------------------------------------------------------
292
293
nscoord nsListControlFrame::CalcBSizeOfARow() {
294
// Calculate the block size in our writing mode of a single row in the
295
// listbox or dropdown list by using the tallest thing in the subtree,
296
// since there may be option groups in addition to option elements,
297
// either of which may be visible or invisible, may use different
298
// fonts, etc.
299
nscoord rowBSize(0);
300
if (StyleDisplay()->IsContainSize() ||
301
!GetMaxRowBSize(GetOptionsContainer(), GetWritingMode(), &rowBSize)) {
302
// We don't have any <option>s or <optgroup> labels with a frame.
303
// (Or we're size-contained, which has the same outcome for our sizing.)
304
float inflation = nsLayoutUtils::FontSizeInflationFor(this);
305
rowBSize = CalcFallbackRowBSize(inflation);
306
}
307
return rowBSize;
308
}
309
310
nscoord nsListControlFrame::GetPrefISize(gfxContext* aRenderingContext) {
311
nscoord result;
312
DISPLAY_PREF_INLINE_SIZE(this, result);
313
314
// Always add scrollbar inline sizes to the pref-inline-size of the
315
// scrolled content. Combobox frames depend on this happening in the
316
// dropdown, and standalone listboxes are overflow:scroll so they need
317
// it too.
318
WritingMode wm = GetWritingMode();
319
result = StyleDisplay()->IsContainSize()
320
? 0
321
: GetScrolledFrame()->GetPrefISize(aRenderingContext);
322
LogicalMargin scrollbarSize(
323
wm, GetDesiredScrollbarSizes(PresContext(), aRenderingContext));
324
result = NSCoordSaturatingAdd(result, scrollbarSize.IStartEnd(wm));
325
return result;
326
}
327
328
nscoord nsListControlFrame::GetMinISize(gfxContext* aRenderingContext) {
329
nscoord result;
330
DISPLAY_MIN_INLINE_SIZE(this, result);
331
332
// Always add scrollbar inline sizes to the min-inline-size of the
333
// scrolled content. Combobox frames depend on this happening in the
334
// dropdown, and standalone listboxes are overflow:scroll so they need
335
// it too.
336
WritingMode wm = GetWritingMode();
337
result = StyleDisplay()->IsContainSize()
338
? 0
339
: GetScrolledFrame()->GetMinISize(aRenderingContext);
340
LogicalMargin scrollbarSize(
341
wm, GetDesiredScrollbarSizes(PresContext(), aRenderingContext));
342
result += scrollbarSize.IStartEnd(wm);
343
344
return result;
345
}
346
347
void nsListControlFrame::Reflow(nsPresContext* aPresContext,
348
ReflowOutput& aDesiredSize,
349
const ReflowInput& aReflowInput,
350
nsReflowStatus& aStatus) {
351
MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!");
352
NS_WARNING_ASSERTION(aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE,
353
"Must have a computed inline size");
354
355
SchedulePaint();
356
357
mHasPendingInterruptAtStartOfReflow = aPresContext->HasPendingInterrupt();
358
359
// If all the content and frames are here
360
// then initialize it before reflow
361
if (mIsAllContentHere && !mHasBeenInitialized) {
362
if (false == mIsAllFramesHere) {
363
CheckIfAllFramesHere();
364
}
365
if (mIsAllFramesHere && !mHasBeenInitialized) {
366
mHasBeenInitialized = true;
367
}
368
}
369
370
if (GetStateBits() & NS_FRAME_FIRST_REFLOW) {
371
nsCheckboxRadioFrame::RegUnRegAccessKey(this, true);
372
}
373
374
if (IsInDropDownMode()) {
375
ReflowAsDropdown(aPresContext, aDesiredSize, aReflowInput, aStatus);
376
return;
377
}
378
379
MarkInReflow();
380
/*
381
* Due to the fact that our intrinsic block size depends on the block
382
* sizes of our kids, we end up having to do two-pass reflow, in
383
* general -- the first pass to find the intrinsic block size and a
384
* second pass to reflow the scrollframe at that block size (which
385
* will size the scrollbars correctly, etc).
386
*
387
* Naturally, we want to avoid doing the second reflow as much as
388
* possible.
389
* We can skip it in the following cases (in all of which the first
390
* reflow is already happening at the right block size):
391
*
392
* - We're reflowing with a constrained computed block size -- just
393
* use that block size.
394
* - We're not dirty and have no dirty kids and shouldn't be reflowing
395
* all kids. In this case, our cached max block size of a child is
396
* not going to change.
397
* - We do our first reflow using our cached max block size of a
398
* child, then compute the new max block size and it's the same as
399
* the old one.
400
*/
401
402
bool autoBSize = (aReflowInput.ComputedBSize() == NS_UNCONSTRAINEDSIZE);
403
404
mMightNeedSecondPass = autoBSize && (NS_SUBTREE_DIRTY(this) ||
405
aReflowInput.ShouldReflowAllKids());
406
407
ReflowInput state(aReflowInput);
408
int32_t length = GetNumberOfRows();
409
410
nscoord oldBSizeOfARow = BSizeOfARow();
411
412
if (!(GetStateBits() & NS_FRAME_FIRST_REFLOW) && autoBSize) {
413
// When not doing an initial reflow, and when the block size is
414
// auto, start off with our computed block size set to what we'd
415
// expect our block size to be.
416
nscoord computedBSize = CalcIntrinsicBSize(oldBSizeOfARow, length);
417
computedBSize = state.ApplyMinMaxBSize(computedBSize);
418
state.SetComputedBSize(computedBSize);
419
}
420
421
nsHTMLScrollFrame::Reflow(aPresContext, aDesiredSize, state, aStatus);
422
423
if (!mMightNeedSecondPass) {
424
NS_ASSERTION(!autoBSize || BSizeOfARow() == oldBSizeOfARow,
425
"How did our BSize of a row change if nothing was dirty?");
426
NS_ASSERTION(!autoBSize || !(GetStateBits() & NS_FRAME_FIRST_REFLOW),
427
"How do we not need a second pass during initial reflow at "
428
"auto BSize?");
429
NS_ASSERTION(!IsScrollbarUpdateSuppressed(),
430
"Shouldn't be suppressing if we don't need a second pass!");
431
if (!autoBSize) {
432
// Update our mNumDisplayRows based on our new row block size now
433
// that we know it. Note that if autoBSize and we landed in this
434
// code then we already set mNumDisplayRows in CalcIntrinsicBSize.
435
// Also note that we can't use BSizeOfARow() here because that
436
// just uses a cached value that we didn't compute.
437
nscoord rowBSize = CalcBSizeOfARow();
438
if (rowBSize == 0) {
439
// Just pick something
440
mNumDisplayRows = 1;
441
} else {
442
mNumDisplayRows = std::max(1, state.ComputedBSize() / rowBSize);
443
}
444
}
445
446
return;
447
}
448
449
mMightNeedSecondPass = false;
450
451
// Now see whether we need a second pass. If we do, our
452
// nsSelectsAreaFrame will have suppressed the scrollbar update.
453
if (!IsScrollbarUpdateSuppressed()) {
454
// All done. No need to do more reflow.
455
return;
456
}
457
458
SetSuppressScrollbarUpdate(false);
459
460
// Gotta reflow again.
461
// XXXbz We're just changing the block size here; do we need to dirty
462
// ourselves or anything like that? We might need to, per the letter
463
// of the reflow protocol, but things seem to work fine without it...
464
// Is that just an implementation detail of nsHTMLScrollFrame that
465
// we're depending on?
466
nsHTMLScrollFrame::DidReflow(aPresContext, &state);
467
468
// Now compute the block size we want to have
469
nscoord computedBSize = CalcIntrinsicBSize(BSizeOfARow(), length);
470
computedBSize = state.ApplyMinMaxBSize(computedBSize);
471
state.SetComputedBSize(computedBSize);
472
473
// XXXbz to make the ascent really correct, we should add our
474
// mComputedPadding.top to it (and subtract it from descent). Need that
475
// because nsGfxScrollFrame just adds in the border....
476
aStatus.Reset();
477
nsHTMLScrollFrame::Reflow(aPresContext, aDesiredSize, state, aStatus);
478
}
479
480
void nsListControlFrame::ReflowAsDropdown(nsPresContext* aPresContext,
481
ReflowOutput& aDesiredSize,
482
const ReflowInput& aReflowInput,
483
nsReflowStatus& aStatus) {
484
MOZ_ASSERT(aReflowInput.ComputedBSize() == NS_UNCONSTRAINEDSIZE,
485
"We should not have a computed block size here!");
486
487
mMightNeedSecondPass =
488
NS_SUBTREE_DIRTY(this) || aReflowInput.ShouldReflowAllKids();
489
490
WritingMode wm = aReflowInput.GetWritingMode();
491
#ifdef DEBUG
492
nscoord oldBSizeOfARow = BSizeOfARow();
493
nscoord oldVisibleBSize = (GetStateBits() & NS_FRAME_FIRST_REFLOW)
494
? NS_UNCONSTRAINEDSIZE
495
: GetScrolledFrame()->BSize(wm);
496
#endif
497
498
ReflowInput state(aReflowInput);
499
500
if (!(GetStateBits() & NS_FRAME_FIRST_REFLOW)) {
501
// When not doing an initial reflow, and when the block size is
502
// auto, start off with our computed block size set to what we'd
503
// expect our block size to be.
504
// Note: At this point, mLastDropdownComputedBSize can be
505
// NS_UNCONSTRAINEDSIZE in cases when last time we didn't have to
506
// constrain the block size. That's fine; just do the same thing as
507
// last time.
508
state.SetComputedBSize(mLastDropdownComputedBSize);
509
}
510
511
nsHTMLScrollFrame::Reflow(aPresContext, aDesiredSize, state, aStatus);
512
513
if (!mMightNeedSecondPass) {
514
NS_ASSERTION(oldVisibleBSize == GetScrolledFrame()->BSize(wm),
515
"How did our kid's BSize change if nothing was dirty?");
516
NS_ASSERTION(BSizeOfARow() == oldBSizeOfARow,
517
"How did our BSize of a row change if nothing was dirty?");
518
NS_ASSERTION(!IsScrollbarUpdateSuppressed(),
519
"Shouldn't be suppressing if we don't need a second pass!");
520
NS_ASSERTION(!(GetStateBits() & NS_FRAME_FIRST_REFLOW),
521
"How can we avoid a second pass during first reflow?");
522
return;
523
}
524
525
mMightNeedSecondPass = false;
526
527
// Now see whether we need a second pass. If we do, our nsSelectsAreaFrame
528
// will have suppressed the scrollbar update.
529
if (!IsScrollbarUpdateSuppressed()) {
530
// All done. No need to do more reflow.
531
NS_ASSERTION(!(GetStateBits() & NS_FRAME_FIRST_REFLOW),
532
"How can we avoid a second pass during first reflow?");
533
return;
534
}
535
536
SetSuppressScrollbarUpdate(false);
537
538
nscoord visibleBSize = GetScrolledFrame()->BSize(wm);
539
nscoord blockSizeOfARow = BSizeOfARow();
540
541
// Gotta reflow again.
542
// XXXbz We're just changing the block size here; do we need to dirty
543
// ourselves or anything like that? We might need to, per the letter
544
// of the reflow protocol, but things seem to work fine without it...
545
// Is that just an implementation detail of nsHTMLScrollFrame that
546
// we're depending on?
547
nsHTMLScrollFrame::DidReflow(aPresContext, &state);
548
549
// Now compute the block size we want to have.
550
// Note: no need to apply min/max constraints, since we have no such
551
// rules applied to the combobox dropdown.
552
553
mDropdownCanGrow = false;
554
if (visibleBSize <= 0 || blockSizeOfARow <= 0 || XRE_IsContentProcess()) {
555
// Looks like we have no options. Just size us to a single row
556
// block size.
557
state.SetComputedBSize(blockSizeOfARow);
558
mNumDisplayRows = 1;
559
} else {
560
nsComboboxControlFrame* combobox =
561
static_cast<nsComboboxControlFrame*>(mComboboxFrame);
562
LogicalPoint translation(wm);
563
nscoord before, after;
564
combobox->GetAvailableDropdownSpace(wm, &before, &after, &translation);
565
if (before <= 0 && after <= 0) {
566
state.SetComputedBSize(blockSizeOfARow);
567
mNumDisplayRows = 1;
568
mDropdownCanGrow = GetNumberOfRows() > 1;
569
} else {
570
nscoord bp = aReflowInput.ComputedLogicalBorderPadding().BStartEnd(wm);
571
nscoord availableBSize = std::max(before, after) - bp;
572
nscoord newBSize;
573
uint32_t rows;
574
if (visibleBSize <= availableBSize) {
575
// The dropdown fits in the available block size.
576
rows = GetNumberOfRows();
577
mNumDisplayRows = clamped<uint32_t>(rows, 1, kMaxDropDownRows);
578
if (mNumDisplayRows == rows) {
579
newBSize = visibleBSize; // use the exact block size
580
} else {
581
newBSize = mNumDisplayRows * blockSizeOfARow; // approximate
582
// The approximation here might actually be too big (bug 1208978);
583
// don't let it exceed the actual block-size of the list.
584
newBSize = std::min(newBSize, visibleBSize);
585
}
586
} else {
587
rows = availableBSize / blockSizeOfARow;
588
mNumDisplayRows = clamped<uint32_t>(rows, 1, kMaxDropDownRows);
589
newBSize = mNumDisplayRows * blockSizeOfARow; // approximate
590
}
591
state.SetComputedBSize(newBSize);
592
mDropdownCanGrow = visibleBSize - newBSize >= blockSizeOfARow &&
593
mNumDisplayRows != kMaxDropDownRows;
594
}
595
}
596
597
mLastDropdownComputedBSize = state.ComputedBSize();
598
599
aStatus.Reset();
600
nsHTMLScrollFrame::Reflow(aPresContext, aDesiredSize, state, aStatus);
601
}
602
603
ScrollStyles nsListControlFrame::GetScrollStyles() const {
604
// We can't express this in the style system yet; when we can, this can go
605
// away and GetScrollStyles can be devirtualized
606
auto style = IsInDropDownMode() ? StyleOverflow::Auto : StyleOverflow::Scroll;
607
if (GetWritingMode().IsVertical()) {
608
return ScrollStyles(style, StyleOverflow::Hidden);
609
} else {
610
return ScrollStyles(StyleOverflow::Hidden, style);
611
}
612
}
613
614
bool nsListControlFrame::ShouldPropagateComputedBSizeToScrolledContent() const {
615
return !IsInDropDownMode();
616
}
617
618
//---------------------------------------------------------
619
nsContainerFrame* nsListControlFrame::GetContentInsertionFrame() {
620
return GetOptionsContainer()->GetContentInsertionFrame();
621
}
622
623
//---------------------------------------------------------
624
bool nsListControlFrame::ExtendedSelection(int32_t aStartIndex,
625
int32_t aEndIndex, bool aClearAll) {
626
return SetOptionsSelectedFromFrame(aStartIndex, aEndIndex, true, aClearAll);
627
}
628
629
//---------------------------------------------------------
630
bool nsListControlFrame::SingleSelection(int32_t aClickedIndex,
631
bool aDoToggle) {
632
if (mComboboxFrame) {
633
mComboboxFrame->UpdateRecentIndex(GetSelectedIndex());
634
}
635
636
bool wasChanged = false;
637
// Get Current selection
638
if (aDoToggle) {
639
wasChanged = ToggleOptionSelectedFromFrame(aClickedIndex);
640
} else {
641
wasChanged =
642
SetOptionsSelectedFromFrame(aClickedIndex, aClickedIndex, true, true);
643
}
644
AutoWeakFrame weakFrame(this);
645
ScrollToIndex(aClickedIndex);
646
if (!weakFrame.IsAlive()) {
647
return wasChanged;
648
}
649
650
#ifdef ACCESSIBILITY
651
bool isCurrentOptionChanged = mEndSelectionIndex != aClickedIndex;
652
#endif
653
mStartSelectionIndex = aClickedIndex;
654
mEndSelectionIndex = aClickedIndex;
655
InvalidateFocus();
656
657
#ifdef ACCESSIBILITY
658
if (isCurrentOptionChanged) {
659
FireMenuItemActiveEvent();
660
}
661
#endif
662
663
return wasChanged;
664
}
665
666
void nsListControlFrame::InitSelectionRange(int32_t aClickedIndex) {
667
//
668
// If nothing is selected, set the start selection depending on where
669
// the user clicked and what the initial selection is:
670
// - if the user clicked *before* selectedIndex, set the start index to
671
// the end of the first contiguous selection.
672
// - if the user clicked *after* the end of the first contiguous
673
// selection, set the start index to selectedIndex.
674
// - if the user clicked *within* the first contiguous selection, set the
675
// start index to selectedIndex.
676
// The last two rules, of course, boil down to the same thing: if the user
677
// clicked >= selectedIndex, return selectedIndex.
678
//
679
// This makes it so that shift click works properly when you first click
680
// in a multiple select.
681
//
682
int32_t selectedIndex = GetSelectedIndex();
683
if (selectedIndex >= 0) {
684
// Get the end of the contiguous selection
685
RefPtr<dom::HTMLOptionsCollection> options = GetOptions();
686
NS_ASSERTION(options, "Collection of options is null!");
687
uint32_t numOptions = options->Length();
688
// Push i to one past the last selected index in the group.
689
uint32_t i;
690
for (i = selectedIndex + 1; i < numOptions; i++) {
691
if (!options->ItemAsOption(i)->Selected()) {
692
break;
693
}
694
}
695
696
if (aClickedIndex < selectedIndex) {
697
// User clicked before selection, so start selection at end of
698
// contiguous selection
699
mStartSelectionIndex = i - 1;
700
mEndSelectionIndex = selectedIndex;
701
} else {
702
// User clicked after selection, so start selection at start of
703
// contiguous selection
704
mStartSelectionIndex = selectedIndex;
705
mEndSelectionIndex = i - 1;
706
}
707
}
708
}
709
710
static uint32_t CountOptionsAndOptgroups(nsIFrame* aFrame) {
711
uint32_t count = 0;
712
nsFrameList::Enumerator e(aFrame->PrincipalChildList());
713
for (; !e.AtEnd(); e.Next()) {
714
nsIFrame* child = e.get();
715
nsIContent* content = child->GetContent();
716
if (content) {
717
if (content->IsHTMLElement(nsGkAtoms::option)) {
718
++count;
719
} else {
720
RefPtr<HTMLOptGroupElement> optgroup =
721
HTMLOptGroupElement::FromNode(content);
722
if (optgroup) {
723
nsAutoString label;
724
optgroup->GetLabel(label);
725
if (label.Length() > 0) {
726
++count;
727
}
728
count += CountOptionsAndOptgroups(child);
729
}
730
}
731
}
732
}
733
return count;
734
}
735
736
uint32_t nsListControlFrame::GetNumberOfRows() {
737
return ::CountOptionsAndOptgroups(GetContentInsertionFrame());
738
}
739
740
//---------------------------------------------------------
741
bool nsListControlFrame::PerformSelection(int32_t aClickedIndex, bool aIsShift,
742
bool aIsControl) {
743
bool wasChanged = false;
744
745
if (aClickedIndex == kNothingSelected && !mForceSelection) {
746
// Ignore kNothingSelected unless the selection is forced
747
} else if (GetMultiple()) {
748
if (aIsShift) {
749
// Make sure shift+click actually does something expected when
750
// the user has never clicked on the select
751
if (mStartSelectionIndex == kNothingSelected) {
752
InitSelectionRange(aClickedIndex);
753
}
754
755
// Get the range from beginning (low) to end (high)
756
// Shift *always* works, even if the current option is disabled
757
int32_t startIndex;
758
int32_t endIndex;
759
if (mStartSelectionIndex == kNothingSelected) {
760
startIndex = aClickedIndex;
761
endIndex = aClickedIndex;
762
} else if (mStartSelectionIndex <= aClickedIndex) {
763
startIndex = mStartSelectionIndex;
764
endIndex = aClickedIndex;
765
} else {
766
startIndex = aClickedIndex;
767
endIndex = mStartSelectionIndex;
768
}
769
770
// Clear only if control was not pressed
771
wasChanged = ExtendedSelection(startIndex, endIndex, !aIsControl);
772
AutoWeakFrame weakFrame(this);
773
ScrollToIndex(aClickedIndex);
774
if (!weakFrame.IsAlive()) {
775
return wasChanged;
776
}
777
778
if (mStartSelectionIndex == kNothingSelected) {
779
mStartSelectionIndex = aClickedIndex;
780
}
781
#ifdef ACCESSIBILITY
782
bool isCurrentOptionChanged = mEndSelectionIndex != aClickedIndex;
783
#endif
784
mEndSelectionIndex = aClickedIndex;
785
InvalidateFocus();
786
787
#ifdef ACCESSIBILITY
788
if (isCurrentOptionChanged) {
789
FireMenuItemActiveEvent();
790
}
791
#endif
792
} else if (aIsControl) {
793
wasChanged = SingleSelection(aClickedIndex, true); // might destroy us
794
} else {
795
wasChanged = SingleSelection(aClickedIndex, false); // might destroy us
796
}
797
} else {
798
wasChanged = SingleSelection(aClickedIndex, false); // might destroy us
799
}
800
801
return wasChanged;
802
}
803
804
//---------------------------------------------------------
805
bool nsListControlFrame::HandleListSelection(dom::Event* aEvent,
806
int32_t aClickedIndex) {
807
MouseEvent* mouseEvent = aEvent->AsMouseEvent();
808
bool isControl;
809
#ifdef XP_MACOSX
810
isControl = mouseEvent->MetaKey();
811
#else
812
isControl = mouseEvent->CtrlKey();
813
#endif
814
bool isShift = mouseEvent->ShiftKey();
815
return PerformSelection(aClickedIndex, isShift,
816
isControl); // might destroy us
817
}
818
819
//---------------------------------------------------------
820
void nsListControlFrame::CaptureMouseEvents(bool aGrabMouseEvents) {
821
// Currently cocoa widgets use a native popup widget which tracks clicks
822
// synchronously, so we never want to do mouse capturing. Note that we only
823
// bail if the list is in drop-down mode, and the caller is requesting capture
824
// (we let release capture requests go through to ensure that we can release
825
// capture requested via other code paths, if any exist).
826
if (aGrabMouseEvents && IsInDropDownMode() &&
827
nsComboboxControlFrame::ToolkitHasNativePopup())
828
return;
829
830
if (aGrabMouseEvents) {
831
PresShell::SetCapturingContent(mContent, CaptureFlags::IgnoreAllowedState);
832
} else {
833
nsIContent* capturingContent = PresShell::GetCapturingContent();
834
835
bool dropDownIsHidden = false;
836
if (IsInDropDownMode()) {
837
dropDownIsHidden = !mComboboxFrame->IsDroppedDown();
838
}
839
if (capturingContent == mContent || dropDownIsHidden) {
840
// only clear the capturing content if *we* are the ones doing the
841
// capturing (or if the dropdown is hidden, in which case NO-ONE should
842
// be capturing anything - it could be a scrollbar inside this listbox
843
// which is actually grabbing
844
// This shouldn't be necessary. We should simply ensure that events
845
// targeting scrollbars are never visible to DOM consumers.
846
PresShell::ReleaseCapturingContent();
847
}
848
}
849
}
850
851
//---------------------------------------------------------
852
nsresult nsListControlFrame::HandleEvent(nsPresContext* aPresContext,
853
WidgetGUIEvent* aEvent,
854
nsEventStatus* aEventStatus) {
855
NS_ENSURE_ARG_POINTER(aEventStatus);
856
857
/*const char * desc[] = {"eMouseMove",
858
"NS_MOUSE_LEFT_BUTTON_UP",
859
"NS_MOUSE_LEFT_BUTTON_DOWN",
860
"<NA>","<NA>","<NA>","<NA>","<NA>","<NA>","<NA>",
861
"NS_MOUSE_MIDDLE_BUTTON_UP",
862
"NS_MOUSE_MIDDLE_BUTTON_DOWN",
863
"<NA>","<NA>","<NA>","<NA>","<NA>","<NA>","<NA>","<NA>",
864
"NS_MOUSE_RIGHT_BUTTON_UP",
865
"NS_MOUSE_RIGHT_BUTTON_DOWN",
866
"eMouseOver",
867
"eMouseOut",
868
"NS_MOUSE_LEFT_DOUBLECLICK",
869
"NS_MOUSE_MIDDLE_DOUBLECLICK",
870
"NS_MOUSE_RIGHT_DOUBLECLICK",
871
"NS_MOUSE_LEFT_CLICK",
872
"NS_MOUSE_MIDDLE_CLICK",
873
"NS_MOUSE_RIGHT_CLICK"};
874
int inx = aEvent->mMessage - eMouseEventFirst;
875
if (inx >= 0 && inx <= (NS_MOUSE_RIGHT_CLICK - eMouseEventFirst)) {
876
printf("Mouse in ListFrame %s [%d]\n", desc[inx], aEvent->mMessage);
877
} else {
878
printf("Mouse in ListFrame <UNKNOWN> [%d]\n", aEvent->mMessage);
879
}*/
880
881
if (nsEventStatus_eConsumeNoDefault == *aEventStatus) return NS_OK;
882
883
// disabled state affects how we're selected, but we don't want to go through
884
// nsHTMLScrollFrame if we're disabled.
885
if (IsContentDisabled()) {
886
return nsFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
887
}
888
889
return nsHTMLScrollFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
890
}
891
892
//---------------------------------------------------------
893
void nsListControlFrame::SetInitialChildList(ChildListID aListID,
894
nsFrameList& aChildList) {
895
if (aListID == kPrincipalList) {
896
// First check to see if all the content has been added
897
mIsAllContentHere = mContent->IsDoneAddingChildren();
898
if (!mIsAllContentHere) {
899
mIsAllFramesHere = false;
900
mHasBeenInitialized = false;
901
}
902
}
903
nsHTMLScrollFrame::SetInitialChildList(aListID, aChildList);
904
905
// If all the content is here now check
906
// to see if all the frames have been created
907
/*if (mIsAllContentHere) {
908
// If all content and frames are here
909
// the reset/initialize
910
if (CheckIfAllFramesHere()) {
911
ResetList(aPresContext);
912
mHasBeenInitialized = true;
913
}
914
}*/
915
}
916
917
//---------------------------------------------------------
918
void nsListControlFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
919
nsIFrame* aPrevInFlow) {
920
nsHTMLScrollFrame::Init(aContent, aParent, aPrevInFlow);
921
922
if (IsInDropDownMode()) {
923
AddStateBits(NS_FRAME_IN_POPUP);
924
CreateView();
925
}
926
927
// we shouldn't have to unregister this listener because when
928
// our frame goes away all these content node go away as well
929
// because our frame is the only one who references them.
930
// we need to hook up our listeners before the editor is initialized
931
mEventListener = new nsListEventListener(this);
932
933
mContent->AddSystemEventListener(NS_LITERAL_STRING("keydown"), mEventListener,
934
false, false);
935
mContent->AddSystemEventListener(NS_LITERAL_STRING("keypress"),
936
mEventListener, false, false);
937
mContent->AddSystemEventListener(NS_LITERAL_STRING("mousedown"),
938
mEventListener, false, false);
939
mContent->AddSystemEventListener(NS_LITERAL_STRING("mouseup"), mEventListener,
940
false, false);
941
mContent->AddSystemEventListener(NS_LITERAL_STRING("mousemove"),
942
mEventListener, false, false);
943
944
mStartSelectionIndex = kNothingSelected;
945
mEndSelectionIndex = kNothingSelected;
946
947
mLastDropdownBackstopColor = PresContext()->DefaultBackgroundColor();
948
}
949
950
dom::HTMLOptionsCollection* nsListControlFrame::GetOptions() const {
951
dom::HTMLSelectElement* select =
952
dom::HTMLSelectElement::FromNodeOrNull(mContent);
953
NS_ENSURE_TRUE(select, nullptr);
954
955
return select->Options();
956
}
957
958
dom::HTMLOptionElement* nsListControlFrame::GetOption(uint32_t aIndex) const {
959
dom::HTMLSelectElement* select =
960
dom::HTMLSelectElement::FromNodeOrNull(mContent);
961
NS_ENSURE_TRUE(select, nullptr);
962
963
return select->Item(aIndex);
964
}
965
966
NS_IMETHODIMP
967
nsListControlFrame::OnOptionSelected(int32_t aIndex, bool aSelected) {
968
if (aSelected) {
969
ScrollToIndex(aIndex);
970
}
971
return NS_OK;
972
}
973
974
void nsListControlFrame::OnContentReset() { ResetList(true); }
975
976
void nsListControlFrame::ResetList(bool aAllowScrolling) {
977
// if all the frames aren't here
978
// don't bother reseting
979
if (!mIsAllFramesHere) {
980
return;
981
}
982
983
if (aAllowScrolling) {
984
mPostChildrenLoadedReset = true;
985
986
// Scroll to the selected index
987
int32_t indexToSelect = kNothingSelected;
988
989
HTMLSelectElement* selectElement = HTMLSelectElement::FromNode(mContent);
990
if (selectElement) {
991
indexToSelect = selectElement->SelectedIndex();
992
AutoWeakFrame weakFrame(this);
993
ScrollToIndex(indexToSelect);
994
if (!weakFrame.IsAlive()) {
995
return;
996
}
997
}
998
}
999
1000
mStartSelectionIndex = kNothingSelected;
1001
mEndSelectionIndex = kNothingSelected;
1002
InvalidateFocus();
1003
// Combobox will redisplay itself with the OnOptionSelected event
1004
}
1005
1006
void nsListControlFrame::SetFocus(bool aOn, bool aRepaint) {
1007
InvalidateFocus();
1008
1009
if (aOn) {
1010
ComboboxFocusSet();
1011
mFocused = this;
1012
} else {
1013
mFocused = nullptr;
1014
}
1015
1016
InvalidateFocus();
1017
}
1018
1019
void nsListControlFrame::ComboboxFocusSet() { gLastKeyTime = 0; }
1020
1021
void nsListControlFrame::SetComboboxFrame(nsIFrame* aComboboxFrame) {
1022
if (nullptr != aComboboxFrame) {
1023
mComboboxFrame = do_QueryFrame(aComboboxFrame);
1024
}
1025
}
1026
1027
void nsListControlFrame::GetOptionText(uint32_t aIndex, nsAString& aStr) {
1028
aStr.Truncate();
1029
if (dom::HTMLOptionElement* optionElement = GetOption(aIndex)) {
1030
optionElement->GetText(aStr);
1031
}
1032
}
1033
1034
int32_t nsListControlFrame::GetSelectedIndex() {
1035
dom::HTMLSelectElement* select =
1036
dom::HTMLSelectElement::FromNodeOrNull(mContent);
1037
return select->SelectedIndex();
1038
}
1039
1040
dom::HTMLOptionElement* nsListControlFrame::GetCurrentOption() {
1041
// The mEndSelectionIndex is what is currently being selected. Use
1042
// the selected index if this is kNothingSelected.
1043
int32_t focusedIndex = (mEndSelectionIndex == kNothingSelected)
1044
? GetSelectedIndex()
1045
: mEndSelectionIndex;
1046
1047
if (focusedIndex != kNothingSelected) {
1048
return GetOption(AssertedCast<uint32_t>(focusedIndex));
1049
}
1050
1051
// There is no selected option. Return the first non-disabled option, if any.
1052
return GetNonDisabledOptionFrom(0);
1053
}
1054
1055
HTMLOptionElement* nsListControlFrame::GetNonDisabledOptionFrom(
1056
int32_t aFromIndex, int32_t* aFoundIndex) {
1057
RefPtr<dom::HTMLSelectElement> selectElement =
1058
dom::HTMLSelectElement::FromNode(mContent);
1059
1060
const uint32_t length = selectElement->Length();
1061
for (uint32_t i = std::max(aFromIndex, 0); i < length; ++i) {
1062
HTMLOptionElement* node = selectElement->Item(i);
1063
if (!node) {
1064
break;
1065
}
1066
if (IsOptionInteractivelySelectable(selectElement, node)) {
1067
if (aFoundIndex) {
1068
*aFoundIndex = i;
1069
}
1070
return node;
1071
}
1072
}
1073
return nullptr;
1074
}
1075
1076
bool nsListControlFrame::IsInDropDownMode() const {
1077
return (mComboboxFrame != nullptr);
1078
}
1079
1080
uint32_t nsListControlFrame::GetNumberOfOptions() {
1081
dom::HTMLOptionsCollection* options = GetOptions();
1082
if (!options) {
1083
return 0;
1084
}
1085
1086
return options->Length();
1087
}
1088
1089
//----------------------------------------------------------------------
1090
// nsISelectControlFrame
1091
//----------------------------------------------------------------------
1092
bool nsListControlFrame::CheckIfAllFramesHere() {
1093
// XXX Need to find a fail proof way to determine that
1094
// all the frames are there
1095
mIsAllFramesHere = true;
1096
1097
// now make sure we have a frame each piece of content
1098
1099
return mIsAllFramesHere;
1100
}
1101
1102
NS_IMETHODIMP
1103
nsListControlFrame::DoneAddingChildren(bool aIsDone) {
1104
mIsAllContentHere = aIsDone;
1105
if (mIsAllContentHere) {
1106
// Here we check to see if all the frames have been created
1107
// for all the content.
1108
// If so, then we can initialize;
1109
if (!mIsAllFramesHere) {
1110
// if all the frames are now present we can initialize
1111
if (CheckIfAllFramesHere()) {
1112
mHasBeenInitialized = true;
1113
ResetList(true);
1114
}
1115
}
1116
}
1117
return NS_OK;
1118
}
1119
1120
NS_IMETHODIMP
1121
nsListControlFrame::AddOption(int32_t aIndex) {
1122
#ifdef DO_REFLOW_DEBUG
1123
printf("---- Id: %d nsLCF %p Added Option %d\n", mReflowId, this, aIndex);
1124
#endif
1125
1126
if (!mIsAllContentHere) {
1127
mIsAllContentHere = mContent->IsDoneAddingChildren();
1128
if (!mIsAllContentHere) {
1129
mIsAllFramesHere = false;
1130
mHasBeenInitialized = false;
1131
} else {
1132
mIsAllFramesHere =
1133
(aIndex == static_cast<int32_t>(GetNumberOfOptions() - 1));
1134
}
1135
}
1136
1137
// Make sure we scroll to the selected option as needed
1138
mNeedToReset = true;
1139
1140
if (!mHasBeenInitialized) {
1141
return NS_OK;
1142
}
1143
1144
mPostChildrenLoadedReset = mIsAllContentHere;
1145
return NS_OK;
1146
}
1147
1148
static int32_t DecrementAndClamp(int32_t aSelectionIndex, int32_t aLength) {
1149
return aLength == 0 ? kNothingSelected : std::max(0, aSelectionIndex - 1);
1150
}
1151
1152
NS_IMETHODIMP
1153
nsListControlFrame::RemoveOption(int32_t aIndex) {
1154
MOZ_ASSERT(aIndex >= 0, "negative <option> index");
1155
1156
// Need to reset if we're a dropdown
1157
if (IsInDropDownMode()) {
1158
mNeedToReset = true;
1159
mPostChildrenLoadedReset = mIsAllContentHere;
1160
}
1161
1162
if (mStartSelectionIndex != kNothingSelected) {
1163
NS_ASSERTION(mEndSelectionIndex != kNothingSelected, "");
1164
int32_t numOptions = GetNumberOfOptions();
1165
// NOTE: numOptions is the new number of options whereas aIndex is the
1166
// unadjusted index of the removed option (hence the <= below).
1167
NS_ASSERTION(aIndex <= numOptions, "out-of-bounds <option> index");
1168
1169
int32_t forward = mEndSelectionIndex - mStartSelectionIndex;
1170
int32_t* low = forward >= 0 ? &mStartSelectionIndex : &mEndSelectionIndex;
1171
int32_t* high = forward >= 0 ? &mEndSelectionIndex : &mStartSelectionIndex;
1172
if (aIndex < *low) *low = ::DecrementAndClamp(*low, numOptions);
1173
if (aIndex <= *high) *high = ::DecrementAndClamp(*high, numOptions);
1174
if (forward == 0) *low = *high;
1175
} else
1176
NS_ASSERTION(mEndSelectionIndex == kNothingSelected, "");
1177
1178
InvalidateFocus();
1179
return NS_OK;
1180
}
1181
1182
//---------------------------------------------------------
1183
// Set the option selected in the DOM. This method is named
1184
// as it is because it indicates that the frame is the source
1185
// of this event rather than the receiver.
1186
bool nsListControlFrame::SetOptionsSelectedFromFrame(int32_t aStartIndex,
1187
int32_t aEndIndex,
1188
bool aValue,
1189
bool aClearAll) {
1190
RefPtr<dom::HTMLSelectElement> selectElement =
1191
dom::HTMLSelectElement::FromNode(mContent);
1192
1193
uint32_t mask = dom::HTMLSelectElement::NOTIFY;
1194
if (mForceSelection) {
1195
mask |= dom::HTMLSelectElement::SET_DISABLED;
1196
}
1197
if (aValue) {
1198
mask |= dom::HTMLSelectElement::IS_SELECTED;
1199
}
1200
if (aClearAll) {
1201
mask |= dom::HTMLSelectElement::CLEAR_ALL;
1202
}
1203
1204
return selectElement->SetOptionsSelectedByIndex(aStartIndex, aEndIndex, mask);
1205
}
1206
1207
bool nsListControlFrame::ToggleOptionSelectedFromFrame(int32_t aIndex) {
1208
RefPtr<dom::HTMLOptionElement> option =
1209
GetOption(static_cast<uint32_t>(aIndex));
1210
NS_ENSURE_TRUE(option, false);
1211
1212
RefPtr<dom::HTMLSelectElement> selectElement =
1213
dom::HTMLSelectElement::FromNode(mContent);
1214
1215
uint32_t mask = dom::HTMLSelectElement::NOTIFY;
1216
if (!option->Selected()) {
1217
mask |= dom::HTMLSelectElement::IS_SELECTED;
1218
}
1219
1220
return selectElement->SetOptionsSelectedByIndex(aIndex, aIndex, mask);
1221
}
1222
1223
// Dispatch event and such
1224
bool nsListControlFrame::UpdateSelection() {
1225
if (mIsAllFramesHere) {
1226
// if it's a combobox, display the new text
1227
AutoWeakFrame weakFrame(this);
1228
if (mComboboxFrame) {
1229
mComboboxFrame->RedisplaySelectedText();
1230
1231
// When dropdown list is open, onchange event will be fired when Enter key
1232
// is hit or when dropdown list is dismissed.
1233
if (mComboboxFrame->IsDroppedDown()) {
1234
return weakFrame.IsAlive();
1235
}
1236
}
1237
if (mIsAllContentHere) {
1238
FireOnInputAndOnChange();
1239
}
1240
return weakFrame.IsAlive();
1241
}
1242
return true;
1243
}
1244
1245
void nsListControlFrame::ComboboxFinish(int32_t aIndex) {
1246
gLastKeyTime = 0;
1247
1248
if (mComboboxFrame) {
1249
int32_t displayIndex = mComboboxFrame->GetIndexOfDisplayArea();
1250
// Make sure we can always reset to the displayed index
1251
mForceSelection = displayIndex == aIndex;
1252
1253
AutoWeakFrame weakFrame(this);
1254
PerformSelection(aIndex, false, false); // might destroy us
1255
if (!weakFrame.IsAlive() || !mComboboxFrame) {
1256
return;
1257
}
1258
1259
if (displayIndex != aIndex) {
1260
mComboboxFrame->RedisplaySelectedText(); // might destroy us
1261
}
1262
1263
if (weakFrame.IsAlive() && mComboboxFrame) {
1264
mComboboxFrame->RollupFromList(); // might destroy us
1265
}
1266
}
1267
}
1268
1269
// Send out an onInput and onChange notification.
1270
void nsListControlFrame::FireOnInputAndOnChange() {
1271
if (mComboboxFrame) {
1272
// Return hit without changing anything
1273
int32_t index = mComboboxFrame->UpdateRecentIndex(NS_SKIP_NOTIFY_INDEX);
1274
if (index == NS_SKIP_NOTIFY_INDEX) {
1275
return;
1276
}
1277
1278
// See if the selection actually changed
1279
if (index == GetSelectedIndex()) {
1280
return;
1281
}
1282
}
1283
1284
RefPtr<Element> element = Element::FromNodeOrNull(mContent);
1285
if (NS_WARN_IF(!element)) {
1286
return;
1287
}
1288
// Dispatch the input event.
1289
DebugOnly<nsresult> rvIgnored = nsContentUtils::DispatchInputEvent(element);
1290
NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
1291
"Failed to dispatch input event");
1292
1293
// Dispatch the change event.
1294
nsContentUtils::DispatchTrustedEvent(element->OwnerDoc(), element,
1295
NS_LITERAL_STRING("change"),
1296
CanBubble::eYes, Cancelable::eNo);
1297
}
1298
1299
NS_IMETHODIMP_(void)
1300
nsListControlFrame::OnSetSelectedIndex(int32_t aOldIndex, int32_t aNewIndex) {
1301
if (mComboboxFrame) {
1302
// UpdateRecentIndex with NS_SKIP_NOTIFY_INDEX, so that we won't fire an
1303
// onchange event for this setting of selectedIndex.
1304
mComboboxFrame->UpdateRecentIndex(NS_SKIP_NOTIFY_INDEX);
1305
}
1306
1307
AutoWeakFrame weakFrame(this);
1308
ScrollToIndex(aNewIndex);
1309
if (!weakFrame.IsAlive()) {
1310
return;
1311
}
1312
mStartSelectionIndex = aNewIndex;
1313
mEndSelectionIndex = aNewIndex;
1314
InvalidateFocus();
1315
1316
#ifdef ACCESSIBILITY
1317
FireMenuItemActiveEvent();
1318
#endif
1319
}
1320
1321
//----------------------------------------------------------------------
1322
// End nsISelectControlFrame
1323
//----------------------------------------------------------------------
1324
1325
nsresult nsListControlFrame::SetFormProperty(nsAtom* aName,
1326
const nsAString& aValue) {
1327
if (nsGkAtoms::selected == aName) {
1328
return NS_ERROR_INVALID_ARG; // Selected is readonly according to spec.
1329
} else if (nsGkAtoms::selectedindex == aName) {
1330
// You shouldn't be calling me for this!!!
1331
return NS_ERROR_INVALID_ARG;
1332
}
1333
1334
// We should be told about selectedIndex by the DOM element through
1335
// OnOptionSelected
1336
1337
return NS_OK;
1338
}
1339
1340
void nsListControlFrame::AboutToDropDown() {
1341
NS_ASSERTION(IsInDropDownMode(),
1342
"AboutToDropDown called without being in dropdown mode");
1343
1344
// Our widget doesn't get invalidated on changes to the rest of the document,
1345
// so compute and store this color at the start of a dropdown so we don't
1346
// get weird painting behaviour.
1347
// We start looking for backgrounds above the combobox frame to avoid
1348
// duplicating the combobox frame's background and compose each background
1349
// color we find underneath until we have an opaque color, or run out of
1350
// backgrounds. We compose with the PresContext default background color,
1351
// which is always opaque, in case we don't end up with an opaque color.
1352
// This gives us a very poor approximation of translucency.
1353
nsIFrame* comboboxFrame = do_QueryFrame(mComboboxFrame);
1354
nsIFrame* ancestor = comboboxFrame->GetParent();
1355
mLastDropdownBackstopColor = NS_RGBA(0, 0, 0, 0);
1356
while (NS_GET_A(mLastDropdownBackstopColor) < 255 && ancestor) {
1357
ComputedStyle* context = ancestor->Style();
1358
mLastDropdownBackstopColor =
1359
NS_ComposeColors(context->StyleBackground()->BackgroundColor(context),
1360
mLastDropdownBackstopColor);
1361
ancestor = ancestor->GetParent();
1362
}
1363
mLastDropdownBackstopColor = NS_ComposeColors(
1364
PresContext()->DefaultBackgroundColor(), mLastDropdownBackstopColor);
1365
1366
if (mIsAllContentHere && mIsAllFramesHere && mHasBeenInitialized) {
1367
AutoWeakFrame weakFrame(this);
1368
ScrollToIndex(GetSelectedIndex());
1369
if (!weakFrame.IsAlive()) {
1370
return;
1371
}
1372
#ifdef ACCESSIBILITY
1373
FireMenuItemActiveEvent(); // Inform assistive tech what got focus
1374
#endif
1375
}
1376
mItemSelectionStarted = false;
1377
mForceSelection = false;
1378
}
1379
1380
// We are about to be rolledup from the outside (ComboboxFrame)
1381
void nsListControlFrame::AboutToRollup() {
1382
// We've been updating the combobox with the keyboard up until now, but not
1383
// with the mouse. The problem is, even with mouse selection, we are
1384
// updating the <select>. So if the mouse goes over an option just before
1385
// he leaves the box and clicks, that's what the <select> will show.
1386
//
1387
// To deal with this we say "whatever is in the combobox is canonical."
1388
// - IF the combobox is different from the current selected index, we
1389
// reset the index.
1390
1391
if (IsInDropDownMode()) {
1392
ComboboxFinish(
1393
mComboboxFrame->GetIndexOfDisplayArea()); // might destroy us
1394
}
1395
}
1396
1397
void nsListControlFrame::DidReflow(nsPresContext* aPresContext,
1398
const ReflowInput* aReflowInput) {
1399
bool wasInterrupted = !mHasPendingInterruptAtStartOfReflow &&
1400
aPresContext->HasPendingInterrupt();
1401
1402
nsHTMLScrollFrame::DidReflow(aPresContext, aReflowInput);
1403
1404
if (mNeedToReset && !wasInterrupted) {
1405
mNeedToReset = false;
1406
// Suppress scrolling to the selected element if we restored
1407
// scroll history state AND the list contents have not changed
1408
// since we loaded all the children AND nothing else forced us
1409
// to scroll by calling ResetList(true). The latter two conditions
1410
// are folded into mPostChildrenLoadedReset.
1411
//
1412
// The idea is that we want scroll history restoration to trump ResetList
1413
// scrolling to the selected element, when the ResetList was probably only
1414
// caused by content loading normally.
1415
ResetList(!DidHistoryRestore() || mPostChildrenLoadedReset);
1416
}
1417
1418
mHasPendingInterruptAtStartOfReflow = false;
1419
}
1420
1421
#ifdef DEBUG_FRAME_DUMP
1422
nsresult nsListControlFrame::GetFrameName(nsAString& aResult) const {
1423
return MakeFrameName(NS_LITERAL_STRING("ListControl"), aResult);
1424
}
1425
#endif
1426
1427
nscoord nsListControlFrame::GetBSizeOfARow() { return BSizeOfARow(); }
1428
1429
bool nsListControlFrame::IsOptionInteractivelySelectable(int32_t aIndex) const {
1430
if (HTMLSelectElement* sel = HTMLSelectElement::FromNode(mContent)) {
1431
if (HTMLOptionElement* item = sel->Item(aIndex)) {
1432
return IsOptionInteractivelySelectable(sel, item);
1433
}
1434
}
1435
return false;
1436
}
1437
1438
bool nsListControlFrame::IsOptionInteractivelySelectable(
1439
HTMLSelectElement* aSelect, HTMLOptionElement* aOption) {
1440
return !aSelect->IsOptionDisabled(aOption) && aOption->GetPrimaryFrame();
1441
}
1442
1443
//----------------------------------------------------------------------
1444
// helper
1445
//----------------------------------------------------------------------
1446
bool nsListControlFrame::IsLeftButton(dom::Event* aMouseEvent) {
1447
// only allow selection with the left button
1448
MouseEvent* mouseEvent = aMouseEvent->AsMouseEvent();
1449
return mouseEvent && mouseEvent->Button() == 0;
1450
}
1451
1452
nscoord nsListControlFrame::CalcFallbackRowBSize(float aFontSizeInflation) {
1453
RefPtr<nsFontMetrics> fontMet =
1454
nsLayoutUtils::GetFontMetricsForFrame(this, aFontSizeInflation);
1455
return fontMet->MaxHeight();
1456
}
1457
1458
nscoord nsListControlFrame::CalcIntrinsicBSize(nscoord aBSizeOfARow,
1459
int32_t aNumberOfOptions) {
1460
MOZ_ASSERT(!IsInDropDownMode(),
1461
"Shouldn't be in dropdown mode when we call this");
1462
1463
dom::HTMLSelectElement* select =
1464
dom::HTMLSelectElement::FromNodeOrNull(mContent);
1465
if (select) {
1466
mNumDisplayRows = select->Size();
1467
} else {
1468
mNumDisplayRows = 1;
1469
}
1470
1471
if (mNumDisplayRows < 1) {
1472
mNumDisplayRows = 4;
1473
}
1474
1475
return mNumDisplayRows * aBSizeOfARow;
1476
}
1477
1478
//----------------------------------------------------------------------
1479
// nsIDOMMouseListener
1480
//----------------------------------------------------------------------
1481
nsresult nsListControlFrame::MouseUp(dom::Event* aMouseEvent) {
1482
NS_ASSERTION(aMouseEvent != nullptr, "aMouseEvent is null.");
1483
1484
MouseEvent* mouseEvent = aMouseEvent->AsMouseEvent();
1485
NS_ENSURE_TRUE(mouseEvent, NS_ERROR_FAILURE);
1486
1487
UpdateInListState(aMouseEvent);
1488
1489
mButtonDown = false;
1490
1491
EventStates eventStates = mContent->AsElement()->State();
1492
if (eventStates.HasState(NS_EVENT_STATE_DISABLED)) {
1493
return NS_OK;
1494
}
1495
1496
// only allow selection with the left button
1497
// if a right button click is on the combobox itself
1498
// or on the select when in listbox mode, then let the click through
1499
if (!IsLeftButton(aMouseEvent)) {
1500
if (IsInDropDownMode()) {
1501
if (!IgnoreMouseEventForSelection(aMouseEvent)) {
1502
aMouseEvent->PreventDefault();
1503
aMouseEvent->StopPropagation();
1504
} else {
1505
CaptureMouseEvents(false);
1506
return NS_OK;
1507
}
1508
CaptureMouseEvents(false);
1509
return NS_ERROR_FAILURE; // means consume event
1510
} else {
1511
CaptureMouseEvents(false);
1512
return NS_OK;
1513
}
1514
}
1515
1516
const nsStyleVisibility* vis = StyleVisibility();
1517
1518
if (!vis->IsVisible()) {
1519
return NS_OK;
1520
}
1521
1522
if (IsInDropDownMode()) {
1523
// XXX This is a bit of a hack, but.....
1524
// But the idea here is to make sure you get an "onclick" event when you
1525
// mouse down on the select and the drag over an option and let go And then
1526
// NOT get an "onclick" event when when you click down on the select and
1527
// then up outside of the select the EventStateManager tracks the content of
1528
// the mouse down and the mouse up to make sure they are the same, and the
1529
// onclick is sent in the PostHandleEvent depeneding on whether the
1530
// clickCount is non-zero. So we cheat here by either setting or unsetting
1531
// the clcikCount in the native event so the right thing happens for the
1532
// onclick event
1533
WidgetMouseEvent* mouseEvent =
1534
aMouseEvent->WidgetEventPtr()->AsMouseEvent();
1535
1536
int32_t selectedIndex;
1537
if (NS_SUCCEEDED(GetIndexFromDOMEvent(aMouseEvent, selectedIndex))) {
1538
// If it's not selectable, disallow the click and leave.
1539
if (!IsOptionInteractivelySelectable(selectedIndex)) {
1540
aMouseEvent->PreventDefault();
1541
aMouseEvent->StopPropagation();
1542
CaptureMouseEvents(false);
1543
return NS_ERROR_FAILURE;
1544
}
1545
1546
if (kNothingSelected != selectedIndex) {
1547
AutoWeakFrame weakFrame(this);
1548
ComboboxFinish(selectedIndex);
1549
if (!weakFrame.IsAlive()) {
1550
return NS_OK;
1551
}
1552
1553
FireOnInputAndOnChange();
1554
}
1555
1556
mouseEvent->mClickCount = 1;
1557
} else {
1558
// the click was out side of the select or its dropdown
1559
mouseEvent->mClickCount =
1560
IgnoreMouseEventForSelection(aMouseEvent) ? 1 : 0;
1561
}
1562
} else {
1563
CaptureMouseEvents(false);
1564
// Notify
1565
if (mChangesSinceDragStart) {
1566
// reset this so that future MouseUps without a prior MouseDown
1567
// won't fire onchange
1568
mChangesSinceDragStart = false;
1569
FireOnInputAndOnChange();
1570
}
1571
}
1572
1573
return NS_OK;
1574
}
1575
1576
void nsListControlFrame::UpdateInListState(dom::Event* aEvent) {
1577
if (!mComboboxFrame || !mComboboxFrame->IsDroppedDown()) return;
1578
1579
nsPoint pt = nsLayoutUtils::GetDOMEventCoordinatesRelativeTo(aEvent, this);
1580
nsRect borderInnerEdge = GetScrollPortRect();
1581
if (pt.y >= borderInnerEdge.y && pt.y < borderInnerEdge.YMost()) {
1582
mItemSelectionStarted = true;
1583
}
1584
}
1585
1586
bool nsListControlFrame::IgnoreMouseEventForSelection(dom::Event* aEvent) {
1587
if (!mComboboxFrame) return false;
1588
1589
// Our DOM listener does get called when the dropdown is not
1590
// showing, because it listens to events on the SELECT element
1591
if (!mComboboxFrame->IsDroppedDown()) return true;
1592
1593
return !mItemSelectionStarted;
1594
}
1595
1596
#ifdef ACCESSIBILITY
1597
void nsListControlFrame::FireMenuItemActiveEvent() {
1598
if (mFocused != this && !IsInDropDownMode()) {
1599
return;
1600
}
1601
1602
nsCOMPtr<nsIContent> optionContent = GetCurrentOption();
1603
if (!optionContent) {
1604
return;
1605
}
1606
1607
FireDOMEvent(NS_LITERAL_STRING("DOMMenuItemActive"), optionContent);
1608
}
1609
#endif
1610
1611
nsresult nsListControlFrame::GetIndexFromDOMEvent(dom::Event* aMouseEvent,
1612
int32_t& aCurIndex) {
1613
if (IgnoreMouseEventForSelection(aMouseEvent)) return NS_ERROR_FAILURE;
1614
1615
if (PresShell::GetCapturingContent() != mContent) {
1616
// If we're not capturing, then ignore movement in the border
1617
nsPoint pt =
1618
nsLayoutUtils::GetDOMEventCoordinatesRelativeTo(aMouseEvent, this);
1619
nsRect borderInnerEdge = GetScrollPortRect();
1620
if (!borderInnerEdge.Contains(pt)) {
1621
return NS_ERROR_FAILURE;
1622
}
1623
}
1624
1625
RefPtr<dom::HTMLOptionElement> option;
1626
for (nsCOMPtr<nsIContent> content =
1627
PresContext()->EventStateManager()->GetEventTargetContent(nullptr);
1628
content && !option; content = content->GetParent()) {
1629
option = dom::HTMLOptionElement::FromNode(content);
1630
}
1631
1632
if (option) {
1633
aCurIndex = option->Index();
1634
MOZ_ASSERT(aCurIndex >= 0);
1635
return NS_OK;
1636
}
1637
1638
return NS_ERROR_FAILURE;
1639
}
1640
1641
static bool FireShowDropDownEvent(nsIContent* aContent, bool aShow,
1642
bool aIsSourceTouchEvent) {
1643
if (ShouldFireDropDownEvent()) {
1644
nsString eventName;
1645
if (aShow) {
1646
eventName = aIsSourceTouchEvent
1647
? NS_LITERAL_STRING("mozshowdropdown-sourcetouch")
1648
: NS_LITERAL_STRING("mozshowdropdown");
1649
} else {
1650
eventName = NS_LITERAL_STRING("mozhidedropdown");
1651
}
1652
nsContentUtils::DispatchChromeEvent(aContent->OwnerDoc(), aContent,
1653
eventName, CanBubble::eYes,
1654
Cancelable::eNo);
1655
return true;
1656
}
1657
1658
return false;
1659
}
1660
1661
nsresult nsListControlFrame::MouseDown(dom::Event* aMouseEvent) {
1662
NS_ASSERTION(aMouseEvent != nullptr, "aMouseEvent is null.");
1663
1664
MouseEvent* mouseEvent = aMouseEvent->AsMouseEvent();
1665
NS_ENSURE_TRUE(mouseEvent, NS_ERROR_FAILURE);
1666
1667
UpdateInListState(aMouseEvent);
1668
1669
EventStates eventStates = mContent->AsElement()->State();
1670
if (eventStates.HasState(NS_EVENT_STATE_DISABLED)) {
1671
return NS_OK;
1672
}
1673
1674
// only allow selection with the left button
1675
// if a right button click is on the combobox itself
1676
// or on the select when in listbox mode, then let the click through
1677
if (!IsLeftButton(aMouseEvent)) {
1678
if (IsInDropDownMode()) {
1679
if (!IgnoreMouseEventForSelection(aMouseEvent)) {
1680
aMouseEvent->PreventDefault();
1681
aMouseEvent->StopPropagation();
1682
} else {
1683
return NS_OK;
1684
}
1685
return NS_ERROR_FAILURE; // means consume event
1686
} else {
1687
return NS_OK;
1688
}
1689
}
1690
1691
int32_t selectedIndex;
1692
if (NS_SUCCEEDED(GetIndexFromDOMEvent(aMouseEvent, selectedIndex))) {
1693
// Handle Like List
1694
mButtonDown = true;
1695
CaptureMouseEvents(true);
1696
AutoWeakFrame weakFrame(this);
1697
bool change =
1698
HandleListSelection(aMouseEvent, selectedIndex); // might destroy us
1699
if (!weakFrame.IsAlive()) {
1700
return NS_OK;
1701
}
1702
mChangesSinceDragStart = change;
1703
} else {
1704
// NOTE: the combo box is responsible for dropping it down
1705
if (mComboboxFrame) {
1706
// Ignore the click that occurs on the option element when one is
1707
// selected from the parent process popup.
1708
if (mComboboxFrame->IsOpenInParentProcess()) {
1709
nsCOMPtr<nsIContent> econtent =
1710
do_QueryInterface(aMouseEvent->GetTarget());
1711
HTMLOptionElement* option = HTMLOptionElement::FromNodeOrNull(econtent);
1712
if (option) {
1713
return NS_OK;
1714
}
1715
}
1716
1717
uint16_t inputSource = mouseEvent->MozInputSource();
1718
bool isSourceTouchEvent =
1719
inputSource == MouseEvent_Binding::MOZ_SOURCE_TOUCH;
1720
if (FireShowDropDownEvent(
1721
mContent, !mComboboxFrame->IsDroppedDownOrHasParentPopup(),
1722
isSourceTouchEvent)) {
1723
return NS_OK;
1724
}
1725
1726
if (!IgnoreMouseEventForSelection(aMouseEvent)) {
1727
return NS_OK;
1728
}
1729
1730
if (!nsComboboxControlFrame::ToolkitHasNativePopup()) {
1731
bool isDroppedDown = mComboboxFrame->IsDroppedDown();
1732
nsIFrame* comboFrame = do_QueryFrame(mComboboxFrame);
1733
AutoWeakFrame weakFrame(comboFrame);
1734
mComboboxFrame->ShowDropDown(!isDroppedDown);
1735
if (!weakFrame.IsAlive()) return NS_OK;
1736
if (isDroppedDown) {
1737
CaptureMouseEvents(false);
1738
}
1739
}
1740
}
1741
}
1742
1743
return NS_OK;
1744
}
1745
1746
nsresult nsListControlFrame::MouseMove(dom::Event* aMouseEvent) {
1747
NS_ASSERTION(aMouseEvent, "aMouseEvent is null.");
1748
MouseEvent* mouseEvent = aMouseEvent->AsMouseEvent();
1749
NS_ENSURE_TRUE(mouseEvent, NS_ERROR_FAILURE);
1750
1751
UpdateInListState(aMouseEvent);
1752
1753
if (IsInDropDownMode()) {
1754
if (mComboboxFrame->IsDroppedDown()) {
1755
int32_t selectedIndex;
1756
if (NS_SUCCEEDED(GetIndexFromDOMEvent(aMouseEvent, selectedIndex))) {
1757
PerformSelection(selectedIndex, false, false); // might destroy us
1758
}
1759
}
1760
} else { // XXX - temporary until we get drag events
1761
if (mButtonDown) {
1762
return DragMove(aMouseEvent); // might destroy us
1763
}
1764
}
1765
return NS_OK;
1766
}
1767
1768
nsresult nsListControlFrame::DragMove(dom::Event* aMouseEvent) {
1769
NS_ASSERTION(aMouseEvent, "aMouseEvent is null.");
1770
1771
UpdateInListState(aMouseEvent);
1772
1773
if (!IsInDropDownMode()) {
1774
int32_t selectedIndex;
1775
if (NS_SUCCEEDED(GetIndexFromDOMEvent(aMouseEvent, selectedIndex))) {
1776
// Don't waste cycles if we already dragged over this item
1777
if (selectedIndex == mEndSelectionIndex) {
1778
return NS_OK;
1779
}
1780
MouseEvent* mouseEvent = aMouseEvent->AsMouseEvent();
1781
NS_ASSERTION(mouseEvent, "aMouseEvent is not a MouseEvent!");
1782
bool isControl;
1783
#ifdef XP_MACOSX
1784
isControl = mouseEvent->MetaKey();
1785
#else
1786
isControl = mouseEvent->CtrlKey();
1787
#endif
1788
AutoWeakFrame weakFrame(this);
1789
// Turn SHIFT on when you are dragging, unless control is on.
1790
bool wasChanged = PerformSelection(selectedIndex, !isControl, isControl);
1791
if (!weakFrame.IsAlive()) {
1792
return NS_OK;
1793
}
1794
mChangesSinceDragStart = mChangesSinceDragStart || wasChanged;
1795
}
1796
}
1797
return NS_OK;
1798
}
1799
1800
//----------------------------------------------------------------------
1801
// Scroll helpers.
1802
//----------------------------------------------------------------------
1803
void nsListControlFrame::ScrollToIndex(int32_t aIndex) {
1804
if (aIndex < 0) {
1805
// XXX shouldn't we just do nothing if we're asked to scroll to
1806
// kNothingSelected?
1807
ScrollTo(nsPoint(0, 0), ScrollMode::Instant);
1808
} else {
1809
RefPtr<dom::HTMLOptionElement> option =
1810
GetOption(AssertedCast<uint32_t>(aIndex));
1811
if (option) {
1812
ScrollToFrame(*option);
1813
}
1814
}
1815
}
1816
1817
void nsListControlFrame::ScrollToFrame(dom::HTMLOptionElement& aOptElement) {
1818
// otherwise we find the content's frame and scroll to it
1819
nsIFrame* childFrame = aOptElement.GetPrimaryFrame();
1820
if (childFrame) {
1821
RefPtr<mozilla::PresShell> presShell = PresShell();
1822
presShell->ScrollFrameRectIntoView(
1823
childFrame, nsRect(nsPoint(0, 0), childFrame->GetSize()), ScrollAxis(),
1824
ScrollAxis(),
1825
ScrollFlags::ScrollOverflowHidden |
1826
ScrollFlags::ScrollFirstAncestorOnly |
1827
ScrollFlags::IgnoreMarginAndPadding);
1828
}
1829
}
1830
1831
//---------------------------------------------------------------------
1832
// Ok, the entire idea of this routine is to move to the next item that
1833
// is suppose to be selected. If the item is disabled then we search in
1834
// the same direction looking for the next item to select. If we run off
1835
// the end of the list then we start at the end of the list and search
1836
// backwards until we get back to the original item or an enabled option
1837
//
1838
// aStartIndex - the index to start searching from
1839
// aNewIndex - will get set to the new index if it finds one
1840
// aNumOptions - the total number of options in the list
1841
// aDoAdjustInc - the initial increment 1-n
1842
// aDoAdjustIncNext - the increment used to search for the next enabled option
1843
//
1844
// the aDoAdjustInc could be a "1" for a single item or
1845
// any number greater representing a page of items
1846
//
1847
void nsListControlFrame::AdjustIndexForDisabledOpt(int32_t aStartIndex,
1848
int32_t& aNewIndex,
1849
int32_t aNumOptions,
1850
int32_t aDoAdjustInc,
1851
int32_t aDoAdjustIncNext) {
1852
// Cannot select anything if there is nothing to select
1853
if (aNumOptions == 0) {
1854
aNewIndex = kNothingSelected;
1855
return;
1856
}
1857
1858
// means we reached the end of the list and now we are searching backwards
1859
bool doingReverse = false;
1860
// lowest index in the search range
1861
int32_t bottom = 0;
1862
// highest index in the search range
1863
int32_t top = aNumOptions;
1864
1865
// Start off keyboard options at selectedIndex if nothing else is defaulted to
1866
//
1867
// XXX Perhaps this should happen for mouse too, to start off shift click
1868
// automatically in multiple ... to do this, we'd need to override
1869
// OnOptionSelected and set mStartSelectedIndex if nothing is selected. Not
1870
// sure of the effects, though, so I'm not doing it just yet.
1871
int32_t startIndex = aStartIndex;
1872
if (startIndex < bottom) {
1873
startIndex = GetSelectedIndex();
1874
}
1875
int32_t newIndex = startIndex + aDoAdjustInc;
1876
1877
// make sure we start off in the range
1878
if (newIndex < bottom) {
1879
newIndex = 0;
1880
} else if (newIndex >= top) {
1881
newIndex = aNumOptions - 1;
1882
}
1883
1884
while (1) {
1885
// if the newIndex is selectable, we are golden, bail out
1886
if (IsOptionInteractivelySelectable(newIndex)) {
1887
break;
1888
}
1889
1890
// it WAS disabled, so sart looking ahead for the next enabled option
1891
newIndex += aDoAdjustIncNext;
1892
1893
// well, if we reach end reverse the search
1894
if (newIndex < bottom) {
1895
if (doingReverse) {
1896
return; // if we are in reverse mode and reach the end bail out
1897
} else {
1898
// reset the newIndex to the end of the list we hit
1899
// reverse the incrementer
1900
// set the other end of the list to our original starting index
1901
newIndex = bottom;
1902
aDoAdjustIncNext = 1;
1903
doingReverse = true;
1904
top = startIndex;
1905
}
1906
} else if (newIndex >= top) {
1907
if (doingReverse) {
1908
return; // if we are in reverse mode and reach the end bail out
1909
} else {
1910
// reset the newIndex to the end of the list we hit
1911
// reverse the incrementer
1912
// set the other end of the list to our original starting index
1913
newIndex = top - 1;
1914
aDoAdjustIncNext = -1;
1915
doingReverse = true;
1916
bottom = startIndex;
1917
}