UBPersistenceManager.cpp 30.7 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1
/*
Claudio Valerio's avatar
Claudio Valerio committed
2 3
 * 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
Claudio Valerio's avatar
Claudio Valerio committed
4
 * the Free Software Foundation, either version 2 of the License, or
Claudio Valerio's avatar
Claudio Valerio committed
5
 * (at your option) any later version.
Claudio Valerio's avatar
Claudio Valerio committed
6
 *
Claudio Valerio's avatar
Claudio Valerio committed
7 8 9 10 11 12 13
 * 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, see <http://www.gnu.org/licenses/>.
Claudio Valerio's avatar
Claudio Valerio committed
14 15 16
 */

#include "UBPersistenceManager.h"
17
#include "gui/UBMainWindow.h"
Claudio Valerio's avatar
Claudio Valerio committed
18 19 20 21 22 23 24 25 26 27

#include <QtXml>

#include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBFileSystemUtils.h"

#include "core/UBApplication.h"
#include "core/UBSettings.h"
#include "core/UBSetting.h"

Claudio Valerio's avatar
Claudio Valerio committed
28 29 30
#include "gui/UBDockTeacherGuideWidget.h"
#include "gui/UBTeacherGuideWidget.h"

Claudio Valerio's avatar
Claudio Valerio committed
31 32 33 34 35 36 37
#include "document/UBDocumentProxy.h"

#include "adaptors/UBExportPDF.h"
#include "adaptors/UBSvgSubsetAdaptor.h"
#include "adaptors/UBThumbnailAdaptor.h"
#include "adaptors/UBMetadataDcSubsetAdaptor.h"

38
#include "board/UBBoardController.h"
Claudio Valerio's avatar
Claudio Valerio committed
39
#include "board/UBBoardPaletteManager.h"
40 41 42

#include "interfaces/IDataStorage.h"

43
#include "core/memcheck.h"
Claudio Valerio's avatar
Claudio Valerio committed
44 45 46 47 48 49

const QString UBPersistenceManager::imageDirectory = "images"; // added to UBPersistenceManager::mAllDirectories
const QString UBPersistenceManager::objectDirectory = "objects"; // added to UBPersistenceManager::mAllDirectories
const QString UBPersistenceManager::widgetDirectory = "widgets"; // added to UBPersistenceManager::mAllDirectories
const QString UBPersistenceManager::videoDirectory = "videos"; // added to UBPersistenceManager::mAllDirectories
const QString UBPersistenceManager::audioDirectory = "audios"; // added to
50
const QString UBPersistenceManager::teacherGuideDirectory = "teacherGuideObjects";
Claudio Valerio's avatar
Claudio Valerio committed
51 52 53 54 55 56 57 58 59 60 61 62 63

UBPersistenceManager * UBPersistenceManager::sSingleton = 0;

UBPersistenceManager::UBPersistenceManager(QObject *pParent)
    : QObject(pParent)
    , mHasPurgedDocuments(false)
{

    mDocumentSubDirectories << imageDirectory;
    mDocumentSubDirectories << objectDirectory;
    mDocumentSubDirectories << widgetDirectory;
    mDocumentSubDirectories << videoDirectory;
    mDocumentSubDirectories << audioDirectory;
64
    mDocumentSubDirectories << teacherGuideDirectory;
Claudio Valerio's avatar
Claudio Valerio committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

    documentProxies = allDocumentProxies();
    emit proxyListChanged();
}

UBPersistenceManager* UBPersistenceManager::persistenceManager()
{
    if (!sSingleton)
    {
        sSingleton = new UBPersistenceManager(UBApplication::staticMemoryCleaner);
    }

    return sSingleton;
}

80 81 82 83 84 85 86
void UBPersistenceManager::destroy()
{
    if (sSingleton)
        delete sSingleton;
    sSingleton = NULL;
}

Claudio Valerio's avatar
Claudio Valerio committed
87 88 89 90 91 92 93 94 95 96 97
UBPersistenceManager::~UBPersistenceManager()
{
    foreach(QPointer<UBDocumentProxy> proxyGuard, documentProxies)
    {
        if (!proxyGuard.isNull())
            delete proxyGuard.data();
    }
}

