KisDocument.cpp 70.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* This file is part of the Krita project
 *
 * Copyright (C) 2014 Boudewijn Rempt <boud@kogmbh.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "KisMainWindow.h" // XXX: remove
Halla Rempt's avatar
Halla Rempt committed
22
#include <QMessageBox> // XXX: remove
23

24 25
#include <QMimeDatabase>
#include <QMimeType>
26 27 28 29 30 31 32 33 34 35

#include <KoCanvasBase.h>
#include <KoColor.h>
#include <KoColorProfile.h>
#include <KoColorSpaceEngine.h>
#include <KoColorSpace.h>
#include <KoColorSpaceRegistry.h>
#include <KoDocumentInfoDlg.h>
#include <KoDocumentInfo.h>
#include <KoDpi.h>
36
#include <KoUnit.h>
37 38 39 40 41 42 43 44
#include <KoEmbeddedDocumentSaver.h>
#include <KoFileDialog.h>
#include <KoID.h>
#include <KoOdfReadStore.h>
#include <KoProgressProxy.h>
#include <KoProgressUpdater.h>
#include <KoSelection.h>
#include <KoShape.h>
45
#include <KoShapeController.h>
46 47 48 49
#include <KoStore.h>
#include <KoUpdater.h>
#include <KoXmlWriter.h>

50
#include <klocalizedstring.h>
Halla Rempt's avatar
Halla Rempt committed
51
#include <kis_debug.h>
52 53
#include <kdesktopfile.h>
#include <kconfiggroup.h>
54
#include <QTemporaryFile>
55
#include <kbackup.h>
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

#include <QApplication>
#include <QBuffer>
#include <QDesktopServices>
#include <QDir>
#include <QDomDocument>
#include <QDomElement>
#include <QFileInfo>
#include <QImage>
#include <QList>
#include <QPainter>
#include <QRect>
#include <QScopedPointer>
#include <QSize>
#include <QStringList>
#include <QtGlobal>
#include <QTimer>
#include <QWidget>

// Krita Image
#include <kis_config.h>
#include <flake/kis_shape_layer.h>
#include <kis_debug.h>
#include <kis_group_layer.h>
#include <kis_image.h>
#include <kis_layer.h>
#include <kis_name_server.h>
#include <kis_paint_layer.h>
#include <kis_painter.h>
#include <kis_selection.h>
#include <kis_fill_painter.h>
#include <kis_document_undo_store.h>
#include <kis_painting_assistants_decoration.h>
89 90
#include <kis_idle_watcher.h>
#include <kis_signal_auto_connection.h>
Halla Rempt's avatar
Halla Rempt committed
91
#include <kis_debug.h>
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

// Local
#include "KisViewManager.h"
#include "kis_clipboard.h"
#include "widgets/kis_custom_image_widget.h"
#include "canvas/kis_canvas2.h"
#include "flake/kis_shape_controller.h"
#include "kra/kis_kra_loader.h"
#include "kra/kis_kra_saver.h"
#include "kis_statusbar.h"
#include "widgets/kis_progress_widget.h"
#include "kis_canvas_resource_provider.h"
#include "kis_resource_server_provider.h"
#include "kis_node_manager.h"
#include "KisPart.h"
107 108 109 110 111 112
#include "KisApplication.h"
#include "KisDocument.h"
#include "KisImportExportManager.h"
#include "KisPart.h"
#include "KisView.h"

113 114 115 116

static const char CURRENT_DTD_VERSION[] = "2.0";

// Define the protocol used here for embedded documents' URL
Halla Rempt's avatar
Halla Rempt committed
117
// This used to "store" but QUrl didn't like it,
118 119
// so let's simply make it "tar" !
#define STORE_PROTOCOL "tar"
Halla Rempt's avatar
Halla Rempt committed
120
// The internal path is a hack to make QUrl happy and for document children
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
#define INTERNAL_PROTOCOL "intern"
#define INTERNAL_PREFIX "intern:/"
// Warning, keep it sync in koStore.cc

#include <unistd.h>

using namespace std;

/**********************************************************
 *
 * KisDocument
 *
 **********************************************************/

namespace {

class DocumentProgressProxy : public KoProgressProxy {
public:
    KisMainWindow *m_mainWindow;
    DocumentProgressProxy(KisMainWindow *mainWindow)
        : m_mainWindow(mainWindow)
    {
    }

    ~DocumentProgressProxy() {
        // signal that the job is done
        setValue(-1);
    }

    int maximum() const {
        return 100;
    }

    void setValue(int value) {
        if (m_mainWindow) {
            m_mainWindow->slotProgress(value);
        }
    }

    void setRange(int /*minimum*/, int /*maximum*/) {

    }

    void setFormat(const QString &/*format*/) {

    }
};
}

//static
QString KisDocument::newObjectName()
{
    static int s_docIFNumber = 0;
    QString name; name.setNum(s_docIFNumber++); name.prepend("document_");
    return name;
}


class UndoStack : public KUndo2Stack
{
public:
    UndoStack(KisDocument *doc)
        : m_doc(doc)
    {
    }

    void setIndex(int idx) {
        KisImageWSP image = this->image();
        image->requestStrokeCancellation();
        if(image->tryBarrierLock()) {
            KUndo2Stack::setIndex(idx);
            image->unlock();
        }
    }

196 197 198 199 200 201
    void notifySetIndexChangedOneCommand() {
        KisImageWSP image = this->image();
        image->unlock();
        image->barrierLock();
    }

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
    void undo() {
        KisImageWSP image = this->image();
        image->requestUndoDuringStroke();
        if(image->tryBarrierLock()) {
            KUndo2Stack::undo();
            image->unlock();
        }
    }

    void redo() {
        KisImageWSP image = this->image();
        if(image->tryBarrierLock()) {
            KUndo2Stack::redo();
            image->unlock();
        }
    }

private:
    KisImageWSP image() {
        KisImageWSP currentImage = m_doc->image();
        Q_ASSERT(currentImage);
        return currentImage;
    }

private:
    KisDocument *m_doc;
};

