utils.cpp 12.4 KB
Newer Older
1 2
/***************************************************************************
 *   Copyright (C) 2006 by Luigi Toscano <luigi.toscano@tiscali.it>        *
3
 *   Copyright (C) 2008 by Pino Toscano <pino@kde.org>                     *
4 5 6 7 8 9 10 11
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include "utils.h"
12
#include "utils_p.h"
13

14
#include <QtCore/QRect>
15 16
#include <QApplication>
#include <QDesktopWidget>
17
#include <QImage>
18
#include <QIODevice>
19

20
#ifdef Q_WS_X11
21 22 23
  #include "config-okular.h"
  #if HAVE_LIBKSCREEN
   #include <kscreen/config.h>
24
   #include <kscreen/edid.h>
25 26
  #endif
  #include <QX11Info>
27 28 29 30 31 32 33 34 35
#endif

#ifdef Q_WS_MAC
#include <ApplicationServices/ApplicationServices.h>
#include <IOKit/graphics/IOGraphicsLib.h>
#endif



36
using namespace Okular;
37

38
QRect Utils::rotateRect( const QRect & source, int width, int height, int orientation )
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
{
    QRect ret;

    // adapt the coordinates of the boxes to the rotation
    switch ( orientation )
    {
        case 1:
            ret = QRect( width - source.y() - source.height(), source.x(),
                         source.height(), source.width() );
            break;
        case 2:
            ret = QRect( width - source.x() - source.width(), height - source.y() - source.height(),
                         source.width(), source.height() );
            break;
        case 3:
            ret = QRect( source.y(), height - source.x() - source.width(),
                         source.height(), source.width() );
            break;
        case 0:  // no modifications
        default: // other cases
            ret = source;
    }

    return ret;
}
64 65

#if defined(Q_WS_X11)
66 67 68

double Utils::dpiX()
{
69 70 71
    return QX11Info::appDpiX();
}

72 73
double Utils::dpiY()
{
74 75
    return QX11Info::appDpiY();
}
76

77 78 79
double Utils::realDpiX()
{
    const QDesktopWidget* w = QApplication::desktop();
80
    if (w->width() > 0 && w->widthMM() > 0) {
81
        kDebug() << "Pix:" << w->width() << "MM:" << w->widthMM();
82 83 84 85
        return (double(w->width()) * 25.4) / double(w->widthMM());
    } else {
        return dpiX();
    }
86 87 88 89 90
}

double Utils::realDpiY()
{
    const QDesktopWidget* w = QApplication::desktop();
91
    if (w->height() > 0 && w->heightMM() > 0) {
92
        kDebug() << "Pix:" << w->height() << "MM:" << w->heightMM();
93 94 95 96
        return (double(w->height()) * 25.4) / double(w->heightMM());
    } else {
        return dpiY();
    }
97 98
}

99 100
QSizeF Utils::realDpi(QWidget* widgetOnScreen)
{
101 102 103
    if (widgetOnScreen)
    {
        // Firstly try to retrieve DPI via LibKScreen
104
#if HAVE_LIBKSCREEN
105
        KScreen::Config* config = KScreen::Config::current();
106 107 108 109 110 111 112 113 114 115
        if (config) {
            KScreen::OutputList outputs = config->outputs();
            QPoint globalPos = widgetOnScreen->parentWidget() ?
                        widgetOnScreen->mapToGlobal(widgetOnScreen->pos()):
                        widgetOnScreen->pos();
            QRect widgetRect(globalPos, widgetOnScreen->size());

            KScreen::Output* selectedOutput = 0;
            int maxArea = 0;
            Q_FOREACH(KScreen::Output *output, outputs)
116
            {
117
                if (output->currentMode())
118
                {
119 120 121 122 123 124 125 126
                    QRect outputRect(output->pos(),output->currentMode()->size());
                    QRect intersection = outputRect.intersected(widgetRect);
                    int area = intersection.width()*intersection.height();
                    if (area > maxArea)
                    {
                        maxArea = area;
                        selectedOutput = output;
                    }
127
                }
128 129
            }

130 131 132 133 134
            if (selectedOutput)
            {
                kDebug() << "Found widget at output #" << selectedOutput->id();
                QRect outputRect(selectedOutput->pos(),selectedOutput->currentMode()->size());
                QSize szMM = selectedOutput->sizeMm();
Albert Astals Cid's avatar
Albert Astals Cid committed
135 136
                kDebug() << "Output size is (mm) " << szMM;
                kDebug() << "Output rect is " << outputRect;
137
                if (selectedOutput->edid()) {
Albert Astals Cid's avatar
Albert Astals Cid committed
138
                    kDebug() << "EDID WxH (cm): " << selectedOutput->edid()->width()  << 'x' << selectedOutput->edid()->height();
139 140 141
                }
                if (szMM.width() > 0 && szMM.height() > 0 && outputRect.width() > 0 && outputRect.height() > 0
                    && selectedOutput->edid()
Vadim Zhukov's avatar
Vadim Zhukov committed
142 143
                    && qAbs(static_cast<int>(selectedOutput->edid()->width()*10) - szMM.width()) < 10
                    && qAbs(static_cast<int>(selectedOutput->edid()->height()*10) - szMM.height()) < 10)
144 145
                {
                    // sizes in EDID seem to be consistent
146
                    QSizeF res(static_cast<qreal>(outputRect.width())*25.4/szMM.width(),
147 148 149 150 151 152
                              static_cast<qreal>(outputRect.height())*25.4/szMM.height());
                    if (!selectedOutput->isHorizontal())
                    {
                        kDebug() << "Output is vertical, transposing DPI rect";
                        res.transpose();
                    }
153 154 155 156 157
                    if (qAbs(res.width() - res.height()) / qMin(res.height(), res.width()) < 0.05) {
                        return res;
                    } else {
                        kDebug() << "KScreen calculation returned a non square dpi." << res << ". Falling back";
                    }
158
                }
159
            }
160 161 162 163 164 165 166 167
            else
            {
                kDebug() << "Didn't find a KScreen selectedOutput to calculate DPI. Falling back";
            }
        }
        else
        {
            kDebug() << "Didn't find a KScreen config to calculate DPI. Falling back";
168
        }
169
#endif
170
    }
171 172
    // this is also fallback for LibKScreen branch if KScreen::Output
    // for particular widget was not found
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    QSizeF res = QSizeF(realDpiX(), realDpiY());
    if (qAbs(res.width() - res.height()) / qMin(res.height(), res.width()) < 0.05) {
        return res;
    } else {
        kDebug() << "QDesktopWidget calculation returned a non square dpi." << res << ". Falling back";
    }

    res = QSizeF(dpiX(), dpiY());
    if (qAbs(res.width() - res.height()) / qMin(res.height(), res.width()) < 0.05) {
        return res;
    } else {
        kDebug() << "QX11Info returned a non square dpi." << res << ". Falling back";
    }
    
    res = QSizeF(72, 72);
    return res;
189 190
}

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
#elif defined(Q_WS_MAC)
    /*
     * Code copied from http://developer.apple.com/qa/qa2001/qa1217.html
     */
    //    Handy utility function for retrieving an int from a CFDictionaryRef
    static int GetIntFromDictionaryForKey( CFDictionaryRef desc, CFStringRef key )
    {
        CFNumberRef value;
        int num = 0;
        if ( (value = (CFNumberRef)CFDictionaryGetValue(desc, key)) == NULL || CFGetTypeID(value) != CFNumberGetTypeID())
            return 0;
        CFNumberGetValue(value, kCFNumberIntType, &num);
        return num;
    }

