File indexing completed on 2024-11-17 05:01:08

0001 /*
0002     SPDX-FileCopyrightText: 2014 Weng Xuetian <wengxt@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005 */
0006 
0007 #include "screen.h"
0008 #include <QGuiApplication>
0009 #include <QScreen>
0010 #include <limits.h>
0011 
0012 int pointToRect(int x, int y, const QRect &r)
0013 {
0014     int dx = 0;
0015     int dy = 0;
0016     if (x < r.left()) {
0017         dx = r.left() - x;
0018     } else if (x > r.right()) {
0019         dx = x - r.right();
0020     }
0021     if (y < r.top()) {
0022         dy = r.top() - y;
0023     } else if (y > r.bottom()) {
0024         dy = y - r.bottom();
0025     }
0026     return dx + dy;
0027 }
0028 
0029 Screen::Screen(QObject *parent)
0030     : QObject(parent)
0031 {
0032 }
0033 
0034 Screen::~Screen()
0035 {
0036 }
0037 
0038 QScreen *screenForPoint(int x, int y)
0039 {
0040     const QList<QScreen *> screens = qApp->screens();
0041     QScreen *closestScreen = nullptr;
0042     int shortestDistance = INT_MAX;
0043     for (QScreen *screen : screens) {
0044         QRect rect = screen->availableGeometry();
0045         rect.setSize(rect.size() * screen->devicePixelRatio());
0046         int thisDistance = pointToRect(x, y, rect);
0047         if (thisDistance < shortestDistance) {
0048             shortestDistance = thisDistance;
0049             closestScreen = screen;
0050         }
0051     }
0052 
0053     if (!closestScreen) {
0054         closestScreen = qApp->primaryScreen();
0055     }
0056 
0057     return closestScreen;
0058 }
0059 
0060 QRect Screen::geometryForPoint(int x, int y)
0061 {
0062     auto closestScreen = screenForPoint(x, y);
0063 
0064     if (closestScreen) {
0065         auto rect = closestScreen->availableGeometry();
0066         rect.setSize(rect.size() * closestScreen->devicePixelRatio());
0067         return rect;
0068     }
0069     return QRect();
0070 }
0071 
0072 qreal Screen::devicePixelRatioForPoint(int x, int y)
0073 {
0074     auto closestScreen = screenForPoint(x, y);
0075 
0076     if (closestScreen) {
0077         return closestScreen->devicePixelRatio();
0078     }
0079     return 1.0;
0080 }