230
class Q_DECL_HIDDEN KisDocument::Private
231 232
{
public:
233
    Private(KisDocument *document) :
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
        document(document),
        // XXX: the part should _not_ be modified from the document
        docInfo(0),
        progressUpdater(0),
        progressProxy(0),
        profileStream(0),
        filterManager(0),
        specialOutputFlag(0),   // default is native format
        isImporting(false),
        isExporting(false),
        password(QString()),
        modifiedAfterAutosave(false),
        autosaving(false),
        shouldCheckAutoSaveFile(true),
        autoErrorHandlingEnabled(true),
        backupFile(true),
        backupPath(QString()),
        doNotSaveExtDoc(false),
        storeInternal(false),
        isLoading(false),
        undoStack(0),
255 256 257 258 259
        m_saveOk(false),
        m_waitForSave(false),
        m_duringSaveAs(false),
        m_bTemp(false),
        m_bAutoDetectedMime(false),
260 261 262 263 264
        modified(false),
        readwrite(true),
        disregardAutosaveFailure(false),
        nserver(0),
        macroNestDepth(0),
265
        imageIdleWatcher(2000 /*ms*/),
266 267
        kraLoader(0)
    {
268
        if (QLocale().measurementSystem() == QLocale::ImperialSystem) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
            unit = KoUnit::Inch;
        } else {
            unit = KoUnit::Centimeter;
        }
    }

    ~Private() {
        // Don't delete m_d->shapeController because it's in a QObject hierarchy.
        delete nserver;
    }

    KisDocument *document;

    KoDocumentInfo *docInfo;

    KoProgressUpdater *progressUpdater;
    KoProgressProxy *progressProxy;
    QTextStream *profileStream;
    QTime profileReferenceTime;

    KoUnit unit;

    KisImportExportManager *filterManager; // The filter-manager to use when loading/saving [for the options]

    QByteArray mimeType; // The actual mimetype of the document
    QByteArray outputMimeType; // The mimetype to use when saving
295
    bool confirmNonNativeSave [2] = {true, true}; // used to pop up a dialog when saving for the
296 297 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
    // first time if the file is in a foreign format
    // (Save/Save As, Export)
    int specialOutputFlag; // See KoFileDialog in koMainWindow.cc
    bool isImporting;
    bool isExporting; // File --> Import/Export vs File --> Open/Save
    QString password; // The password used to encrypt an encrypted document

    QTimer autoSaveTimer;
    QString lastErrorMessage; // see openFile()
    int autoSaveDelay; // in seconds, 0 to disable.
    bool modifiedAfterAutosave;
    bool autosaving;
    bool shouldCheckAutoSaveFile; // usually true
    bool autoErrorHandlingEnabled; // usually true
    bool backupFile;
    QString backupPath;
    bool doNotSaveExtDoc; // makes it possible to save only internally stored child documents
    bool storeInternal; // Store this doc internally even if url is external
    bool isLoading; // True while loading (openUrl is async)

    KUndo2Stack *undoStack;

    KoGridData gridData;
    KoGuidesData guidesData;

    bool isEmpty;

    KoPageLayout pageLayout;

Halla Rempt's avatar
Halla Rempt committed
325
    QUrl m_originalURL; // for saveAs
326 327 328 329 330 331
    QString m_originalFilePath; // for saveAs
    bool m_saveOk : 1;
    bool m_waitForSave : 1;
    bool m_duringSaveAs : 1;
    bool m_bTemp: 1;      // If @p true, @p m_file is a temporary file that needs to be deleted later.
    bool m_bAutoDetectedMime : 1; // whether the mimetype in the arguments was detected by the part itself
Halla Rempt's avatar
Halla Rempt committed
332
    QUrl m_url; // Remote (or local) url - the one displayed to the user.
333 334 335 336 337 338
    QString m_file; // Local file - the only one the part implementation should deal with.
    QEventLoop m_eventLoop;

    bool modified;
    bool readwrite;

339 340 341
    QDateTime firstMod;
    QDateTime lastMod;

342 343 344 345 346 347 348 349
    bool disregardAutosaveFailure;

    KisNameServer *nserver;
    qint32 macroNestDepth;

    KisImageSP image;
    KisNodeSP preActivatedNode;
    KisShapeController* shapeController;
350
    KoShapeController* koShapeController;
351 352 353
    KisIdleWatcher imageIdleWatcher;
    QScopedPointer<KisSignalAutoConnection> imageIdleConnection;

354 355 356 357 358 359 360 361 362 363 364

    KisKraLoader* kraLoader;
    KisKraSaver* kraSaver;

    QList<KisPaintingAssistant*> assistants;

    bool openFile()
    {
        DocumentProgressProxy *progressProxy = 0;
        if (!document->progressProxy()) {
            KisMainWindow *mainWindow = 0;
365 366
            if (KisPart::instance()->mainWindows().count() > 0) {
                mainWindow = KisPart::instance()->mainWindows()[0];
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            }
            progressProxy = new DocumentProgressProxy(mainWindow);
            document->setProgressProxy(progressProxy);
        }
        document->setUrl(m_url);

        bool ok = document->openFile();

        if (progressProxy) {
            document->setProgressProxy(0);
            delete progressProxy;
        }
        return ok;
    }

    bool openLocalFile()
    {
        m_bTemp = false;
        // set the mimetype only if it was not already set (for example, by the host application)
        if (mimeType.isEmpty()) {
            // get the mimetype of the file
            // using findByUrl() to avoid another string -> url conversion
Halla Rempt's avatar
Halla Rempt committed
389 390 391 392
            QMimeDatabase db;
            QMimeType mime = db.mimeTypeForFile(m_url.toLocalFile());
            if (mime.isValid()) {
                mimeType = mime.name().toLocal8Bit();
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
                m_bAutoDetectedMime = true;
            }
        }
        const bool ret = openFile();
        if (ret) {
            emit document->completed();
        } else {
            emit document->canceled(QString());
        }
        return ret;
    }

    // Set m_file correctly for m_url
    void prepareSaving()
    {
        // Local file
        if ( m_url.isLocalFile() )
        {
            if ( m_bTemp ) // get rid of a possible temp file first
            {              // (happens if previous url was remote)
                QFile::remove( m_file );
                m_bTemp = false;
            }
            m_file = m_url.toLocalFile();
        }
    }

420 421
    void setImageAndInitIdleWatcher(KisImageSP _image) {
        image = _image;
422

423 424 425 426 427 428 429 430 431
        imageIdleWatcher.setTrackedImage(image);

        if (image) {
            imageIdleConnection.reset(
                new KisSignalAutoConnection(
                    &imageIdleWatcher, SIGNAL(startedIdleMode()),
                    image.data(), SLOT(explicitRegenerateLevelOfDetail())));
        }
    }
432 433
};

434 435
KisDocument::KisDocument()
    : d(new Private(this))
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
{
    d->undoStack = new UndoStack(this);
    d->undoStack->setParent(this);

    d->isEmpty = true;
    d->filterManager = new KisImportExportManager(this, d->progressUpdater);

    connect(&d->autoSaveTimer, SIGNAL(timeout()), this, SLOT(slotAutoSave()));
    setAutoSave(defaultAutoSave());

    setObjectName(newObjectName());

    d->docInfo = new KoDocumentInfo(this);

    d->pageLayout.width = 0;
    d->pageLayout.height = 0;
    d->pageLayout.topMargin = 0;
    d->pageLayout.bottomMargin = 0;
    d->pageLayout.leftMargin = 0;
    d->pageLayout.rightMargin = 0;


458
    KConfigGroup cfgGrp( KSharedConfig::openConfig(), "Undo");
459 460
    d->undoStack->setUndoLimit(cfgGrp.readEntry("UndoLimit", 1000));

461 462 463
    d->firstMod = QDateTime::currentDateTime();
    d->lastMod = QDateTime::currentDateTime();

464 465 466 467 468 469 470 471
    connect(d->undoStack, SIGNAL(indexChanged(int)), this, SLOT(slotUndoStackIndexChanged(int)));

    // preload the krita resources
    KisResourceServerProvider::instance();

    init();
    undoStack()->setUndoLimit(KisConfig().undoStackLimit());
    setBackupFile(KisConfig().backupFile());
472 473 474 475 476

    gridData().setShowGrid(false);
    KisConfig cfg;
    gridData().setGrid(cfg.getGridHSpacing(), cfg.getGridVSpacing());

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
}

