kpDocument_Save.cpp 17 KB
Newer Older
1
/*
2
   Copyright (c) 2003-2007 Clarence Dang <dang@kde.org>
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/


#define DEBUG_KP_DOCUMENT 0


#include <kpDocument.h>
#include <kpDocumentPrivate.h>

#include <math.h>

#include <qcolor.h>
#include <qbitmap.h>
#include <qbrush.h>
#include <qfile.h>
#include <qimage.h>
#include <qlist.h>
42
#include <QImage>
43 44
#include <qpainter.h>
#include <qrect.h>
Christoph Feck's avatar
Christoph Feck committed
45
#include <qsavefile.h>
46
#include <qsize.h>
47
#include <qtemporaryfile.h>
48 49 50 51 52 53 54 55 56
#include <qmatrix.h>

#include <kdebug.h>
#include <kimageio.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kmimetype.h>  // TODO: isn't this in KIO?

57 58 59
#include <kpColor.h>
#include <kpColorToolBar.h>
#include <kpDefs.h>
60
#include <kpDocumentEnvironment.h>
61 62
#include <kpDocumentSaveOptions.h>
#include <kpDocumentMetaInfo.h>
63
#include <kpEffectReduceColors.h>
64 65 66
#include <kpPixmapFX.h>
#include <kpTool.h>
#include <kpToolToolBar.h>
67
#include <kpUrlFormatter.h>
68
#include <kpViewManager.h>
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84


bool kpDocument::save (bool overwritePrompt, bool lossyPrompt)
{
#if DEBUG_KP_DOCUMENT
    kDebug () << "kpDocument::save("
               << "overwritePrompt=" << overwritePrompt
               << ",lossyPrompt=" << lossyPrompt
               << ") url=" << m_url
               << " savedAtLeastOnceBefore=" << savedAtLeastOnceBefore ()
               << endl;
#endif

    // TODO: check feels weak
    if (m_url.isEmpty () || m_saveOptions->mimeType ().isEmpty ())
    {
85
        KMessageBox::detailedError (d->environ->dialogParent (),
86 87 88 89 90 91 92
            i18n ("Could not save image - insufficient information."),
            i18n ("URL: %1\n"
                  "Mimetype: %2",
                  prettyUrl (),
                  m_saveOptions->mimeType ().isEmpty () ?
                          i18n ("<empty>") :
                          m_saveOptions->mimeType ()),
93
            i18nc ("@title:window", "Internal Error"));
94 95 96 97 98 99 100 101
        return false;
    }

    return saveAs (m_url, *m_saveOptions,
                   overwritePrompt,
                   lossyPrompt);
}

102
//---------------------------------------------------------------------
103 104

// public static
105
bool kpDocument::lossyPromptContinue (const QImage &pixmap,
106 107 108 109
                                      const kpDocumentSaveOptions &saveOptions,
                                      QWidget *parent)
{
#if DEBUG_KP_DOCUMENT
110
    kDebug () << "kpDocument::lossyPromptContinue()";
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
#endif

#define QUIT_IF_CANCEL(messageBoxCommand)            \
{                                                    \
    if (messageBoxCommand != KMessageBox::Continue)  \
    {                                                \
        return false;                                \
    }                                                \
}

    const int lossyType = saveOptions.isLossyForSaving (pixmap);
    if (lossyType & (kpDocumentSaveOptions::MimeTypeMaximumColorDepthLow |
                     kpDocumentSaveOptions::Quality))
    {
        QUIT_IF_CANCEL (
            KMessageBox::warningContinueCancel (parent,
                i18n ("<qt><p>The <b>%1</b> format may not be able"
                      " to preserve all of the image's color information.</p>"

                      "<p>Are you sure you want to save in this format?</p></qt>",
                      KMimeType::mimeType (saveOptions.mimeType ())->comment ()),
                // TODO: caption misleading for lossless formats that have
                //       low maximum colour depth
134
                i18nc ("@title:window", "Lossy File Format"),
135
                KStandardGuiItem::save (),
136
                KStandardGuiItem::cancel(),
137 138 139 140 141 142 143 144 145
                QLatin1String ("SaveInLossyMimeTypeDontAskAgain")));
    }
    else if (lossyType & kpDocumentSaveOptions::ColorDepthLow)
    {
        QUIT_IF_CANCEL (
            KMessageBox::warningContinueCancel (parent,
                i18n ("<qt><p>Saving the image at the low color depth of %1-bit"
                        " may result in the loss of color information."

146 147 148 149
                        // TODO: It looks like 8-bit QImage's now support alpha.
                        //       Update kpDocumentSaveOptions::isLossyForSaving()
                        //       and change "might" to "will".
                        " Any transparency might also be removed.</p>"
150 151 152

                        "<p>Are you sure you want to save at this color depth?</p></qt>",
                      saveOptions.colorDepth ()),
153
                i18nc ("@title:window", "Low Color Depth"),
154
                KStandardGuiItem::save (),
155
                KStandardGuiItem::cancel(),
156 157 158 159 160 161 162
                QLatin1String ("SaveAtLowColorDepthDontAskAgain")));
    }
#undef QUIT_IF_CANCEL

    return true;
}

163 164
//---------------------------------------------------------------------

165
// public static
166
bool kpDocument::savePixmapToDevice (const QImage &image,
167 168 169 170 171 172 173 174 175 176
                                     QIODevice *device,
                                     const kpDocumentSaveOptions &saveOptions,
                                     const kpDocumentMetaInfo &metaInfo,
                                     bool lossyPrompt,
                                     QWidget *parent,
                                     bool *userCancelled)
{
    if (userCancelled)
        *userCancelled = false;

177 178 179 180 181 182 183 184 185 186 187
    QStringList types = KImageIO::typeForMime (saveOptions.mimeType ());
#if DEBUG_KP_DOCUMENT
    kDebug () << "\ttypes=" << types;
#endif
    if (types.isEmpty ())
        return false;

    // It's safe to arbitrarily choose the 0th type as any type in the list
    // should invoke the same KImageIO image loader.
    const QString type = types [0];

188 189 190 191 192
#if DEBUG_KP_DOCUMENT
    kDebug () << "\tmimeType=" << saveOptions.mimeType ()
               << " type=" << type << endl;
#endif

193
    if (lossyPrompt && !lossyPromptContinue (image, saveOptions, parent))
194 195 196 197 198
    {
        if (userCancelled)
            *userCancelled = true;

    #if DEBUG_KP_DOCUMENT
199
        kDebug () << "\treturning false because of lossyPrompt";
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    #endif
        return false;
    }


    // TODO: fix dup with kpDocumentSaveOptions::isLossyForSaving()
    const bool useSaveOptionsColorDepth =
        (saveOptions.mimeTypeHasConfigurableColorDepth () &&
         !saveOptions.colorDepthIsInvalid ());
    const bool useSaveOptionsQuality =
        (saveOptions.mimeTypeHasConfigurableQuality () &&
         !saveOptions.qualityIsInvalid ());


    //
    // Reduce colors if required
    //

218 219
#if DEBUG_KP_DOCUMENT
    kDebug () << "\tuseSaveOptionsColorDepth=" << useSaveOptionsColorDepth
220
              << "current image depth=" << image.depth ()
221 222
              << "save options depth=" << saveOptions.colorDepth ();
#endif
223 224
    QImage imageToSave(image);

225 226 227
    if (useSaveOptionsColorDepth &&
        imageToSave.depth () != saveOptions.colorDepth ())
    {
228 229 230 231 232
        // TODO: I think this erases the mask!
        //
        //       I suspect this doesn't matter since this is only called to
        //       reduce color depth and QImage's with depth < 32 don't
        //       support masks anyway.
Clarence Dang's avatar
Clarence Dang committed
233 234 235
        //
        //       Later: I think the mask is preserved for 8-bit since Qt4
        //              seems to support it for QImage.
236 237 238 239 240 241 242 243 244 245 246 247 248 249
        imageToSave = kpEffectReduceColors::convertImageDepth (imageToSave,
                                           saveOptions.colorDepth (),
                                           saveOptions.dither ());
    }


    //
    // Write Meta Info
    //

    imageToSave.setDotsPerMeterX (metaInfo.dotsPerMeterX ());
    imageToSave.setDotsPerMeterY (metaInfo.dotsPerMeterY ());
    imageToSave.setOffset (metaInfo.offset ());

250
    QList <QString> keyList = metaInfo.textKeys ();
Laurent Montel's avatar
Laurent Montel committed
251 252
    for (QList <QString>::const_iterator it = keyList.constBegin ();
         it != keyList.constEnd ();
Martin Koller's avatar
Martin Koller committed
253
         ++it)
254
    {
255
        imageToSave.setText (*it, metaInfo.text (*it));
256 257 258 259 260 261 262 263 264 265 266 267
    }


    //
    // Save at required quality
    //

    int quality = -1;  // default

    if (useSaveOptionsQuality)
        quality = saveOptions.quality ();

268 269 270
#if DEBUG_KP_DOCUMENT
    kDebug () << "\tsaving";
#endif
271 272 273
    if (!imageToSave.save (device, type.toLatin1 (), quality))
    {
    #if DEBUG_KP_DOCUMENT
274
        kDebug () << "\tQImage::save() returned false";
275 276 277 278 279 280
    #endif
        return false;
    }


#if DEBUG_KP_DOCUMENT
281
    kDebug () << "\tsave OK";
282 283 284 285
#endif
    return true;
}

286
//---------------------------------------------------------------------
287 288 289 290 291 292 293

static void CouldNotCreateTemporaryFileDialog (QWidget *parent)
{
    KMessageBox::error (parent,
                        i18n ("Could not save image - unable to create temporary file."));
}

294 295
//---------------------------------------------------------------------

Christoph Feck's avatar
Christoph Feck committed
296
static void CouldNotSaveDialog (const QUrl &url, QWidget *parent)
297 298 299 300
{
    // TODO: use file.errorString()
    KMessageBox::error (parent,
                        i18n ("Could not save as \"%1\".",
301
                              kpUrlFormatter::PrettyFilename (url)));
302 303
}

304 305
//---------------------------------------------------------------------

306
// public static
307
bool kpDocument::savePixmapToFile (const QImage &pixmap,
Christoph Feck's avatar
Christoph Feck committed
308
                                   const QUrl &url,
309 310 311 312 313 314
                                   const kpDocumentSaveOptions &saveOptions,
                                   const kpDocumentMetaInfo &metaInfo,
                                   bool overwritePrompt,
                                   bool lossyPrompt,
                                   QWidget *parent)
{
315 316 317
    // TODO: Use KIO::NetAccess:mostLocalURL() for accessing home:/ (and other
    //       such local URLs) for efficiency and because only local writes
    //       are atomic.
318 319 320 321 322 323 324 325 326 327
#if DEBUG_KP_DOCUMENT
    kDebug () << "kpDocument::savePixmapToFile ("
               << url
               << ",overwritePrompt=" << overwritePrompt
               << ",lossyPrompt=" << lossyPrompt
               << ")" << endl;
    saveOptions.printDebug (QLatin1String ("\tsaveOptions"));
    metaInfo.printDebug (QLatin1String ("\tmetaInfo"));
#endif

328 329
    if (overwritePrompt &&
        KIO::NetAccess::exists (url, KIO::NetAccess::DestinationSide/*write*/, parent))