QList<QPointer<UBDocumentProxy> > UBPersistenceManager::allDocumentProxies()
{
98
    mDocumentRepositoryPath = UBSettings::userDocumentDirectory();
Claudio Valerio's avatar
Claudio Valerio committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

    QDir rootDir(mDocumentRepositoryPath);
    rootDir.mkpath(rootDir.path());


    QFileSystemWatcher* watcher = new QFileSystemWatcher(this);
    watcher->addPath(mDocumentRepositoryPath);

    connect(watcher, SIGNAL(directoryChanged(const QString&)), this, SLOT(documentRepositoryChanged(const QString&)));

    QList<QPointer<UBDocumentProxy> > proxies;

    foreach(QString path, rootDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot,
            QDir::Time | QDir::Reversed))
    {
        QString fullPath = rootDir.path() + "/" + path;

        QDir dir(fullPath);

        if (dir.entryList(QDir::Files | QDir::NoDotAndDotDot).size() > 0)
        {
            UBDocumentProxy* proxy = new UBDocumentProxy(fullPath); // deleted in UBPersistenceManager::destructor

            QMap<QString, QVariant> metadatas = UBMetadataDcSubsetAdaptor::load(fullPath);

            foreach(QString key, metadatas.keys())
            {
                proxy->setMetaData(key, metadatas.value(key));
            }

            proxy->setPageCount(sceneCount(proxy));

            proxies << QPointer<UBDocumentProxy>(proxy);

        }
    }

    return proxies;
}


QStringList UBPersistenceManager::allShapes()
{
142
    QString shapeLibraryPath = UBSettings::settings()->applicationShapeLibraryDirectory();
Claudio Valerio's avatar
Claudio Valerio committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    QDir dir(shapeLibraryPath);

    if (!dir.exists())
        dir.mkpath(shapeLibraryPath);

    QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
    QStringList paths;

    foreach(QString file, files)
    {
        paths.append(shapeLibraryPath + QString("/") + file);
    }

    return paths;
}

QStringList UBPersistenceManager::allGips()
{
162
    QString gipLibraryPath = UBSettings::settings()->userGipLibraryDirectory();
Claudio Valerio's avatar
Claudio Valerio committed
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 196 197 198 199 200 201 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 230 231 232 233

    QDir dir(gipLibraryPath);

    QStringList files = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
    QStringList paths;

    foreach(QString file, files)
    {
        QFileInfo fi(file);

        if (UBSettings::settings()->widgetFileExtensions.contains(fi.suffix()))
            paths.append(dir.path() + QString("/") + file);
    }

    return paths;
}

QStringList UBPersistenceManager::allImages(const QDir& dir)
{
    if (!dir.exists())
        dir.mkpath(dir.path());

    QStringList files = dir.entryList(QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot, QDir::Name);
    QStringList paths;

    foreach(QString file, files)
    {
        paths.append(dir.path() + QString("/") + file);
    }

    return paths;
}


QStringList UBPersistenceManager::allVideos(const QDir& dir)
{
    if (!dir.exists())
        dir.mkpath(dir.path());

    QStringList files = dir.entryList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
    QStringList paths;

    foreach(QString file, files)
    {
        paths.append(dir.path() + QString("/") + file);
    }

    return paths;
}


QStringList UBPersistenceManager::allWidgets(const QDir& dir)
{
    if (!dir.exists())
        dir.mkpath(dir.path());

    QStringList files = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
    QStringList paths;

    foreach(QString file, files)
    {
        QFileInfo fi(file);

        if (UBSettings::settings()->widgetFileExtensions.contains(fi.suffix()))
            paths.append(dir.path() + QString("/") + file);
    }

    return paths;
}


234
UBDocumentProxy* UBPersistenceManager::createDocument(const QString& pGroupName, const QString& pName, bool withEmptyPage)
Claudio Valerio's avatar
Claudio Valerio committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
{
    checkIfDocumentRepositoryExists();

    UBDocumentProxy *doc = new UBDocumentProxy(); // deleted in UBPersistenceManager::destructor

    if (pGroupName.length() > 0)
    {
        doc->setMetaData(UBSettings::documentGroupName, pGroupName);
    }

    if (pName.length() > 0)
    {
        doc->setMetaData(UBSettings::documentName, pName);
    }

    doc->setMetaData(UBSettings::documentVersion, UBSettings::currentFileVersion);
251 252 253
    QString currentDate =  UBStringUtils::toUtcIsoDateTime(QDateTime::currentDateTime());
    doc->setMetaData(UBSettings::documentUpdatedAt,currentDate);
    doc->setMetaData(UBSettings::documentDate,currentDate);
Claudio Valerio's avatar
Claudio Valerio committed
254

255
    if (withEmptyPage) createDocumentSceneAt(doc, 0);
Claudio Valerio's avatar
Claudio Valerio committed
256 257 258 259 260 261 262 263 264 265 266 267

    documentProxies.insert(0, QPointer<UBDocumentProxy>(doc));

    emit proxyListChanged();

    emit documentCreated(doc);

    mDocumentCreatedDuringSession << doc;

    return doc;
}