KisDocument::~KisDocument()
{
    /**
     * Push a timebomb, which will try to release the memory after
     * the document has been deleted
     */
    KisPaintDevice::createMemoryReleaseObject()->deleteLater();

    d->autoSaveTimer.disconnect(this);
    d->autoSaveTimer.stop();

    delete d->filterManager;

    // Despite being QObject they needs to be deleted before the image
    delete d->shapeController;
494

495
    delete d->koShapeController;
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514

    if (d->image) {
        d->image->notifyAboutToBeDeleted();
    }
    // The following line trigger the deletion of the image
    d->image.clear();

    delete d;
}

void KisDocument::init()
{
    delete d->nserver;
    d->nserver = 0;

    d->nserver = new KisNameServer(1);
    Q_CHECK_PTR(d->nserver);

    d->shapeController = new KisShapeController(this, d->nserver);
515
    d->koShapeController = new KoShapeController(0, d->shapeController);
516 517 518 519 520 521 522 523 524 525 526

    d->kraSaver = 0;
    d->kraLoader = 0;
}

bool KisDocument::reload()
{
    // XXX: reimplement!
    return false;
}

Halla Rempt's avatar
Halla Rempt committed
527
bool KisDocument::exportDocument(const QUrl &_url)
528 529 530 531 532 533 534 535 536 537 538 539 540
{
    bool ret;

    d->isExporting = true;

    //
    // Preserve a lot of state here because we need to restore it in order to
    // be able to fake a File --> Export.  Can't do this in saveFile() because,
    // for a start, KParts has already set url and m_file and because we need
    // to restore the modified flag etc. and don't want to put a load on anyone
    // reimplementing saveFile() (Note: importDocument() and exportDocument()
    // will remain non-virtual).
    //
Halla Rempt's avatar
Halla Rempt committed
541
    QUrl oldURL = url();
542 543 544 545 546 547 548 549 550 551 552 553 554
    QString oldFile = localFilePath();

    bool wasModified = isModified();
    QByteArray oldMimeType = mimeType();

    // save...
    ret = saveAs(_url);


    //
    // This is sooooo hacky :(
    // Hopefully we will restore enough state.
    //
Halla Rempt's avatar
Halla Rempt committed
555
    dbgUI << "Restoring KisDocument state to before export";
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576

    // always restore url & m_file because KParts has changed them
    // (regardless of failure or success)
    setUrl(oldURL);
    setLocalFilePath(oldFile);

    // on successful export we need to restore modified etc. too
    // on failed export, mimetype/modified hasn't changed anyway
    if (ret) {
        setModified(wasModified);
        d->mimeType = oldMimeType;
    }


    d->isExporting = false;

    return ret;
}

bool KisDocument::saveFile()
{
Halla Rempt's avatar
Halla Rempt committed
577
    dbgUI << "doc=" << url().url();
578 579 580 581 582 583 584 585 586 587 588 589

    // Save it to be able to restore it after a failed save
    const bool wasModified = isModified();

    // The output format is set by koMainWindow, and by openFile
    QByteArray outputMimeType = d->outputMimeType;
    if (outputMimeType.isEmpty())
        outputMimeType = d->outputMimeType = nativeFormatMimeType();

    QApplication::setOverrideCursor(Qt::WaitCursor);

    if (backupFile()) {
Halla Rempt's avatar
Halla Rempt committed
590 591
        Q_ASSERT(url().isLocalFile());
        KBackup::backupFile(url().toLocalFile(), d->backupPath);
592 593 594 595 596 597 598
    }

    emit statusBarMessage(i18n("Saving..."));
    qApp->processEvents();
    bool ret = false;
    bool suppressErrorDialog = false;
    if (!isNativeFormat(outputMimeType)) {
Halla Rempt's avatar
Halla Rempt committed
599
        dbgUI << "Saving to format" << outputMimeType << "in" << localFilePath();
600 601 602 603
        // Not native format : save using export filter
        KisImportExportFilter::ConversionStatus status = d->filterManager->exportDocument(localFilePath(), outputMimeType);
        ret = status == KisImportExportFilter::OK;
        suppressErrorDialog = (status == KisImportExportFilter::UserCancelled || status == KisImportExportFilter::BadConversionGraph);
604
        dbgFile << "Export status was" << status;
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    } else {
        // Native format => normal save
        Q_ASSERT(!localFilePath().isEmpty());
        ret = saveNativeFormat(localFilePath());
    }

    if (ret) {
        d->undoStack->setClean();
        removeAutoSaveFiles();
        // Restart the autosave timer
        // (we don't want to autosave again 2 seconds after a real save)
        setAutoSave(d->autoSaveDelay);
    }

    QApplication::restoreOverrideCursor();
    if (!ret) {
        if (!suppressErrorDialog) {
            if (errorMessage().isEmpty()) {
623
                QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not save\n%1", localFilePath()));
624
            } else if (errorMessage() != "USER_CANCELED") {
Halla Rempt's avatar
Halla Rempt committed
625
                QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not save %1\nReason: %2", localFilePath(), errorMessage()));
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
            }

        }

        // couldn't save file so this new URL is invalid
        // FIXME: we should restore the current document's true URL instead of
        // setting it to nothing otherwise anything that depends on the URL
        // being correct will not work (i.e. the document will be called
        // "Untitled" which may not be true)
        //
        // Update: now the URL is restored in KisMainWindow but really, this
        // should still be fixed in KisDocument/KParts (ditto for file).
        // We still resetURL() here since we may or may not have been called
        // by KisMainWindow - Clarence
        resetURL();

        // As we did not save, restore the "was modified" status
        setModified(wasModified);
    }

    if (ret) {
        d->mimeType = outputMimeType;
        setConfirmNonNativeSave(isExporting(), false);
    }
    emit clearStatusBarMessage();

    return ret;
}


QByteArray KisDocument::mimeType() const
{
    return d->mimeType;
}

void KisDocument::setMimeType(const QByteArray & mimeType)
{
    d->mimeType = mimeType;
}

void KisDocument::setOutputMimeType(const QByteArray & mimeType, int specialOutputFlag)
{
    d->outputMimeType = mimeType;
    d->specialOutputFlag = specialOutputFlag;
}

QByteArray KisDocument::outputMimeType() const
{
    return d->outputMimeType;
}

