| 1 |
/** |
| 2 |
* Copyright (c) 2022 The xterm.js authors. All rights reserved. |
| 3 |
* @license MIT |
| 4 |
*/ |
| 5 |
|
| 6 |
import { toDisposable, IDisposable } from 'vs/base/common/lifecycle'; |
| 7 |
|
| 8 |
export function observeDevicePixelDimensions(element: HTMLElement, parentWindow: Window & typeof globalThis, callback: (deviceWidth: number, deviceHeight: number) => void): IDisposable { |
| 9 |
// Observe any resizes to the element and extract the actual pixel size of the element if the |
| 10 |
// devicePixelContentBoxSize API is supported. This allows correcting rounding errors when |
| 11 |
// converting between CSS pixels and device pixels which causes blurry rendering when device |
| 12 |
// pixel ratio is not a round number. |
| 13 |
let observer: ResizeObserver | undefined = new parentWindow.ResizeObserver((entries) => { |
| 14 |
const entry = entries.find((entry) => entry.target === element); |
| 15 |
if (!entry) { |
| 16 |
return; |
| 17 |
} |
| 18 |
|
| 19 |
// Disconnect if devicePixelContentBoxSize isn't supported by the browser |
| 20 |
if (!('devicePixelContentBoxSize' in entry)) { |
| 21 |
observer?.disconnect(); |
| 22 |
observer = undefined; |
| 23 |
return; |
| 24 |
} |
| 25 |
|
| 26 |
// Fire the callback, ignore events where the dimensions are 0x0 as the canvas is likely hidden |
| 27 |
const width = entry.devicePixelContentBoxSize[0].inlineSize; |
| 28 |
const height = entry.devicePixelContentBoxSize[0].blockSize; |
| 29 |
if (width > 0 && height > 0) { |
| 30 |
callback(width, height); |
| 31 |
} |
| 32 |
}); |
| 33 |
try { |
| 34 |
observer.observe(element, { box: ['device-pixel-content-box'] } as any); |
| 35 |
} catch { |
| 36 |
observer.disconnect(); |
| 37 |
observer = undefined; |
| 38 |
} |
| 39 |
return toDisposable(() => observer?.disconnect()); |
| 40 |
} |