268
UBDocumentProxy* UBPersistenceManager::createDocumentFromDir(const QString& pDocumentDirectory, const QString& pGroupName, const QString& pName, bool withEmptyPage, bool addTitlePage)
Claudio Valerio's avatar
Claudio Valerio committed
269 270 271 272 273
{
    checkIfDocumentRepositoryExists();

    UBDocumentProxy* doc = new UBDocumentProxy(pDocumentDirectory); // deleted in UBPersistenceManager::destructor

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
274 275 276 277 278 279 280 281 282
    if (pGroupName.length() > 0)
    {
        doc->setMetaData(UBSettings::documentGroupName, pGroupName);
    }

    if (pName.length() > 0)
    {
        doc->setMetaData(UBSettings::documentName, pName);
    }
283 284
    if(withEmptyPage) createDocumentSceneAt(doc, 0);
    if(addTitlePage) persistDocumentScene(doc, mSceneCache.createScene(doc, 0, false), 0);
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
285

Claudio Valerio's avatar
Claudio Valerio committed
286 287 288 289 290 291 292 293 294 295 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 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
    QMap<QString, QVariant> metadatas = UBMetadataDcSubsetAdaptor::load(pDocumentDirectory);

    foreach(QString key, metadatas.keys())
    {
        doc->setMetaData(key, metadatas.value(key));
    }

    doc->setUuid(QUuid::createUuid());
    doc->setPageCount(sceneCount(doc));

    UBMetadataDcSubsetAdaptor::persist(doc);

    for(int i = 0; i < doc->pageCount(); i++)
    {
        UBSvgSubsetAdaptor::setSceneUuid(doc, i, QUuid::createUuid());
    }

    documentProxies << QPointer<UBDocumentProxy>(doc);

    emit proxyListChanged();

    emit documentCreated(doc);

    return doc;
}


void UBPersistenceManager::deleteDocument(UBDocumentProxy* pDocumentProxy)
{
    checkIfDocumentRepositoryExists();

    emit documentWillBeDeleted(pDocumentProxy);

    UBFileSystemUtils::deleteDir(pDocumentProxy->persistencePath());

    documentProxies.removeAll(QPointer<UBDocumentProxy>(pDocumentProxy));
    mDocumentCreatedDuringSession.removeAll(pDocumentProxy);

    mSceneCache.removeAllScenes(pDocumentProxy);

    pDocumentProxy->deleteLater();

    emit proxyListChanged();

}


UBDocumentProxy* UBPersistenceManager::duplicateDocument(UBDocumentProxy* pDocumentProxy)
{
    checkIfDocumentRepositoryExists();

    UBDocumentProxy *copy = new UBDocumentProxy(); // deleted in UBPersistenceManager::destructor

    generatePathIfNeeded(copy);

    UBFileSystemUtils::copyDir(pDocumentProxy->persistencePath(), copy->persistencePath());

    // regenerate scenes UUIDs
    for(int i = 0; i < pDocumentProxy->pageCount(); i++)
    {
        UBSvgSubsetAdaptor::setSceneUuid(pDocumentProxy, i, QUuid::createUuid());
    }

    foreach(QString key, pDocumentProxy->metaDatas().keys())
    {
        copy->setMetaData(key, pDocumentProxy->metaDatas().value(key));
    }

    copy->setMetaData(UBSettings::documentName,
            pDocumentProxy->metaData(UBSettings::documentName).toString() + " " + tr("(copy)"));

    copy->setUuid(QUuid::createUuid());

    persistDocumentMetadata(copy);

    copy->setPageCount(sceneCount(copy));

    documentProxies << QPointer<UBDocumentProxy>(copy);

    emit proxyListChanged();

    emit documentCreated(copy);

    return copy;

}


void UBPersistenceManager::deleteDocumentScenes(UBDocumentProxy* proxy, const QList<int>& indexes)
{
376
    checkIfDocumentRepositoryExists();
Claudio Valerio's avatar
Claudio Valerio committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

    int pageCount = UBPersistenceManager::persistenceManager()->sceneCount(proxy);

    QList<int> compactedIndexes;

    foreach(int index, indexes)
    {
        if (!compactedIndexes.contains(index))
            compactedIndexes.append(index);
    }

    if (compactedIndexes.size() == pageCount)
    {
        deleteDocument(proxy);
        return;
    }

    if (compactedIndexes.size() == 0)
        return;

    foreach(int index, compactedIndexes)
    {
        emit documentSceneWillBeDeleted(proxy, index);
    }

    QString sourceGroupName = proxy->metaData(UBSettings::documentGroupName).toString();
    QString sourceName = proxy->metaData(UBSettings::documentName).toString();
404
    UBDocumentProxy *trashDocProxy = createDocument(UBSettings::trashedDocumentGroupNamePrefix + sourceGroupName, sourceName, false);
Claudio Valerio's avatar
Claudio Valerio committed
405 406 407 408 409 410

    foreach(int index, compactedIndexes)
    {
        UBGraphicsScene *scene = loadDocumentScene(proxy, index);
        if (scene)
        {
411
            //scene is about to move into new document
Claudio Valerio's avatar
Claudio Valerio committed
412 413 414 415 416 417 418 419 420 421 422 423
            foreach (QUrl relativeFile, scene->relativeDependencies())
            {
                QString source = scene->document()->persistencePath() + "/" + relativeFile.toString();
                QString target = trashDocProxy->persistencePath() + "/" + relativeFile.toString();

                QFileInfo fi(target);
                QDir d = fi.dir();

                d.mkpath(d.absolutePath());
                QFile::copy(source, target);
            }

424
            insertDocumentSceneAt(trashDocProxy, scene, trashDocProxy->pageCount());
Claudio Valerio's avatar
Claudio Valerio committed
425 426 427 428 429 430 431 432 433 434
        }
    }

    for (int i = 1; i < pageCount; i++)
    {
        renamePage(trashDocProxy, i , i - 1);
    }

    foreach(int index, compactedIndexes)
    {
435
        QString svgFileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", index);
Claudio Valerio's avatar
Claudio Valerio committed
436 437 438

        QFile::remove(svgFileName);

439
        QString thumbFileName = proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", index);
Claudio Valerio's avatar
Claudio Valerio committed
440 441 442

        QFile::remove(thumbFileName);

443
        mSceneCache.removeScene(proxy, index);
Claudio Valerio's avatar
Claudio Valerio committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

        proxy->decPageCount();

    }

    qSort(compactedIndexes);

    int offset = 1;

    for (int i = compactedIndexes.at(0) + 1; i < pageCount; i++)
    {
        if(compactedIndexes.contains(i))
        {
            offset++;
        }
        else
        {
            renamePage(proxy, i , i - offset);

            mSceneCache.moveScene(proxy, i, i - offset);

        }
    }
}


