KisWindowLayoutResource.cpp 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 *  Copyright (c) 2018 Jouni Pentikäinen <joupent@gmail.com>
 *
 *  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.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
#include "KisWindowLayoutResource.h"
19
#include "KisWindowLayoutManager.h"
20 21

#include <QVector>
22
#include <QList>
23 24
#include <QFile>
#include <QDomDocument>
25
#include <QApplication>
Yuri Chornoivan's avatar
Yuri Chornoivan committed
26
#include <QEventLoop>
27 28
#include <QWindow>
#include <QScreen>
29 30 31

#include <KisPart.h>
#include <KisDocument.h>
32
#include <kis_dom_utils.h>
33 34 35 36 37

static const int WINDOW_LAYOUT_VERSION = 1;

struct KisWindowLayoutResource::Private
{
38 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    struct WindowGeometry{
        int screen = -1;
        Qt::WindowStates stateFlags = Qt::WindowNoState;
        QByteArray data;

        static WindowGeometry fromWindow(const QWidget *window, QList<QScreen*> screens)
        {
            WindowGeometry geometry;
            QWindow *windowHandle = window->windowHandle();

            geometry.data = window->saveGeometry();
            geometry.stateFlags = windowHandle->windowState();

            int index = screens.indexOf(windowHandle->screen());
            if (index >= 0) {
                geometry.screen = index;
            }

            return geometry;
        }

        void forceOntoCorrectScreen(QWidget *window, QList<QScreen*> screens)
        {
            QWindow *windowHandle = window->windowHandle();

            if (screens.indexOf(windowHandle->screen()) != screen) {
                QScreen *qScreen = screens[screen];
                windowHandle->setScreen(qScreen);
                windowHandle->setPosition(qScreen->availableGeometry().topLeft());
            }

            if (stateFlags) {
                window->setWindowState(stateFlags);
            }
        }

        void save(QDomDocument &doc, QDomElement &elem) const
        {
            if (screen >= 0) {
                elem.setAttribute("screen", screen);
            }

            if (stateFlags & Qt::WindowMaximized) {
                elem.setAttribute("maximized", "1");
            }

            QDomElement geometry = doc.createElement("geometry");
            geometry.appendChild(doc.createCDATASection(data.toBase64()));
            elem.appendChild(geometry);
        }

        static WindowGeometry load(const QDomElement &element)
        {
            WindowGeometry geometry;
            geometry.screen = element.attribute("screen", "-1").toInt();

            if (element.attribute("maximized", "0") != "0") {
                geometry.stateFlags |= Qt::WindowMaximized;
            }

            QDomElement dataElement = element.firstChildElement("geometry");
            geometry.data = QByteArray::fromBase64(dataElement.text().toLatin1());

            return geometry;
        }
    };

105
    struct Window {
106
        QUuid windowId;
107
        QByteArray windowState;
108 109 110 111
        WindowGeometry geometry;

        bool canvasDetached = false;
        WindowGeometry canvasWindowGeometry;
112 113 114
    };

    QVector<Window> windows;
115
    bool showImageInAllWindows;
116 117
    bool primaryWorkspaceFollowsFocus;
    QUuid primaryWindow;
118 119 120 121 122 123 124 125 126 127

    Private() = default;

    explicit Private(QVector<Window> windows)
        : windows(std::move(windows))
    {}

    void openNecessaryWindows(QList<QPointer<KisMainWindow>> &currentWindows) {
        auto *kisPart = KisPart::instance();

128
        Q_FOREACH(const Window &window, windows) {
129
            QPointer<KisMainWindow> mainWindow = kisPart->windowById(window.windowId);
130

131 132
            if (mainWindow.isNull()) {
                mainWindow = kisPart->createMainWindow(window.windowId);
133 134 135
                currentWindows.append(mainWindow);
                mainWindow->show();
            }
136 137 138 139
        }
    }