int KisDocument::specialOutputFlag() const
{
    return d->specialOutputFlag;
}

bool KisDocument::confirmNonNativeSave(const bool exporting) const
{
    // "exporting ? 1 : 0" is different from "exporting" because a bool is
    // usually implemented like an "int", not "unsigned : 1"
    return d->confirmNonNativeSave [ exporting ? 1 : 0 ];
}

void KisDocument::setConfirmNonNativeSave(const bool exporting, const bool on)
{
    d->confirmNonNativeSave [ exporting ? 1 : 0] = on;
}

bool KisDocument::saveInBatchMode() const
{
    return d->filterManager->getBatchMode();
}

void KisDocument::setSaveInBatchMode(const bool batchMode)
{
    d->filterManager->setBatchMode(batchMode);
}

bool KisDocument::isImporting() const
{
    return d->isImporting;
}

bool KisDocument::isExporting() const
{
    return d->isExporting;
}

void KisDocument::setCheckAutoSaveFile(bool b)
{
    d->shouldCheckAutoSaveFile = b;
}

void KisDocument::setAutoErrorHandlingEnabled(bool b)
{
    d->autoErrorHandlingEnabled = b;
}

bool KisDocument::isAutoErrorHandlingEnabled() const
{
    return d->autoErrorHandlingEnabled;
}

void KisDocument::slotAutoSave()
{
    if (d->modified && d->modifiedAfterAutosave && !d->isLoading) {
        // Give a warning when trying to autosave an encrypted file when no password is known (should not happen)
        if (d->specialOutputFlag == SaveEncrypted && d->password.isNull()) {
            // That advice should also fix this error from occurring again
            emit statusBarMessage(i18n("The password of this encrypted document is not known. Autosave aborted! Please save your work manually."));
        } else {
737
            connect(this, SIGNAL(sigProgress(int)), KisPart::instance()->currentMainwindow(), SLOT(slotProgress(int)));
738 739 740 741 742 743 744 745 746 747
            emit statusBarMessage(i18n("Autosaving..."));
            d->autosaving = true;
            bool ret = saveNativeFormat(autoSaveFile(localFilePath()));
            setModified(true);
            if (ret) {
                d->modifiedAfterAutosave = false;
                d->autoSaveTimer.stop(); // until the next change
            }
            d->autosaving = false;
            emit clearStatusBarMessage();
748
            disconnect(this, SIGNAL(sigProgress(int)), KisPart::instance()->currentMainwindow(), SLOT(slotProgress(int)));
749 750 751 752 753 754 755 756 757 758 759 760
            if (!ret && !d->disregardAutosaveFailure) {
                emit statusBarMessage(i18n("Error during autosave! Partition full?"));
            }
        }
    }
}

void KisDocument::setReadWrite(bool readwrite)
{
    d->readwrite = readwrite;
    setAutoSave(d->autoSaveDelay);

761
    Q_FOREACH (KisMainWindow *mainWindow, KisPart::instance()->mainWindows()) {
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        mainWindow->setReadWrite(readwrite);
    }

}

void KisDocument::setAutoSave(int delay)
{
    d->autoSaveDelay = delay;
    if (isReadWrite() && d->autoSaveDelay > 0)
        d->autoSaveTimer.start(d->autoSaveDelay * 1000);
    else
        d->autoSaveTimer.stop();
}

KoDocumentInfo *KisDocument::documentInfo() const
{
    return d->docInfo;
}

bool KisDocument::isModified() const
{
    return d->modified;
}

bool KisDocument::saveNativeFormat(const QString & file)
{
    const int realAutoSaveInterval = KisConfig().autoSaveInterval();
    const int emergencyAutoSaveInterval = 10; // sec

    if (!d->image->tryBarrierLock()) {
        if (isAutosaving()) {
            setDisregardAutosaveFailure(true);
            if (realAutoSaveInterval) {
                setAutoSave(emergencyAutoSaveInterval);
            }
            return false;
        } else {
            d->image->requestStrokeEnd();
            QApplication::processEvents();
            if (!d->image->tryBarrierLock()) {
                return false;
            }
        }
    }

    setDisregardAutosaveFailure(false);

    d->lastErrorMessage.clear();
Halla Rempt's avatar
Halla Rempt committed
810
    //dbgUI <<"Saving to store";
811 812 813 814

    KoStore::Backend backend = KoStore::Auto;
    if (d->specialOutputFlag == SaveAsDirectoryStore) {
        backend = KoStore::Directory;
Halla Rempt's avatar
Halla Rempt committed
815
        dbgUI << "Saving as uncompressed XML, using directory store.";
816 817
    }
    else if (d->specialOutputFlag == SaveAsFlatXML) {
Halla Rempt's avatar
Halla Rempt committed
818
        dbgUI << "Saving as a flat XML file.";
819 820 821 822 823 824 825 826 827
        QFile f(file);
        if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
            bool success = saveToStream(&f);
            f.close();
            return success;
        } else
            return false;
    }

Halla Rempt's avatar
Halla Rempt committed
828
    dbgUI << "KisDocument::saveNativeFormat nativeFormatMimeType=" << nativeFormatMimeType();
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

    // TODO: use std::auto_ptr or create store on stack [needs API fixing],
    // to remove all the 'delete store' in all the branches
    KoStore *store = KoStore::createStore(file, KoStore::Write, d->outputMimeType, backend);
    if (d->specialOutputFlag == SaveEncrypted && !d->password.isNull()) {
        store->setPassword(d->password);
    }
    if (store->bad()) {
        d->lastErrorMessage = i18n("Could not create the file for saving");   // more details needed?
        delete store;
        d->image->unlock();
        setAutoSave(realAutoSaveInterval);

        return false;
    }

    d->image->unlock();
    setAutoSave(realAutoSaveInterval);

    return saveNativeFormatCalligra(store);
}

bool KisDocument::saveNativeFormatCalligra(KoStore *store)
{
Halla Rempt's avatar
Halla Rempt committed
853
    dbgUI << "Saving root";
854 855 856
    if (store->open("root")) {
        KoStoreDevice dev(store);
        if (!saveToStream(&dev) || !store->close()) {
Halla Rempt's avatar
Halla Rempt committed
857
            dbgUI << "saveToStream failed";
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
            delete store;
            return false;
        }
    } else {
        d->lastErrorMessage = i18n("Not able to write '%1'. Partition full?", QString("maindoc.xml"));
        delete store;
        return false;
    }
    if (store->open("documentinfo.xml")) {
        QDomDocument doc = KisDocument::createDomDocument("document-info"
                           /*DTD name*/, "document-info" /*tag name*/, "1.1");


        doc = d->docInfo->save(doc);
        KoStoreDevice dev(store);

        QByteArray s = doc.toByteArray(); // this is already Utf8!
        (void)dev.write(s.data(), s.size());
        (void)store->close();
    }

879 880 881 882 883 884
    if (!isAutosaving()) {
        if (store->open("preview.png")) {
            // ### TODO: missing error checking (The partition could be full!)
            savePreview(store);
            (void)store->close();
        }
885 886 887 888 889 890
    }

    if (!completeSaving(store)) {
        delete store;
        return false;
    }
Halla Rempt's avatar
Halla Rempt committed
891
    dbgUI << "Saving done of url:" << url().url();
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    if (!store->finalize()) {
        delete store;
        return false;
    }
    // Success
    delete store;
    return true;
}

