Files
palemoon27/layout/xul/nsTextBoxFrame.cpp
T
roytam1 049b3235ac import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1207494 - Part 8: Remove use of expression closure from dom/identity/. r=ferjm (34fac889f8)
- minor crash thing (13fe2827c2)
- Bug 1243359 - initialize mScrollSeriesNumber in all ScrollWheelInput constructors. r=roc (94163d8eca)
- fix misspatch (b380a7bbe4)
- Bug 1207412 - Make SystemTimeConverter use TimeStamp::Now() when converting times; r=karlt (f408549605)
- Bug 1212102 - Drop unnecessary assertion comparing timestamps in SystemTimeConverter; r=karlt (1efaa04b3f)
- Bug 1241302 - Slightly modernize this code. r=jst (c1e97bc069)
- bug 1216916 clean up when InvokeDragSessionWithImage/Selection() fails r=roc (9cdf71b717)
- Bug 1231329 - run ConvertToUnscaledDevPixels if *aPresContext is valid. r=roc (d10f23633b)
- Bug 1245927: Innerize before creating DOM files from the file picker. r=baku (8754128362)
- Bug 1155214 - Mark nsIBidiKeyboard as builtinclass; r=mrbkap (2d00326d2b)
- reorder (c3c1ba92c9)
- Bug 1236566 - add override declarations for widget/windows/GfxInfo.h; r=roc (940b40ed91)
- Bug 1242659: Part 1. More information on the mismatches. r=jrmuizel (78331ddad2)
- Block some Radeon drivers that crash on D3D9. (bug 1213107, r=jrmuizel) (482b66d313)
- Bug 1203199 - Blacklist DXVA on some older intel drivers for causing crashes. r=jrmuizel (f1827d4498)
- Bug 1203199 - Fix driver range with blacklist to avoid blacklisting other OSes. (2c2d547296)
- Bug 1203199 - Bustage fix. CLOSED TREE (3233d407f3)
- Bug 1178385. Enable DXVA on the G45 r=ajones (3c59a58a15)
- Bug 1188442 IMMHandler::GetSelection() should use static Selection instance when IME doesn't have focus and return its or mSelection's reference r=emk (5cc4b30433)
- Bug 1238899 Create hidden native caret for ATOK at composing in windowless plugin r=m_kato (40ef5bb4aa)
- Bug 1257919 part 1. Kill off nsIXSLTException. r=khuey (11f37643f2)
- Bug 1242072 - Change implementation of BaseProxyHandler::get() to follow ES6 [[Get]] specification. r=jorendorff (094a67f284)
- Bug 489636 - Add a GC u-bench test for property tree splitting via deletion; r=sfink (9282fec25f)
- Bug 1257919 part 2. Make nsIException and nsIStackFrame builtinclass, so we can start using [implicit_jscontext] on them. r=khuey (0e65fb8554)
- Bug 1257919 part 3. Make the various toString methods on exceptions take an explicit JSContext. r=khuey (b342fb4930)
- Bug 1257919 part 4. Stop returning StackFrame instances from exceptions::CreateStack. C++ callers of GetCurrentJSStack or exceptions::CreateStack always check for null anyway, and none of them seem to want this non-JS thing. r=khuey (d34036ccf9)
- Bug 1257919 part 5. Get rid of the now-unused StackFrame class. r=khuey (aa13af0dfe)
- Bug 1141222 - Create ScriptError with stack from Cu.reportError. r=bholley (b83ad26aa0)
- Bug 1208641 - Extract stack from DOM/XPC exception. r=bholley (e382b5f48c)
- Bug 1254380 part 1. Find the relevant window when the compartment we've got is an addon sandbox compartment in AutoJSAPI exception/warning reporting code. r=bholley (4b1f6c64a9)
- Bug 1250630 - remove PBackgroundTest and ifdef ENABLE_TEST blocks. r=khuey (d7b36860a3)
- Bug 1250963 part 1. Change NotifyRunnable::Dispatch to not require a JSContext. r=khuey (48e03c2fc2)
- Bug 1250963 part 2. Remove the unused JSContext argument of WorkerPrivate::ModifyBusyCount. r=khuey (0f5ca42be1)
- Bug 1250291 part 1. Stop pretending to report exceptions in MainThreadStopSyncLoopRunnable::PostDispatch. r=khuey (6e1c81cc06)
- Bug 1250291 part 2. Stop pretending to report exceptions in MainThreadWorkerSyncRunnable::PostDispatch. r=khuey (f3d846ea31)
- Bug 1250291 part 3. Stop pretending to report exceptions in WorkerDebuggerRunnable::PostDispatch. r=khuey (10bc1710d1)
- Bug 1250975. Stop passing a JSContext argument to WorkerRunnable::PreDispatch and its overrides. r=khuey (71ab9046f0)
- Bug 1255298. Just pass through the JSContext when passing through the NotificationOptions in notification code. r=wchen (552ae8e33e)
- Bug 1250185 part 2. Remove some JSContext stuff that's no longer needed in Notification code. r=khuey (20b99ef28b)
- Bug 1251045 part 8. Remove the JSContext argument from some nsINotificationStorageCallback methods. r=khuey (170c4afabc)
- Bug 1227015 P7 Supress unused ErrorResult exception if the worker runnable failed to dispatch. r=catalinb (23a3cc6f45)
- Bug 1251045 part 3. Remove the JSContext argument of WorkerRunnable::PostDispatch and its overrides. r=khuey (6a666d1a4a)
- Bug 1251045 part 2. Remove the JSContext argument of ModifyBusyCountFromWorker. r=khuey (105bc4f59e)
- Bug 1252130. Remove unnecessary JSContext argument from NotificationWorkerRunnable::WorkerRunInternal. r=khuey (642727f6f6)
- Bug 1252127. Remove unnecessary JSContext argument from PromiseWorkerProxy::CleanUp. r=khuey (339e1157d1)
- Bug 1251045 part 1. Make it possible to dispatch a ModifyBusyCountRunnable without a JSContext. r=khuey (665c1f81b4)
- Bug 1251045 part 4. Remove the JSContext argument of WorkerRunnable::Dispatch. r=khuey (6c5cdab2b7)
- Bug 1250185 part 1. nsIStructuredCloneContainer.initFromBase64 doesn't need a JSContext argument. r=khuey (d63a219209)
- fix (773c0393aa)
- Bug 1251045 part 5. Remove the JSContext argument from WorkerPrivateParent::Freeze/Thaw. r=khuey (cd419bfd2c)
- Bug 1251045 part 6. Remove the JSContext argument from some worker debugger methods that no longer need it. r=khuey (abcc437cb9)
- Bug 1251045 part 7. Remove the JSContext argument from some worker methods that no longer need it. r=khuey (3ddcbca08c)
- Bug 1249652 part 1. Add a method on ErrorResult to steal an exception, if any, from a JSContext. r=khuey (9c07f5044b)
- Bug 1229071 - importScripts should throw the correct error result in case the loading of one of scripts fails, r=bz (cd37645d76)
- Bug 1229970 Abort script loading start requests if a load has been canceled. r=khuey (a44d9128ca)
- Bug 1233171 Cancel channel when ScriptLoader is aborted during service worker script load. r=khuey (3b6ceafec7)
- Bug 1249351 part 1. When doing importScripts of multiple scripts in a service worker, make sure to track the cache streams per-loadinfo, instead of trying to make them all wait on the same stream. r=bkelly (e1ccea9685)
- Bug 1157544 - Fix a typo in the test; r=baku (8c0bf8f504)
- Bug 1249351 part 2. Clean up test_importscript.html and add multiple-url importScript() case. r=bz (52b0a31032)
- Bug 1249652 part 2. ScriptExecutorRunnable::WorkerRun should immediately move JS exceptions to its ErrorResult instead of allowing them to linger on the JSContext. r=baku,khuey (f628d3c8ba)
- Bug 1249652 part 3. Simplify way we handle canceling when ScriptLoaderRunnable::RunInternal fails by canceling things with its actual failure code, so we don't have to guess which failed loads are actual failures and which are just canceled via this mechanism. r=baku,khuey (388543fbc3)
- Bug 1251369. Use an AutoJSAPI that reports its own exceptions around the main runloop in workers. r=khuey (28b33287cd)
- Bug 1251518. Fix js::ErrorReportToString to make a bit more sense, and change worker code to not use it anyway, so it matches the mainthread code. r=bholley,terrence (a48a40de90)
- Bug 1254380 part 2. Go ahead and log the stack from our exception in AutoJSAPI::ReportException even if we don't have a window. r=bholley (64532b6017)
- Bug 1212328 - Clean up some JSErrorReport-related code. r=Waldo,bz (d5aa611edc)
- Bug 1255192 part 1. Remove the JSContext argument of JS::ExceptionStackOrNull. r=bholley (39b631d5ad)
- bug 1252687 - make the ctor for CycleCollectorStats constexpr r=mccr8 (9e8168d8ac)
- Bug 1254380 part 3. Skip firing error events for mainthread out of memory exceptions via AutoJSAPI::ReportException. r=bholley (d5e4e7dc29)
- Bug 1254230 kinda-fix. Make sure to never send script errors with stacks attached to the console service if the associated windows have already had FreeInnerObjects called on them. r=bholley (8c379fe0e0)
- Bug 1255192 part 2. Clean up the JSContext usage around xpc::FindExceptionStackForConsoleReport now that it just needs a JSContext for rooting. r=bholley (cade862491)
- Bug 1255201. Improve the stack handling in nsXPCComponents_Utils::ReportError for the DOMException case to include the stack from the DOMException. r=bholley (fc6c065284)
- Bug 1257919 part 6. Make the filename getter on JSStackFrame take an explicit JSContext. r=khuey (cde115b789)
- Bug 1257919 part 7. Make the name getter on JSStackFrame take an explicit JSContext. r=khuey (d7466e9eab)
- Bug 1257919 part 8. Make the line/column number getters on JSStackFrame take an explicit JSContext. r=khuey (b8766b98b2)
- Bug 1257919 part 9. Make the asyncCause/asyncCaller getters on JSStackFrame take an explicit JSContext. r=khuey (b776ff9c6d)
- Bug 1257919 part 10. Make the caller and formattedStack getters on JSStackFrame take an explicit JSContext. r=khuey (dc4d3d9091)
- Bug 1252091. Add/RemoveFeature don't need a JSContext argument. r=khuey (5be6253a67)
- Bug 1252123. Remove some unnecessary JSContext arguments from worker ScriptLoader methods. r=khuey (1657a35268)
- Bug 1255181. Remove AutoJSAPI::InitWithLegacyErrorReporting. r=bholley (5ee7ac506e)
- Bug 1254847 part 1. Take ownership of error reporting on the AutoEntryScript in nsXPCWrappedJSClass::DelegatedQueryInterface. r=bholley (62d987b030)
- make style wrong again.... (fa4e6cfbc1)
- Bug 1254847 part 2. Change nsJSNPRuntime to always use AutoEntryScript and always take ownership of error reporting. r=bholley (d24cb80622)
- Bug 1251655 - Remove support for JavaScript-global-constructor-prototype-alias. r=bz. (2b354ea423)
- Bug 1251655 - Remove support for JavaScript-DOM-class and JavaScript-DOM-interface. r=bz. (dd6786ea57)
- Bug 1251275. Switch to using an AutoEntryScript in WorkerPrivate::RunExpiredTimeouts. r=khuey (f10d1b0dec)
- Bug 1072144 part 1. Just release-assert that Promise::Resolve does not fail in service worker code. It can only do that on OOM or overrecursion anyway, and overrecursion is not likely if we're coming right off a runnable. r=khuey (ba4c89a3bc)
- Bug 1072144 part 2. When UnregisterWorker tries to ScheduleWorker and that throws, just suppress the exception: there is no good place to report it anyway. r=khuey (ca563ec5cd)
- Bug 1072144 part 3. Hoist the exception reporting out of WorkerRunnable::PostRun into WorkerRunnable::Run and make it unconditional. r=khuey (9914acd4a6)
- Bug 1252221. When GetOrCreateGlobalScope fails while trying to run a ScriptExecutorRunnable::WorkerRun, just suppress the exception, because there is no way to report it without a compartment to work with. r=khuey (abcc9df148)
- Bug 1072144 part 4. Add a WorkerRunnable::PreRun so that we can move worker global creation to it and always have an AutoEntryScript by the time we're evaluating the main worker script. r=khuey (007b528868)
- Bug 1251276 part 1. Change WorkerPrivate::CancelAllTimeouts to no longer call RunExpiredTimeouts. r=khuey (6b937370a1)
- Bug 1251276 part 2. Remove the JSContext argument of WorkerPrivate::CancelAllTimeouts. r=khuey (336b788e03)
- Bug 1251380. Change things so that WorkerPrivate::NotifyInternal (hopefully) never throws. r=khuey (1d4863f83a)
- Bug 1254846. Add an AutoEntryScript constructor that takes a JSObject instead of an nsIGlobalObject, for convenience. r=bholley (693857f9b0)
- Bug 1255706 part 1. Remove JSContext argument from WorkerPrivate constructor. r=khuey (0486bdb01c)
- Bug 1255706 part 2. Remove JSContext argument from WorkerPrivate::Terminate. r=khuey (f0b62de092)
- Bug 1257568. Remove the JSContext argument of WorkerPrivate::Kill. r=khuey (ebe7d247b5)
- Bug 1252189. Remove the unnecessary JSContext argument from WorkerPrivate::FreezeInternal/ThawInternal. r=khuey (22b137b05e)
- Bug 1119490 - Expose the URL constructor to WorkerDebuggerGlobalScope;r=khuey (6f4fc13e1e)
- Bug 1241841 - Clear the worker's debugger event queue before destroying its context;r=khuey (a1e8dd4b2d)
- Bug 1249950 - Add Performance Markers for MessagePort - patch 1 - remove non-useful 'explicit', r=smaug (8a014b53e6)
- Bug 1249950 - Add Performance Markers for MessagePort - patch 2, r=smaug, r=vporof (560caf0ae1)
- bug 1250486 - make the ComponentsSH ctor constexpr r=bz (1c441dbb0f)
- Bug 1257032: Make files in dom/workers actually build without unification. r=baku (6ab4ae0b65)
- Bug 1241522 - handle OOM in nsExpatDriver::HandleCharacterData; r=hsivonen (b652220cdc)
- Bug 1219482: Replace PRLogModuleInfo with LazyLogModule in various files.r=benjamin (5fd5e8dbc8)
- Bug 1238545 - Remove nsISimpleUnicharStreamFactory; r=froydnj (f0018c5b16)
- Bug 1257335. Replace some AutoSafeJSContext uses with AutoJSAPI or AutoJSContext uses. r=bholley (7baf79deb7)
- Bug 1247635 - Unify PostMessageRunnable and DispatchEventRunnable in MessagePort.cpp, r=smaug (df2765c215)
- Bug 1250572 - Force a parent object in MessagePort/Channel and in StructuredCloneHolder, r=smaug (2a929d59d1)
- Bug 1255375 - MessagePort should not leak if DispatchMessage() fails, r=smaug (0a5cdebfb0)
- Bug 1251272. Remove the dead code in ReportErrorRunnable::ReportError that could fail, and make it infallible. r=khuey (89e80694d0)
- Bug 1072144 part 5. Stop fiddling with compartments on the JSContext before calling PostRun in WorkerRunnable::Run. Add some documentation explaining what's going on. r=khuey (91f4bb6a7c)
- Bug 1072144 part 6. Switch WorkerRunnable::Run to calling TakeOwnershipOfErrorReporting on its AutoJSAPI/AutoEntryScript and remove the remaining JS_ReportPendingException callers in worker code. r=khuey (405d9e0282)
- Bug 1179548 - Close the windows opened in private browsing worker tests; r=baku (acf3430b69)
- Bug 1179753 - Use pushPrefEnv more in worker tests; r=baku (4bfd949c72)
- Bug 1134224 - More test for test_bug1132395.html, r=ehsan (626eb100cd)
- Bug 1134224 - onerror for test_bug1132395.html, r=ehsan (147195f57e)
- Bug 1207635 - get rid of dom.workers.sharedWorkers.enabled pref, r=khuey (22fe2965c6)
- Bug 1252592. JS warnings should not trigger error events on shared workers. r=khuey (7f05c2c00d)
- Bug 1251308; r=luke (3cbec95738)
- Bug 1246838 - Handle const qualifiers and references better in Variant. r=waldo (30da6e3ebf)
- Bug 1254565 - Allow passing matchers as rvalues to Variant::match. r=froydnj (1dd799fb0a)
- Bug 1246841 - Allow construction of Variant values using type inference. r=waldo (6ba3e6704c)
- Bug 1250666 - Forward Variant's move constructor argument correctly to the underlying variant type. r=waldo (7353a53bf0)
- Bug 1252185. Remove the dead "target" variable from CloseEventRunnable::WorkerRun. r=khuey (be172da10b)
- Bug 1253059: Use fallible allocation in the worker error reporter. r=baku (963222bdd4)
- Bug 1253199 - MessagePort should handle the dispatching a message when the parent window is gone, r=smaug (d552e3cd9e)
- Bug 1252839 - Remove some if stmt after allocation with 'new' - patch 2, r=bz (3c7eb959bc)
- Bug 1252839 - Remove some if stmt after allocation with 'new' - patch 1, r=bz (85067dbfb6)
- Bug 1254855. Switch AutoEntryScripts in nsDirectoryViewer to take ownership of error reporting. r=bholley (8c10532323)
- Bug 1252565 part 1. Push the script environment preparer bits up from XPCJSRuntime to CycleCollectedJSRuntime, because we need them on workers to do ctypes on workers properly. r=bholley (aecf2595dd)
- Bug 1252565 part 2. Make dom::WarningOnlyErrorReporter handle workers. r=bholley (f415b8868b)
- Bug 1244222 - Check for function interfaces in DelegatedQueryInterface. r=bz (d213eec83c)
- Bug 1254393. Take ownership of error reporting on the AutoEntryScript in nsXPCWrappedJSClass::CallMethod. r=bholley (4765b501c0)
- Bug 1251769 - Remove remaining references to MOZILLA_XPCOMRT_API from mfbt. r=froydnj (236adc1d4c)
- Bug 1247835 (part 0) - Minor comment and style tweaks in BinarySearch.h. r=luke. (db04793721)
- Bug 1244074 - Part 1: Move SheetParsingMode to a separate file. r=dholbert (290adaadea)
- Bug 1244074 - Part 2: Add HandleRefPtr for refcounting StyleSheetHandles. r=dholbert r=waldo (8549b24392)
- Bug 1244068 - Part 1: Add enum to represent the style system backend type. r=dholbert (c2e53feaf2)
- Bug 1244068 - Part 2: Add skeleton ServoStyleSet and a StyleSetHandle smart pointer. r=dholbert (71a5c28629)
- Bug 1244068 - Part 3: Factor out nsStyleSet getting in RestyleManager/ElementRestyler. r=dholbert (9e9f4f2e80)
- Bug 1245406: In ReflowBlockFrame, use Maybe<> to destroy & reconstruct a stack-allocated object, instead of an explicit call to destructor & placement 'new'. r=dbaron (d36858b818)
- Bug 1244068 - Part 4: Use StyleSetHandle instead of concrete style set class in most places. r=dholbert (93f9bcf799)
- Bug 1244074 - Part 3: Add skeleton ServoStyleSheet and a StyleSheetHandle smart pointer. r=dholbert (5b4fbdce38)
- Bug 1195173 - Apply CSP to preloaded styles within layout/style/Loader.cpp (r=bz) (d1ba920fd3)
- Bug 1245681 - Fix addOverrideStyleSheet. r=bz (64099eac73)
- Bug 1244074 - Part 4: Use StyleSheetHandle instead of concrete style sheet class in most places. r=dholberti (867470ac83)
- Bug 1246013 (part 1) - Store a copy of the ETLDEntry directly in DomainEntry instead of a pointer to it. r=jduell. (587b3a9fb7)
- Bug 1246013 (part 2) - Change "explicit/xpcom/effective-TLD-service" path to the more sensible "explicit/network/effective-TLD-service". r=jduell. (2e0df6f28f)
- Bug 1247835 (part 1) - Use binary search instead of a hash table in nsEffectiveTLDService. r=jduell. (685dae01c0)
- Bug 1257121 part 1 - Use struct for passing some params of font metrics. r=jfkthame (1dfd7a7429)
- Bug 1257121 part 2 - Merge nsFontMetrics::Init to the constructor and remove unused failure handling code. r=jfkthame (0cdc441511)
- Bug 1257121 part 3 - Add GetInflatedFontMetricsForFrame function to simplify a common use pattern. r=jfkthame (d9630ebd1b)
- Bug 1257121 part 4 - Use return value rather than out param to retur font metrics. r=jfkthame (c9a5b1d1dd)
- Bug 1257121 part 5 - Make nsDeviceContext::mFontCache a RefPtr. r=jfkthame (9c53238a6a)
2024-01-29 15:26:23 +08:00