206 207
    static CGDisplayErr GetDisplayDPI( CFDictionaryRef displayModeDict, CGDirectDisplayID displayID,
                                       double *horizontalDPI, double *verticalDPI )
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    {
        CGDisplayErr err = kCGErrorFailure;
        io_connect_t displayPort;
        CFDictionaryRef displayDict;

        //    Grab a connection to IOKit for the requested display
        displayPort = CGDisplayIOServicePort( displayID );
        if ( displayPort != MACH_PORT_NULL )
        {
            //    Find out what IOKit knows about this display
            displayDict = IODisplayCreateInfoDictionary(displayPort, 0);
            if ( displayDict != NULL )
            {
                const double mmPerInch = 25.4;
                double horizontalSizeInInches =
                    (double)GetIntFromDictionaryForKey(displayDict,
                                                       CFSTR(kDisplayHorizontalImageSize)) / mmPerInch;
                double verticalSizeInInches =
                    (double)GetIntFromDictionaryForKey(displayDict,
                                                       CFSTR(kDisplayVerticalImageSize)) / mmPerInch;

                //    Make sure to release the dictionary we got from IOKit
                CFRelease(displayDict);

                // Now we can calculate the actual DPI
                // with information from the displayModeDict
                *horizontalDPI =
                    (double)GetIntFromDictionaryForKey( displayModeDict, kCGDisplayWidth )
                    / horizontalSizeInInches;
                *verticalDPI = (double)GetIntFromDictionaryForKey( displayModeDict,
                        kCGDisplayHeight ) / verticalSizeInInches;
                err = CGDisplayNoErr;
            }
        }
        return err;
    }

