Files
palemoon27/widget/TextEventDispatcher.cpp
T
roytam1 eeee2498f7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1153978 - Part 1: Separate buildIdOp from AsmJSCacheOps. r=jandem,bz (3e2b2c2754)
- Bug 1190032 - Sandbox failure in nsPluginHost::GetPluginTempDir. r=areinald (5698ee5709)
- Bug 1190032 - Sandbox failure in nsPluginHost::GetPluginTempDir, tighten earlier patch. r=areinald (81fad0767b)
- Bug 1201935 - Allow reading from TmpD in OS X content processes. r=smichaud (d67de1d8da)
- Bug 1237847 - [e10s] Null deref crash when running test_pluginstream_newstream.html; r=bobowen (c61e5fa268)
- Add a helper function for iterating indirect layer trees. (bug 1245765 part 1, r=mattwoodrow) (9fcc19e731)
- Propagate D3D9 device resets to remote layers. (bug 1245765 part 2, r=mattwoodrow) (15ab24ebd6)
- Don't propagate simulated device resets to child processes. (bug 1245765 part 3, r=mattwoodrow) (fe0986532c)
- Fix async drawing when we lose the D3D11 device. (bug 1245765 part 4, r=mattwoodrow) (fcf9e1a009)
- Factor compositor initialization out of LayerManagerComposite. (bug 1245765 part 6, r=mattwoodrow) (7af570b6fc)
- Bug 1232042: Execute an additional present for D3D11 on the compositor thread when a WM_PAINT event has returned. r=jrmuizel (ac14c78377)
- Handle device resets by recreating the compositor, rather than the compositor IPDL stack. (bug 1245765 part 7, r=mattwoodrow) (87292d6e2b)
- Ensure that content processes recreate rendering devices. (bug 1245765 part 8, r=mattwoodrow) (8c4e712c6e)
- Invalidate layers when starting a transaction on a stale device. (bug 1245765 part 9, r=mattwoodrow) (330efa7199)
- Bug 1041599 - Maintain a single volume control session between browser, content, and plugins on Windows. r=aklotz (bdab2a3b35)
- align more tests (c6445e1646)
- Bug 1241646 - remove unused token arguments from nsIX509CertDB r=keeler (13e50d449c)
- Bug 1064402 - Part 1: Remove Import button in Servers tab of the Certificate Manager. r=keeler (181a5a0be2)
- Bug 1064402 - Part 2: Remove nsIX509CertDB.importServerCertificate() and nsIX509Cert::SERVER_CERT support in importCertsFromFile(). r=keeler (a4ee6e83f4)
- Bug 1130418 - Remove broken e-mail cert trust editing UI. r=emk (d8dca873c1)
- Bug 1243182 - Enable eslint "space-infix-ops" rule for PSM. r=keeler (9f5110213f)
- Bug 1244245 - Enable eslint "curly" rule for PSM. r=keeler (09b4d913ab)
- Bug 1246365 - Enable eslint "comma-spacing" and "semi" rules for PSM. r=keeler (e85d033547)
- bug 1246765 - remove unnecessary resource://app/ registration from getHSTSPreloadList.js r=Cykesiopka DONTBUILD NPOTB (e4eb6d1a1e)
- Bug 1249595 - Enable 11 more ESLint rules for PSM. r=keeler (7daa42685a)
- Bug 1224968 - Support public key input to unbreak periodic HPKP updates. r=keeler (a14415f3c3)
- Bug 1229284 - Remove support for SHA-1 hashes in genHPKPStaticPins.js. r=keeler (2e54ef3566)
- Bug 1197607, Automated hsts & hpkp updates are failing on mozilla-central, mozilla-aurora, mozilla-esr38, r=cykesiopka (8754cce3ba)
- Bug 1224481 - Comment out CA certs removed in NSS 3.21 in PreloadedHPKPins.json to keep periodic Static HPKP updates working. r=dkeeler (6680c85a1b)
- bug 1232766 - update the preloaded pinset for Google domains r=rbarnes (83697d274b)
- Bug 1250254 - Enable ESLint "no-throw-literal" rule for PSM. r=dkeeler (300ef6f5b8)
- Bug 1256088 - Merge mock app-info implementation into AppInfo.jsm. r=gps (e38ae85b3d)
- Bug 1153978 - Part 0: Separate nsIPlatformInfo from nsIXULAppInfo. r=jst,gps (2f4eef64c1)
- Bug 1153978 - Part 2: Clear pending exception thrown from XDR related APIs when ignoring ReadCachedScript failure. r=bz (09f06d4c74)
- Bug 1153978 - Part 3: Use the build id instead of the XDR_BYTECODE_VERSION constant. r=jandem (2e8e01f534)
- bug 1241317 - gather telemetry on prevalence of FIPS r=jcj r=vladan (905485c911)
- Bug 1220237 - Remove uses of nsIEnumerator from PSM. r=keeler (6b17abd967)
- bug 1239455 - rework telemetry for SHA-1 certificates to reflect possible policy states r=Cykesiopka,mgoodwin,rbarnes (95fb0f63ab)
- Bug 1247847 - Use smart pointers in nsNSSCertHelper.cpp to manage NSS resources. r=keeler (56140f95c4)
- Bug 1248874 - Replace Scoped.h templates used only by PSM in ScopedNSSTypes.h with UniquePtr equivalents. r=dkeeler (1cedc01ab9)
- Bug 1016555 - Disable OCSP checking for certificates covered by OneCRL r=keeler (3dc16a87d6)
- Bug 1227970 - Perform preference checks to allow OCSP Bypass for OneCRL via Kinto r=keeler (58136eb9e5)
- Bug 1219482: Replace PRLogModuleInfo with LazyLogModule in security subdirectory.r=nfroyd (896838cc5d)
- Bug 1226928 - remove Wshadow warning in ScopedNSSTypes, r=keeler (52ccbac1bc)
- Bug 1226928 - signature verification for content-signing, r=keeler,mayhemer (5f589bf0e0)
- Bug 1250256 - Partially clean up nsSDR.cpp. r=keeler (665c582a90)
- bug 1241650 - remove nsIX509CertDB.findCertNicknames r=mgoodwin (bf0c26772b)
- Bug 1250258 - Partially clean up nsNSSCertificateDB.cpp import methods. r=keeler (693e213484)
- Bug 1204202 - Package Universal CRT DLLs for VS2015. r=glandium,ehsan (9b9e1e4057)
- bug 496234 - add test vectors from RFC 1320 for md4 implementation r=mayhemer (6526e81ec7)
- bug 1228175 - fix IsCertBuiltInRoot r=Cykesiopka,mgoodwin (13bdaf7bb3)
- bug 1240118 - add functionality to treat a test certificate as a built-in root r=mgoodwin (bf31c4365b)
- Bug 1245649: Turn on valid-typeof, no-invalid-regexp, no-empty-pattern and no-empty-character-class. r=felipe (f637f26dc7)
- Bug 1245916: Add additional default globals. r=felipe (229e39bbbe)
- Bug 1251011 - Enable ESLint "no-undef" rule for PSM. r=keeler r=mossop (a6e17d09aa)
- Bug 1243636. Switch to gfx::CriticalSection (a4d6172870)
- Bug 1137561 part.1 Implement WinTextEventDispatcherListener as a singleton class for using TextEventDispatcher at handling native keyboard and IME events r=m_kato (f4582070b0)
- Bug 1137572 part.1 TextEventDispatcher should manage its input transaction type r=smaug (ccafc27024)
- Bug 1137572 part.2 Add nsIWidget::GetNativeTextEventDispatcherListener() for TextEventDispatcher::NotifyIME() r=smaug, sr=smaug (21571501e8)
- Bug 1137572 part.3 Use pseudo IME context when TextEventDispatcher has input transaction which is not for native event handler r=smaug (40be7193b1)
- Bug 1137572 part.4 TextEventDispatcher::DispatchInputEvent() should decide if dispatches events with nsIWidget::DispatchInputEvent() with input transaction type r=smaug (ae71f47af2)
- Bug 1137572 part.5 Implement TextEventDispatcher::SetPendingComposition() for some platforms whose clause information may overlap each other or the order may not be from start to the end r=smaug (fd046de0fc)
- Bug 1137572 part.6 TextEventDispatcher::DispatchKeyboardEventInternal() should copy mNativeKeyEvent when it's in native text input transaction r=smaug (eb17ab1738)
- Bug 1137572 part.7 Add TextEventDispatcherListener::WillDispatchKeyboardEvent() for easier to maintain r=smaug (e66759a731)
- Bug 1137572 part.8 Callers of methods to dispatch composition events of TextEventDispatcher should be able to specify specific time/timeStamp r=smaug (2cdfd2f3d4)
- Bug 1137572 part.9 TextEventDispatcher should not allow WillDispatchKeyboardEvent() modifies unexpected members of WidgetKeyboardEvent r=smaug (94f97ff72d)
- Bug 1137561 part.2 Make TSFTextStore use TextEventDispatcher r=m_kato (5b0d92117d)
- Bug 1137561 part.3 Make IMMHandler use TextEventDispatcher r=m_kato (2b5ef42de7)
- Bug 1137561 part.4 Make NativeKey use TextEventDispatcher r=m_kato (e98eb8b72f)
- Bug 1137561 part.5 TextEventDispatcher should decide if keypress events should be fired for specific keys r=m_kato (b5ad4d702c)
2024-01-31 13:43:16 +08:00