1209 lines
39 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 "nsTextBoxFrame.h"
#include "gfx2DGlue.h"
#include "gfxUtils.h"
#include "mozilla/gfx/2D.h"
#include "nsFontMetrics.h"
#include "nsReadableUtils.h"
#include "nsCOMPtr.h"
#include "nsGkAtoms.h"
#include "nsPresContext.h"
#include "nsRenderingContext.h"
#include "nsStyleContext.h"
#include "nsIContent.h"
#include "nsNameSpaceManager.h"
#include "nsBoxLayoutState.h"
#include "nsMenuBarListener.h"
#include "nsXPIDLString.h"
#include "nsIServiceManager.h"
#include "nsIDOMElement.h"
#include "nsIDOMXULLabelElement.h"
#include "mozilla/EventStateManager.h"
#include "nsITheme.h"
#include "nsUnicharUtils.h"
#include "nsContentUtils.h"
#include "nsDisplayList.h"
#include "nsCSSRendering.h"
#include "nsIReflowCallback.h"
#include "nsBoxFrame.h"
#include "mozilla/Preferences.h"
#include "nsLayoutUtils.h"
#include "mozilla/Attributes.h"
#ifdef ACCESSIBILITY
#include "nsAccessibilityService.h"
#endif
#include "nsBidiUtils.h"
#include "nsBidiPresUtils.h"
using namespace mozilla;
using namespace mozilla::gfx;
class nsAccessKeyInfo
{
public:
int32_t mAccesskeyIndex;
nscoord mBeforeWidth, mAccessWidth, mAccessUnderlineSize, mAccessOffset;
};
bool nsTextBoxFrame::gAlwaysAppendAccessKey = false;
bool nsTextBoxFrame::gAccessKeyPrefInitialized = false;
bool nsTextBoxFrame::gInsertSeparatorBeforeAccessKey = false;
bool nsTextBoxFrame::gInsertSeparatorPrefInitialized = false;
nsIFrame*
NS_NewTextBoxFrame (nsIPresShell* aPresShell, nsStyleContext* aContext)
{
return new (aPresShell) nsTextBoxFrame(aContext);
}
NS_IMPL_FRAMEARENA_HELPERS(nsTextBoxFrame)
NS_QUERYFRAME_HEAD(nsTextBoxFrame)
NS_QUERYFRAME_ENTRY(nsTextBoxFrame)
NS_QUERYFRAME_TAIL_INHERITING(nsTextBoxFrameSuper)
nsresult
nsTextBoxFrame::AttributeChanged(int32_t aNameSpaceID,
nsIAtom* aAttribute,
int32_t aModType)
{
bool aResize;
bool aRedraw;
UpdateAttributes(aAttribute, aResize, aRedraw);
if (aResize) {
PresContext()->PresShell()->
FrameNeedsReflow(this, nsIPresShell::eStyleChange,
NS_FRAME_IS_DIRTY);
} else if (aRedraw) {
nsBoxLayoutState state(PresContext());
Redraw(state);
}
// If the accesskey changed, register for the new value
// The old value has been unregistered in nsXULElement::SetAttr
if (aAttribute == nsGkAtoms::accesskey || aAttribute == nsGkAtoms::control)
RegUnregAccessKey(true);
return NS_OK;
}
nsTextBoxFrame::nsTextBoxFrame(nsStyleContext* aContext):
nsLeafBoxFrame(aContext), mAccessKeyInfo(nullptr), mCropType(CropRight),
mNeedsReflowCallback(false)
{
MarkIntrinsicISizesDirty();
}
nsTextBoxFrame::~nsTextBoxFrame()
{
delete mAccessKeyInfo;
}
void
nsTextBoxFrame::Init(nsIContent* aContent,
nsContainerFrame* aParent,
nsIFrame* aPrevInFlow)
{
nsTextBoxFrameSuper::Init(aContent, aParent, aPrevInFlow);
bool aResize;
bool aRedraw;
UpdateAttributes(nullptr, aResize, aRedraw); /* update all */
// register access key
RegUnregAccessKey(true);
}
void
nsTextBoxFrame::DestroyFrom(nsIFrame* aDestructRoot)
{
// unregister access key
RegUnregAccessKey(false);
nsTextBoxFrameSuper::DestroyFrom(aDestructRoot);
}
bool
nsTextBoxFrame::AlwaysAppendAccessKey()
{
if (!gAccessKeyPrefInitialized)
{
gAccessKeyPrefInitialized = true;
const char* prefName = "intl.menuitems.alwaysappendaccesskeys";
nsAdoptingString val = Preferences::GetLocalizedString(prefName);
gAlwaysAppendAccessKey = val.EqualsLiteral("true");
}
return gAlwaysAppendAccessKey;
}
bool
nsTextBoxFrame::InsertSeparatorBeforeAccessKey()
{
if (!gInsertSeparatorPrefInitialized)
{
gInsertSeparatorPrefInitialized = true;
const char* prefName = "intl.menuitems.insertseparatorbeforeaccesskeys";
nsAdoptingString val = Preferences::GetLocalizedString(prefName);
gInsertSeparatorBeforeAccessKey = val.EqualsLiteral("true");
}
return gInsertSeparatorBeforeAccessKey;
}
class nsAsyncAccesskeyUpdate final : public nsIReflowCallback
{
public:
explicit nsAsyncAccesskeyUpdate(nsIFrame* aFrame) : mWeakFrame(aFrame)
{
}
virtual bool ReflowFinished() override
{
bool shouldFlush = false;
nsTextBoxFrame* frame =
static_cast<nsTextBoxFrame*>(mWeakFrame.GetFrame());
if (frame) {
shouldFlush = frame->UpdateAccesskey(mWeakFrame);
}
delete this;
return shouldFlush;
}
virtual void ReflowCallbackCanceled() override
{
delete this;
}
nsWeakFrame mWeakFrame;
};
bool
nsTextBoxFrame::UpdateAccesskey(nsWeakFrame& aWeakThis)
{
nsAutoString accesskey;
nsCOMPtr<nsIDOMXULLabelElement> labelElement = do_QueryInterface(mContent);
NS_ENSURE_TRUE(aWeakThis.IsAlive(), false);
if (labelElement) {
// Accesskey may be stored on control.
labelElement->GetAccessKey(accesskey);
NS_ENSURE_TRUE(aWeakThis.IsAlive(), false);
}
else {
mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, accesskey);
}
if (!accesskey.Equals(mAccessKey)) {
// Need to get clean mTitle.
RecomputeTitle();
mAccessKey = accesskey;
UpdateAccessTitle();
PresContext()->PresShell()->
FrameNeedsReflow(this, nsIPresShell::eStyleChange,
NS_FRAME_IS_DIRTY);
return true;
}
return false;
}
void
nsTextBoxFrame::UpdateAttributes(nsIAtom* aAttribute,
bool& aResize,
bool& aRedraw)
{
bool doUpdateTitle = false;
aResize = false;
aRedraw = false;
if (aAttribute == nullptr || aAttribute == nsGkAtoms::crop) {
static nsIContent::AttrValuesArray strings[] =
{&nsGkAtoms::left, &nsGkAtoms::start, &nsGkAtoms::center,
&nsGkAtoms::right, &nsGkAtoms::end, nullptr};
CroppingStyle cropType;
switch (mContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::crop,
strings, eCaseMatters)) {
case 0:
case 1:
cropType = CropLeft;
break;
case 2:
cropType = CropCenter;
break;
case 3:
case 4:
cropType = CropRight;
break;
default:
cropType = CropNone;
break;
}
if (cropType != mCropType) {
aResize = true;
mCropType = cropType;
}
}
if (aAttribute == nullptr || aAttribute == nsGkAtoms::value) {
RecomputeTitle();
doUpdateTitle = true;
}
if (aAttribute == nullptr || aAttribute == nsGkAtoms::accesskey) {
mNeedsReflowCallback = true;
// Ensure that layout is refreshed and reflow callback called.
aResize = true;
}
if (doUpdateTitle) {
UpdateAccessTitle();
aResize = true;
}
}
class nsDisplayXULTextBox : public nsDisplayItem {
public:
nsDisplayXULTextBox(nsDisplayListBuilder* aBuilder,
nsTextBoxFrame* aFrame) :
nsDisplayItem(aBuilder, aFrame),
mDisableSubpixelAA(false)
{
MOZ_COUNT_CTOR(nsDisplayXULTextBox);
}
#ifdef NS_BUILD_REFCNT_LOGGING
virtual ~nsDisplayXULTextBox() {
MOZ_COUNT_DTOR(nsDisplayXULTextBox);
}
#endif
virtual void Paint(nsDisplayListBuilder* aBuilder,
nsRenderingContext* aCtx) override;
virtual nsRect GetBounds(nsDisplayListBuilder* aBuilder,
bool* aSnap) override;
NS_DISPLAY_DECL_NAME("XULTextBox", TYPE_XUL_TEXT_BOX)
virtual nsRect GetComponentAlphaBounds(nsDisplayListBuilder* aBuilder) override;
virtual void DisableComponentAlpha() override {
mDisableSubpixelAA = true;
}
void PaintTextToContext(nsRenderingContext* aCtx,
nsPoint aOffset,
const nscolor* aColor);
bool mDisableSubpixelAA;
};
static void
PaintTextShadowCallback(nsRenderingContext* aCtx,
nsPoint aShadowOffset,
const nscolor& aShadowColor,
void* aData)
{
reinterpret_cast<nsDisplayXULTextBox*>(aData)->
PaintTextToContext(aCtx, aShadowOffset, &aShadowColor);
}
void
nsDisplayXULTextBox::Paint(nsDisplayListBuilder* aBuilder,
nsRenderingContext* aCtx)
{
DrawTargetAutoDisableSubpixelAntialiasing disable(aCtx->GetDrawTarget(),
mDisableSubpixelAA);
// Paint the text shadow before doing any foreground stuff
nsRect drawRect = static_cast<nsTextBoxFrame*>(mFrame)->mTextDrawRect +
ToReferenceFrame();
nsLayoutUtils::PaintTextShadow(mFrame, aCtx,
drawRect, mVisibleRect,
mFrame->StyleColor()->mColor,
PaintTextShadowCallback,
(void*)this);
PaintTextToContext(aCtx, nsPoint(0, 0), nullptr);
}
void
nsDisplayXULTextBox::PaintTextToContext(nsRenderingContext* aCtx,
nsPoint aOffset,
const nscolor* aColor)
{
static_cast<nsTextBoxFrame*>(mFrame)->
PaintTitle(*aCtx, mVisibleRect, ToReferenceFrame() + aOffset, aColor);
}
nsRect
nsDisplayXULTextBox::GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) {
*aSnap = false;
return mFrame->GetVisualOverflowRectRelativeToSelf() + ToReferenceFrame();
}
nsRect
nsDisplayXULTextBox::GetComponentAlphaBounds(nsDisplayListBuilder* aBuilder)
{
return static_cast<nsTextBoxFrame*>(mFrame)->GetComponentAlphaBounds() +
ToReferenceFrame();
}
void
nsTextBoxFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
const nsRect& aDirtyRect,
const nsDisplayListSet& aLists)
{
if (!IsVisibleForPainting(aBuilder))
return;
nsLeafBoxFrame::BuildDisplayList(aBuilder, aDirtyRect, aLists);
aLists.Content()->AppendNewToTop(new (aBuilder)
nsDisplayXULTextBox(aBuilder, this));
}
void
nsTextBoxFrame::PaintTitle(nsRenderingContext& aRenderingContext,
const nsRect& aDirtyRect,
nsPoint aPt,
const nscolor* aOverrideColor)
{
if (mTitle.IsEmpty())
return;
DrawText(aRenderingContext, aDirtyRect, mTextDrawRect + aPt, aOverrideColor);
}
void
nsTextBoxFrame::DrawText(nsRenderingContext& aRenderingContext,
const nsRect& aDirtyRect,
const nsRect& aTextRect,
const nscolor* aOverrideColor)
{
nsPresContext* presContext = PresContext();
int32_t appUnitsPerDevPixel = presContext->AppUnitsPerDevPixel();
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
// paint the title
nscolor overColor;
nscolor underColor;
nscolor strikeColor;
uint8_t overStyle;
uint8_t underStyle;
uint8_t strikeStyle;
// Begin with no decorations
uint8_t decorations = NS_STYLE_TEXT_DECORATION_LINE_NONE;
// A mask of all possible decorations.
uint8_t decorMask = NS_STYLE_TEXT_DECORATION_LINE_LINES_MASK;
WritingMode wm = GetWritingMode();
bool vertical = wm.IsVertical();
nsIFrame* f = this;
do { // find decoration colors
nsStyleContext* context = f->StyleContext();
if (!context->HasTextDecorationLines()) {
break;
}
const nsStyleTextReset* styleText = context->StyleTextReset();
if (decorMask & styleText->mTextDecorationLine) { // a decoration defined here
nscolor color;
if (aOverrideColor) {
color = *aOverrideColor;
} else {
bool isForeground;
styleText->GetDecorationColor(color, isForeground);
if (isForeground) {
color = nsLayoutUtils::GetColor(f, eCSSProperty_color);
}
}
uint8_t style = styleText->GetDecorationStyle();
if (NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE & decorMask &
styleText->mTextDecorationLine) {
underColor = color;
underStyle = style;
decorMask &= ~NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE;
decorations |= NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE;
}
if (NS_STYLE_TEXT_DECORATION_LINE_OVERLINE & decorMask &
styleText->mTextDecorationLine) {
overColor = color;
overStyle = style;
decorMask &= ~NS_STYLE_TEXT_DECORATION_LINE_OVERLINE;
decorations |= NS_STYLE_TEXT_DECORATION_LINE_OVERLINE;
}
if (NS_STYLE_TEXT_DECORATION_LINE_LINE_THROUGH & decorMask &
styleText->mTextDecorationLine) {
strikeColor = color;
strikeStyle = style;
decorMask &= ~NS_STYLE_TEXT_DECORATION_LINE_LINE_THROUGH;
decorations |= NS_STYLE_TEXT_DECORATION_LINE_LINE_THROUGH;
}
}
} while (0 != decorMask &&
(f = nsLayoutUtils::GetParentOrPlaceholderFor(f)));
RefPtr<nsFontMetrics> fontMet =
nsLayoutUtils::GetFontMetricsForFrame(this, 1.0f);
fontMet->SetVertical(wm.IsVertical());
fontMet->SetTextOrientation(StyleVisibility()->mTextOrientation);
nscoord offset;
nscoord size;
nscoord ascent = fontMet->MaxAscent();
nsPoint baselinePt;
if (wm.IsVertical()) {
baselinePt.x =
presContext->RoundAppUnitsToNearestDevPixels(aTextRect.x +
(wm.IsVerticalRL() ? aTextRect.width - ascent : ascent));
baselinePt.y = aTextRect.y;
} else {
baselinePt.x = aTextRect.x;
baselinePt.y =
presContext->RoundAppUnitsToNearestDevPixels(aTextRect.y + ascent);
}
gfxPoint pt(presContext->AppUnitsToGfxUnits(aTextRect.x),
presContext->AppUnitsToGfxUnits(aTextRect.y));
gfxFloat width = presContext->AppUnitsToGfxUnits(aTextRect.width);
gfxFloat ascentPixel = presContext->AppUnitsToGfxUnits(ascent);
Float xInFrame = Float(PresContext()->AppUnitsToGfxUnits(mTextDrawRect.x));
gfxRect dirtyRect(presContext->AppUnitsToGfxUnits(aDirtyRect));
// XXX todo: vertical-mode support for decorations not tested yet,
// probably won't be positioned correctly
// Underlines are drawn before overlines, and both before the text
// itself, per http://www.w3.org/TR/CSS21/zindex.html point 7.2.1.4.1.1.
// (We don't apply this rule to the access-key underline because we only
// find out where that is as a side effect of drawing the text, in the
// general case -- see below.)
if (decorations & (NS_STYLE_TEXT_DECORATION_LINE_OVERLINE |
NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE)) {
fontMet->GetUnderline(offset, size);
gfxFloat offsetPixel = presContext->AppUnitsToGfxUnits(offset);
gfxFloat sizePixel = presContext->AppUnitsToGfxUnits(size);
if ((decorations & NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE) &&
underStyle != NS_STYLE_TEXT_DECORATION_STYLE_NONE) {
nsCSSRendering::PaintDecorationLine(this, *drawTarget,
ToRect(dirtyRect), underColor,
pt, xInFrame, gfxSize(width, sizePixel),
ascentPixel, offsetPixel,
NS_STYLE_TEXT_DECORATION_LINE_UNDERLINE, underStyle,
vertical);
}
if ((decorations & NS_STYLE_TEXT_DECORATION_LINE_OVERLINE) &&
overStyle != NS_STYLE_TEXT_DECORATION_STYLE_NONE) {
nsCSSRendering::PaintDecorationLine(this, *drawTarget,
ToRect(dirtyRect), overColor,
pt, xInFrame, gfxSize(width, sizePixel),
ascentPixel, ascentPixel,
NS_STYLE_TEXT_DECORATION_LINE_OVERLINE, overStyle,
vertical);
}
}
nsRenderingContext refContext(
PresContext()->PresShell()->CreateReferenceRenderingContext());
DrawTarget* refDrawTarget = refContext.GetDrawTarget();
CalculateUnderline(refDrawTarget, *fontMet);
nscolor c = aOverrideColor ? *aOverrideColor : StyleColor()->mColor;
ColorPattern color(ToDeviceColor(c));
aRenderingContext.ThebesContext()->SetColor(Color::FromABGR(c));
nsresult rv = NS_ERROR_FAILURE;
if (mState & NS_FRAME_IS_BIDI) {
presContext->SetBidiEnabled();
nsBidiLevel level = nsBidiPresUtils::BidiLevelFromStyle(StyleContext());
if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
// We let the RenderText function calculate the mnemonic's
// underline position for us.
nsBidiPositionResolve posResolve;
posResolve.logicalIndex = mAccessKeyInfo->mAccesskeyIndex;
rv = nsBidiPresUtils::RenderText(mCroppedTitle.get(), mCroppedTitle.Length(), level,
presContext, aRenderingContext,
refDrawTarget, *fontMet,
baselinePt.x, baselinePt.y,
&posResolve,
1);
mAccessKeyInfo->mBeforeWidth = posResolve.visualLeftTwips;
mAccessKeyInfo->mAccessWidth = posResolve.visualWidth;
}
else
{
rv = nsBidiPresUtils::RenderText(mCroppedTitle.get(), mCroppedTitle.Length(), level,
presContext, aRenderingContext,
refDrawTarget, *fontMet,
baselinePt.x, baselinePt.y);
}
}
if (NS_FAILED(rv)) {
fontMet->SetTextRunRTL(false);
if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
// In the simple (non-BiDi) case, we calculate the mnemonic's
// underline position by getting the text metric.
// XXX are attribute values always two byte?
if (mAccessKeyInfo->mAccesskeyIndex > 0)
mAccessKeyInfo->mBeforeWidth = nsLayoutUtils::
AppUnitWidthOfString(mCroppedTitle.get(),
mAccessKeyInfo->mAccesskeyIndex,
*fontMet, refDrawTarget);
else
mAccessKeyInfo->mBeforeWidth = 0;
}
fontMet->DrawString(mCroppedTitle.get(), mCroppedTitle.Length(),
baselinePt.x, baselinePt.y, &aRenderingContext,
refDrawTarget);
}
if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
nsRect r(aTextRect.x + mAccessKeyInfo->mBeforeWidth,
aTextRect.y + mAccessKeyInfo->mAccessOffset,
mAccessKeyInfo->mAccessWidth,
mAccessKeyInfo->mAccessUnderlineSize);
Rect devPxRect =
NSRectToSnappedRect(r, appUnitsPerDevPixel, *drawTarget);
drawTarget->FillRect(devPxRect, color);
}
// Strikeout is drawn on top of the text, per
// http://www.w3.org/TR/CSS21/zindex.html point 7.2.1.4.1.1.
if ((decorations & NS_STYLE_TEXT_DECORATION_LINE_LINE_THROUGH) &&
strikeStyle != NS_STYLE_TEXT_DECORATION_STYLE_NONE) {
fontMet->GetStrikeout(offset, size);
gfxFloat offsetPixel = presContext->AppUnitsToGfxUnits(offset);
gfxFloat sizePixel = presContext->AppUnitsToGfxUnits(size);
nsCSSRendering::PaintDecorationLine(this, *drawTarget, ToRect(dirtyRect),
strikeColor,
pt, xInFrame, gfxSize(width, sizePixel), ascentPixel,
offsetPixel, NS_STYLE_TEXT_DECORATION_LINE_LINE_THROUGH,
strikeStyle, vertical);
}
}
void
nsTextBoxFrame::CalculateUnderline(DrawTarget* aDrawTarget,
nsFontMetrics& aFontMetrics)
{
if (mAccessKeyInfo && mAccessKeyInfo->mAccesskeyIndex != kNotFound) {
// Calculate all fields of mAccessKeyInfo which
// are the same for both BiDi and non-BiDi frames.
const char16_t *titleString = mCroppedTitle.get();
aFontMetrics.SetTextRunRTL(false);
mAccessKeyInfo->mAccessWidth = nsLayoutUtils::
AppUnitWidthOfString(titleString[mAccessKeyInfo->mAccesskeyIndex],
aFontMetrics, aDrawTarget);
nscoord offset, baseline;
aFontMetrics.GetUnderline(offset, mAccessKeyInfo->mAccessUnderlineSize);
baseline = aFontMetrics.MaxAscent();
mAccessKeyInfo->mAccessOffset = baseline - offset;
}
}
nscoord
nsTextBoxFrame::CalculateTitleForWidth(nsRenderingContext& aRenderingContext,
nscoord aWidth)
{
DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
if (mTitle.IsEmpty()) {
mCroppedTitle.Truncate();
return 0;
}
RefPtr<nsFontMetrics> fm =
nsLayoutUtils::GetFontMetricsForFrame(this, 1.0f);
// see if the text will completely fit in the width given
nscoord titleWidth =
nsLayoutUtils::AppUnitWidthOfStringBidi(mTitle, this, *fm,
aRenderingContext);
if (titleWidth <= aWidth) {
mCroppedTitle = mTitle;
if (HasRTLChars(mTitle) ||
StyleVisibility()->mDirection == NS_STYLE_DIRECTION_RTL) {
mState |= NS_FRAME_IS_BIDI;
}
return titleWidth; // fits, done.
}
const nsDependentString& kEllipsis = nsContentUtils::GetLocalizedEllipsis();
// start with an ellipsis
mCroppedTitle.Assign(kEllipsis);
// see if the width is even smaller than the ellipsis
// if so, clear the text (XXX set as many '.' as we can?).
fm->SetTextRunRTL(false);
titleWidth = nsLayoutUtils::AppUnitWidthOfString(kEllipsis, *fm,
drawTarget);
if (titleWidth > aWidth) {
mCroppedTitle.SetLength(0);
return 0;
}
// if the ellipsis fits perfectly, no use in trying to insert
if (titleWidth == aWidth)
return titleWidth;
aWidth -= titleWidth;
// XXX: This whole block should probably take surrogates into account
// XXX and clusters!
// ok crop things
switch (mCropType)
{
case CropNone:
case CropRight:
{
nscoord cwidth;
nscoord twidth = 0;
int length = mTitle.Length();
int i;
for (i = 0; i < length; ++i) {
char16_t ch = mTitle.CharAt(i);
// still in LTR mode
cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
drawTarget);
if (twidth + cwidth > aWidth)
break;
twidth += cwidth;
if (UCS2_CHAR_IS_BIDI(ch) ) {
mState |= NS_FRAME_IS_BIDI;
}
}
if (i == 0)
return titleWidth;
// insert what character we can in.
nsAutoString title( mTitle );
title.Truncate(i);
mCroppedTitle.Insert(title, 0);
}
break;
case CropLeft:
{
nscoord cwidth;
nscoord twidth = 0;
int length = mTitle.Length();
int i;
for (i=length-1; i >= 0; --i) {
char16_t ch = mTitle.CharAt(i);
cwidth = nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
drawTarget);
if (twidth + cwidth > aWidth)
break;
twidth += cwidth;
if (UCS2_CHAR_IS_BIDI(ch) ) {
mState |= NS_FRAME_IS_BIDI;
}
}
if (i == length-1)
return titleWidth;
nsAutoString copy;
mTitle.Right(copy, length-1-i);
mCroppedTitle += copy;
}
break;
case CropCenter:
{
nscoord stringWidth =
nsLayoutUtils::AppUnitWidthOfStringBidi(mTitle, this, *fm,
aRenderingContext);
if (stringWidth <= aWidth) {
// the entire string will fit in the maximum width
mCroppedTitle.Insert(mTitle, 0);
break;
}
// determine how much of the string will fit in the max width
nscoord charWidth = 0;
nscoord totalWidth = 0;
char16_t ch;
int leftPos, rightPos;
nsAutoString leftString, rightString;
rightPos = mTitle.Length() - 1;
fm->SetTextRunRTL(false);
for (leftPos = 0; leftPos <= rightPos;) {
// look at the next character on the left end
ch = mTitle.CharAt(leftPos);
charWidth = nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
drawTarget);
totalWidth += charWidth;
if (totalWidth > aWidth)
// greater than the allowable width
break;
leftString.Insert(ch, leftString.Length());
if (UCS2_CHAR_IS_BIDI(ch))
mState |= NS_FRAME_IS_BIDI;
// look at the next character on the right end
if (rightPos > leftPos) {
// haven't looked at this character yet
ch = mTitle.CharAt(rightPos);
charWidth =
nsLayoutUtils::AppUnitWidthOfString(ch, *fm,
drawTarget);
totalWidth += charWidth;
if (totalWidth > aWidth)
// greater than the allowable width
break;
rightString.Insert(ch, 0);
if (UCS2_CHAR_IS_BIDI(ch))
mState |= NS_FRAME_IS_BIDI;
}
// look at the next two characters
leftPos++;
rightPos--;
}
mCroppedTitle = leftString + kEllipsis + rightString;
}
break;
}
return nsLayoutUtils::AppUnitWidthOfStringBidi(mCroppedTitle, this, *fm,
aRenderingContext);
}
#define OLD_ELLIPSIS NS_LITERAL_STRING("...")
// the following block is to append the accesskey to mTitle if there is an accesskey
// but the mTitle doesn't have the character
void
nsTextBoxFrame::UpdateAccessTitle()
{
/*
* Note that if you change appending access key label spec,
* you need to maintain same logic in following methods. See bug 324159.
* toolkit/content/commonDialog.js (setLabelForNode)
* toolkit/content/widgets/text.xml (formatAccessKey)
*/
int32_t menuAccessKey;
nsMenuBarListener::GetMenuAccessKey(&menuAccessKey);
if (!menuAccessKey || mAccessKey.IsEmpty())
return;
if (!AlwaysAppendAccessKey() &&
FindInReadable(mAccessKey, mTitle, nsCaseInsensitiveStringComparator()))
return;
nsAutoString accessKeyLabel;
accessKeyLabel += '(';
accessKeyLabel += mAccessKey;
ToUpperCase(accessKeyLabel);
accessKeyLabel += ')';
if (mTitle.IsEmpty()) {
mTitle = accessKeyLabel;
return;
}
const nsDependentString& kEllipsis = nsContentUtils::GetLocalizedEllipsis();
uint32_t offset = mTitle.Length();
if (StringEndsWith(mTitle, kEllipsis)) {
offset -= kEllipsis.Length();
} else if (StringEndsWith(mTitle, OLD_ELLIPSIS)) {
// Try to check with our old ellipsis (for old addons)
offset -= OLD_ELLIPSIS.Length();
} else {
// Try to check with
// our default ellipsis (for non-localized addons) or ':'
const char16_t kLastChar = mTitle.Last();
if (kLastChar == char16_t(0x2026) || kLastChar == char16_t(':'))
offset--;
}
if (InsertSeparatorBeforeAccessKey() &&
offset > 0 && !NS_IS_SPACE(mTitle[offset - 1])) {
mTitle.Insert(' ', offset);
offset++;
}
mTitle.Insert(accessKeyLabel, offset);
}
void
nsTextBoxFrame::UpdateAccessIndex()
{
int32_t menuAccessKey;
nsMenuBarListener::GetMenuAccessKey(&menuAccessKey);
if (menuAccessKey) {
if (mAccessKey.IsEmpty()) {
if (mAccessKeyInfo) {
delete mAccessKeyInfo;
mAccessKeyInfo = nullptr;
}
} else {
if (!mAccessKeyInfo) {
mAccessKeyInfo = new nsAccessKeyInfo();
if (!mAccessKeyInfo)
return;
}
nsAString::const_iterator start, end;
mCroppedTitle.BeginReading(start);
mCroppedTitle.EndReading(end);
// remember the beginning of the string
nsAString::const_iterator originalStart = start;
bool found;
if (!AlwaysAppendAccessKey()) {
// not appending access key - do case-sensitive search
// first
found = FindInReadable(mAccessKey, start, end);
if (!found) {
// didn't find it - perform a case-insensitive search
start = originalStart;
found = FindInReadable(mAccessKey, start, end,
nsCaseInsensitiveStringComparator());
}
} else {
found = RFindInReadable(mAccessKey, start, end,
nsCaseInsensitiveStringComparator());
}
if (found)
mAccessKeyInfo->mAccesskeyIndex = Distance(originalStart, start);
else
mAccessKeyInfo->mAccesskeyIndex = kNotFound;
}
}
}
void
nsTextBoxFrame::RecomputeTitle()
{
mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::value, mTitle);
// This doesn't handle language-specific uppercasing/lowercasing
// rules, unlike textruns.
uint8_t textTransform = StyleText()->mTextTransform;
if (textTransform == NS_STYLE_TEXT_TRANSFORM_UPPERCASE) {
ToUpperCase(mTitle);
} else if (textTransform == NS_STYLE_TEXT_TRANSFORM_LOWERCASE) {
ToLowerCase(mTitle);
}
// We can't handle NS_STYLE_TEXT_TRANSFORM_CAPITALIZE because we
// have no clue about word boundaries here. We also don't handle
// NS_STYLE_TEXT_TRANSFORM_FULLWIDTH.
}
void
nsTextBoxFrame::DidSetStyleContext(nsStyleContext* aOldStyleContext)
{
if (!aOldStyleContext) {
// We're just being initialized
return;
}
const nsStyleText* oldTextStyle = aOldStyleContext->PeekStyleText();
// We should really have oldTextStyle here, since we asked for our
// nsStyleText during Init(), but if it's not there for some reason
// just assume the worst and recompute mTitle.
if (!oldTextStyle ||
oldTextStyle->mTextTransform != StyleText()->mTextTransform) {
RecomputeTitle();
UpdateAccessTitle();
}
}
NS_IMETHODIMP
nsTextBoxFrame::DoLayout(nsBoxLayoutState& aBoxLayoutState)
{
if (mNeedsReflowCallback) {
nsIReflowCallback* cb = new nsAsyncAccesskeyUpdate(this);
if (cb) {
PresContext()->PresShell()->PostReflowCallback(cb);
}
mNeedsReflowCallback = false;
}
nsresult rv = nsLeafBoxFrame::DoLayout(aBoxLayoutState);
CalcDrawRect(*aBoxLayoutState.GetRenderingContext());
const nsStyleText* textStyle = StyleText();
nsRect scrollBounds(nsPoint(0, 0), GetSize());
nsRect textRect = mTextDrawRect;
RefPtr<nsFontMetrics> fontMet =
nsLayoutUtils::GetFontMetricsForFrame(this, 1.0f);
nsBoundingMetrics metrics =
fontMet->GetInkBoundsForVisualOverflow(mCroppedTitle.get(),
mCroppedTitle.Length(),
aBoxLayoutState.GetRenderingContext()->GetDrawTarget());
WritingMode wm = GetWritingMode();
LogicalRect tr(wm, textRect, GetSize());
tr.IStart(wm) -= metrics.leftBearing;
tr.ISize(wm) = metrics.width;
// In DrawText() we always draw with the baseline at MaxAscent() (relative to mTextDrawRect),
tr.BStart(wm) += fontMet->MaxAscent() - metrics.ascent;
tr.BSize(wm) = metrics.ascent + metrics.descent;
textRect = tr.GetPhysicalRect(wm, GetSize());
// Our scrollable overflow is our bounds; our visual overflow may
// extend beyond that.
nsRect visualBounds;
visualBounds.UnionRect(scrollBounds, textRect);
nsOverflowAreas overflow(visualBounds, scrollBounds);
if (textStyle->mTextShadow) {
// text-shadow extends our visual but not scrollable bounds
nsRect &vis = overflow.VisualOverflow();
vis.UnionRect(vis, nsLayoutUtils::GetTextShadowRectsUnion(mTextDrawRect, this));
}
FinishAndStoreOverflow(overflow, GetSize());
return rv;
}
nsRect
nsTextBoxFrame::GetComponentAlphaBounds()
{
if (StyleText()->mTextShadow) {
return GetVisualOverflowRectRelativeToSelf();
}
return mTextDrawRect;
}
bool
nsTextBoxFrame::ComputesOwnOverflowArea()
{
return true;
}
/* virtual */ void
nsTextBoxFrame::MarkIntrinsicISizesDirty()
{
mNeedsRecalc = true;
nsTextBoxFrameSuper::MarkIntrinsicISizesDirty();
}
void
nsTextBoxFrame::GetTextSize(nsRenderingContext& aRenderingContext,
const nsString& aString,
nsSize& aSize, nscoord& aAscent)
{
RefPtr<nsFontMetrics> fontMet =
nsLayoutUtils::GetFontMetricsForFrame(this, 1.0f);
aSize.height = fontMet->MaxHeight();
aSize.width =
nsLayoutUtils::AppUnitWidthOfStringBidi(aString, this, *fontMet,
aRenderingContext);
aAscent = fontMet->MaxAscent();
}
void
nsTextBoxFrame::CalcTextSize(nsBoxLayoutState& aBoxLayoutState)
{
if (mNeedsRecalc) {
nsSize size;
nsRenderingContext* rendContext = aBoxLayoutState.GetRenderingContext();
if (rendContext) {
GetTextSize(*rendContext, mTitle, size, mAscent);
if (GetWritingMode().IsVertical()) {
Swap(size.width, size.height);
}
mTextSize = size;
mNeedsRecalc = false;
}
}
}
void
nsTextBoxFrame::CalcDrawRect(nsRenderingContext &aRenderingContext)
{
WritingMode wm = GetWritingMode();
LogicalRect textRect(wm, LogicalPoint(wm, 0, 0), GetLogicalSize(wm));
nsMargin borderPadding;
GetBorderAndPadding(borderPadding);
textRect.Deflate(wm, LogicalMargin(wm, borderPadding));
// determine (cropped) title and underline position
// determine (cropped) title which fits in aRect, and its width
// (where "width" is the text measure along its baseline, i.e. actually
// a physical height in vertical writing modes)
nscoord titleWidth =
CalculateTitleForWidth(aRenderingContext, textRect.ISize(wm));
#ifdef ACCESSIBILITY
// Make sure to update the accessible tree in case when cropped title is
// changed.
nsAccessibilityService* accService = GetAccService();
if (accService) {
accService->UpdateLabelValue(PresContext()->PresShell(), mContent,
mCroppedTitle);
}
#endif
// determine if and at which position to put the underline
UpdateAccessIndex();
// make the rect as small as our (cropped) text.
nscoord outerISize = textRect.ISize(wm);
textRect.ISize(wm) = titleWidth;
// Align our text within the overall rect by checking our text-align property.
const nsStyleText* textStyle = StyleText();
if (textStyle->mTextAlign == NS_STYLE_TEXT_ALIGN_CENTER) {
textRect.IStart(wm) += (outerISize - textRect.ISize(wm)) / 2;
} else if (textStyle->mTextAlign == NS_STYLE_TEXT_ALIGN_END ||
(textStyle->mTextAlign == NS_STYLE_TEXT_ALIGN_LEFT &&
!wm.IsBidiLTR()) ||
(textStyle->mTextAlign == NS_STYLE_TEXT_ALIGN_RIGHT &&
wm.IsBidiLTR())) {
textRect.IStart(wm) += (outerISize - textRect.ISize(wm));
}
mTextDrawRect = textRect.GetPhysicalRect(wm, GetSize());
}
/**
* Ok return our dimensions
*/
nsSize
nsTextBoxFrame::GetPrefSize(nsBoxLayoutState& aBoxLayoutState)
{
CalcTextSize(aBoxLayoutState);
nsSize size = mTextSize;
DISPLAY_PREF_SIZE(this, size);
AddBorderAndPadding(size);
bool widthSet, heightSet;
nsIFrame::AddCSSPrefSize(this, size, widthSet, heightSet);
return size;
}
/**
* Ok return our dimensions
*/
nsSize
nsTextBoxFrame::GetMinSize(nsBoxLayoutState& aBoxLayoutState)
{
CalcTextSize(aBoxLayoutState);
nsSize size = mTextSize;
DISPLAY_MIN_SIZE(this, size);
// if there is cropping our min width becomes our border and padding
if (mCropType != CropNone) {
if (GetWritingMode().IsVertical()) {
size.height = 0;
} else {
size.width = 0;
}
}
AddBorderAndPadding(size);
bool widthSet, heightSet;
nsIFrame::AddCSSMinSize(aBoxLayoutState, this, size, widthSet, heightSet);
return size;
}
nscoord
nsTextBoxFrame::GetBoxAscent(nsBoxLayoutState& aBoxLayoutState)
{
CalcTextSize(aBoxLayoutState);
nscoord ascent = mAscent;
nsMargin m(0,0,0,0);
GetBorderAndPadding(m);
WritingMode wm = GetWritingMode();
ascent += LogicalMargin(wm, m).BStart(wm);
return ascent;
}
#ifdef DEBUG_FRAME_DUMP
nsresult
nsTextBoxFrame::GetFrameName(nsAString& aResult) const
{
MakeFrameName(NS_LITERAL_STRING("TextBox"), aResult);
aResult += NS_LITERAL_STRING("[value=") + mTitle + NS_LITERAL_STRING("]");
return NS_OK;
}
#endif
// If you make changes to this function, check its counterparts
// in nsBoxFrame and nsXULLabelFrame
nsresult
nsTextBoxFrame::RegUnregAccessKey(bool aDoReg)
{
// if we have no content, we can't do anything
if (!mContent)
return NS_ERROR_FAILURE;
// check if we have a |control| attribute
// do this check first because few elements have control attributes, and we
// can weed out most of the elements quickly.
// XXXjag a side-effect is that we filter out anonymous <label>s
// in e.g. <menu>, <menuitem>, <button>. These <label>s inherit
// |accesskey| and would otherwise register themselves, overwriting
// the content we really meant to be registered.
if (!mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::control))
return NS_OK;
// see if we even have an access key
nsAutoString accessKey;
mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, accessKey);
if (accessKey.IsEmpty())
return NS_OK;
// With a valid PresContext we can get the ESM
// and (un)register the access key
EventStateManager* esm = PresContext()->EventStateManager();
uint32_t key = accessKey.First();
if (aDoReg)
esm->RegisterAccessKey(mContent, key);
else
esm->UnregisterAccessKey(mContent, key);
return NS_OK;
}