1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set sw=2 ts=2 expandtab: */
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/. */
7 #include "nsDeviceContext.h"
8 #include <algorithm> // for max
9 #include "gfxContext.h"
10 #include "gfxImageSurface.h" // for gfxImageSurface
11 #include "gfxPoint.h" // for gfxSize
12 #include "gfxTextRun.h" // for gfxFontGroup
13 #include "mozilla/LookAndFeel.h"
14 #include "mozilla/gfx/PathHelpers.h"
15 #include "mozilla/gfx/PrintTarget.h"
16 #include "mozilla/Preferences.h" // for Preferences
17 #include "mozilla/Services.h" // for GetObserverService
18 #include "mozilla/StaticPrefs_layout.h"
19 #include "mozilla/mozalloc.h" // for operator new
20 #include "mozilla/widget/Screen.h" // for Screen
21 #include "nsCRT.h" // for nsCRT
22 #include "nsDebug.h" // for NS_ASSERTION, etc
23 #include "nsFont.h" // for nsFont
24 #include "nsFontCache.h" // for nsFontCache
25 #include "nsFontMetrics.h" // for nsFontMetrics
26 #include "nsAtom.h" // for nsAtom, NS_Atomize
28 #include "nsIDeviceContextSpec.h" // for nsIDeviceContextSpec
29 #include "nsLanguageAtomService.h" // for nsLanguageAtomService
30 #include "nsIObserver.h" // for nsIObserver, etc
31 #include "nsIObserverService.h" // for nsIObserverService
32 #include "nsISupportsImpl.h" // for MOZ_COUNT_CTOR, etc
33 #include "nsISupportsUtils.h" // for NS_ADDREF, NS_RELEASE
34 #include "nsIWidget.h" // for nsIWidget, NS_NATIVE_WINDOW
35 #include "nsRect.h" // for nsRect
36 #include "nsServiceManagerUtils.h" // for do_GetService
37 #include "nsString.h" // for nsDependentString
38 #include "nsTArray.h" // for nsTArray, nsTArray_Impl
39 #include "nsThreadUtils.h" // for NS_IsMainThread
40 #include "mozilla/gfx/Logging.h"
41 #include "mozilla/widget/ScreenManager.h" // for ScreenManager
43 using namespace mozilla
;
44 using namespace mozilla::gfx
;
45 using mozilla::widget::ScreenManager
;
47 nsDeviceContext::nsDeviceContext()
50 mAppUnitsPerDevPixel(-1),
51 mAppUnitsPerDevPixelAtUnitFullZoom(-1),
52 mAppUnitsPerPhysicalInch(-1),
55 mPrintingTranslate(gfxPoint(0, 0)),
56 mIsCurrentlyPrintingDoc(false) {
57 MOZ_ASSERT(NS_IsMainThread(), "nsDeviceContext created off main thread");
60 nsDeviceContext::~nsDeviceContext() = default;
62 void nsDeviceContext::SetDPI() {
65 // Use the printing DC to determine DPI values, if we have one.
66 if (mDeviceContextSpec
) {
67 dpi
= mDeviceContextSpec
->GetDPI();
68 mPrintingScale
= mDeviceContextSpec
->GetPrintingScale();
69 mPrintingTranslate
= mDeviceContextSpec
->GetPrintingTranslate();
70 mAppUnitsPerDevPixelAtUnitFullZoom
=
71 NS_lround((AppUnitsPerCSSPixel() * 96) / dpi
);
73 // A value of -1 means use the maximum of 96 and the system DPI.
74 // A value of 0 means use the system DPI. A positive value is used as the
75 // DPI. This sets the physical size of a device pixel and thus controls the
76 // interpretation of physical units.
77 int32_t prefDPI
= StaticPrefs::layout_css_dpi();
81 dpi
= mWidget
->GetDPI();
84 dpi
= std::max(96.0f
, dpi
);
90 CSSToLayoutDeviceScale scale
=
91 mWidget
? mWidget
->GetDefaultScale() : CSSToLayoutDeviceScale(1.0);
92 MOZ_ASSERT(scale
.scale
> 0.0);
93 mAppUnitsPerDevPixelAtUnitFullZoom
=
94 std::max(1, NS_lround(AppUnitsPerCSSPixel() / scale
.scale
));
97 NS_ASSERTION(dpi
!= -1.0, "no dpi set");
99 mAppUnitsPerPhysicalInch
=
100 NS_lround(dpi
* mAppUnitsPerDevPixelAtUnitFullZoom
);
101 UpdateAppUnitsForFullZoom();
104 void nsDeviceContext::Init(nsIWidget
* aWidget
) {
105 if (mIsInitialized
&& mWidget
== aWidget
) {
109 // We can't assert |!mIsInitialized| here since EndSwapDocShellsForDocument
110 // re-initializes nsDeviceContext objects. We can only assert in
111 // InitForPrinting (below).
112 mIsInitialized
= true;
118 // XXX This is only for printing. We should make that obvious in the name.
119 already_AddRefed
<gfxContext
> nsDeviceContext::CreateRenderingContext() {
120 return CreateRenderingContextCommon(/* not a reference context */ false);
123 already_AddRefed
<gfxContext
>
124 nsDeviceContext::CreateReferenceRenderingContext() {
125 return CreateRenderingContextCommon(/* a reference context */ true);
128 already_AddRefed
<gfxContext
> nsDeviceContext::CreateRenderingContextCommon(
129 bool aWantReferenceContext
) {
130 MOZ_ASSERT(IsPrinterContext());
131 MOZ_ASSERT(mWidth
> 0 && mHeight
> 0);
133 if (NS_WARN_IF(!mPrintTarget
)) {
134 // Printing canceled already.
138 RefPtr
<gfx::DrawTarget
> dt
;
139 if (aWantReferenceContext
) {
140 dt
= mPrintTarget
->GetReferenceDrawTarget();
142 // This will be null if printing a page from the parent process.
143 RefPtr
<DrawEventRecorder
> recorder
;
144 mDeviceContextSpec
->GetDrawEventRecorder(getter_AddRefs(recorder
));
145 dt
= mPrintTarget
->MakeDrawTarget(gfx::IntSize(mWidth
, mHeight
), recorder
);
148 if (!dt
|| !dt
->IsValid()) {
149 gfxCriticalNote
<< "Failed to create draw target in device context sized "
150 << mWidth
<< "x" << mHeight
<< " and pointer "
151 << hexa(mPrintTarget
);
155 dt
->AddUserData(&sDisablePixelSnapping
, (void*)0x1, nullptr);
157 RefPtr
<gfxContext
> pContext
= gfxContext::CreateOrNull(dt
);
158 MOZ_ASSERT(pContext
); // already checked draw target above
161 transform
.PreTranslate(mPrintingTranslate
);
162 transform
.PreScale(mPrintingScale
, mPrintingScale
);
163 pContext
->SetMatrixDouble(transform
);
164 return pContext
.forget();
167 uint32_t nsDeviceContext::GetDepth() {
168 RefPtr
<widget::Screen
> screen
= FindScreen();
170 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
171 screen
= screenManager
.GetPrimaryScreen();
175 screen
->GetColorDepth(&depth
);
176 return uint32_t(depth
);
179 dom::ScreenColorGamut
nsDeviceContext::GetColorGamut() {
180 RefPtr
<widget::Screen
> screen
= FindScreen();
182 auto& screenManager
= ScreenManager::GetSingleton();
183 screen
= screenManager
.GetPrimaryScreen();
186 dom::ScreenColorGamut colorGamut
;
187 screen
->GetColorGamut(&colorGamut
);
191 hal::ScreenOrientation
nsDeviceContext::GetScreenOrientationType() {
192 RefPtr
<widget::Screen
> screen
= FindScreen();
194 auto& screenManager
= ScreenManager::GetSingleton();
195 screen
= screenManager
.GetPrimaryScreen();
198 return screen
->GetOrientationType();
201 uint16_t nsDeviceContext::GetScreenOrientationAngle() {
202 RefPtr
<widget::Screen
> screen
= FindScreen();
204 auto& screenManager
= ScreenManager::GetSingleton();
205 screen
= screenManager
.GetPrimaryScreen();
208 return screen
->GetOrientationAngle();
211 nsresult
nsDeviceContext::GetDeviceSurfaceDimensions(nscoord
& aWidth
,
213 if (IsPrinterContext()) {
218 ComputeFullAreaUsingScreen(&area
);
219 aWidth
= area
.Width();
220 aHeight
= area
.Height();
226 nsresult
nsDeviceContext::GetRect(nsRect
& aRect
) {
227 if (IsPrinterContext()) {
228 aRect
.SetRect(0, 0, mWidth
, mHeight
);
230 ComputeFullAreaUsingScreen(&aRect
);
235 nsresult
nsDeviceContext::GetClientRect(nsRect
& aRect
) {
236 if (IsPrinterContext()) {
237 aRect
.SetRect(0, 0, mWidth
, mHeight
);
239 ComputeClientRectUsingScreen(&aRect
);
244 nsresult
nsDeviceContext::InitForPrinting(nsIDeviceContextSpec
* aDevice
) {
245 NS_ENSURE_ARG_POINTER(aDevice
);
247 MOZ_ASSERT(!mIsInitialized
,
248 "Only initialize once, immediately after construction");
250 // We don't set mIsInitialized here. The Init() call below does that.
252 mPrintTarget
= aDevice
->MakePrintTarget();
254 return NS_ERROR_FAILURE
;
257 mDeviceContextSpec
= aDevice
;
261 if (!CalcPrintingSize()) {
262 return NS_ERROR_FAILURE
;
268 nsresult
nsDeviceContext::BeginDocument(const nsAString
& aTitle
,
269 const nsAString
& aPrintToFileName
,
270 int32_t aStartPage
, int32_t aEndPage
) {
271 MOZ_DIAGNOSTIC_ASSERT(!mIsCurrentlyPrintingDoc
,
272 "Mismatched BeginDocument/EndDocument calls");
274 nsresult rv
= mPrintTarget
->BeginPrinting(aTitle
, aPrintToFileName
,
275 aStartPage
, aEndPage
);
277 if (NS_SUCCEEDED(rv
)) {
278 if (mDeviceContextSpec
) {
279 rv
= mDeviceContextSpec
->BeginDocument(aTitle
, aPrintToFileName
,
280 aStartPage
, aEndPage
);
282 mIsCurrentlyPrintingDoc
= true;
285 // Warn about any failure (except user cancelling):
286 NS_WARNING_ASSERTION(NS_SUCCEEDED(rv
) || rv
== NS_ERROR_ABORT
,
287 "nsDeviceContext::BeginDocument failed");
292 RefPtr
<PrintEndDocumentPromise
> nsDeviceContext::EndDocument() {
293 MOZ_DIAGNOSTIC_ASSERT(mIsCurrentlyPrintingDoc
,
294 "Mismatched BeginDocument/EndDocument calls");
295 MOZ_DIAGNOSTIC_ASSERT(mPrintTarget
);
297 mIsCurrentlyPrintingDoc
= false;
300 auto result
= mPrintTarget
->EndPrinting();
301 if (NS_FAILED(result
)) {
302 return PrintEndDocumentPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE
,
305 mPrintTarget
->Finish();
306 mPrintTarget
= nullptr;
309 if (mDeviceContextSpec
) {
310 return mDeviceContextSpec
->EndDocument();
313 return PrintEndDocumentPromise::CreateAndResolve(true, __func__
);
316 nsresult
nsDeviceContext::AbortDocument() {
317 MOZ_DIAGNOSTIC_ASSERT(mIsCurrentlyPrintingDoc
,
318 "Mismatched BeginDocument/EndDocument calls");
320 nsresult rv
= mPrintTarget
->AbortPrinting();
321 mIsCurrentlyPrintingDoc
= false;
323 if (mDeviceContextSpec
) {
324 Unused
<< mDeviceContextSpec
->EndDocument();
327 mPrintTarget
= nullptr;
332 nsresult
nsDeviceContext::BeginPage() {
333 MOZ_DIAGNOSTIC_ASSERT(!mIsCurrentlyPrintingDoc
|| mPrintTarget
,
334 "What nulled out our print target while printing?");
335 if (mDeviceContextSpec
) {
336 MOZ_TRY(mDeviceContextSpec
->BeginPage());
339 MOZ_TRY(mPrintTarget
->BeginPage());
344 nsresult
nsDeviceContext::EndPage() {
345 MOZ_DIAGNOSTIC_ASSERT(!mIsCurrentlyPrintingDoc
|| mPrintTarget
,
346 "What nulled out our print target while printing?");
348 MOZ_TRY(mPrintTarget
->EndPage());
350 if (mDeviceContextSpec
) {
351 MOZ_TRY(mDeviceContextSpec
->EndPage());
356 void nsDeviceContext::ComputeClientRectUsingScreen(nsRect
* outRect
) {
357 // we always need to recompute the clientRect
358 // because the window may have moved onto a different screen. In the single
359 // monitor case, we only need to do the computation if we haven't done it
360 // once already, and remember that we have because we're assured it won't
362 if (RefPtr
<widget::Screen
> screen
= FindScreen()) {
363 *outRect
= LayoutDeviceIntRect::ToAppUnits(screen
->GetAvailRect(),
364 AppUnitsPerDevPixel());
368 void nsDeviceContext::ComputeFullAreaUsingScreen(nsRect
* outRect
) {
369 // if we have more than one screen, we always need to recompute the clientRect
370 // because the window may have moved onto a different screen. In the single
371 // monitor case, we only need to do the computation if we haven't done it
372 // once already, and remember that we have because we're assured it won't
374 if (RefPtr
<widget::Screen
> screen
= FindScreen()) {
375 *outRect
= LayoutDeviceIntRect::ToAppUnits(screen
->GetRect(),
376 AppUnitsPerDevPixel());
377 mWidth
= outRect
->Width();
378 mHeight
= outRect
->Height();
385 // Determines which screen intersects the largest area of the given surface.
387 already_AddRefed
<widget::Screen
> nsDeviceContext::FindScreen() {
394 if (RefPtr
<widget::Screen
> screen
= mWidget
->GetWidgetScreen()) {
395 return screen
.forget();
398 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
399 return screenManager
.GetPrimaryScreen();
402 bool nsDeviceContext::CalcPrintingSize() {
403 gfxSize
size(mPrintTarget
->GetSize());
404 // For printing, CSS inches and physical inches are identical
405 // so it doesn't matter which we use here
406 mWidth
= NSToCoordRound(size
.width
* AppUnitsPerPhysicalInch() /
407 POINTS_PER_INCH_FLOAT
);
408 mHeight
= NSToCoordRound(size
.height
* AppUnitsPerPhysicalInch() /
409 POINTS_PER_INCH_FLOAT
);
411 return (mWidth
> 0 && mHeight
> 0);
414 bool nsDeviceContext::CheckDPIChange() {
415 int32_t oldDevPixels
= mAppUnitsPerDevPixelAtUnitFullZoom
;
416 int32_t oldInches
= mAppUnitsPerPhysicalInch
;
420 return oldDevPixels
!= mAppUnitsPerDevPixelAtUnitFullZoom
||
421 oldInches
!= mAppUnitsPerPhysicalInch
;
424 bool nsDeviceContext::SetFullZoom(float aScale
) {
426 MOZ_ASSERT_UNREACHABLE("Invalid full zoom value");
429 int32_t oldAppUnitsPerDevPixel
= mAppUnitsPerDevPixel
;
431 UpdateAppUnitsForFullZoom();
432 return oldAppUnitsPerDevPixel
!= mAppUnitsPerDevPixel
;
435 static int32_t ApplyFullZoom(int32_t aUnzoomedAppUnits
, float aFullZoom
) {
436 if (aFullZoom
== 1.0f
) {
437 return aUnzoomedAppUnits
;
439 return std::max(1, NSToIntRound(float(aUnzoomedAppUnits
) / aFullZoom
));
442 int32_t nsDeviceContext::AppUnitsPerDevPixelInTopLevelChromePage() const {
443 // The only zoom that applies to chrome pages is the system zoom, if any.
444 return ApplyFullZoom(mAppUnitsPerDevPixelAtUnitFullZoom
,
445 LookAndFeel::SystemZoomSettings().mFullZoom
);
448 void nsDeviceContext::UpdateAppUnitsForFullZoom() {
449 mAppUnitsPerDevPixel
=
450 ApplyFullZoom(mAppUnitsPerDevPixelAtUnitFullZoom
, mFullZoom
);
451 // adjust mFullZoom to reflect appunit rounding
452 mFullZoom
= float(mAppUnitsPerDevPixelAtUnitFullZoom
) / mAppUnitsPerDevPixel
;
455 DesktopToLayoutDeviceScale
nsDeviceContext::GetDesktopToDeviceScale() {
456 if (RefPtr
<widget::Screen
> screen
= FindScreen()) {
457 return screen
->GetDesktopToLayoutDeviceScale();
459 return DesktopToLayoutDeviceScale(1.0);