330 331 332 333
    {
        int result = KMessageBox::warningContinueCancel (parent,
            i18n ("A document called \"%1\" already exists.\n"
                  "Do you want to overwrite it?",
334
                  kpUrlFormatter::PrettyFilename (url)),
335
            QString(),
336 337 338 339 340
            KGuiItem(i18n ("Overwrite")));

        if (result != KMessageBox::Continue)
        {
        #if DEBUG_KP_DOCUMENT
341
            kDebug () << "\tuser doesn't want to overwrite";
342 343 344 345 346 347 348 349 350 351
        #endif

            return false;
        }
    }


    if (lossyPrompt && !lossyPromptContinue (pixmap, saveOptions, parent))
    {
    #if DEBUG_KP_DOCUMENT
352
        kDebug () << "\treturning false because of lossyPrompt";
353 354 355 356 357
    #endif
        return false;
    }


358 359
    // Local file?
    if (url.isLocalFile ())
360
    {
361
        const QString filename = url.toLocalFile ();
362

Christoph Feck's avatar
Christoph Feck committed
363 364
        // sync: All failure exit paths _must_ call QSaveFile::cancelWriting() or
        //       else, the QSaveFile destructor will overwrite the file,
365
        //       <filename>, despite the failure.
Christoph Feck's avatar
Christoph Feck committed
366
        QSaveFile atomicFileWriter (filename);
367
        {
Christoph Feck's avatar
Christoph Feck committed
368
            if (!atomicFileWriter.open (QIODevice::WriteOnly))
369 370 371
            {
                // We probably don't need this as <filename> has not been
                // opened.
Christoph Feck's avatar
Christoph Feck committed
372
                atomicFileWriter.cancelWriting ();
373 374

            #if DEBUG_KP_DOCUMENT
Christoph Feck's avatar
Christoph Feck committed
375
                kDebug () << "\treturning false because could not open QSaveFile"
376 377 378 379 380 381 382 383 384 385 386 387
                          << " error=" << atomicFileWriter.error () << endl;
            #endif
                ::CouldNotCreateTemporaryFileDialog (parent);
                return false;
            }

            // Write to local temporary file.
            if (!savePixmapToDevice (pixmap, &atomicFileWriter,
                                     saveOptions, metaInfo,
                                     false/*no lossy prompt*/,
                                     parent))
            {
Christoph Feck's avatar
Christoph Feck committed
388
                atomicFileWriter.cancelWriting ();
389 390 391 392 393 394 395 396 397 398 399

            #if DEBUG_KP_DOCUMENT
                kDebug () << "\treturning false because could not save pixmap to device"
                          << endl;
            #endif
                ::CouldNotSaveDialog (url, parent);
                return false;
            }

            // Atomically overwrite local file with the temporary file
            // we saved to.
Christoph Feck's avatar
Christoph Feck committed
400
            if (!atomicFileWriter.commit ())
401
            {
Christoph Feck's avatar
Christoph Feck committed
402
                atomicFileWriter.cancelWriting ();
403 404

            #if DEBUG_KP_DOCUMENT
Christoph Feck's avatar
Christoph Feck committed
405
                kDebug () << "\tcould not close QSaveFile";
406 407 408 409
            #endif
                ::CouldNotSaveDialog (url, parent);
                return false;
            }
Christoph Feck's avatar
Christoph Feck committed
410
        }  // sync QSaveFile.cancelWriting()
411
    }
