Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qohosplatformscreen.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include <QtCore/private/qcore_ohos_p.h>
5#include <QtCore/qdebug.h>
6#include <QtCore/qdatetime.h>
7
8#include <qpa/qwindowsysteminterface.h>
9
10#include <qohosdisplayinfo.h>
15#include "qohosjsmain.h"
17#include "render/qohosview.h"
18#include <algorithm>
19#include <multimedia/image_framework/image/pixelmap_native.h>
20#include <optional>
21#include <qarkui/qarkuiutils.h>
22#include <qohosapppermissions_p.h>
23#include <qohosjsutils.h>
24#include <QtGui/private/qohosimageconversions_p.h>
25#include <qohospixelmapconversions.h>
26#include <qohosutils.h>
27#include <render/qwindowproxyregistry.h>
28#include <window_manager/oh_display_capture.h>
29#include <window_manager/oh_display_manager.h>
30
31#include <QtGui/qguiapplication.h>
32#include <QtGui/qwindow.h>
33#include <QtCore/private/qnapi_p.h>
34#include <QtCore/private/qnumeric_p.h>
35#include <QtCore/private/qohoslogger_p.h>
36#include <QtGui/private/qwindow_p.h>
37
38#include <vector>
39
41
42namespace {
43
44static const int ohosLogicalDpi = 72;
45
47 QOhosJsState &, QOhosDisplayInfo::JsDisplayId displayId)
48{
49 ::OH_PixelmapNative *pixelMapNativePtr;
50
51 QArkUi::callArkUiOrFailOnErrorResult(
52 Q_OHOS_NAMED_FUNC(::OH_NativeDisplayManager_CaptureScreenPixelmap),
53 static_cast<std::uint32_t>(displayId.value()), &pixelMapNativePtr);
54
55 return wrapOhosNativePixelMapPtr(pixelMapNativePtr);
56}
57
59 QOhosJsState &jsState, QOhosDisplayInfo::JsDisplayId displayId,
60 QOhosConsumer<std::shared_ptr<::OH_PixelmapNative>> pixelMapOrNullConsumer)
61{
62 static constexpr const char *ohosCustomScreenCapturePermission =
63 "ohos.permission.CUSTOM_SCREEN_CAPTURE";
64
66 jsState, ohosCustomScreenCapturePermission,
67 [pixelMapOrNullConsumer = std::move(pixelMapOrNullConsumer), displayId](
68 auto &jsState, bool permissionGranted) {
69 if (permissionGranted) {
70 pixelMapOrNullConsumer(captureScreenPixelmap(jsState, displayId));
71 } else {
72 qOhosPrintfError(
73 "%s: %s hasn't been granted by user. Cannot grab window.", Q_FUNC_INFO,
74 ohosCustomScreenCapturePermission);
75 pixelMapOrNullConsumer(nullptr);
76 }
77 });
78}
79
81{
82 auto allWindows = qApp->allWindows();
83 auto windowItByWId = std::find_if(
84 std::begin(allWindows), std::end(allWindows),
85 [&](QWindow *w) {
86 return w->winId() == wId;
87 });
88
89 if (windowItByWId == allWindows.end())
90 return nullptr;
91
92 return *windowItByWId;
93}
94
96 const QSize &windowSnapshotSize, const QRect &windowSpaceCaptureRect)
97{
98 return {
99 windowSpaceCaptureRect.width() < 0
100 ? qMax(0, windowSnapshotSize.width() - windowSpaceCaptureRect.x())
101 : windowSpaceCaptureRect.width(),
102 windowSpaceCaptureRect.height() < 0
103 ? qMax(0, windowSnapshotSize.height() - windowSpaceCaptureRect.y())
104 : windowSpaceCaptureRect.height()
105 };
106}
107
109 const QRect &windowSpaceCaptureRect, const QRect &windowFragmentRect)
110{
111 return {
112 qAbs(windowSpaceCaptureRect.x() - windowFragmentRect.x()),
113 qAbs(windowSpaceCaptureRect.y() - windowFragmentRect.y()),
114 windowFragmentRect.width(),
115 windowFragmentRect.height()
116 };
117}
118
120 const QPixmap &capturedWindowPixmap, const QRect &windowSpaceCaptureRect)
121{
122 auto resultSize = calculateResultWindowCapturePixmapSize(
123 capturedWindowPixmap.size(), windowSpaceCaptureRect);
124
125 if (resultSize.isEmpty())
126 return {};
127
128 auto windowFragmentRect = capturedWindowPixmap.rect().intersected(
129 QRect(windowSpaceCaptureRect.topLeft(), resultSize));
130
131 if (windowFragmentRect.isEmpty())
132 return QPixmap(resultSize);
133
134 auto resultSpaceWindowFragmentRect =
135 calculateResultPixmapWindowFragmentRect(windowSpaceCaptureRect, windowFragmentRect);
136
137 QPixmap result(resultSize);
138 QPainter p(&result);
139 p.drawPixmap(resultSpaceWindowFragmentRect, capturedWindowPixmap, windowFragmentRect);
140
141 return result;
142}
143
145{
146 using JsDisplayOrientation = QOhosDisplayInfo::JsDisplayOrientation;
147
148 switch (jsDisplayOrientation) {
149 case JsDisplayOrientation::PORTRAIT:
150 return Qt::ScreenOrientation::PortraitOrientation;
151 case JsDisplayOrientation::LANDSCAPE:
152 return Qt::ScreenOrientation::LandscapeOrientation;
153 case JsDisplayOrientation::PORTRAIT_INVERTED:
154 return Qt::ScreenOrientation::InvertedPortraitOrientation;
155 case JsDisplayOrientation::LANDSCAPE_INVERTED:
156 return Qt::ScreenOrientation::InvertedLandscapeOrientation;
157 }
158
159 return std::nullopt;
160}
161
162// log2 index, one step per 90 degrees, as in QPlatformScreen::angleBetween().
163int orientationToIndex(Qt::ScreenOrientation orientation)
164{
165 switch (orientation) {
166 case Qt::ScreenOrientation::PortraitOrientation:
167 return 0;
168 case Qt::ScreenOrientation::LandscapeOrientation:
169 return 1;
170 case Qt::ScreenOrientation::InvertedPortraitOrientation:
171 return 2;
172 case Qt::ScreenOrientation::InvertedLandscapeOrientation:
173 return 3;
174 default:
175 return -1;
176 }
177}
178
180tryMapNativeDisplayOrientationToQt(NativeDisplayManager_Orientation nativeOrientation)
181{
182 switch (nativeOrientation) {
183 case DISPLAY_MANAGER_PORTRAIT:
184 return Qt::ScreenOrientation::PortraitOrientation;
185 case DISPLAY_MANAGER_LANDSCAPE:
186 return Qt::ScreenOrientation::LandscapeOrientation;
187 case DISPLAY_MANAGER_PORTRAIT_INVERTED:
188 return Qt::ScreenOrientation::InvertedPortraitOrientation;
189 case DISPLAY_MANAGER_LANDSCAPE_INVERTED:
190 return Qt::ScreenOrientation::InvertedLandscapeOrientation;
191 case DISPLAY_MANAGER_UNKNOWN:
192 break;
193 }
194
195 return std::nullopt;
196}
197
199{
200 switch (((index % 4) + 4) % 4) {
201 case 0:
202 return Qt::ScreenOrientation::PortraitOrientation;
203 case 1:
204 return Qt::ScreenOrientation::LandscapeOrientation;
205 case 2:
206 return Qt::ScreenOrientation::InvertedPortraitOrientation;
207 default:
208 return Qt::ScreenOrientation::InvertedLandscapeOrientation;
209 }
210}
211
212}
213
214QOhosPlatformScreen::QOhosPlatformScreen(const QOhosDisplayInfo &displayInfo, QOhosSupplier<std::vector<QOhosPlatformScreen *>> platformScreenListSupplier)
215 : QObject()
216 , QPlatformScreen()
217 , m_format(QImage::Format_ARGB32_Premultiplied)
218 , m_depth(32)
219 , m_platformCursor(new QOhosPlatformCursor())
220 , m_displayInfo(displayInfo)
221 , m_availableGeometry(getAvailableArea())
222 , m_platformScreenListSupplier(std::move(platformScreenListSupplier))
223{
224 auto __dbg = make_QCScopedDebug("QOhosPlatformScreen::QOhosPlatformScreen");
225}
226
228
229QOhosPlatformScreen *QOhosPlatformScreen::fromQScreen(QScreen *screen)
230{
231 auto *platformScreen = screen->handle();
232 if (Q_UNLIKELY(platformScreen == nullptr))
233 qOhosReportFatalErrorAndAbort("QScreen::handle() returned null");
234 return static_cast<QOhosPlatformScreen *>(platformScreen);
235}
236
237QWindow *QOhosPlatformScreen::topLevelAt(const QPoint &p) const
238{
239 for (auto *platformScreen : virtualSiblings()) {
240 auto *ohosPlatformScreen = static_cast<QOhosPlatformScreen *>(platformScreen);
241
242 auto windowIds = QOhosWindowProxy::queryWindowIdsByCoordinate(ohosPlatformScreen->m_displayInfo.id, p);
243 if (!windowIds.empty())
244 return QWindowProxyRegistry::instance().findQWindowByJsWindowIdOrNull(windowIds.front());
245 }
246
247 return nullptr;
248}
249
251{
252 return m_platformCursor.data();
253}
254
256{
257 auto geometryChanged = displayInfo.displayGeometryPixels() != m_displayInfo.displayGeometryPixels();
258 auto logicalDpiChanged = displayInfo.densityDPI != m_displayInfo.densityDPI;
259 const Qt::ScreenOrientation previousOrientation = orientation();
260
261 QVector<QPair<QWindow *, std::optional<QRect>>> windowRectPairs;
262
263 if (logicalDpiChanged) {
264 for (auto *window : qGuiApp->allWindows()) {
265 auto *platformWindow = QOhosPlatformWindow::fromQWindowOrNull(window);
266 if (platformWindow == nullptr || platformWindow->screen() != this || !window->isVisible())
267 continue;
268
269 auto *ownedView = platformWindow->ownedViewOrNull();
270 if (ownedView == nullptr)
271 continue;
272
273 windowRectPairs.push_back({
274 window,
275 ownedView->viewType() == QOhosView::ViewType::EmbeddedWindow
276 ? std::optional(window->geometry())
277 : std::nullopt});
278 }
279 }
280
281 m_displayInfo = displayInfo;
282
283 if (geometryChanged)
284 QWindowSystemInterface::handleScreenGeometryChange(QPlatformScreen::screen(), geometry(), availableGeometry());
285
286 if (orientation() != previousOrientation)
287 QWindowSystemInterface::handleScreenOrientationChange(QPlatformScreen::screen(), orientation());
288
289 if (logicalDpiChanged) {
290 auto ldpi = logicalDpi();
291 QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(
292 screen(), ldpi.first, ldpi.second);
293
294 QWindowSystemInterface::flushWindowSystemEvents();
295
296 for (const auto &windowRectPair : windowRectPairs) {
297 auto *qWindow = windowRectPair.first;
298 auto *platformWindow = QOhosPlatformWindow::fromQWindow(qWindow);
299 if (windowRectPair.second.has_value())
300 qWindow->setGeometry(windowRectPair.second.value());
301 platformWindow->handleDpiChange();
302 }
303 }
304}
305
307{
308 qreal lDpi = m_displayInfo.densityPixels * ohosLogicalDpi;
309 return QDpi(lDpi, lDpi);
310}
311
313{
314 // densityPixels is the scaling coefficient between the virtual pixel
315 // and the physical pixels.
316 return m_displayInfo.densityPixels;
317}
318
320{
321 return m_displayInfo.refreshRate;
322}
323
328
330{
331 return
332 qAndThen(m_displayInfo.orientation, tryMapJsDisplayOrientationToQt)
333 .value_or(Qt::ScreenOrientation::PrimaryOrientation);
334}
335
337{
338 // No direct query exists, so derive it from this display's orientation
339 // stepped back by its rotation. A hardware constant, so cache it.
340 if (m_nativeOrientation)
341 return *m_nativeOrientation;
342
343 NativeDisplayManager_DisplayInfo *displayInfo = nullptr;
344 const auto displayId = static_cast<uint32_t>(m_displayInfo.id.value());
345 if (OH_NativeDisplayManager_CreateDisplayById(displayId, &displayInfo) != DISPLAY_MANAGER_OK
346 || displayInfo == nullptr) {
347 return Qt::ScreenOrientation::PrimaryOrientation;
348 }
349
350 const NativeDisplayManager_Orientation nativeOrientation = displayInfo->orientation;
351 const NativeDisplayManager_Rotation rotation = displayInfo->rotation;
352 OH_NativeDisplayManager_DestroyDisplay(displayInfo);
353
354 const auto current = tryMapNativeDisplayOrientationToQt(nativeOrientation);
355 if (!current)
356 return Qt::ScreenOrientation::PrimaryOrientation;
357
358 const int currentIndex = orientationToIndex(*current);
359 if (currentIndex < 0)
360 return Qt::ScreenOrientation::PrimaryOrientation;
361
362 m_nativeOrientation = orientationFromIndex(currentIndex - static_cast<int>(rotation));
363 return *m_nativeOrientation;
364}
365
366QRect QOhosPlatformScreen::getAvailableArea() const
367{
368 return QOhosJsThreadGateway::evalWithPromise<QRect>(
369 [&](QOhosJsState &jsState, QOhosTaskPromise<QRect> evalPromise) {
370
371 QNapi::Object display;
372 try {
373 display = jsState.eval<QNapi::Object>(
374 "@ohos.display.getDisplayByIdSync(*)", {m_displayInfo.id.value()});
375 } catch (const Napi::Error &error) {
376 qOhosPrintfError(
377 "%s: getDisplayByIdSync(%f) failed with error: %s",
378 Q_FUNC_INFO, m_displayInfo.id.value(), error.Message().c_str());
379 evalPromise(QRect());
380 return;
381 }
382
383 auto thenCatchPromises = std::move(evalPromise).makeThenCatchBranches(Q_FUNC_INFO);
384 display.evalToPromiseOrRejectOnThrow("getAvailableArea()")
385 .onThen(
386 [thenPromise = std::move(thenCatchPromises.first)](const QOhosCallbackInfo &cbInfo) {
387 auto availableArea = cbInfo.getFirstArg<QNapi::Object>(Q_FUNC_INFO);
388 thenPromise(
389 QRect(
390 availableArea.get<QNapi::Number>("left"),
391 availableArea.get<QNapi::Number>("top"),
392 availableArea.get<QNapi::Number>("width"),
393 availableArea.get<QNapi::Number>("height")));
394 })
395 .onCatch(
396 [catchPromise = std::move(thenCatchPromises.second)](const QOhosCallbackInfo &cbInfo) {
397 QtOhos::logJsCallbackError(cbInfo, "Error occurred in JS getAvailableArea()");
398 catchPromise(QRect());
399 });
400 },
401 Q_FUNC_INFO);
402}
403
404void QOhosPlatformScreen::releaseSurface()
405{
406}
407
409{
410 return m_displayInfo;
411}
412
414{
415 const auto jsDisplayId = m_displayInfo.id.value();
416 qint64 displayId = 0;
417 if (!convertDoubleTo(jsDisplayId, &displayId))
418 qOhosReportFatalErrorAndAbort("%s: display ID %g is out of the qint64 range", Q_FUNC_INFO, jsDisplayId);
419 return displayId;
420}
421
423{
424 return m_displayInfo.displayGeometryPixels();
425}
426
428{
429 auto screenGeometry = geometry();
430 return !m_availableGeometry.isEmpty()
431 ? m_availableGeometry.translated(screenGeometry.topLeft())
432 : screenGeometry;
433}
434
436{
437 return m_depth;
438}
439
441{
442 return m_format;
443}
444
446{
447 return m_displayInfo.physicalSize();
448}
449
451{
452 if (rect != m_availableGeometry) {
453 m_availableGeometry = rect;
454 QWindowSystemInterface::handleScreenGeometryChange(QPlatformScreen::screen(), geometry(), availableGeometry());
455 }
456}
457
459{
460 if (!m_displayInfo.isDisplayMainOrExtended())
461 return QPlatformScreen::virtualSiblings();
462
463 QList<QPlatformScreen *> result;
464 auto allPlatformScreens = m_platformScreenListSupplier();
465 std::copy_if(
466 allPlatformScreens.begin(), allPlatformScreens.end(),
467 std::back_inserter(result),
468 [](QOhosPlatformScreen *ohosPlatformScreen) {
469 return ohosPlatformScreen->displayInfo().isDisplayMainOrExtended();
470 });
471
472 return result;
473}
474
475QPixmap QOhosPlatformScreen::grabWindow(WId wId, int x, int y, int width, int height) const
476{
477 auto captureRect = QRect(x, y, width, height);
478
479 if (wId != 0) {
480 auto *window = tryFindWindowByWIdOrNull(wId);
481 if (window == nullptr) {
482 qOhosPrintfError(
483 "%s: Cannot find window with the given WId: %lld.", Q_FUNC_INFO, wId);
484 return {};
485 }
486 auto *platformWindow = QOhosPlatformWindow::fromQWindow(window);
487 auto *view = platformWindow->ownedViewOrNull();
488 if (view == nullptr)
489 return {};
490 const QRect content = view->nodeScreenGeometryPixels();
491 const QRect frame = view->viewGeometry().frameGeometry;
492 if (content.isEmpty() || !frame.contains(content))
493 return {};
494 const QRect contentRect(content.topLeft() - frame.topLeft(), content.size());
495 return grabWindowFromCapturedScreenPixmap(
496 platformWindow->makeSnapshot().copy(contentRect), captureRect);
497 }
498
499 auto capturedScreenPixmap = QOhosJsThreadGateway::evalWithPromise<QPixmap>(
500 [displayId = m_displayInfo.id](
501 QOhosJsState &jsState, QOhosTaskPromise<QPixmap> evalPromise) {
502 auto sharedEvalPromise = QtOhos::moveToSharedPtr(std::move(evalPromise).makeChained(Q_FUNC_INFO));
503 tryCaptureScreenPixelmapWithPermissionCheck(
504 jsState, displayId,
505 [sharedEvalPromise](
506 std::shared_ptr<::OH_PixelmapNative> optPixelMap) {
507 (*sharedEvalPromise)(
508 optPixelMap
509 ? QPixmap::fromImage(createQImageFromNativePixelMap(optPixelMap.get()))
510 : QPixmap());
511 });
512 },
513 Q_FUNC_INFO);
514
515 return capturedScreenPixmap.copy(captureRect);
516}
517
519{
520 return m_displayInfo.name;
521}
522
523QT_END_NAMESPACE
qint64 displayId() const override
QPixmap grabWindow(WId wId, int x, int y, int width, int height) const override
This function is called when Qt needs to be able to grab the content of a window.
QWindow * topLevelAt(const QPoint &p) const override
Return the given top level window for a given position.
Qt::ScreenOrientation orientation() const override
Reimplement this function in subclass to return the current orientation of the screen,...
QRect availableGeometry() const override
Reimplement in subclass to return the pixel geometry of the available space This normally is the desk...
QSizeF physicalSize() const override
Reimplement this function in subclass to return the physical size of the screen, in millimeters.
qreal refreshRate() const override
Reimplement this function in subclass to return the vertical refresh rate of the screen,...
QImage::Format format() const override
Reimplement in subclass to return the image format which corresponds to the screen format.
Qt::ScreenOrientation nativeOrientation() const override
Reimplement this function in subclass to return the native orientation of the screen,...
const QOhosDisplayInfo & displayInfo() const
QList< QPlatformScreen * > virtualSiblings() const override
Returns a list of all the platform screens that are part of the same virtual desktop.
QString name() const override
QPlatformCursor * cursor() const override
Reimplement this function in subclass to return the cursor of the screen.
qreal pixelScalingCoefficient() const
void setAvailableGeometry(const QRect &rect)
void setDisplayInfo(const QOhosDisplayInfo &displayInfo)
QRect geometry() const override
Reimplement in subclass to return the pixel geometry of the screen.
QDpi logicalDpi() const override
Reimplement this function in subclass to return the logical horizontal and vertical dots per inch met...
int depth() const override
Reimplement in subclass to return current depth of the screen.
QDpi logicalBaseDpi() const override
Reimplement to return the base logical DPI for the platform.
void checkAppPermissionGrantedWithConsumer(QOhosJsState &jsState, const std::string &permissionName, QOhosConsumer< QOhosJsState &, bool > resultConsumer)
Combined button and popup list for selecting options.
Qt::ScreenOrientation orientationFromIndex(int index)
QWindow * tryFindWindowByWIdOrNull(WId wId)
QPixmap grabWindowFromCapturedScreenPixmap(const QPixmap &capturedWindowPixmap, const QRect &windowSpaceCaptureRect)
QRect calculateResultPixmapWindowFragmentRect(const QRect &windowSpaceCaptureRect, const QRect &windowFragmentRect)
std::optional< Qt::ScreenOrientation > tryMapJsDisplayOrientationToQt(QOhosDisplayInfo::JsDisplayOrientation jsDisplayOrientation)
std::shared_ptr<::OH_PixelmapNative > captureScreenPixelmap(QOhosJsState &, QOhosDisplayInfo::JsDisplayId displayId)
static const int ohosLogicalDpi
void tryCaptureScreenPixelmapWithPermissionCheck(QOhosJsState &jsState, QOhosDisplayInfo::JsDisplayId displayId, QOhosConsumer< std::shared_ptr<::OH_PixelmapNative > > pixelMapOrNullConsumer)
std::optional< Qt::ScreenOrientation > tryMapNativeDisplayOrientationToQt(NativeDisplayManager_Orientation nativeOrientation)
int orientationToIndex(Qt::ScreenOrientation orientation)
QSize calculateResultWindowCapturePixmapSize(const QSize &windowSnapshotSize, const QRect &windowSpaceCaptureRect)
bool isDisplayMainOrExtended() const
QtOhosQpa::enums::ohos::display::Orientation JsDisplayOrientation