void UBPersistenceManager::duplicateDocumentScene(UBDocumentProxy* proxy, int index)
{
    checkIfDocumentRepositoryExists();

    int pageCount = UBPersistenceManager::persistenceManager()->sceneCount(proxy);

    for (int i = pageCount; i > index + 1; i--)
    {
        renamePage(proxy, i - 1 , i);

        mSceneCache.moveScene(proxy, i - 1, i);

    }

    copyPage(proxy, index , index + 1);

    proxy->incPageCount();

488
    emit documentSceneCreated(proxy, index + 1);
Claudio Valerio's avatar
Claudio Valerio committed
489 490 491
}


Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
492
UBGraphicsScene* UBPersistenceManager::createDocumentSceneAt(UBDocumentProxy* proxy, int index, bool useUndoRedoStack)
Claudio Valerio's avatar
Claudio Valerio committed
493 494 495 496 497 498 499 500
{
    int count = sceneCount(proxy);

    for(int i = count - 1; i >= index; i--)
        renamePage(proxy, i , i + 1);

    mSceneCache.shiftUpScenes(proxy, index, count -1);

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
501
    UBGraphicsScene *newScene = mSceneCache.createScene(proxy, index, useUndoRedoStack);
Claudio Valerio's avatar
Claudio Valerio committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

    newScene->setBackground(UBSettings::settings()->isDarkBackground(),
            UBSettings::settings()->UBSettings::isCrossedBackground());

    persistDocumentScene(proxy, newScene, index);

    proxy->incPageCount();

    emit documentSceneCreated(proxy, index);

    return newScene;
}


void UBPersistenceManager::insertDocumentSceneAt(UBDocumentProxy* proxy, UBGraphicsScene* scene, int index)
{
    scene->setDocument(proxy);

    int count = sceneCount(proxy);

    for(int i = count - 1; i >= index; i--)
    {
        renamePage(proxy, i , i + 1);
    }

    mSceneCache.shiftUpScenes(proxy, index, count -1);

    mSceneCache.insert(proxy, index, scene);

    persistDocumentScene(proxy, scene, index);

    proxy->incPageCount();

    emit documentSceneCreated(proxy, index);

}