bool KisDocument::saveToStream(QIODevice *dev)
{
    QDomDocument doc = saveXML();
    // Save to buffer
    QByteArray s = doc.toByteArray(); // utf8 already
    dev->open(QIODevice::WriteOnly);
    int nwritten = dev->write(s.data(), s.size());
    if (nwritten != (int)s.size())
Halla Rempt's avatar
Halla Rempt committed
909
        warnUI << "wrote " << nwritten << "- expected" <<  s.size();
910 911 912
    return nwritten == (int)s.size();
}

Halla Rempt's avatar
Halla Rempt committed
913
QString KisDocument::checkImageMimeTypes(const QString &mimeType, const QUrl &url) const
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
{
    if (!url.isLocalFile()) return mimeType;

    if (url.toLocalFile().endsWith(".kpp")) return "image/png";

    QStringList imageMimeTypes;
    imageMimeTypes << "image/jpeg"
                   << "image/x-psd" << "image/photoshop" << "image/x-photoshop" << "image/x-vnd.adobe.photoshop" << "image/vnd.adobe.photoshop"
                   << "image/x-portable-pixmap" << "image/x-portable-graymap" << "image/x-portable-bitmap"
                   << "application/pdf"
                   << "image/x-exr"
                   << "image/x-xcf"
                   << "image/x-eps"
                   << "image/png"
                   << "image/bmp" << "image/x-xpixmap" << "image/gif" << "image/x-xbitmap"
                   << "image/tiff"
930
                   << "image/x-gimp-brush" << "image/x-gimp-brush-animated"
931 932 933 934 935
                   << "image/jp2";

    if (!imageMimeTypes.contains(mimeType)) return mimeType;

    QFile f(url.toLocalFile());
936
    if (!f.open(QIODevice::ReadOnly)) {
Halla Rempt's avatar
Halla Rempt committed
937
        warnKrita << "Could not open file to check the mimetype" << url;
938
    }
939
    QByteArray ba = f.read(qMin(f.size(), (qint64)512)); // should be enough for images
Halla Rempt's avatar
Halla Rempt committed
940 941
    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForData(ba);
942 943
    f.close();

Halla Rempt's avatar
Halla Rempt committed
944
    if (!mime.isValid()) {
945 946 947
        return mimeType;
    }

948
    // Checking the content failed as well, so let's fall back on the extension again
Halla Rempt's avatar
Halla Rempt committed
949
    if (mime.name() == "application/octet-stream") {
950 951 952
        return mimeType;
    }

Halla Rempt's avatar
Halla Rempt committed
953
    return mime.name();
954 955 956 957 958
}

// Called for embedded documents
bool KisDocument::saveToStore(KoStore *_store, const QString & _path)
{
Halla Rempt's avatar
Halla Rempt committed
959
    dbgUI << "Saving document to store" << _path;
960 961 962 963

    _store->pushDirectory();
    // Use the path as the internal url
    if (_path.startsWith(STORE_PROTOCOL))
Halla Rempt's avatar
Halla Rempt committed
964
        setUrl(QUrl(_path));
965
    else // ugly hack to pass a relative URI
Halla Rempt's avatar
Halla Rempt committed
966
        setUrl(QUrl(INTERNAL_PREFIX +  _path));
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984

    // In the current directory we're the king :-)
    if (_store->open("root")) {
        KoStoreDevice dev(_store);
        if (!saveToStream(&dev)) {
            _store->close();
            return false;
        }
        if (!_store->close())
            return false;
    }

    if (!completeSaving(_store))
        return false;

    // Now that we're done leave the directory again
    _store->popDirectory();

Halla Rempt's avatar
Halla Rempt committed
985
    dbgUI << "Saved document to store";
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

    return true;
}

bool KisDocument::savePreview(KoStore *store)
{
    QPixmap pix = generatePreview(QSize(256, 256));
    const QImage preview(pix.toImage().convertToFormat(QImage::Format_ARGB32, Qt::ColorOnly));
    KoStoreDevice io(store);
    if (!io.open(QIODevice::WriteOnly))
        return false;
    if (! preview.save(&io, "PNG"))     // ### TODO What is -9 in quality terms?
        return false;
    io.close();
    return true;
}

QPixmap KisDocument::generatePreview(const QSize& size)
{
    if (d->image) {
        QRect bounds = d->image->bounds();
        QSize newSize = bounds.size();
        newSize.scale(size, Qt::KeepAspectRatio);
1009
        return QPixmap::fromImage(d->image->convertToQImage(newSize, 0));
1010 1011 1012 1013 1014 1015 1016 1017 1018
    }
    return QPixmap(size);
}

QString KisDocument::autoSaveFile(const QString & path) const
{
    QString retval;

    // Using the extension allows to avoid relying on the mime magic when opening
Halla Rempt's avatar
Halla Rempt committed
1019 1020 1021
    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForName(nativeFormatMimeType());
    if (!mime.isValid()) {
1022 1023
        qFatal("It seems your installation is broken/incomplete because we failed to load the native mimetype \"%s\".", nativeFormatMimeType().constData());
    }
1024
    const QString extension = QLatin1Char('.') + mime.preferredSuffix();
1025 1026 1027 1028 1029

    if (path.isEmpty()) {
        // Never saved?
#ifdef Q_OS_WIN
        // On Windows, use the temp location (https://bugs.kde.org/show_bug.cgi?id=314921)
1030
        retval = QString("%1/.%2-%3-%4-autosave%5").arg(QDir::tempPath()).arg("krita").arg(qApp->applicationPid()).arg(objectName()).arg(extension);
1031 1032
#else
        // On Linux, use a temp file in $HOME then. Mark it with the pid so two instances don't overwrite each other's autosave file
1033
        retval = QString("%1/.%2-%3-%4-autosave%5").arg(QDir::homePath()).arg("krita").arg(qApp->applicationPid()).arg(objectName()).arg(extension);
1034 1035
#endif
    } else {
Halla Rempt's avatar
Halla Rempt committed
1036 1037 1038
        QFileInfo fi(path);
        QString dir = fi.absolutePath();
        QString filename = fi.fileName();
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        retval = QString("%1.%2-autosave%3").arg(dir).arg(filename).arg(extension);
    }
    return retval;
}

void KisDocument::setDisregardAutosaveFailure(bool disregardFailure)
{
    d->disregardAutosaveFailure = disregardFailure;
}