760 lines
24 KiB
C++

/* -*- Mode: C++; tab-width: 2; 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 "mozilla/Preferences.h"
#include "mozilla/TextEvents.h"
#include "mozilla/TextEventDispatcher.h"
#include "nsIDocShell.h"
#include "nsIFrame.h"
#include "nsIPresShell.h"
#include "nsIWidget.h"
#include "nsPIDOMWindow.h"
#include "nsView.h"
namespace mozilla {
namespace widget {
/******************************************************************************
* TextEventDispatcher
*****************************************************************************/
bool TextEventDispatcher::sDispatchKeyEventsDuringComposition = false;
TextEventDispatcher::TextEventDispatcher(nsIWidget* aWidget)
: mWidget(aWidget)
, mDispatchingEvent(0)
, mInputTransactionType(eNoInputTransaction)
, mIsComposing(false)
{
MOZ_RELEASE_ASSERT(mWidget, "aWidget must not be nullptr");
static bool sInitialized = false;
if (!sInitialized) {
Preferences::AddBoolVarCache(
&sDispatchKeyEventsDuringComposition,
"dom.keyboardevent.dispatch_during_composition",
false);
sInitialized = true;
}
}
nsresult
TextEventDispatcher::BeginInputTransaction(
TextEventDispatcherListener* aListener)
{
return BeginInputTransactionInternal(aListener,
eSameProcessSyncInputTransaction);
}
nsresult
TextEventDispatcher::BeginTestInputTransaction(
TextEventDispatcherListener* aListener,
bool aIsAPZAware)
{
return BeginInputTransactionInternal(aListener,
aIsAPZAware ? eAsyncTestInputTransaction :
eSameProcessSyncTestInputTransaction);
}
nsresult
TextEventDispatcher::BeginNativeInputTransaction()
{
if (NS_WARN_IF(!mWidget)) {
return NS_ERROR_FAILURE;
}
RefPtr<TextEventDispatcherListener> listener =
mWidget->GetNativeTextEventDispatcherListener();
if (NS_WARN_IF(!listener)) {
return NS_ERROR_FAILURE;
}
return BeginInputTransactionInternal(listener, eNativeInputTransaction);
}
nsresult
TextEventDispatcher::BeginInputTransactionInternal(
TextEventDispatcherListener* aListener,
InputTransactionType aType)
{
if (NS_WARN_IF(!aListener)) {
return NS_ERROR_INVALID_ARG;
}
nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
if (listener) {
if (listener == aListener && mInputTransactionType == aType) {
return NS_OK;
}
// If this has composition or is dispatching an event, any other listener
// can steal ownership. Especially, if the latter case is allowed,
// nobody cannot begin input transaction with this if a modal dialog is
// opened during dispatching an event.
if (IsComposing() || IsDispatchingEvent()) {
return NS_ERROR_ALREADY_INITIALIZED;
}
}
mListener = do_GetWeakReference(aListener);
mInputTransactionType = aType;
if (listener && listener != aListener) {
listener->OnRemovedFrom(this);
}
return NS_OK;
}
void
TextEventDispatcher::EndInputTransaction(TextEventDispatcherListener* aListener)
{
if (NS_WARN_IF(IsComposing()) || NS_WARN_IF(IsDispatchingEvent())) {
return;
}
mInputTransactionType = eNoInputTransaction;
nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
if (NS_WARN_IF(!listener)) {
return;
}
if (NS_WARN_IF(listener != aListener)) {
return;
}
mListener = nullptr;
listener->OnRemovedFrom(this);
}
void
TextEventDispatcher::OnDestroyWidget()
{
mWidget = nullptr;
mPendingComposition.Clear();
nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
mListener = nullptr;
mInputTransactionType = eNoInputTransaction;
if (listener) {
listener->OnRemovedFrom(this);
}
}
nsresult
TextEventDispatcher::GetState() const
{
nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
if (!listener) {
return NS_ERROR_NOT_INITIALIZED;
}
if (!mWidget || mWidget->Destroyed()) {
return NS_ERROR_NOT_AVAILABLE;
}
return NS_OK;
}
void
TextEventDispatcher::InitEvent(WidgetGUIEvent& aEvent) const
{
aEvent.time = PR_IntervalNow();
aEvent.refPoint = LayoutDeviceIntPoint(0, 0);
aEvent.mFlags.mIsSynthesizedForTests = IsForTests();
if (aEvent.mClass != eCompositionEventClass) {
return;
}
void* pseudoIMEContext = GetPseudoIMEContext();
if (pseudoIMEContext) {
aEvent.AsCompositionEvent()->mNativeIMEContext.
InitWithRawNativeIMEContext(pseudoIMEContext);
}
#ifdef DEBUG
else {
MOZ_ASSERT(!XRE_IsContentProcess(),
"Why did the content process start native event transaction?");
MOZ_ASSERT(aEvent.AsCompositionEvent()->mNativeIMEContext.IsValid(),
"Native IME context shouldn't be invalid");
}
#endif // #ifdef DEBUG
}
nsresult
TextEventDispatcher::DispatchEvent(nsIWidget* aWidget,
WidgetGUIEvent& aEvent,
nsEventStatus& aStatus)
{
MOZ_ASSERT(!aEvent.AsInputEvent(), "Use DispatchInputEvent()");
RefPtr<TextEventDispatcher> kungFuDeathGrip(this);
nsCOMPtr<nsIWidget> widget(aWidget);
mDispatchingEvent++;
nsresult rv = widget->DispatchEvent(&aEvent, aStatus);
mDispatchingEvent--;
return rv;
}
nsresult
TextEventDispatcher::DispatchInputEvent(nsIWidget* aWidget,
WidgetInputEvent& aEvent,
nsEventStatus& aStatus)
{
RefPtr<TextEventDispatcher> kungFuDeathGrip(this);
nsCOMPtr<nsIWidget> widget(aWidget);
mDispatchingEvent++;
// If the event is dispatched via nsIWidget::DispatchInputEvent(), it
// sends the event to the parent process first since APZ needs to handle it
// first. However, some callers (e.g., keyboard apps on B2G and tests
// expecting synchronous dispatch) don't want this to do that.
nsresult rv = NS_OK;
if (ShouldSendInputEventToAPZ()) {
aStatus = widget->DispatchInputEvent(&aEvent);
} else {
rv = widget->DispatchEvent(&aEvent, aStatus);
}
mDispatchingEvent--;
return rv;
}
nsresult
TextEventDispatcher::StartComposition(nsEventStatus& aStatus,
const WidgetEventTime* aEventTime)
{
aStatus = nsEventStatus_eIgnore;
nsresult rv = GetState();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (NS_WARN_IF(mIsComposing)) {
return NS_ERROR_FAILURE;
}
mIsComposing = true;
WidgetCompositionEvent compositionStartEvent(true, eCompositionStart,
mWidget);
InitEvent(compositionStartEvent);
if (aEventTime) {
compositionStartEvent.AssignEventTime(*aEventTime);
}
rv = DispatchEvent(mWidget, compositionStartEvent, aStatus);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult
TextEventDispatcher::StartCompositionAutomaticallyIfNecessary(
nsEventStatus& aStatus,
const WidgetEventTime* aEventTime)
{
if (IsComposing()) {
return NS_OK;
}
nsresult rv = StartComposition(aStatus, aEventTime);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// If started composition has already been committed, we shouldn't dispatch
// the compositionchange event.
if (!IsComposing()) {
aStatus = nsEventStatus_eConsumeNoDefault;
return NS_OK;
}
// Note that the widget might be destroyed during a call of
// StartComposition(). In such case, we shouldn't keep dispatching next
// event.
rv = GetState();
if (NS_FAILED(rv)) {
MOZ_ASSERT(rv != NS_ERROR_NOT_INITIALIZED,
"aDispatcher must still be initialized in this case");
aStatus = nsEventStatus_eConsumeNoDefault;
return NS_OK; // Don't throw exception in this case
}
aStatus = nsEventStatus_eIgnore;
return NS_OK;
}
nsresult
TextEventDispatcher::CommitComposition(nsEventStatus& aStatus,
const nsAString* aCommitString,
const WidgetEventTime* aEventTime)
{
aStatus = nsEventStatus_eIgnore;
nsresult rv = GetState();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
// When there is no composition, caller shouldn't try to commit composition
// with non-existing composition string nor commit composition with empty
// string.
if (NS_WARN_IF(!IsComposing() &&
(!aCommitString || aCommitString->IsEmpty()))) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIWidget> widget(mWidget);
rv = StartCompositionAutomaticallyIfNecessary(aStatus, aEventTime);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (aStatus == nsEventStatus_eConsumeNoDefault) {
return NS_OK;
}
// End current composition and make this free for other IMEs.
mIsComposing = false;
EventMessage message = aCommitString ? eCompositionCommit :
eCompositionCommitAsIs;
WidgetCompositionEvent compositionCommitEvent(true, message, widget);
InitEvent(compositionCommitEvent);
if (aEventTime) {
compositionCommitEvent.AssignEventTime(*aEventTime);
}
if (message == eCompositionCommit) {
compositionCommitEvent.mData = *aCommitString;
// Don't send CRLF, replace it with LF here.
compositionCommitEvent.mData.ReplaceSubstring(NS_LITERAL_STRING("\r\n"),
NS_LITERAL_STRING("\n"));
}
rv = DispatchEvent(widget, compositionCommitEvent, aStatus);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
nsresult
TextEventDispatcher::NotifyIME(const IMENotification& aIMENotification)
{
nsresult rv = NS_ERROR_NOT_IMPLEMENTED;
// First, send the notification to current input transaction's listener.
nsCOMPtr<TextEventDispatcherListener> listener = do_QueryReferent(mListener);
if (listener) {
rv = listener->NotifyIME(this, aIMENotification);
}
if (mInputTransactionType == eNativeInputTransaction || !mWidget) {
return rv;
}
// If current input transaction isn't for native event handler, we should
// send the notification to the native text event dispatcher listener
// since native event handler may need to do something from
// TextEventDispatcherListener::NotifyIME() even before there is no
// input transaction yet. For example, native IME handler may need to
// create new context at receiving NOTIFY_IME_OF_FOCUS. In this case,
// mListener may not be initialized since input transaction should be
// initialized immediately before dispatching every WidgetKeyboardEvent
// and WidgetCompositionEvent (dispatching events always occurs after
// focus move).
nsCOMPtr<TextEventDispatcherListener> nativeListener =
mWidget->GetNativeTextEventDispatcherListener();
if (!nativeListener) {
return rv;
}
switch (aIMENotification.mMessage) {
case REQUEST_TO_COMMIT_COMPOSITION:
case REQUEST_TO_CANCEL_COMPOSITION:
// It's not necessary to notify native IME of requests.
return rv;
default: {
// Even if current input transaction's listener returns NS_OK or
// something, we need to notify native IME of notifications because
// when user typing after TIP does something, the changed information
// is necessary for them.
nsresult rv2 =
nativeListener->NotifyIME(this, aIMENotification);
// But return the result from current listener except when the
// notification isn't handled.
return rv == NS_ERROR_NOT_IMPLEMENTED ? rv2 : rv;
}
}
}
bool
TextEventDispatcher::DispatchKeyboardEvent(
EventMessage aMessage,
const WidgetKeyboardEvent& aKeyboardEvent,
nsEventStatus& aStatus,
void* aData)
{
return DispatchKeyboardEventInternal(aMessage, aKeyboardEvent, aStatus,
aData);
}
bool
TextEventDispatcher::DispatchKeyboardEventInternal(
EventMessage aMessage,
const WidgetKeyboardEvent& aKeyboardEvent,
nsEventStatus& aStatus,
void* aData,
uint32_t aIndexOfKeypress)
{
MOZ_ASSERT(aMessage == eKeyDown || aMessage == eKeyUp ||
aMessage == eKeyPress, "Invalid aMessage value");
nsresult rv = GetState();
if (NS_WARN_IF(NS_FAILED(rv))) {
return false;
}
// If the key shouldn't cause keypress events, don't this patch them.
if (aMessage == eKeyPress && !aKeyboardEvent.ShouldCauseKeypressEvents()) {
return false;
}
// Basically, key events shouldn't be dispatched during composition.
if (IsComposing()) {
// However, if we need to behave like other browsers, we need the keydown
// and keyup events. Note that this behavior is also allowed by D3E spec.
// FYI: keypress events must not be fired during composition.
if (!sDispatchKeyEventsDuringComposition || aMessage == eKeyPress) {
return false;
}
// XXX If there was mOnlyContentDispatch for this case, it might be useful
// because our chrome doesn't assume that key events are fired during
// composition.
}
WidgetKeyboardEvent keyEvent(true, aMessage, mWidget);
InitEvent(keyEvent);
keyEvent.AssignKeyEventData(aKeyboardEvent, false);
if (aStatus == nsEventStatus_eConsumeNoDefault) {
// If the key event should be dispatched as consumed event, marking it here.
// This is useful to prevent double action. E.g., when the key was already
// handled by system, our chrome shouldn't handle it.
keyEvent.mFlags.mDefaultPrevented = true;
}
// Corrects each member for the specific key event type.
if (aMessage == eKeyDown || aMessage == eKeyUp) {
MOZ_ASSERT(!aIndexOfKeypress,
"aIndexOfKeypress must be 0 for either eKeyDown or eKeyUp");
// charCode of keydown and keyup should be 0.
keyEvent.charCode = 0;
} else if (keyEvent.mKeyNameIndex != KEY_NAME_INDEX_USE_STRING) {
MOZ_ASSERT(!aIndexOfKeypress,
"aIndexOfKeypress must be 0 for eKeyPress of non-printable key");
// If keypress event isn't caused by printable key, its charCode should
// be 0.
keyEvent.charCode = 0;
} else {
MOZ_RELEASE_ASSERT(
!aIndexOfKeypress || aIndexOfKeypress < keyEvent.mKeyValue.Length(),
"aIndexOfKeypress must be 0 - mKeyValue.Length() - 1");
keyEvent.keyCode = 0;
wchar_t ch =
keyEvent.mKeyValue.IsEmpty() ? 0 : keyEvent.mKeyValue[aIndexOfKeypress];
keyEvent.charCode = static_cast<uint32_t>(ch);
if (ch) {
keyEvent.mKeyValue.Assign(ch);
} else {
keyEvent.mKeyValue.Truncate();
}
}
if (aMessage == eKeyUp) {
// mIsRepeat of keyup event must be false.
keyEvent.mIsRepeat = false;
}
// mIsComposing should be initialized later.
keyEvent.mIsComposing = false;
if (mInputTransactionType == eNativeInputTransaction) {
// Copy mNativeKeyEvent here because for safety for other users of
// AssignKeyEventData(), it doesn't copy this.
keyEvent.mNativeKeyEvent = aKeyboardEvent.mNativeKeyEvent;
} else {
// If it's not a keyboard event for native key event, we should ensure that
// mNativeKeyEvent and mPluginEvent are null/empty.
keyEvent.mNativeKeyEvent = nullptr;
keyEvent.mPluginEvent.Clear();
}
// TODO: Manage mUniqueId here.
// Request the alternative char codes for the key event.
// XXX Currently, they are necessary only when the event is eKeyPress.
keyEvent.alternativeCharCodes.Clear();
if (aMessage == eKeyPress &&
(keyEvent.IsControl() || keyEvent.IsAlt() ||
keyEvent.IsMeta() || keyEvent.IsOS())) {
nsCOMPtr<TextEventDispatcherListener> listener =
do_QueryReferent(mListener);
if (listener) {
DebugOnly<WidgetKeyboardEvent> original(keyEvent);
listener->WillDispatchKeyboardEvent(this, keyEvent, aIndexOfKeypress,
aData);
MOZ_ASSERT(keyEvent.mMessage ==
static_cast<WidgetKeyboardEvent&>(original).mMessage);
MOZ_ASSERT(keyEvent.keyCode ==
static_cast<WidgetKeyboardEvent&>(original).keyCode);
MOZ_ASSERT(keyEvent.location ==
static_cast<WidgetKeyboardEvent&>(original).location);
MOZ_ASSERT(keyEvent.mIsRepeat ==
static_cast<WidgetKeyboardEvent&>(original).mIsRepeat);
MOZ_ASSERT(keyEvent.mIsComposing ==
static_cast<WidgetKeyboardEvent&>(original).mIsComposing);
MOZ_ASSERT(keyEvent.mKeyNameIndex ==
static_cast<WidgetKeyboardEvent&>(original).mKeyNameIndex);
MOZ_ASSERT(keyEvent.mCodeNameIndex ==
static_cast<WidgetKeyboardEvent&>(original).mCodeNameIndex);
MOZ_ASSERT(keyEvent.mKeyValue ==
static_cast<WidgetKeyboardEvent&>(original).mKeyValue);
MOZ_ASSERT(keyEvent.mCodeValue ==
static_cast<WidgetKeyboardEvent&>(original).mCodeValue);
}
}
DispatchInputEvent(mWidget, keyEvent, aStatus);
return true;
}
bool
TextEventDispatcher::MaybeDispatchKeypressEvents(
const WidgetKeyboardEvent& aKeyboardEvent,
nsEventStatus& aStatus,
void* aData)
{
// If the key event was consumed, keypress event shouldn't be fired.
if (aStatus == nsEventStatus_eConsumeNoDefault) {
return false;
}
// If the key shouldn't cause keypress events, don't fire them.
if (!aKeyboardEvent.ShouldCauseKeypressEvents()) {
return false;
}
// If the key isn't a printable key or just inputting one character or
// no character, we should dispatch only one keypress. Otherwise, i.e.,
// if the key is a printable key and inputs multiple characters, keypress
// event should be dispatched the count of inputting characters times.
size_t keypressCount =
aKeyboardEvent.mKeyNameIndex != KEY_NAME_INDEX_USE_STRING ?
1 : std::max(static_cast<nsAString::size_type>(1),
aKeyboardEvent.mKeyValue.Length());
bool isDispatched = false;
bool consumed = false;
for (size_t i = 0; i < keypressCount; i++) {
aStatus = nsEventStatus_eIgnore;
if (!DispatchKeyboardEventInternal(eKeyPress, aKeyboardEvent,
aStatus, aData, i)) {
// The widget must have been gone.
break;
}
isDispatched = true;
if (!consumed) {
consumed = (aStatus == nsEventStatus_eConsumeNoDefault);
}
}
// If one of the keypress event was consumed, return ConsumeNoDefault.
if (consumed) {
aStatus = nsEventStatus_eConsumeNoDefault;
}
return isDispatched;
}
/******************************************************************************
* TextEventDispatcher::PendingComposition
*****************************************************************************/
TextEventDispatcher::PendingComposition::PendingComposition()
{
Clear();
}
void
TextEventDispatcher::PendingComposition::Clear()
{
mString.Truncate();
mClauses = nullptr;
mCaret.mRangeType = 0;
}
void
TextEventDispatcher::PendingComposition::EnsureClauseArray()
{
if (mClauses) {
return;
}
mClauses = new TextRangeArray();
}
nsresult
TextEventDispatcher::PendingComposition::SetString(const nsAString& aString)
{
mString = aString;
return NS_OK;
}
nsresult
TextEventDispatcher::PendingComposition::AppendClause(uint32_t aLength,
uint32_t aAttribute)
{
if (NS_WARN_IF(!aLength)) {
return NS_ERROR_INVALID_ARG;
}
switch (aAttribute) {
case NS_TEXTRANGE_RAWINPUT:
case NS_TEXTRANGE_SELECTEDRAWTEXT:
case NS_TEXTRANGE_CONVERTEDTEXT:
case NS_TEXTRANGE_SELECTEDCONVERTEDTEXT: {
EnsureClauseArray();
TextRange textRange;
textRange.mStartOffset =
mClauses->IsEmpty() ? 0 : mClauses->LastElement().mEndOffset;
textRange.mEndOffset = textRange.mStartOffset + aLength;
textRange.mRangeType = aAttribute;
mClauses->AppendElement(textRange);
return NS_OK;
}
default:
return NS_ERROR_INVALID_ARG;
}
}
nsresult
TextEventDispatcher::PendingComposition::SetCaret(uint32_t aOffset,
uint32_t aLength)
{
mCaret.mStartOffset = aOffset;
mCaret.mEndOffset = mCaret.mStartOffset + aLength;
mCaret.mRangeType = NS_TEXTRANGE_CARETPOSITION;
return NS_OK;
}
nsresult
TextEventDispatcher::PendingComposition::Set(const nsAString& aString,
const TextRangeArray* aRanges)
{
Clear();
nsAutoString str(aString);
// Don't expose CRLF to web contents, instead, use LF.
str.ReplaceSubstring(NS_LITERAL_STRING("\r\n"), NS_LITERAL_STRING("\n"));
nsresult rv = SetString(str);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (!aRanges || aRanges->IsEmpty()) {
// Create dummy range if aString isn't empty.
if (!aString.IsEmpty()) {
rv = AppendClause(str.Length(), NS_TEXTRANGE_RAWINPUT);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
}
return NS_OK;
}
// Adjust offsets in the ranges for XP linefeed character (only \n).
// XXX Following code is the safest approach. However, it wastes performance.
// For ensuring the clauses do not overlap each other, we should redesign
// TextRange later.
for (uint32_t i = 0; i < aRanges->Length(); ++i) {
TextRange range = aRanges->ElementAt(i);
TextRange nativeRange = range;
if (nativeRange.mStartOffset > 0) {
nsAutoString preText(Substring(aString, 0, nativeRange.mStartOffset));
preText.ReplaceSubstring(NS_LITERAL_STRING("\r\n"),
NS_LITERAL_STRING("\n"));
range.mStartOffset = preText.Length();
}
if (nativeRange.Length() == 0) {
range.mEndOffset = range.mStartOffset;
} else {
nsAutoString clause(
Substring(aString, nativeRange.mStartOffset, nativeRange.Length()));
clause.ReplaceSubstring(NS_LITERAL_STRING("\r\n"),
NS_LITERAL_STRING("\n"));
range.mEndOffset = range.mStartOffset + clause.Length();
}
if (range.mRangeType == NS_TEXTRANGE_CARETPOSITION) {
mCaret = range;
} else {
EnsureClauseArray();
mClauses->AppendElement(range);
}
}
return NS_OK;
}
nsresult
TextEventDispatcher::PendingComposition::Flush(
TextEventDispatcher* aDispatcher,
nsEventStatus& aStatus,
const WidgetEventTime* aEventTime)
{
aStatus = nsEventStatus_eIgnore;
nsresult rv = aDispatcher->GetState();
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (mClauses && !mClauses->IsEmpty() &&
mClauses->LastElement().mEndOffset != mString.Length()) {
NS_WARNING("Sum of length of the all clauses must be same as the string "
"length");
Clear();
return NS_ERROR_ILLEGAL_VALUE;
}
if (mCaret.mRangeType == NS_TEXTRANGE_CARETPOSITION) {
if (mCaret.mEndOffset > mString.Length()) {
NS_WARNING("Caret position is out of the composition string");
Clear();
return NS_ERROR_ILLEGAL_VALUE;
}
EnsureClauseArray();
mClauses->AppendElement(mCaret);
}
RefPtr<TextEventDispatcher> kungFuDeathGrip(aDispatcher);
nsCOMPtr<nsIWidget> widget(aDispatcher->mWidget);
WidgetCompositionEvent compChangeEvent(true, eCompositionChange, widget);
aDispatcher->InitEvent(compChangeEvent);
if (aEventTime) {
compChangeEvent.AssignEventTime(*aEventTime);
}
compChangeEvent.mData = mString;
if (mClauses) {
MOZ_ASSERT(!mClauses->IsEmpty(),
"mClauses must be non-empty array when it's not nullptr");
compChangeEvent.mRanges = mClauses;
}
// While this method dispatches a composition event, some other event handler
// cause more clauses to be added. So, we should clear pending composition
// before dispatching the event.
Clear();
rv = aDispatcher->StartCompositionAutomaticallyIfNecessary(aStatus,
aEventTime);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
if (aStatus == nsEventStatus_eConsumeNoDefault) {
return NS_OK;
}
rv = aDispatcher->DispatchEvent(widget, compChangeEvent, aStatus);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
return NS_OK;
}
} // namespace widget
} // namespace mozilla