void UBPersistenceManager::moveSceneToIndex(UBDocumentProxy* proxy, int source, int target)
{
    checkIfDocumentRepositoryExists();

    if (source == target)
        return;

547 548
    QFile svgTmp(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", source));
    svgTmp.rename(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.tmp", target));
Claudio Valerio's avatar
Claudio Valerio committed
549

550 551
    QFile thumbTmp(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", source));
    thumbTmp.rename(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.tmp", target));
Claudio Valerio's avatar
Claudio Valerio committed
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567

    if (source < target)
    {
        for (int i = source + 1; i <= target; i++)
        {
            renamePage(proxy, i , i - 1);
        }
    }
    else
    {
        for (int i = source - 1; i >= target; i--)
        {
            renamePage(proxy, i , i + 1);
        }
    }

568 569
    QFile svg(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.tmp", target));
    svg.rename(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", target));
Claudio Valerio's avatar
Claudio Valerio committed
570

571 572
    QFile thumb(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.tmp", target));
    thumb.rename(proxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", target));
Claudio Valerio's avatar
Claudio Valerio committed
573 574 575 576 577 578 579 580 581

    mSceneCache.moveScene(proxy, source, target);
}


UBGraphicsScene* UBPersistenceManager::loadDocumentScene(UBDocumentProxy* proxy, int sceneIndex)
{
    if (mSceneCache.contains(proxy, sceneIndex))
        return mSceneCache.value(proxy, sceneIndex);
582
    else {
Claudio Valerio's avatar
Claudio Valerio committed
583
        UBGraphicsScene* scene = UBSvgSubsetAdaptor::loadScene(proxy, sceneIndex);
584
        if(!scene && UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool()){
Claudio Valerio's avatar
Claudio Valerio committed
585
            createDocumentSceneAt(proxy,0);
586 587
            scene = UBSvgSubsetAdaptor::loadScene(proxy, 0);
        }
Claudio Valerio's avatar
Claudio Valerio committed
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

        if (scene)
            mSceneCache.insert(proxy, sceneIndex, scene);

        return scene;
    }
}

void UBPersistenceManager::persistDocumentScene(UBDocumentProxy* pDocumentProxy, UBGraphicsScene* pScene, const int pSceneIndex)
{
    checkIfDocumentRepositoryExists();

    pScene->deselectAllItems();

    generatePathIfNeeded(pDocumentProxy);

    QDir dir(pDocumentProxy->persistencePath());
    dir.mkpath(pDocumentProxy->persistencePath());

Claudio Valerio's avatar
Claudio Valerio committed
607 608
    UBBoardPaletteManager* paletteManager = UBApplication::boardController->paletteManager();
    bool teacherGuideModified = false;
609
    if(UBApplication::app()->boardController->currentPage() == pSceneIndex &&  paletteManager->teacherGuideDockWidget())
Claudio Valerio's avatar
Claudio Valerio committed
610 611 612
    	teacherGuideModified = paletteManager->teacherGuideDockWidget()->teacherGuideWidget()->isModified();

    if (pDocumentProxy->isModified() || teacherGuideModified)
Claudio Valerio's avatar
Claudio Valerio committed
613 614
        UBMetadataDcSubsetAdaptor::persist(pDocumentProxy);

Claudio Valerio's avatar
Claudio Valerio committed
615
    if (pScene->isModified() || teacherGuideModified)
Claudio Valerio's avatar
Claudio Valerio committed
616 617 618
    {
        UBSvgSubsetAdaptor::persistScene(pDocumentProxy, pScene, pSceneIndex);

619 620
        UBThumbnailAdaptor::persistScene(pDocumentProxy, pScene, pSceneIndex);

Claudio Valerio's avatar
Claudio Valerio committed
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        pScene->setModified(false);
    }

    mSceneCache.insert(pDocumentProxy, pSceneIndex, pScene);
}


UBDocumentProxy* UBPersistenceManager::persistDocumentMetadata(UBDocumentProxy* pDocumentProxy)
{
    UBMetadataDcSubsetAdaptor::persist(pDocumentProxy);

    emit documentMetadataChanged(pDocumentProxy);

    return pDocumentProxy;
}


void UBPersistenceManager::renamePage(UBDocumentProxy* pDocumentProxy, const int sourceIndex, const int targetIndex)
{
640 641
    QFile svg(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", sourceIndex));
    svg.rename(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg",  targetIndex));
Claudio Valerio's avatar
Claudio Valerio committed
642

643 644
    QFile thumb(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", sourceIndex));
    thumb.rename(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", targetIndex));
Claudio Valerio's avatar
Claudio Valerio committed
645 646 647 648 649
}


void UBPersistenceManager::copyPage(UBDocumentProxy* pDocumentProxy, const int sourceIndex, const int targetIndex)
{
650 651
    QFile svg(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg",sourceIndex));
    svg.copy(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", targetIndex));
Claudio Valerio's avatar
Claudio Valerio committed
652 653 654

    UBSvgSubsetAdaptor::setSceneUuid(pDocumentProxy, targetIndex, QUuid::createUuid());

655 656
    QFile thumb(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", sourceIndex));
    thumb.copy(pDocumentProxy->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", targetIndex));
Claudio Valerio's avatar
Claudio Valerio committed
657 658 659 660 661
}


int UBPersistenceManager::sceneCount(const UBDocumentProxy* proxy)
{
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
662
    const QString pPath = proxy->persistencePath();
Claudio Valerio's avatar
Claudio Valerio committed
663 664 665

    int pageIndex = 0;
    bool moreToProcess = true;
666
    bool addedMissingZeroPage = false;
Claudio Valerio's avatar
Claudio Valerio committed
667 668 669

    while (moreToProcess)
    {
670
        QString fileName = pPath + UBFileSystemUtils::digitFileFormat("/page%1.svg", pageIndex);
Claudio Valerio's avatar
Claudio Valerio committed
671 672 673 674 675 676 677 678 679

        QFile file(fileName);

        if (file.exists())
        {
            pageIndex++;
        }
        else
        {
Claudio Valerio's avatar
Claudio Valerio committed
680
            if(UBSettings::settings()->teacherGuidePageZeroActivated->get().toBool() && pageIndex == 0){
681 682 683 684 685 686 687 688
                // the document has no zero file but doesn't means that it hasn't any file
                // at all. Just importing a document without the first page using a configuartion
                // that enables zero page.
                pageIndex++;
                addedMissingZeroPage = true;
            }
            else
                moreToProcess = false;
Claudio Valerio's avatar
Claudio Valerio committed
689 690 691
        }
    }

692 693 694 695 696 697
    if(pageIndex == 1 && addedMissingZeroPage){
        // increment is done only to check if there are other pages than the missing zero page
        // This situation means -> no pages on the document
        return 0;
    }

Claudio Valerio's avatar
Claudio Valerio committed
698 699 700
    return pageIndex;
}

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
701
QStringList UBPersistenceManager::getSceneFileNames(const QString& folder)
Claudio Valerio's avatar
Claudio Valerio committed
702
{
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
703 704 705
    QDir dir(folder, "page???.svg", QDir::Name, QDir::Files);
    return dir.entryList();
}
Claudio Valerio's avatar
Claudio Valerio committed
706

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
707 708
QString UBPersistenceManager::generateUniqueDocumentPath(const QString& baseFolder)
{
Claudio Valerio's avatar
Claudio Valerio committed
709 710 711
    QDateTime now = QDateTime::currentDateTime();
    QString dirName = now.toString("yyyy-MM-dd hh-mm-ss.zzz");

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
712 713 714 715 716 717
    return baseFolder + QString("/Sankore Document %1").arg(dirName);
}

QString UBPersistenceManager::generateUniqueDocumentPath()
{
    return generateUniqueDocumentPath(UBSettings::userDocumentDirectory());
Claudio Valerio's avatar
Claudio Valerio committed
718 719 720 721 722 723 724 725 726 727 728 729
}


void UBPersistenceManager::generatePathIfNeeded(UBDocumentProxy* pDocumentProxy)
{
    if (pDocumentProxy->persistencePath().length() == 0)
    {
        pDocumentProxy->setPersistencePath(generateUniqueDocumentPath());
    }
}


Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
730
bool UBPersistenceManager::addDirectoryContentToDocument(const QString& documentRootFolder, UBDocumentProxy* pDocument)
Claudio Valerio's avatar
Claudio Valerio committed
731
{
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
732 733 734
    QStringList sourceScenes = getSceneFileNames(documentRootFolder);
    if (sourceScenes.empty())
        return false;
Claudio Valerio's avatar
Claudio Valerio committed
735 736 737

    int targetPageCount = pDocument->pageCount();

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
738
    for(int sourceIndex = 0 ; sourceIndex < sourceScenes.size(); sourceIndex++)
Claudio Valerio's avatar
Claudio Valerio committed
739 740 741
    {
        int targetIndex = targetPageCount + sourceIndex;

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
742 743 744
        QFile svg(documentRootFolder + "/" + sourceScenes[sourceIndex]);
        if (!svg.copy(pDocument->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.svg", targetIndex)))
            return false;
Claudio Valerio's avatar
Claudio Valerio committed
745 746 747

        UBSvgSubsetAdaptor::setSceneUuid(pDocument, targetIndex, QUuid::createUuid());

748
        QFile thumb(documentRootFolder + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", sourceIndex));
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
749
        // We can ignore error in this case, thumbnail will be genarated
750
        thumb.copy(pDocument->persistencePath() + UBFileSystemUtils::digitFileFormat("/page%1.thumbnail.jpg", targetIndex));
Claudio Valerio's avatar
Claudio Valerio committed
751 752 753 754 755
    }

    foreach(QString dir, mDocumentSubDirectories)
    {
        qDebug() << "copying " << documentRootFolder << "/" << dir << " to " << pDocument->persistencePath() << "/" + dir;
Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
756 757 758 759 760
        
        QDir srcDir(documentRootFolder + "/" + dir);
        if (srcDir.exists())
            if (!UBFileSystemUtils::copyDir(documentRootFolder + "/" + dir, pDocument->persistencePath() + "/" + dir))
                return false;
Claudio Valerio's avatar
Claudio Valerio committed
761 762 763 764
    }

    pDocument->setPageCount(sceneCount(pDocument));

Anatoly Mihalchenko's avatar
Anatoly Mihalchenko committed
765
    return false;
Claudio Valerio's avatar
Claudio Valerio committed
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 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
}


void UBPersistenceManager::upgradeDocumentIfNeeded(UBDocumentProxy* pDocumentProxy)
{
    int pageCount = pDocumentProxy->pageCount();

    for(int index = 0 ; index < pageCount; index++)
    {
        UBSvgSubsetAdaptor::upgradeScene(pDocumentProxy, index);
    }

    pDocumentProxy->setMetaData(UBSettings::documentVersion, UBSettings::currentFileVersion);

    UBMetadataDcSubsetAdaptor::persist(pDocumentProxy);
}


void UBPersistenceManager::upgradeAllDocumentsIfNeeded()
{
    foreach(QPointer<UBDocumentProxy> proxy, documentProxies)
    {
        upgradeDocumentIfNeeded(proxy);
    }
}



UBDocumentProxy* UBPersistenceManager::documentByUuid(const QUuid& pUuid)
{
    for(int i = 0 ; i < documentProxies.length(); i++)
    {
        UBDocumentProxy* proxy = documentProxies.at(i);

        if (proxy && proxy->uuid() == pUuid)
        {
            return proxy;
        }
    }

    return 0;

}


bool UBPersistenceManager::isEmpty(UBDocumentProxy* pDocumentProxy)
{
    if(!pDocumentProxy)
        return true;

    if (pDocumentProxy->pageCount() > 1)
        return false;

    UBGraphicsScene *theSoleScene = UBSvgSubsetAdaptor::loadScene(pDocumentProxy, 0);

    bool empty = false;

    if (theSoleScene)
    {
        empty = theSoleScene->isEmpty();
        delete theSoleScene;
    }
    else
    {
        empty = true;
    }

    return empty;
}


void UBPersistenceManager::purgeEmptyDocuments()
{
    if(!mHasPurgedDocuments) // hack to workaround the fact that app closing is called twice :-(
    {
        QList<UBDocumentProxy*> toBeDeleted;

        foreach(UBDocumentProxy* docProxy, mDocumentCreatedDuringSession)
        {
            if (isEmpty(docProxy))
            {
                toBeDeleted << docProxy;
            }
        }

        foreach(UBDocumentProxy* docProxy, toBeDeleted)
        {
            deleteDocument(docProxy);
        }

        mHasPurgedDocuments = true;
    }
}

860 861 862 863 864 865 866
QString UBPersistenceManager::teacherGuideAbsoluteObjectPath(UBDocumentProxy* pDocumentProxy)
{
    return pDocumentProxy->persistencePath() + "/" + teacherGuideDirectory;
}

QString UBPersistenceManager::addObjectToTeacherGuideDirectory(UBDocumentProxy* pDocumentProxy, QString pPath)
{
Claudio Valerio's avatar
Claudio Valerio committed
867
    QString path = UBFileSystemUtils::removeLocalFilePrefix(pPath);
868
	QFileInfo fi(path);
869 870 871 872 873 874 875 876 877 878 879 880 881
    QString uuid = QUuid::createUuid();

    if (!fi.exists() || !pDocumentProxy)
        return "";

    QString fileName = UBPersistenceManager::teacherGuideDirectory + "/" + uuid + "." + fi.suffix();

    QString destPath = pDocumentProxy->persistencePath() + "/" + fileName;

    if (!QFile::exists(destPath)){
        QDir dir;
        dir.mkdir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::teacherGuideDirectory);

882
        QFile source(path);
883 884 885 886 887 888 889

        source.copy(destPath);
    }

    return destPath;
}

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
QString UBPersistenceManager::addWidgetToTeacherGuideDirectory(UBDocumentProxy* pDocumentProxy, QString pPath)
{
    QString path = UBFileSystemUtils::removeLocalFilePrefix(pPath);
    QFileInfo fi(path);
    Q_ASSERT(fi.isDir());

    int lastIndex = path.lastIndexOf(".");
    QString extension("");
    if(lastIndex != -1)
        extension = path.right(path.length() - lastIndex);

    QString uuid = QUuid::createUuid();

    if (!fi.exists() || !pDocumentProxy)
        return "";

    QString directoryName = UBPersistenceManager::teacherGuideDirectory + "/" + uuid + extension;
    QString destPath = pDocumentProxy->persistencePath() + "/" + directoryName;

    if (!QDir(destPath).exists()){
        QDir dir;
        dir.mkdir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::teacherGuideDirectory);
        UBFileSystemUtils::copyDir(path,destPath);
    }

    return destPath;
}

918 919 920 921 922 923
bool UBPersistenceManager::addFileToDocument(UBDocumentProxy* pDocumentProxy, 
                                                     QString path, 
                                                     const QString& subdir,
                                                     QUuid objectUuid,
                                                     QString& destinationPath,
                                                     QByteArray* data)
Claudio Valerio's avatar
Claudio Valerio committed
924
{
Claudio Valerio's avatar
Claudio Valerio committed
925
    Q_ASSERT(path.length());
Claudio Valerio's avatar
Claudio Valerio committed
926 927 928
    QFileInfo fi(path);

    if (!pDocumentProxy || objectUuid.isNull())
929 930 931
        return false;
    if (data == NULL && !fi.exists())
        return false;
Claudio Valerio's avatar
Claudio Valerio committed
932

Claudio Valerio's avatar
Claudio Valerio committed
933 934
    qDebug() << fi.suffix();

935
    QString fileName = subdir + "/" + objectUuid.toString() + "." + fi.suffix();
Claudio Valerio's avatar
Claudio Valerio committed
936

937
    destinationPath = pDocumentProxy->persistencePath() + "/" + fileName;
Claudio Valerio's avatar
Claudio Valerio committed
938

939
    if (!QFile::exists(destinationPath))
Claudio Valerio's avatar
Claudio Valerio committed
940 941
    {
        QDir dir;
942 943 944
        dir.mkdir(pDocumentProxy->persistencePath() + "/" + subdir);
        if (!QFile::exists(pDocumentProxy->persistencePath() + "/" + subdir))
            return false;
Claudio Valerio's avatar
Claudio Valerio committed
945

946
        if (data == NULL)
Claudio Valerio's avatar
Claudio Valerio committed
947
        {
948 949
            QFile source(path);
            return source.copy(destinationPath);
Claudio Valerio's avatar
Claudio Valerio committed
950
        }
951
        else
Claudio Valerio's avatar
Claudio Valerio committed
952
        {
953 954 955 956 957 958 959 960 961 962 963 964 965
            QFile newFile(destinationPath);

            if (newFile.open(QIODevice::WriteOnly))
            {
                qint64 n = newFile.write(*data);
                newFile.flush();
                newFile.close();
                return n == data->size();
            }
            else
            {
                return false;
            }
Claudio Valerio's avatar
Claudio Valerio committed
966 967
        }
    }
968
    else
Claudio Valerio's avatar
Claudio Valerio committed
969
    {
970
        return false;    
Claudio Valerio's avatar
Claudio Valerio committed
971 972
    }
}
973 974 975 976 977

bool UBPersistenceManager::addGraphicsWidgteToDocument(UBDocumentProxy *pDocumentProxy, 
                                                       QString path, 
                                                       QUuid objectUuid,
                                                       QString& destinationPath)
978 979 980 981
{
    QFileInfo fi(path);

    if (!fi.exists() || !pDocumentProxy || objectUuid.isNull())
982
        return false;
983 984 985

    QString widgetRootDir = path;
    QString extension = QFileInfo(widgetRootDir).suffix();
Claudio Valerio's avatar
Claudio Valerio committed
986

987
    destinationPath = pDocumentProxy->persistencePath() + "/" + widgetDirectory +  "/" + objectUuid.toString() + "." + extension;
988

989
    if (!QFile::exists(destinationPath)) {
990
        QDir dir;
991 992 993
        if (!dir.mkpath(destinationPath))
            return false;
        return UBFileSystemUtils::copyDir(widgetRootDir, destinationPath);
994
    }
995 996
    else
        return false;
997
}
Claudio Valerio's avatar
Claudio Valerio committed
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017


void UBPersistenceManager::documentRepositoryChanged(const QString& path)
{
    Q_UNUSED(path);
    checkIfDocumentRepositoryExists();
}


void UBPersistenceManager::checkIfDocumentRepositoryExists()
{
    QDir rp(mDocumentRepositoryPath);

    if (!rp.exists())
    {
        // we have lost the document repository ..

        QString humanPath = QDir::cleanPath(mDocumentRepositoryPath);
        humanPath = QDir::toNativeSeparators(humanPath);

1018
        UBApplication::mainWindow->warning(tr("Document Repository Loss"),tr("Sankore has lost access to the document repository '%1'. Unfortunately the application must shut down to avoid data corruption. Latest changes may be lost as well.").arg(humanPath));
Claudio Valerio's avatar
Claudio Valerio committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066

        UBApplication::quit();
    }
}


bool UBPersistenceManager::mayHaveVideo(UBDocumentProxy* pDocumentProxy)
{
    QDir videoDir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::videoDirectory);

    return videoDir.exists() && videoDir.entryInfoList().length() > 0;
}

bool UBPersistenceManager::mayHaveAudio(UBDocumentProxy* pDocumentProxy)
{
    QDir audioDir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::audioDirectory);

    return audioDir.exists() && audioDir.entryInfoList().length() > 0;
}

bool UBPersistenceManager::mayHavePDF(UBDocumentProxy* pDocumentProxy)
{
    QDir objectDir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::objectDirectory);

    QStringList filters;
    filters << "*.pdf";

    return objectDir.exists() && objectDir.entryInfoList(filters).length() > 0;
}


bool UBPersistenceManager::mayHaveSVGImages(UBDocumentProxy* pDocumentProxy)
{
    QDir imageDir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::imageDirectory);

    QStringList filters;
    filters << "*.svg";

    return imageDir.exists() && imageDir.entryInfoList(filters).length() > 0;
}


bool UBPersistenceManager::mayHaveWidget(UBDocumentProxy* pDocumentProxy)
{
    QDir widgetDir(pDocumentProxy->persistencePath() + "/" + UBPersistenceManager::widgetDirectory);

    return widgetDir.exists() && widgetDir.entryInfoList(QDir::Dirs).length() > 0;
}