Halla Rempt's avatar
Halla Rempt committed
1049
bool KisDocument::importDocument(const QUrl &_url)
1050 1051 1052
{
    bool ret;

Halla Rempt's avatar
Halla Rempt committed
1053
    dbgUI << "url=" << _url.url();
1054 1055 1056 1057 1058 1059 1060 1061
    d->isImporting = true;

    // open...
    ret = openUrl(_url);

    // reset url & m_file (kindly? set by KisParts::openUrl()) to simulate a
    // File --> Import
    if (ret) {
Halla Rempt's avatar
Halla Rempt committed
1062
        dbgUI << "success, resetting url";
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        resetURL();
        setTitleModified();
    }

    d->isImporting = false;

    return ret;
}


Halla Rempt's avatar
Halla Rempt committed
1073
bool KisDocument::openUrl(const QUrl &_url, KisDocument::OpenUrlFlags flags)
1074
{
1075 1076 1077 1078
    if (!_url.isLocalFile()) {
        qDebug() << "not a local file" << _url;
        return false;
    }
Halla Rempt's avatar
Halla Rempt committed
1079
    dbgUI << "url=" << _url.url();
1080 1081 1082 1083 1084 1085 1086 1087
    d->lastErrorMessage.clear();

    // Reimplemented, to add a check for autosave files and to improve error reporting
    if (!_url.isValid()) {
        d->lastErrorMessage = i18n("Malformed URL\n%1", _url.url());  // ## used anywhere ?
        return false;
    }

Halla Rempt's avatar
Halla Rempt committed
1088
    QUrl url(_url);
1089 1090 1091 1092 1093 1094
    bool autosaveOpened = false;
    d->isLoading = true;
    if (url.isLocalFile() && d->shouldCheckAutoSaveFile) {
        QString file = url.toLocalFile();
        QString asf = autoSaveFile(file);
        if (QFile::exists(asf)) {
Halla Rempt's avatar
Halla Rempt committed
1095
            //dbgUI <<"asf=" << asf;
1096
            // ## TODO compare timestamps ?
Halla Rempt's avatar
Halla Rempt committed
1097 1098 1099
            int res = QMessageBox::warning(0,
                                           i18nc("@title:window", "Krita"),
                                           i18n("An autosaved file exists for this document.\nDo you want to open it instead?"),
1100
                                           QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes);
1101
            switch (res) {
Halla Rempt's avatar
Halla Rempt committed
1102
            case QMessageBox::Yes :
1103 1104 1105
                url.setPath(asf);
                autosaveOpened = true;
                break;
Halla Rempt's avatar
Halla Rempt committed
1106
            case QMessageBox::No :
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
                QFile::remove(asf);
                break;
            default: // Cancel
                d->isLoading = false;
                return false;
            }
        }
    }

    bool ret = openUrlInternal(url);

    if (autosaveOpened) {
        resetURL(); // Force save to act like 'Save As'
        setReadWrite(true); // enable save button
        setModified(true);
    }
    else {
1124 1125 1126
        if( !(flags & OPEN_URL_FLAG_DO_NOT_ADD_TO_RECENT_FILES) ) {
            KisPart::instance()->addRecentURLToAllMainWindows(_url);
        }
1127 1128

        if (ret) {
1129
            // Detect readonly local-files; remote files are assumed to be writable
1130 1131
            QFileInfo fi(url.toLocalFile());
            setReadWrite(fi.isWritable());
1132 1133 1134 1135 1136 1137 1138
        }
    }
    return ret;
}