    void closeUnneededWindows(QList<QPointer<KisMainWindow>> &currentWindows) {
140 141 142 143 144 145 146 147 148 149 150 151 152
        QVector<QPointer<KisMainWindow>> windowsToClose;

        Q_FOREACH(KisMainWindow *mainWindow, currentWindows) {
            bool keep = false;
            Q_FOREACH(const Window &window, windows) {
                if (window.windowId == mainWindow->id()) {
                    keep = true;
                    break;
                }
            }

            if (!keep) {
                windowsToClose.append(mainWindow);
153 154 155 156

                // Set the window hidden to prevent "show image in all windows" feature from opening new views on it
                // while we migrate views onto the remaining windows
                mainWindow->hide();
157 158
            }
        }
159

160
        migrateViewsFromClosingWindows(windowsToClose);
161

162 163
        Q_FOREACH(QPointer<KisMainWindow> mainWindow, windowsToClose) {
            mainWindow->close();
164 165 166
        }
    }

167
    void migrateViewsFromClosingWindows(QVector<QPointer<KisMainWindow>> &closingWindows) const
168 169
    {
        auto *kisPart = KisPart::instance();
170 171 172 173 174 175 176 177 178 179 180 181 182 183
        KisMainWindow *migrationTarget = nullptr;

        Q_FOREACH(KisMainWindow *mainWindow, kisPart->mainWindows()) {
            if (!closingWindows.contains(mainWindow)) {
                migrationTarget = mainWindow;
                break;
            }
        }

        if (!migrationTarget) {
            qWarning() << "Problem: window layout with no windows would leave user with zero main windows.";
            migrationTarget = closingWindows.takeLast();
            migrationTarget->show();
        }
184 185 186 187

        QVector<KisDocument*> visibleDocuments;
        Q_FOREACH(KisView *view, kisPart->views()) {
            KisMainWindow *window = view->mainWindow();
188
            if (!closingWindows.contains(window)) {
189 190 191 192 193 194 195
                visibleDocuments.append(view->document());
            }
        }

        Q_FOREACH(KisDocument *document, kisPart->documents()) {
            if (!visibleDocuments.contains(document)) {
                visibleDocuments.append(document);
196
                migrationTarget->newView(document);
197 198 199
            }
        }
    }
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214


    QList<QScreen*> getScreensInConsistentOrder() {
        QList<QScreen*> screens = QGuiApplication::screens();

        std::sort(screens.begin(), screens.end(), [](const QScreen *a, const QScreen *b) {
            QRect aRect = a->geometry();
            QRect bRect = b->geometry();

            if (aRect.y() == bRect.y()) return aRect.x() < bRect.x();
            return (aRect.y() < aRect.y());
        });

        return screens;
    }
215 216 217 218 219 220 221 222 223 224
};

KisWindowLayoutResource::KisWindowLayoutResource(const QString &filename)
    : KoResource(filename)
    , d(new Private)
{}

KisWindowLayoutResource::~KisWindowLayoutResource()
{}

225
KisWindowLayoutResource * KisWindowLayoutResource::fromCurrentWindows(
226 227
    const QString &filename, const QList<QPointer<KisMainWindow>> &mainWindows, bool showImageInAllWindows,
    bool primaryWorkspaceFollowsFocus, KisMainWindow *primaryWindow
228
)
229
{
230 231
    auto resource = new KisWindowLayoutResource(filename);
    resource->setWindows(mainWindows);
232 233 234
    resource->d->showImageInAllWindows = showImageInAllWindows;
    resource->d->primaryWorkspaceFollowsFocus = primaryWorkspaceFollowsFocus;
    resource->d->primaryWindow = primaryWindow->id();
235
    return resource;
236 237 238 239
}