245 246
double Utils::dpiX()
{
247 248 249 250 251 252 253 254
    double x,y;
    CGDisplayErr err = GetDisplayDPI( CGDisplayCurrentMode(kCGDirectMainDisplay),
                                      kCGDirectMainDisplay,
                                      &x, &y );

    return err == CGDisplayNoErr ? x : 72.0;
}

255 256
double Utils::dpiY()
{
257 258 259 260 261 262 263
    double x,y;
    CGDisplayErr err = GetDisplayDPI( CGDisplayCurrentMode(kCGDirectMainDisplay),
                                      kCGDirectMainDisplay,
                                      &x, &y );

    return err == CGDisplayNoErr ? y : 72.0;
}
264 265 266 267 268 269 270 271 272 273

double Utils::realDpiX()
{
    return dpiX();
}

double Utils::realDpiY()
{
    return dpiY();
}
274 275 276 277 278

QSizeF Utils::realDpi(QWidget*)
{
    return QSizeF(realDpiX(), realDpiY());
}
279
#else
Christian Ehrlicher's avatar
Christian Ehrlicher committed
280 281 282 283 284 285 286 287 288 289

double Utils::dpiX()
{
    return QDesktopWidget().physicalDpiX();
}

double Utils::dpiY()
{
    return QDesktopWidget().physicalDpiY();
}
290 291 292 293 294 295 296 297 298 299

double Utils::realDpiX()
{
    return dpiX();
}

double Utils::realDpiY()
{
    return dpiY();
}
300 301 302 303 304

QSizeF Utils::realDpi(QWidget*)
{
    return QSizeF(realDpiX(), realDpiY());
}
305
#endif
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365

inline static bool isWhite( QRgb argb ) {
    return ( argb & 0xFFFFFF ) == 0xFFFFFF; // ignore alpha
}

NormalizedRect Utils::imageBoundingBox( const QImage * image )
{
    if ( !image )
        return NormalizedRect();

    int width = image->width();
    int height = image->height();
    int left, top, bottom, right, x, y;

#ifdef BBOX_DEBUG
    QTime time;
    time.start();
#endif

    // Scan pixels for top non-white
    for ( top = 0; top < height; ++top )
        for ( x = 0; x < width; ++x )
            if ( !isWhite( image->pixel( x, top ) ) )
                goto got_top;
    return NormalizedRect( 0, 0, 0, 0 ); // the image is blank
got_top:
    left = right = x;

    // Scan pixels for bottom non-white
    for ( bottom = height-1; bottom >= top; --bottom )
        for ( x = width-1; x >= 0; --x )
            if ( !isWhite( image->pixel( x, bottom ) ) )
                goto got_bottom;
    Q_ASSERT( 0 ); // image changed?!
got_bottom:
    if ( x < left )
        left = x;
    if ( x > right )
        right = x;

    // Scan for leftmost and rightmost (we already found some bounds on these):
    for ( y = top; y <= bottom && ( left > 0 || right < width-1 ); ++y )
    {
        for ( x = 0; x < left; ++x )
            if ( !isWhite( image->pixel( x, y ) ) )
                left = x;
        for ( x = width-1; x > right+1; --x )
            if ( !isWhite( image->pixel( x, y ) ) )
                right = x;
    }

    NormalizedRect bbox( QRect( left, top, ( right - left + 1), ( bottom - top + 1 ) ),
                         image->width(), image->height() );

#ifdef BBOX_DEBUG
    kDebug() << "Computed bounding box" << bbox << "in" << time.elapsed() << "ms";
#endif

    return bbox;
}
366 367 368 369 370 371 372 373 374 375 376 377 378

void Okular::copyQIODevice( QIODevice *from, QIODevice *to )
{
    QByteArray buffer( 65536, '\0' );
    qint64 read = 0;
    qint64 written = 0;
    while ( ( read = from->read( buffer.data(), buffer.size() ) ) > 0 )
    {
        written = to->write( buffer.constData(), read );
        if ( read != written )
            break;
    }
}
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

QTransform Okular::buildRotationMatrix(Rotation rotation)
{
    QTransform matrix;
    matrix.rotate( (int)rotation * 90 );

    switch ( rotation )
    {
        case Rotation90:
            matrix.translate( 0, -1 );
            break;
        case Rotation180:
            matrix.translate( -1, -1 );
            break;
        case Rotation270:
            matrix.translate( -1, 0 );
            break;
        default: ;
    }

    return matrix;
}
401 402

/* kate: replace-tabs on; indent-width 4; */