bool KisDocument::openFile()
{
Halla Rempt's avatar
Halla Rempt committed
1139
    //dbgUI <<"for" << localFilePath();
1140 1141 1142 1143
    if (!QFile::exists(localFilePath())) {
        QApplication::restoreOverrideCursor();
        if (d->autoErrorHandlingEnabled)
            // Maybe offer to create a new document with that name ?
Halla Rempt's avatar
Halla Rempt committed
1144
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("File %1 does not exist.", localFilePath()));
1145 1146 1147 1148 1149 1150 1151 1152 1153
        d->isLoading = false;
        return false;
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

    d->specialOutputFlag = 0;
    QByteArray _native_format = nativeFormatMimeType();

1154
    QUrl u = QUrl::fromLocalFile(localFilePath());
1155 1156 1157
    QString typeName = mimeType();

    if (typeName.isEmpty()) {
Halla Rempt's avatar
Halla Rempt committed
1158 1159
        QMimeDatabase db;
        typeName = db.mimeTypeForFile(u.path()).name();
1160 1161 1162 1163 1164
    }

    // for images, always check content.
    typeName = checkImageMimeTypes(typeName, u);

Halla Rempt's avatar
Halla Rempt committed
1165
    //dbgUI << "mimetypes 4:" << typeName;
1166 1167 1168 1169

    // Allow to open backup files, don't keep the mimetype application/x-trash.
    if (typeName == "application/x-trash") {
        QString path = u.path();
Halla Rempt's avatar
Halla Rempt committed
1170 1171 1172
        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForName(typeName);
        const QStringList patterns = mime.isValid() ? mime.globPatterns() : QStringList();
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
        // Find the extension that makes it a backup file, and remove it
        for (QStringList::ConstIterator it = patterns.begin(); it != patterns.end(); ++it) {
            QString ext = *it;
            if (!ext.isEmpty() && ext[0] == '*') {
                ext.remove(0, 1);
                if (path.endsWith(ext)) {
                    path.chop(ext.length());
                    break;
                }
            }
        }
Halla Rempt's avatar
Halla Rempt committed
1184
        typeName = db.mimeTypeForFile(path, QMimeDatabase::MatchExtension).name();
1185 1186 1187 1188 1189 1190
    }

    // Special case for flat XML files (e.g. using directory store)
    if (u.fileName() == "maindoc.xml" || u.fileName() == "content.xml" || typeName == "inode/directory") {
        typeName = _native_format; // Hmm, what if it's from another app? ### Check mimetype
        d->specialOutputFlag = SaveAsDirectoryStore;
Halla Rempt's avatar
Halla Rempt committed
1191
        dbgUI << "loading" << u.fileName() << ", using directory store for" << localFilePath() << "; typeName=" << typeName;
1192
    }
Halla Rempt's avatar
Halla Rempt committed
1193
    dbgUI << localFilePath() << "type:" << typeName;
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284

    QString importedFile = localFilePath();

    // create the main progress monitoring object for loading, this can
    // contain subtasks for filtering and loading
    KoProgressProxy *progressProxy = 0;
    if (d->progressProxy) {
        progressProxy = d->progressProxy;
    }

    d->progressUpdater = new KoProgressUpdater(progressProxy,
            KoProgressUpdater::Unthreaded,
            d->profileStream);

    d->progressUpdater->setReferenceTime(d->profileReferenceTime);
    d->progressUpdater->start(100, i18n("Opening Document"));

    setupOpenFileSubProgress();

    if (!isNativeFormat(typeName.toLatin1())) {
        KisImportExportFilter::ConversionStatus status;
        importedFile = d->filterManager->importDocument(localFilePath(), typeName, status);
        if (status != KisImportExportFilter::OK) {
            QApplication::restoreOverrideCursor();

            QString msg;
            switch (status) {
            case KisImportExportFilter::OK: break;

            case KisImportExportFilter::FilterCreationError:
                msg = i18n("Could not create the filter plugin"); break;

            case KisImportExportFilter::CreationError:
                msg = i18n("Could not create the output document"); break;

            case KisImportExportFilter::FileNotFound:
                msg = i18n("File not found"); break;

            case KisImportExportFilter::StorageCreationError:
                msg = i18n("Cannot create storage"); break;

            case KisImportExportFilter::BadMimeType:
                msg = i18n("Bad MIME type"); break;

            case KisImportExportFilter::EmbeddedDocError:
                msg = i18n("Error in embedded document"); break;

            case KisImportExportFilter::WrongFormat:
                msg = i18n("Format not recognized"); break;

            case KisImportExportFilter::NotImplemented:
                msg = i18n("Not implemented"); break;

            case KisImportExportFilter::ParsingError:
                msg = i18n("Parsing error"); break;

            case KisImportExportFilter::PasswordProtected:
                msg = i18n("Document is password protected"); break;

            case KisImportExportFilter::InvalidFormat:
                msg = i18n("Invalid file format"); break;

            case KisImportExportFilter::InternalError:
            case KisImportExportFilter::UnexpectedEOF:
            case KisImportExportFilter::UnexpectedOpcode:
            case KisImportExportFilter::StupidError: // ?? what is this ??
            case KisImportExportFilter::UsageError:
                msg = i18n("Internal error"); break;

            case KisImportExportFilter::OutOfMemory:
                msg = i18n("Out of memory"); break;

            case KisImportExportFilter::FilterEntryNull:
                msg = i18n("Empty Filter Plugin"); break;

            case KisImportExportFilter::NoDocumentCreated:
                msg = i18n("Trying to load into the wrong kind of document"); break;

            case KisImportExportFilter::DownloadFailed:
                msg = i18n("Failed to download remote file"); break;

            case KisImportExportFilter::UserCancelled:
            case KisImportExportFilter::BadConversionGraph:
                // intentionally we do not prompt the error message here
                break;

            default: msg = i18n("Unknown error"); break;
            }

            if (d->autoErrorHandlingEnabled && !msg.isEmpty()) {
                QString errorMsg(i18n("Could not open %2.\nReason: %1.\n%3", msg, prettyPathOrUrl(), errorMessage()));
Halla Rempt's avatar
Halla Rempt committed
1285
                QMessageBox::critical(0, i18nc("@title:window", "Krita"), errorMsg);
1286 1287 1288 1289 1290 1291 1292 1293
            }

            d->isLoading = false;
            delete d->progressUpdater;
            d->progressUpdater = 0;
            return false;
        }
        d->isEmpty = false;
Halla Rempt's avatar
Halla Rempt committed
1294
        dbgUI << "importedFile" << importedFile << "status:" << static_cast<int>(status);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    }

    QApplication::restoreOverrideCursor();

    bool ok = true;

    if (!importedFile.isEmpty()) { // Something to load (tmp or native file) ?
        // The filter, if any, has been applied. It's all native format now.
        if (!loadNativeFormat(importedFile)) {
            ok = false;
            if (d->autoErrorHandlingEnabled) {
                showLoadingErrorDialog();
            }
        }
    }

    if (importedFile != localFilePath()) {
        // We opened a temporary file (result of an import filter)
        // Set document URL to empty - we don't want to save in /tmp !
        // But only if in readwrite mode (no saving problem otherwise)
        // --
        // But this isn't true at all.  If this is the result of an
        // import, then importedFile=temporary_file.kwd and
        // file/m_url=foreignformat.ext so m_url is correct!
        // So don't resetURL() or else the caption won't be set when
        // foreign files are opened (an annoying bug).
        // - Clarence
        //
#if 0
        if (isReadWrite())
            resetURL();
#endif

        // remove temp file - uncomment this to debug import filters
        if (!importedFile.isEmpty()) {
#ifndef NDEBUG
            if (!getenv("CALLIGRA_DEBUG_FILTERS"))
#endif
            QFile::remove(importedFile);
        }
    }

    if (ok) {
        setMimeTypeAfterLoading(typeName);
Halla Rempt's avatar
Halla Rempt committed
1339
        emit sigLoadingFinished();
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    }

    if (progressUpdater()) {
        QPointer<KoUpdater> updater
                = progressUpdater()->startSubtask(1, "clear undo stack");
        updater->setProgress(0);
        undoStack()->clear();
        updater->setProgress(100);
    }
    delete d->progressUpdater;
    d->progressUpdater = 0;

    d->isLoading = false;

    return ok;
}

KoProgressUpdater *KisDocument::progressUpdater() const
{
    return d->progressUpdater;
}

void KisDocument::setProgressProxy(KoProgressProxy *progressProxy)
{
    d->progressProxy = progressProxy;
}

KoProgressProxy* KisDocument::progressProxy() const
{
    if (!d->progressProxy) {
        KisMainWindow *mainWindow = 0;
1371 1372
        if (KisPart::instance()->mainwindowCount() > 0) {
            mainWindow = KisPart::instance()->mainWindows()[0];
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
        }
        d->progressProxy = new DocumentProgressProxy(mainWindow);
    }
    return d->progressProxy;
}

// shared between openFile and koMainWindow's "create new empty document" code
void KisDocument::setMimeTypeAfterLoading(const QString& mimeType)
{
    d->mimeType = mimeType.toLatin1();

    d->outputMimeType = d->mimeType;

    const bool needConfirm = !isNativeFormat(d->mimeType);
    setConfirmNonNativeSave(false, needConfirm);
    setConfirmNonNativeSave(true, needConfirm);
}

// The caller must call store->close() if loadAndParse returns true.
bool KisDocument::oldLoadAndParse(KoStore *store, const QString& filename, KoXmlDocument& doc)
{
Halla Rempt's avatar
Halla Rempt committed
1394
    //dbgUI <<"Trying to open" << filename;
1395 1396

    if (!store->open(filename)) {
Halla Rempt's avatar
Halla Rempt committed
1397
        warnUI << "Entry " << filename << " not found!";
1398 1399 1400 1401 1402 1403 1404 1405 1406
        d->lastErrorMessage = i18n("Could not find %1", filename);
        return false;
    }
    // Error variables for QDomDocument::setContent
    QString errorMsg;
    int errorLine, errorColumn;
    bool ok = doc.setContent(store->device(), &errorMsg, &errorLine, &errorColumn);
    store->close();
    if (!ok) {
Halla Rempt's avatar
Halla Rempt committed
1407
        errUI << "Parsing error in " << filename << "! Aborting!" << endl
1408 1409 1410 1411 1412 1413 1414 1415
        << " In line: " << errorLine << ", column: " << errorColumn << endl
        << " Error message: " << errorMsg << endl;
        d->lastErrorMessage = i18n("Parsing error in %1 at line %2, column %3\nError message: %4"
                                   , filename  , errorLine, errorColumn ,
                                   QCoreApplication::translate("QXml", errorMsg.toUtf8(), 0,
                                                               QCoreApplication::UnicodeUTF8));
        return false;
    }
Halla Rempt's avatar
Halla Rempt committed
1416
    dbgUI << "File" << filename << " loaded and parsed";
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    return true;
}