void KisWindowLayoutResource::applyLayout()
{
240 241
    auto *kisPart = KisPart::instance();
    auto *layoutManager= KisWindowLayoutManager::instance();
242

243
    layoutManager->setLastUsedLayout(this);
244

245 246
    QList<QPointer<KisMainWindow>> currentWindows = kisPart->mainWindows();

247 248 249 250 251 252 253 254 255 256 257
    if (d->windows.isEmpty()) {
        // No windows defined (e.g. fresh new session). Leave things as they are, but make sure there's at least one visible main window
        if (kisPart->mainwindowCount() == 0) {
            kisPart->createMainWindow();
        } else {
            kisPart->mainWindows().first()->show();
        }
    } else {
        d->openNecessaryWindows(currentWindows);
        d->closeUnneededWindows(currentWindows);
    }
258 259 260 261

    // Wait for the windows to finish opening / closing before applying saved geometry.
    // If we don't, the geometry may get reset after we apply it.
    QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
262 263

    Q_FOREACH(const auto &window, d->windows) {
264
        QPointer<KisMainWindow> mainWindow = kisPart->windowById(window.windowId);
265 266
        KIS_SAFE_ASSERT_RECOVER_BREAK(mainWindow);

267
        mainWindow->restoreGeometry(window.geometry.data);
268
        mainWindow->restoreWorkspaceState(window.windowState);
269 270 271 272

        mainWindow->setCanvasDetached(window.canvasDetached);
        if (window.canvasDetached) {
            QWidget *canvasWindow = mainWindow->canvasWindow();
273
            canvasWindow->restoreGeometry(window.canvasWindowGeometry.data);
274
        }
275 276
    }

277 278 279 280
    QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);

    QList<QScreen*> screens = d->getScreensInConsistentOrder();
    Q_FOREACH(const auto &window, d->windows) {
281 282 283
        Private::WindowGeometry geometry = window.geometry;
        QPointer<KisMainWindow> mainWindow = kisPart->windowById(window.windowId);
        KIS_SAFE_ASSERT_RECOVER_BREAK(mainWindow);
284

285 286 287 288 289 290 291
        if (geometry.screen >= 0 && geometry.screen < screens.size()) {
            geometry.forceOntoCorrectScreen(mainWindow, screens);
        }
        if (window.canvasDetached) {
            Private::WindowGeometry canvasWindowGeometry = window.canvasWindowGeometry;
            if (canvasWindowGeometry.screen >= 0 && canvasWindowGeometry.screen < screens.size()) {
                canvasWindowGeometry.forceOntoCorrectScreen(mainWindow->canvasWindow(), screens);
292 293 294 295
            }
        }
    }

296 297
    layoutManager->setShowImageInAllWindowsEnabled(d->showImageInAllWindows);
    layoutManager->setPrimaryWorkspaceFollowsFocus(d->primaryWorkspaceFollowsFocus, d->primaryWindow);
298 299 300 301 302 303 304 305 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
}

bool KisWindowLayoutResource::save()
{
    if (filename().isEmpty())
        return false;

    QFile file(filename());
    file.open(QIODevice::WriteOnly);
    bool res = saveToDevice(&file);
    file.close();
    return res;
}

bool KisWindowLayoutResource::load()
{
    if (filename().isEmpty())
         return false;

    QFile file(filename());
    if (file.size() == 0) return false;
    if (!file.open(QIODevice::ReadOnly)) {
        warnKrita << "Can't open file " << filename();
        return false;
    }

    bool res = loadFromDevice(&file);
    file.close();
    return res;
}

bool KisWindowLayoutResource::saveToDevice(QIODevice *dev) const
{
    QDomDocument doc;
    QDomElement root = doc.createElement("WindowLayout");
    root.setAttribute("name", name());
    root.setAttribute("version", WINDOW_LAYOUT_VERSION);

336
    saveXml(doc, root);
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360

    doc.appendChild(root);

    QTextStream textStream(dev);
    textStream.setCodec("UTF-8");
    doc.save(textStream, 4);

    KoResource::saveToDevice(dev);

    return true;
}