412
    // Remote file?
413 414
    else
    {
415 416
        // Create temporary file that is deleted when the variable goes
        // out of scope.
417
        QTemporaryFile tempFile;
418
        if (!tempFile.open ())
419
        {
420
        #if DEBUG_KP_DOCUMENT
421
            kDebug () << "\treturning false because could not open tempFile";
422 423 424
        #endif
            ::CouldNotCreateTemporaryFileDialog (parent);
            return false;
425
        }
426 427 428 429 430 431

        // Write to local temporary file.
        if (!savePixmapToDevice (pixmap, &tempFile,
                                 saveOptions, metaInfo,
                                 false/*no lossy prompt*/,
                                 parent))
432
        {
433
        #if DEBUG_KP_DOCUMENT
434
            kDebug () << "\treturning false because could not save pixmap to device"
435 436 437 438
                        << endl;
        #endif
            ::CouldNotSaveDialog (url, parent);
            return false;
439 440
        }

441 442 443 444
        // Collect name of temporary file now, as QTemporaryFile::fileName()
        // stops working after close() is called.
        const QString tempFileName = tempFile.fileName ();
    #if DEBUG_KP_DOCUMENT
445
            kDebug () << "\ttempFileName='" << tempFileName << "'";
446 447
    #endif
        Q_ASSERT (!tempFileName.isEmpty ());
448

449 450 451 452
        tempFile.close ();
        if (tempFile.error () != QFile::NoError)
        {
        #if DEBUG_KP_DOCUMENT
453
            kDebug () << "\treturning false because could not close";
454 455 456 457
        #endif
            ::CouldNotSaveDialog (url, parent);
            return false;
        }
458

459 460 461 462 463
        // Copy local temporary file to overwrite remote.
        // TODO: No one seems to know how to do this atomically
        //       [http://lists.kde.org/?l=kde-core-devel&m=117845162728484&w=2].
        //       At least, fish:// (ssh) is definitely not atomic.
        if (!KIO::NetAccess::upload (tempFileName, url, parent))
464 465
        {
        #if DEBUG_KP_DOCUMENT
466
            kDebug () << "\treturning false because could not upload";
467 468 469 470 471 472 473 474 475 476 477
        #endif
            KMessageBox::error (parent,
                                i18n ("Could not save image - failed to upload."));
            return false;
        }
    }


    return true;
}

478 479
//---------------------------------------------------------------------

Christoph Feck's avatar
Christoph Feck committed
480
bool kpDocument::saveAs (const QUrl &url,
481 482 483 484 485 486 487 488 489
                         const kpDocumentSaveOptions &saveOptions,
                         bool overwritePrompt,
                         bool lossyPrompt)
{
#if DEBUG_KP_DOCUMENT
    kDebug () << "kpDocument::saveAs (" << url << ","
               << saveOptions.mimeType () << ")" << endl;
#endif

490
    if (kpDocument::savePixmapToFile (imageWithSelection (),
491 492 493 494
                                      url,
                                      saveOptions, *metaInfo (),
                                      overwritePrompt,
                                      lossyPrompt,
495
                                      d->environ->dialogParent ()))
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
    {
        setURL (url, true/*is from url*/);
        *m_saveOptions = saveOptions;
        m_modified = false;

        m_savedAtLeastOnceBefore = true;

        emit documentSaved ();
        return true;
    }
    else
    {
        return false;
    }
}
511 512

//---------------------------------------------------------------------