bool KisDocument::loadNativeFormat(const QString & file_)
{
    QString file = file_;
    QFileInfo fileInfo(file);
    if (!fileInfo.exists()) { // check duplicated from openUrl, but this is useful for templates
        d->lastErrorMessage = i18n("The file %1 does not exist.", file);
        return false;
    }
    if (!fileInfo.isFile()) {
        file += "/content.xml";
        QFileInfo fileInfo2(file);
        if (!fileInfo2.exists() || !fileInfo2.isFile()) {
            d->lastErrorMessage = i18n("%1 is not a file." , file_);
            return false;
        }
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

Halla Rempt's avatar
Halla Rempt committed
1439
    dbgUI << file;
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469

    QFile in;
    bool isRawXML = false;
    if (d->specialOutputFlag != SaveAsDirectoryStore) { // Don't try to open a directory ;)
        in.setFileName(file);
        if (!in.open(QIODevice::ReadOnly)) {
            QApplication::restoreOverrideCursor();
            d->lastErrorMessage = i18n("Could not open the file for reading (check read permissions).");
            return false;
        }

        char buf[6];
        buf[5] = 0;
        int pos = 0;
        do {
            if (in.read(buf + pos , 1) < 1) {
                QApplication::restoreOverrideCursor();
                in.close();
                d->lastErrorMessage = i18n("Could not read the beginning of the file.");
                return false;
            }

            if (QChar(buf[pos]).isSpace())
                continue;
            pos++;
        } while (pos < 5);
        isRawXML = (qstrnicmp(buf, "<?xml", 5) == 0);
        if (! isRawXML)
            // also check for broken MathML files, which seem to be rather common
            isRawXML = (qstrnicmp(buf, "<math", 5) == 0);   // file begins with <math ?
Halla Rempt's avatar
Halla Rempt committed
1470
        //dbgUI <<"PATTERN=" << buf;
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    }
    // Is it plain XML?
    if (isRawXML) {
        in.seek(0);
        QString errorMsg;
        int errorLine;
        int errorColumn;
        KoXmlDocument doc = KoXmlDocument(true);
        bool res;
        if (doc.setContent(&in, &errorMsg, &errorLine, &errorColumn)) {
            res = loadXML(doc, 0);
            if (res)
                res = completeLoading(0);
        } else {
Halla Rempt's avatar
Halla Rempt committed
1485
            errUI << "Parsing Error! Aborting! (in KisDocument::loadNativeFormat (QFile))" << endl
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
            << "  Line: " << errorLine << " Column: " << errorColumn << endl
            << "  Message: " << errorMsg << endl;
            d->lastErrorMessage = i18n("parsing error in the main document at line %1, column %2\nError message: %3", errorLine, errorColumn, i18n(errorMsg.toUtf8()));
            res = false;
        }

        QApplication::restoreOverrideCursor();
        in.close();
        d->isEmpty = false;
        return res;
    }
    else { // It's a calligra store (tar.gz, zip, directory, etc.)
        in.close();

        KoStore::Backend backend = (d->specialOutputFlag == SaveAsDirectoryStore) ? KoStore::Directory : KoStore::Auto;
        KoStore *store = KoStore::createStore(file, KoStore::Read, "", backend);

        if (store->bad()) {
1504
            d->lastErrorMessage = i18n("Not a valid Krita file: %1", file);
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
            delete store;
            QApplication::restoreOverrideCursor();
            return false;
        }

        // Remember that the file was encrypted
        if (d->specialOutputFlag == 0 && store->isEncrypted() && !d->isImporting)
            d->specialOutputFlag = SaveEncrypted;

        const bool success = loadNativeFormatFromStoreInternal(store);

        // Retrieve the password after loading the file, only then is it guaranteed to exist
        if (success && store->isEncrypted() && !d->isImporting)
            d->password = store->password();

        delete store;

        return success;

    }
}

bool KisDocument::loadNativeFormatFromByteArray(QByteArray &data)
{
    bool succes;
    KoStore::Backend backend = (d->specialOutputFlag == SaveAsDirectoryStore) ? KoStore::Directory : KoStore::Auto;
    QBuffer buffer(&data);
    KoStore *store = KoStore::createStore(&buffer, KoStore::Read, "", backend);

    if (store->bad()) {
        delete store;
        return false;
    }

    // Remember that the file was encrypted
    if (d->specialOutputFlag == 0 && store->isEncrypted() && !d->isImporting)
        d->specialOutputFlag = SaveEncrypted;

    succes = loadNativeFormatFromStoreInternal(store);

    // Retrieve the password after loading the file, only then is it guaranteed to exist
    if (succes && store->isEncrypted() && !d->isImporting)
        d->password = store->password();

    delete store;

    return succes;
}

bool KisDocument::loadNativeFormatFromStoreInternal(KoStore *store)
{
    if (store->hasFile("root") || store->hasFile("maindoc.xml")) {   // Fallback to "old" file format (maindoc.xml)
        KoXmlDocument doc = KoXmlDocument(true);

        bool ok = oldLoadAndParse(store, "root", doc);
        if (ok)
            ok = loadXML(doc, store);
        if (!ok) {
            QApplication::restoreOverrideCursor();
            return false;
        }

    } else {
Halla Rempt's avatar
Halla Rempt committed
1568
        errUI << "ERROR: No maindoc.xml" << endl;
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
        d->lastErrorMessage = i18n("Invalid document: no file 'maindoc.xml'.");
        QApplication::restoreOverrideCursor();
        return false;
    }

    if (store->hasFile("documentinfo.xml")) {
        KoXmlDocument doc = KoXmlDocument(true);
        if (oldLoadAndParse(store, "documentinfo.xml", doc)) {
            d->docInfo->load(doc);
        }
    } else {
Halla Rempt's avatar
Halla Rempt committed
1580
        //dbgUI <<"cannot open document info";
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
        delete d->docInfo;
        d->docInfo = new KoDocumentInfo(this);
    }

    bool res = completeLoading(store);
    QApplication::restoreOverrideCursor();
    d->isEmpty = false;
    return res;
}

// For embedded documents
bool KisDocument::loadFromStore(KoStore *_store, const QString& url)
{
    if (_store->open(url)) {
        KoXmlDocument doc = KoXmlDocument(true);
        doc.setContent(_store->device());
        if (!loadXML(doc, _store)) {
            _store->close();
            return false