bool KisWindowLayoutResource::loadFromDevice(QIODevice *dev)
{
    QDomDocument doc;
    if (!doc.setContent(dev)) {
        return false;
    }

    QDomElement element = doc.documentElement();
    setName(element.attribute("name"));

    d->windows.clear();

361 362 363 364 365 366 367 368
    loadXml(element);

    setValid(true);
    return true;
}

void KisWindowLayoutResource::saveXml(QDomDocument &doc, QDomElement &root) const
{
369
    root.setAttribute("showImageInAllWindows", (int)d->showImageInAllWindows);
370 371
    root.setAttribute("primaryWorkspaceFollowsFocus", (int)d->primaryWorkspaceFollowsFocus);
    root.setAttribute("primaryWindow", d->primaryWindow.toString());
372

373 374 375 376
    Q_FOREACH(const auto &window, d->windows) {
        QDomElement elem = doc.createElement("window");
        elem.setAttribute("id", window.windowId.toString());

377
        window.geometry.save(doc, elem);
378

379 380 381 382
        if (window.canvasDetached) {
            QDomElement canvasWindowElement = doc.createElement("canvasWindow");
            window.canvasWindowGeometry.save(doc, canvasWindowElement);
            elem.appendChild(canvasWindowElement);
383 384
        }

385 386 387 388 389 390 391 392 393
        QDomElement state = doc.createElement("windowState");
        state.appendChild(doc.createCDATASection(window.windowState.toBase64()));
        elem.appendChild(state);
        root.appendChild(elem);
    }
}

void KisWindowLayoutResource::loadXml(const QDomElement &element) const
{
394
    d->showImageInAllWindows = KisDomUtils::toInt(element.attribute("showImageInAllWindows", "0"));
395 396
    d->primaryWorkspaceFollowsFocus = KisDomUtils::toInt(element.attribute("primaryWorkspaceFollowsFocus", "0"));
    d->primaryWindow = element.attribute("primaryWindow");
397

398 399
    for (auto windowElement = element.firstChildElement("window");
         !windowElement.isNull();
400
         windowElement = windowElement.nextSiblingElement("window")) {
401 402 403

        Private::Window window;

404 405 406 407 408
        window.windowId = QUuid(windowElement.attribute("id", QUuid().toString()));
        if (window.windowId.isNull()) {
            window.windowId = QUuid::createUuid();
        }

409
        window.geometry = Private::WindowGeometry::load(windowElement);
410

411 412 413 414
        QDomElement canvasWindowElement = windowElement.firstChildElement("canvasWindow");
        if (!canvasWindowElement.isNull()) {
            window.canvasDetached = true;
            window.canvasWindowGeometry = Private::WindowGeometry::load(canvasWindowElement);
415 416
        }

417 418 419 420 421 422 423 424 425 426 427 428
        QDomElement state = windowElement.firstChildElement("windowState");
        window.windowState = QByteArray::fromBase64(state.text().toLatin1());

        d->windows.append(window);
    }
}

QString KisWindowLayoutResource::defaultFileExtension() const
{
    return QString(".kwl");
}

429 430 431 432
void KisWindowLayoutResource::setWindows(const QList<QPointer<KisMainWindow>> &mainWindows)
{
    d->windows.clear();

433 434
    QList<QScreen*> screens = d->getScreensInConsistentOrder();

435
    Q_FOREACH(auto window, mainWindows) {
436 437
        if (!window->isVisible()) continue;

438 439 440
        Private::Window state;
        state.windowId = window->id();
        state.windowState = window->saveState();
441
        state.geometry = Private::WindowGeometry::fromWindow(window, screens);
442

443 444 445
        state.canvasDetached = window->canvasDetached();
        if (state.canvasDetached) {
            state.canvasWindowGeometry = Private::WindowGeometry::fromWindow(window->canvasWindow(), screens);
446
        }
447 448 449 450

        d->windows.append(state);
    }
}