projectmanager.cpp 41.8 KB
Newer Older
Till Theato's avatar
Till Theato committed
1
2
3
4
5
6
7
8
9
10
11
/*
Copyright (C) 2014  Till Theato <root@ttill.de>
This file is part of kdenlive. See www.kdenlive.org.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/

#include "projectmanager.h"
12
#include "bin/bin.h"
13
#include "bin/projectitemmodel.h"
Nicolas Carion's avatar
Nicolas Carion committed
14
15
#include "core.h"
#include "doc/kdenlivedoc.h"
16
#include "jobs/jobmanager.h"
Nicolas Carion's avatar
Nicolas Carion committed
17
18
#include "kdenlivesettings.h"
#include "mainwindow.h"
Till Theato's avatar
Till Theato committed
19
#include "monitor/monitormanager.h"
20
#include "profiles/profilemodel.hpp"
Till Theato's avatar
Till Theato committed
21
#include "project/dialogs/archivewidget.h"
22
#include "project/dialogs/backupwidget.h"
23
#include "project/dialogs/noteswidget.h"
Nicolas Carion's avatar
style    
Nicolas Carion committed
24
#include "project/dialogs/projectsettings.h"
25
#include "utils/thumbnailcache.hpp"
26
27
#include "xml/xml.hpp"

28
29
30
// Temporary for testing
#include "bin/model/markerlistmodel.hpp"

31
#include "profiles/profilerepository.hpp"
32
#include "project/notesplugin.h"
33
#include "timeline2/model/builders/meltBuilder.hpp"
34
#include "timeline2/view/timelinecontroller.h"
Nicolas Carion's avatar
linting    
Nicolas Carion committed
35
#include "timeline2/view/timelinewidget.h"
36

Till Theato's avatar
Till Theato committed
37
#include <KActionCollection>
38
#include <KJob>
Till Theato's avatar
Till Theato committed
39
#include <KMessageBox>
Nicolas Carion's avatar
Nicolas Carion committed
40
#include <KRecentDirs>
41
#include <klocalizedstring.h>
42

Nicolas Carion's avatar
Nicolas Carion committed
43
44
45
#include "kdenlive_debug.h"
#include <KConfigGroup>
#include <QAction>
Till Theato's avatar
Till Theato committed
46
#include <QCryptographicHash>
47
#include <QFileDialog>
Nicolas Carion's avatar
Nicolas Carion committed
48
#include <QLocale>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
49
50
#include <QMimeDatabase>
#include <QMimeType>
Nicolas Carion's avatar
Nicolas Carion committed
51
#include <QProgressDialog>
52
#include <QTimeZone>
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
53
#include <audiomixer/mixermanager.hpp>
Till Theato's avatar
Till Theato committed
54

55
56
57
58
59
60
61
62
63
static QString getProjectNameFilters(bool ark=true) {
    auto filter = i18n("Kdenlive project (*.kdenlive)");
    if (ark) {
        filter.append(";;" + i18n("Archived project (*.tar.gz)"));
    }
    return filter;
}


Nicolas Carion's avatar
Nicolas Carion committed
64
ProjectManager::ProjectManager(QObject *parent)
65
    : QObject(parent)
66
    , m_mainTimelineModel(nullptr)
Nicolas Carion's avatar
Nicolas Carion committed
67

Till Theato's avatar
Till Theato committed
68
69
{
    m_fileRevert = KStandardAction::revert(this, SLOT(slotRevert()), pCore->window()->actionCollection());
70
    m_fileRevert->setIcon(QIcon::fromTheme(QStringLiteral("document-revert")));
Till Theato's avatar
Till Theato committed
71
72
    m_fileRevert->setEnabled(false);

Nicolas Carion's avatar
Nicolas Carion committed
73
    QAction *a = KStandardAction::open(this, SLOT(openFile()), pCore->window()->actionCollection());
74
    a->setIcon(QIcon::fromTheme(QStringLiteral("document-open")));
Nicolas Carion's avatar
Nicolas Carion committed
75
    a = KStandardAction::saveAs(this, SLOT(saveFileAs()), pCore->window()->actionCollection());
76
    a->setIcon(QIcon::fromTheme(QStringLiteral("document-save-as")));
Nicolas Carion's avatar
Nicolas Carion committed
77
    a = KStandardAction::openNew(this, SLOT(newFile()), pCore->window()->actionCollection());
78
    a->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
79
    m_recentFilesAction = KStandardAction::openRecent(this, SLOT(openFile(QUrl)), pCore->window()->actionCollection());
80

81
    QAction *backupAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-undo")), i18n("Open Backup File"), this);
82
    pCore->window()->addAction(QStringLiteral("open_backup"), backupAction);
83
    connect(backupAction, SIGNAL(triggered(bool)), SLOT(slotOpenBackup()));
84
85

    m_notesPlugin = new NotesPlugin(this);
86
87

    m_autoSaveTimer.setSingleShot(true);
Laurent Montel's avatar
Laurent Montel committed
88
    connect(&m_autoSaveTimer, &QTimer::timeout, this, &ProjectManager::slotAutoSave);
89

90
91
    // Ensure the default data folder exist
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
92
    dir.mkpath(QStringLiteral(".backup"));
93
    dir.mkdir(QStringLiteral("titles"));
Till Theato's avatar
Till Theato committed
94
95
}

Nicolas Carion's avatar
Nicolas Carion committed
96
ProjectManager::~ProjectManager() = default;
Till Theato's avatar
Till Theato committed
97

98
void ProjectManager::slotLoadOnOpen()
Till Theato's avatar
Till Theato committed
99
{
100
101
    if (m_startUrl.isValid()) {
        openFile();
Laurent Montel's avatar
Laurent Montel committed
102
    } else if (KdenliveSettings::openlastproject()) {
103
        openLastFile();
Laurent Montel's avatar
Laurent Montel committed
104
105
    } else {
        newFile(false);
Till Theato's avatar
Till Theato committed
106
107
    }

Nicolas Carion's avatar
Nicolas Carion committed
108
    if (!m_loadClipsOnOpen.isEmpty() && (m_project != nullptr)) {
Laurent Montel's avatar
Laurent Montel committed
109
        const QStringList list = m_loadClipsOnOpen.split(QLatin1Char(','));
Laurent Montel's avatar
Laurent Montel committed
110
        QList<QUrl> urls;
Laurent Montel's avatar
Laurent Montel committed
111
112
        urls.reserve(list.count());
        for (const QString &path : list) {
Nicolas Carion's avatar
Nicolas Carion committed
113
            // qCDebug(KDENLIVE_LOG) << QDir::current().absoluteFilePath(path);
Till Theato's avatar
Till Theato committed
114
115
            urls << QUrl::fromLocalFile(QDir::current().absoluteFilePath(path));
        }
116
        pCore->bin()->droppedUrls(urls);
Till Theato's avatar
Till Theato committed
117
    }
118
119
120
    m_loadClipsOnOpen.clear();
}

Laurent Montel's avatar
Laurent Montel committed
121
void ProjectManager::init(const QUrl &projectUrl, const QString &clipList)
122
123
124
{
    m_startUrl = projectUrl;
    m_loadClipsOnOpen = clipList;
Till Theato's avatar
Till Theato committed
125
126
}

127
128
129
130
131
132
133
134
135
136
void ProjectManager::newFile(bool showProjectSettings)
{
    QString profileName = KdenliveSettings::default_profile();
    if (profileName.isEmpty()) {
        profileName = pCore->getCurrentProfile()->path();
    }
    newFile(profileName, showProjectSettings);
}

void ProjectManager::newFile(QString profileName, bool showProjectSettings)
Till Theato's avatar
Till Theato committed
137
{
138
    QUrl startFile = QUrl::fromLocalFile(KdenliveSettings::defaultprojectfolder() + QStringLiteral("/_untitled.kdenlive"));
139
    if (checkForBackupFile(startFile, true)) {
140
141
        return;
    }
Till Theato's avatar
Till Theato committed
142
    m_fileRevert->setEnabled(false);
143
    QString projectFolder;
Laurent Montel's avatar
Laurent Montel committed
144
145
    QMap<QString, QString> documentProperties;
    QMap<QString, QString> documentMetadata;
Till Theato's avatar
Till Theato committed
146
    QPoint projectTracks(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks());
147
    pCore->monitorManager()->resetDisplay();
148
149
    QString documentId = QString::number(QDateTime::currentMSecsSinceEpoch());
    documentProperties.insert(QStringLiteral("documentid"), documentId);
Till Theato's avatar
Till Theato committed
150
    if (!showProjectSettings) {
Till Theato's avatar
Till Theato committed
151
152
        if (!closeCurrentDocument()) {
            return;
Till Theato's avatar
Till Theato committed
153
        }
154
155
        if (KdenliveSettings::customprojectfolder()) {
            projectFolder = KdenliveSettings::defaultprojectfolder();
156
            if (!projectFolder.endsWith(QLatin1Char('/'))) {
Laurent Montel's avatar
Laurent Montel committed
157
                projectFolder.append(QLatin1Char('/'));
158
159
            }
            documentProperties.insert(QStringLiteral("storagefolder"), projectFolder + documentId);
160
        }
Till Theato's avatar
Till Theato committed
161
    } else {
Nicolas Carion's avatar
Nicolas Carion committed
162
163
        QPointer<ProjectSettings> w = new ProjectSettings(nullptr, QMap<QString, QString>(), QStringList(), projectTracks.x(), projectTracks.y(),
                                                          KdenliveSettings::defaultprojectfolder(), false, true, pCore->window());
Laurent Montel's avatar
Laurent Montel committed
164
        connect(w.data(), &ProjectSettings::refreshProfiles, pCore->window(), &MainWindow::slotRefreshProfiles);
Till Theato's avatar
Till Theato committed
165
166
167
168
        if (w->exec() != QDialog::Accepted) {
            delete w;
            return;
        }
Till Theato's avatar
Till Theato committed
169
170
171
        if (!closeCurrentDocument()) {
            delete w;
            return;
Till Theato's avatar
Till Theato committed
172
173
174
175
176
177
178
179
        }
        if (KdenliveSettings::videothumbnails() != w->enableVideoThumbs()) {
            pCore->window()->slotSwitchVideoThumbs();
        }
        if (KdenliveSettings::audiothumbnails() != w->enableAudioThumbs()) {
            pCore->window()->slotSwitchAudioThumbs();
        }
        profileName = w->selectedProfile();
180
        projectFolder = w->storageFolder();
Till Theato's avatar
Till Theato committed
181
        projectTracks = w->tracks();
Nicolas Carion's avatar
Nicolas Carion committed
182
183
        documentProperties.insert(QStringLiteral("enableproxy"), QString::number((int)w->useProxy()));
        documentProperties.insert(QStringLiteral("generateproxy"), QString::number((int)w->generateProxy()));
184
185
186
        documentProperties.insert(QStringLiteral("proxyminsize"), QString::number(w->proxyMinSize()));
        documentProperties.insert(QStringLiteral("proxyparams"), w->proxyParams());
        documentProperties.insert(QStringLiteral("proxyextension"), w->proxyExtension());
Nicolas Carion's avatar
Nicolas Carion committed
187
        documentProperties.insert(QStringLiteral("generateimageproxy"), QString::number((int)w->generateImageProxy()));
188
189
        QString preview = w->selectedPreview();
        if (!preview.isEmpty()) {
Laurent Montel's avatar
Laurent Montel committed
190
191
            documentProperties.insert(QStringLiteral("previewparameters"), preview.section(QLatin1Char(';'), 0, 0));
            documentProperties.insert(QStringLiteral("previewextension"), preview.section(QLatin1Char(';'), 1, 1));
192
        }
193
        documentProperties.insert(QStringLiteral("proxyimageminsize"), QString::number(w->proxyImageMinSize()));
194
        if (!projectFolder.isEmpty()) {
195
            if (!projectFolder.endsWith(QLatin1Char('/'))) {
Laurent Montel's avatar
Laurent Montel committed
196
                projectFolder.append(QLatin1Char('/'));
197
            }
Nicolas Carion's avatar
Nicolas Carion committed
198
            documentProperties.insert(QStringLiteral("storagefolder"), projectFolder + documentId);
199
        }
Till Theato's avatar
Till Theato committed
200
201
202
203
        documentMetadata = w->metadata();
        delete w;
    }
    bool openBackup;
204
    m_notesPlugin->clear();
205
    documentProperties.insert(QStringLiteral("decimalPoint"), QLocale().decimalPoint());
Nicolas Carion's avatar
Nicolas Carion committed
206
    KdenliveDoc *doc = new KdenliveDoc(QUrl(), projectFolder, pCore->window()->m_commandStack, profileName, documentProperties, documentMetadata, projectTracks,
207
                                       &openBackup, pCore->window());
208
    doc->m_autosave = new KAutoSaveFile(startFile, doc);
209
    ThumbnailCache::get()->clearCache();
210
    pCore->bin()->setDocument(doc);
211
    m_project = doc;
212
213
    pCore->monitorManager()->activateMonitor(Kdenlive::ProjectMonitor);
    updateTimeline(0);
214
    pCore->window()->connectDocument();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
215
    pCore->mixer()->setModel(m_mainTimelineModel);
216
217
    bool disabled = m_project->getDocumentProperty(QStringLiteral("disabletimelineeffects")) == QLatin1String("1");
    QAction *disableEffects = pCore->window()->actionCollection()->action(QStringLiteral("disable_timeline_effects"));
218
219
220
221
222
223
224
    if (disableEffects) {
        if (disabled != disableEffects->isChecked()) {
            disableEffects->blockSignals(true);
            disableEffects->setChecked(disabled);
            disableEffects->blockSignals(false);
        }
    }
225
    emit docOpened(m_project);
226
    m_lastSave.start();
Till Theato's avatar
Till Theato committed
227
228
}

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
229
bool ProjectManager::closeCurrentDocument(bool saveChanges, bool quit)
Till Theato's avatar
Till Theato committed
230
{
Nicolas Carion's avatar
Nicolas Carion committed
231
    if ((m_project != nullptr) && m_project->isModified() && saveChanges) {
Till Theato's avatar
Till Theato committed
232
233
234
235
236
237
238
239
        QString message;
        if (m_project->url().fileName().isEmpty()) {
            message = i18n("Save changes to document?");
        } else {
            message = i18n("The project <b>\"%1\"</b> has been changed.\nDo you want to save your changes?", m_project->url().fileName());
        }

        switch (KMessageBox::warningYesNoCancel(pCore->window(), message)) {
Nicolas Carion's avatar
Nicolas Carion committed
240
        case KMessageBox::Yes:
Till Theato's avatar
Till Theato committed
241
            // save document here. If saving fails, return false;
Nicolas Carion's avatar
Nicolas Carion committed
242
            if (!saveFile()) {
Till Theato's avatar
Till Theato committed
243
244
                return false;
            }
Till Theato's avatar
Till Theato committed
245
            break;
Nicolas Carion's avatar
Nicolas Carion committed
246
        case KMessageBox::Cancel:
Till Theato's avatar
Till Theato committed
247
248
249
250
251
252
            return false;
            break;
        default:
            break;
        }
    }
253
    pCore->jobManager()->slotCancelJobs();
254
    disconnect(pCore->window()->getMainTimeline()->controller(), &TimelineController::durationChanged, this, &ProjectManager::adjustProjectDuration);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
255
    pCore->window()->getMainTimeline()->controller()->clipActions.clear();
256
    pCore->window()->getMainTimeline()->controller()->prepareClose();
257
258
259
    if (m_mainTimelineModel) {
        m_mainTimelineModel->prepareClose();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
260
    if (!quit && !qApp->isSavingSession()) {
Laurent Montel's avatar
Laurent Montel committed
261
        m_autoSaveTimer.stop();
262
        if (m_project) {
263
            pCore->jobManager()->slotCancelJobs();
264
            pCore->bin()->abortOperations();
Laurent Montel's avatar
Laurent Montel committed
265
            pCore->monitorManager()->clipMonitor()->slotOpenClip(nullptr);
266
            pCore->window()->clearAssetPanel();
267
            delete m_project;
Laurent Montel's avatar
Laurent Montel committed
268
            m_project = nullptr;
269
        }
270
    }
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    /*  // Make sure to reset locale to system's default
        QString requestedLocale = QLocale::system().name();
        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        if (env.contains(QStringLiteral("LC_NUMERIC"))) {
            requestedLocale = env.value(QStringLiteral("LC_NUMERIC"));
        }
        qDebug()<<"//////////// RESETTING LOCALE TO: "<<requestedLocale;

    #ifdef Q_OS_MAC
        setlocale(LC_NUMERIC_MASK, requestedLocale.toUtf8().constData());
    #elif defined(Q_OS_WIN)
        std::locale::global(std::locale(requestedLocale.toUtf8().constData()));
    #else
        QLocale newLocale(requestedLocale);
        char *separator = localeconv()->decimal_point;
        if (QString::fromUtf8(separator) != QString(newLocale.decimalPoint())) {
            pCore->displayBinMessage(i18n("There is a locale conflict on your system, project might get corrupt"), KMessageWidget::Warning);
        }
        setlocale(LC_NUMERIC, requestedLocale.toUtf8().constData());
    #endif
        QLocale::setDefault(newLocale);*/
Till Theato's avatar
Till Theato committed
292
293
294
295
296
    return true;
}

bool ProjectManager::saveFileAs(const QString &outputFileName)
{
297
    pCore->monitorManager()->pauseActiveMonitor();
298
299
    // Sync document properties
    prepareSave();
300
301
    QString saveFolder = QFileInfo(outputFileName).absolutePath();
    QString scene = projectSceneList(saveFolder);
302
303
304
305
306
307
308
    if (!m_replacementPattern.isEmpty()) {
        QMapIterator<QString, QString> i(m_replacementPattern);
        while (i.hasNext()) {
            i.next();
            scene.replace(i.key(), i.value());
        }
    }
Nicolas Carion's avatar
Nicolas Carion committed
309
    if (!m_project->saveSceneList(outputFileName, scene)) {
Till Theato's avatar
Till Theato committed
310
311
        return false;
    }
312
    QUrl url = QUrl::fromLocalFile(outputFileName);
Till Theato's avatar
Till Theato committed
313
    // Save timeline thumbnails
314
315
    QStringList thumbKeys = pCore->window()->getMainTimeline()->controller()->getThumbKeys();
    ThumbnailCache::get()->saveCachedThumbs(thumbKeys);
316
    m_project->setUrl(url);
317
    // setting up autosave file in ~/.kde/data/stalefiles/kdenlive/
318
    // saved under file name
319
320
    // actual saving by KdenliveDoc::slotAutoSave() called by a timer 3 seconds after the document has been edited
    // This timer is set by KdenliveDoc::setModified()
321
322
    const QString projectId = QCryptographicHash::hash(url.fileName().toUtf8(), QCryptographicHash::Md5).toHex();
    QUrl autosaveUrl = QUrl::fromLocalFile(QFileInfo(outputFileName).absoluteDir().absoluteFilePath(projectId + QStringLiteral(".kdenlive")));
Laurent Montel's avatar
Laurent Montel committed
323
    if (m_project->m_autosave == nullptr) {
324
325
        // The temporary file is not opened or created until actually needed.
        // The file filename does not have to exist for KAutoSaveFile to be constructed (if it exists, it will not be touched).
326
        m_project->m_autosave = new KAutoSaveFile(autosaveUrl, m_project);
Till Theato's avatar
Till Theato committed
327
    } else {
328
        m_project->m_autosave->setManagedFile(autosaveUrl);
Till Theato's avatar
Till Theato committed
329
330
    }

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
331
    pCore->window()->setWindowTitle(m_project->description());
Till Theato's avatar
Till Theato committed
332
    m_project->setModified(false);
333
334
    m_recentFilesAction->addUrl(url);
    // remember folder for next project opening
335
    KRecentDirs::add(QStringLiteral(":KdenliveProjectsFolder"), saveFolder);
336
    saveRecentFiles();
Till Theato's avatar
Till Theato committed
337
    m_fileRevert->setEnabled(true);
338
    pCore->window()->m_undoView->stack()->setClean();
Till Theato's avatar
Till Theato committed
339
340
341
342

    return true;
}

343
344
345
346
347
348
349
void ProjectManager::saveRecentFiles()
{
    KSharedConfigPtr config = KSharedConfig::openConfig();
    m_recentFilesAction->saveEntries(KConfigGroup(config, "Recent Files"));
    config->sync();
}

Till Theato's avatar
Till Theato committed
350
351
bool ProjectManager::saveFileAs()
{
352
    QFileDialog fd(pCore->window());
353
    fd.setDirectory(m_project->url().isValid() ? m_project->url().adjusted(QUrl::RemoveFilename).toLocalFile() : KdenliveSettings::defaultprojectfolder());
354
    fd.setNameFilter(getProjectNameFilters(false));
355
    fd.setAcceptMode(QFileDialog::AcceptSave);
356
    fd.setFileMode(QFileDialog::AnyFile);
357
    fd.setDefaultSuffix(QStringLiteral("kdenlive"));
358
    if (fd.exec() != QDialog::Accepted || fd.selectedFiles().isEmpty()) {
359
        return false;
360
    }
361
    
Laurent Montel's avatar
Laurent Montel committed
362
    QString outputFile = fd.selectedFiles().constFirst();
Till Theato's avatar
Till Theato committed
363

364
365
366
    bool ok = false;
    QDir cacheDir = m_project->getCacheDir(CacheBase, &ok);
    if (ok) {
Laurent Montel's avatar
Laurent Montel committed
367
        QFile file(cacheDir.absoluteFilePath(QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral(".") + outputFile))));
368
369
370
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        file.close();
    }
Till Theato's avatar
Till Theato committed
371
372
373
374
375
    return saveFileAs(outputFile);
}

bool ProjectManager::saveFile()
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
376
377
    if (!m_project) {
        // Calling saveFile before a project was created, something is wrong
Laurent Montel's avatar
Laurent Montel committed
378
        qCDebug(KDENLIVE_LOG) << "SaveFile called without project";
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
379
380
        return false;
    }
Till Theato's avatar
Till Theato committed
381
382
    if (m_project->url().isEmpty()) {
        return saveFileAs();
Nicolas Carion's avatar
Nicolas Carion committed
383
384
385
386
    }
    bool result = saveFileAs(m_project->url().toLocalFile());
    m_project->m_autosave->resize(0);
    return result;
Till Theato's avatar
Till Theato committed
387
388
389
390
}

void ProjectManager::openFile()
{
391
    if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
392
        openFile(m_startUrl);
393
        m_startUrl.clear();
Till Theato's avatar
Till Theato committed
394
395
        return;
    }
Nicolas Carion's avatar
Nicolas Carion committed
396
    QUrl url = QFileDialog::getOpenFileUrl(pCore->window(), QString(), QUrl::fromLocalFile(KRecentDirs::dir(QStringLiteral(":KdenliveProjectsFolder"))),
397
                                           getProjectNameFilters());
398
    if (!url.isValid()) {
Till Theato's avatar
Till Theato committed
399
400
        return;
    }
401
    KRecentDirs::add(QStringLiteral(":KdenliveProjectsFolder"), url.adjusted(QUrl::RemoveFilename).toLocalFile());
402
    m_recentFilesAction->addUrl(url);
403
    saveRecentFiles();
Till Theato's avatar
Till Theato committed
404
405
406
407
408
    openFile(url);
}

void ProjectManager::openLastFile()
{
409
    if (m_recentFilesAction->selectableActionGroup()->actions().isEmpty()) {
Till Theato's avatar
Till Theato committed
410
411
412
413
414
        // No files in history
        newFile(false);
        return;
    }

415
    QAction *firstUrlAction = m_recentFilesAction->selectableActionGroup()->actions().last();
Till Theato's avatar
Till Theato committed
416
417
418
419
420
421
422
    if (firstUrlAction) {
        firstUrlAction->trigger();
    } else {
        newFile(false);
    }
}

423
// fix mantis#3160 separate check from openFile() so we can call it from newFile()
424
// to find autosaved files (in ~/.local/share/stalefiles/kdenlive) and recover it
425
bool ProjectManager::checkForBackupFile(const QUrl &url, bool newFile)
426
{
427
    // Check for autosave file that belong to the url we passed in.
428
429
430
    const QString projectId = QCryptographicHash::hash(url.fileName().toUtf8(), QCryptographicHash::Md5).toHex();
    QUrl autosaveUrl = newFile ? url : QUrl::fromLocalFile(QFileInfo(url.path()).absoluteDir().absoluteFilePath(projectId + QStringLiteral(".kdenlive")));
    QList<KAutoSaveFile *> staleFiles = KAutoSaveFile::staleFiles(autosaveUrl);
Laurent Montel's avatar
Laurent Montel committed
431
    KAutoSaveFile *orphanedFile = nullptr;
Laurent Montel's avatar
Laurent Montel committed
432
    // Check if we can have a lock on one of the file,
433
    // meaning it is not handled by any Kdenlive instance
434
    if (!staleFiles.isEmpty()) {
Nicolas Carion's avatar
Nicolas Carion committed
435
        for (KAutoSaveFile *stale : staleFiles) {
436
            if (stale->open(QIODevice::QIODevice::ReadWrite)) {
Laurent Montel's avatar
Laurent Montel committed
437
438
439
                // Found orphaned autosave file
                orphanedFile = stale;
                break;
440
441
442
443
444
            }
        }
    }

    if (orphanedFile) {
Nicolas Carion's avatar
Nicolas Carion committed
445
        if (KMessageBox::questionYesNo(nullptr, i18n("Auto-saved files exist. Do you want to recover them now?"), i18n("File Recovery"),
Pino Toscano's avatar
Pino Toscano committed
446
                                       KGuiItem(i18n("Recover")), KGuiItem(i18n("Do not recover"))) == KMessageBox::Yes) {
447
            doOpenFile(url, orphanedFile);
448
            return true;
Nicolas Carion's avatar
Nicolas Carion committed
449
        }
450
    }
451
452
453
454
455
    // remove the stale files
    for (KAutoSaveFile *stale : staleFiles) {
        stale->open(QIODevice::ReadWrite);
        delete stale;
    }
456
457
458
    return false;
}

459
void ProjectManager::openFile(const QUrl &url)
Till Theato's avatar
Till Theato committed
460
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
461
    QMimeDatabase db;
Till Theato's avatar
Till Theato committed
462
    // Make sure the url is a Kdenlive project file
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
463
    QMimeType mime = db.mimeTypeForUrl(url);
464
    if (mime.inherits(QStringLiteral("application/x-compressed-tar"))) {
Till Theato's avatar
Till Theato committed
465
        // Opening a compressed project file, we need to process it
Nicolas Carion's avatar
Nicolas Carion committed
466
        // qCDebug(KDENLIVE_LOG)<<"Opening archive, processing";
Till Theato's avatar
Till Theato committed
467
468
        QPointer<ArchiveWidget> ar = new ArchiveWidget(url);
        if (ar->exec() == QDialog::Accepted) {
469
            openFile(QUrl::fromLocalFile(ar->extractedProjectFile()));
470
        } else if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
471
472
473
474
475
476
477
            // we tried to open an invalid file from command line, init new project
            newFile(false);
        }
        delete ar;
        return;
    }

478
    /*if (!url.fileName().endsWith(".kdenlive")) {
Till Theato's avatar
Till Theato committed
479
        // This is not a Kdenlive project file, abort loading
480
        KMessageBox::sorry(pCore->window(), i18n("File %1 is not a Kdenlive project file", url.toLocalFile()));
481
        if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
482
483
484
485
            // we tried to open an invalid file from command line, init new project
            newFile(false);
        }
        return;
486
    }*/
Till Theato's avatar
Till Theato committed
487

Nicolas Carion's avatar
Nicolas Carion committed
488
    if ((m_project != nullptr) && m_project->url() == url) {
Till Theato's avatar
Till Theato committed
489
490
491
        return;
    }

Till Theato's avatar
Till Theato committed
492
493
    if (!closeCurrentDocument()) {
        return;
Till Theato's avatar
Till Theato committed
494
    }
495
496
    if (checkForBackupFile(url)) {
        return;
Till Theato's avatar
Till Theato committed
497
    }
498
    pCore->displayMessage(i18n("Opening file %1", url.toLocalFile()), OperationCompletedMessage, 100);
Laurent Montel's avatar
Laurent Montel committed
499
    doOpenFile(url, nullptr);
Till Theato's avatar
Till Theato committed
500
501
}

502
void ProjectManager::doOpenFile(const QUrl &url, KAutoSaveFile *stale)
Till Theato's avatar
Till Theato committed
503
{
Laurent Montel's avatar
Laurent Montel committed
504
    Q_ASSERT(m_project == nullptr);
Till Theato's avatar
Till Theato committed
505
506
    m_fileRevert->setEnabled(true);

507
    delete m_progressDialog;
508
    ThumbnailCache::get()->clearCache();
509
    pCore->monitorManager()->resetDisplay();
510
    pCore->monitorManager()->activateMonitor(Kdenlive::ProjectMonitor);
511
512
    m_progressDialog = new QProgressDialog(pCore->window());
    m_progressDialog->setWindowTitle(i18n("Loading project"));
Laurent Montel's avatar
Laurent Montel committed
513
    m_progressDialog->setCancelButton(nullptr);
514
    m_progressDialog->setLabelText(i18n("Loading project"));
515
516
    m_progressDialog->setMaximum(0);
    m_progressDialog->show();
Till Theato's avatar
Till Theato committed
517
    bool openBackup;
518
    m_notesPlugin->clear();
Nicolas Carion's avatar
linting    
Nicolas Carion committed
519
520
521
522
    KdenliveDoc *doc = new KdenliveDoc(stale ? QUrl::fromLocalFile(stale->fileName()) : url, QString(), pCore->window()->m_commandStack,
                                       KdenliveSettings::default_profile().isEmpty() ? pCore->getCurrentProfile()->path() : KdenliveSettings::default_profile(),
                                       QMap<QString, QString>(), QMap<QString, QString>(),
                                       QPoint(KdenliveSettings::videotracks(), KdenliveSettings::audiotracks()), &openBackup, pCore->window());
Laurent Montel's avatar
Laurent Montel committed
523
    if (stale == nullptr) {
524
525
526
        const QString projectId = QCryptographicHash::hash(url.fileName().toUtf8(), QCryptographicHash::Md5).toHex();
        QUrl autosaveUrl = QUrl::fromLocalFile(QFileInfo(url.path()).absoluteDir().absoluteFilePath(projectId + QStringLiteral(".kdenlive")));
        stale = new KAutoSaveFile(autosaveUrl, doc);
Till Theato's avatar
Till Theato committed
527
528
529
        doc->m_autosave = stale;
    } else {
        doc->m_autosave = stale;
530
        stale->setParent(doc);
531
        // if loading from an autosave of unnamed file then keep unnamed
Laurent Montel's avatar
Laurent Montel committed
532
        if (url.fileName().contains(QStringLiteral("_untitled.kdenlive"))) {
533
            doc->setUrl(QUrl());
Laurent Montel's avatar
Laurent Montel committed
534
        } else {
535
            doc->setUrl(url);
Laurent Montel's avatar
Laurent Montel committed
536
        }
Till Theato's avatar
Till Theato committed
537
538
539
        doc->setModified(true);
        stale->setParent(doc);
    }
540
    m_progressDialog->setLabelText(i18n("Loading clips"));
541
    m_progressDialog->setMaximum(doc->clipsCount());
542
543

    // TODO refac delete this
544
    pCore->bin()->setDocument(doc);
Laurent Montel's avatar
Laurent Montel committed
545
    QList<QAction *> rulerActions;
546
547
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("set_render_timeline_zone"));
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("unset_render_timeline_zone"));
548
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("clear_render_timeline_zone"));
549
550

    // Set default target tracks to upper audio / lower video tracks
551
    m_project = doc;
552

553
554
555
556
557
    if (!updateTimeline(m_project->getDocumentProperty(QStringLiteral("position")).toInt())) {
        delete m_progressDialog;
        m_progressDialog = nullptr;
        return;
    }
558
    pCore->window()->connectDocument();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
559
    pCore->mixer()->setModel(m_mainTimelineModel);
560
    QDateTime documentDate = QFileInfo(m_project->url().toLocalFile()).lastModified();
561
562
563
    pCore->window()->getMainTimeline()->controller()->loadPreview(m_project->getDocumentProperty(QStringLiteral("previewchunks")),
                                                                  m_project->getDocumentProperty(QStringLiteral("dirtypreviewchunks")), documentDate,
                                                                  m_project->getDocumentProperty(QStringLiteral("disablepreview")).toInt());
564

565
    emit docOpened(m_project);
566
    pCore->displayMessage(QString(), OperationCompletedMessage, 100);
Till Theato's avatar
Till Theato committed
567
    if (openBackup) {
568
        slotOpenBackup(url);
Till Theato's avatar
Till Theato committed
569
    }
570
    m_lastSave.start();
571
    delete m_progressDialog;
Laurent Montel's avatar
Laurent Montel committed
572
    m_progressDialog = nullptr;
Till Theato's avatar
Till Theato committed
573
574
575
576
}

void ProjectManager::slotRevert()
{
Nicolas Carion's avatar
Nicolas Carion committed
577
578
579
580
    if (m_project->isModified() &&
        KMessageBox::warningContinueCancel(pCore->window(),
                                           i18n("This will delete all changes made since you last saved your project. Are you sure you want to continue?"),
                                           i18n("Revert to last saved version")) == KMessageBox::Cancel) {
Till Theato's avatar
Till Theato committed
581
582
        return;
    }
583
    QUrl url = m_project->url();
Laurent Montel's avatar
Laurent Montel committed
584
    if (closeCurrentDocument(false)) {
Laurent Montel's avatar
Laurent Montel committed
585
        doOpenFile(url, nullptr);
Laurent Montel's avatar
Laurent Montel committed
586
    }
Till Theato's avatar
Till Theato committed
587
588
}

Laurent Montel's avatar
Laurent Montel committed
589
KdenliveDoc *ProjectManager::current()
Till Theato's avatar
Till Theato committed
590
591
592
593
{
    return m_project;
}

594
bool ProjectManager::slotOpenBackup(const QUrl &url)
595
{
596
597
    QUrl projectFile;
    QUrl projectFolder;
598
    QString projectId;
599
    if (url.isValid()) {
600
        // we could not open the project file, guess where the backups are
601
        projectFolder = QUrl::fromLocalFile(KdenliveSettings::defaultprojectfolder());
602
603
        projectFile = url;
    } else {
604
        projectFolder = QUrl::fromLocalFile(m_project->projectTempFolder());
605
        projectFile = m_project->url();
606
        projectId = m_project->getDocumentProperty(QStringLiteral("documentid"));
607
    }
608
    bool result = false;
609
610
611
    QPointer<BackupWidget> dia = new BackupWidget(projectFile, projectFolder, projectId, pCore->window());
    if (dia->exec() == QDialog::Accepted) {
        QString requestedBackup = dia->selectedFile();
612
        m_project->backupLastSavedVersion(projectFile.toLocalFile());
613
        closeCurrentDocument(false);
Laurent Montel's avatar
Laurent Montel committed
614
        doOpenFile(QUrl::fromLocalFile(requestedBackup), nullptr);
Vincent Pinon's avatar
Vincent Pinon committed
615
616
617
618
        if (m_project) {
            m_project->setUrl(projectFile);
            m_project->setModified(true);
            pCore->window()->setWindowTitle(m_project->description());
619
            result = true;
Vincent Pinon's avatar
Vincent Pinon committed
620
        }
621
622
    }
    delete dia;
623
    return result;
624
625
}

Laurent Montel's avatar
Laurent Montel committed
626
KRecentFilesAction *ProjectManager::recentFilesAction()
627
628
629
630
{
    return m_recentFilesAction;
}

631
632
void ProjectManager::slotStartAutoSave()
{
633
634
635
636
    if (m_lastSave.elapsed() > 300000) {
        // If the project was not saved in the last 5 minute, force save
        m_autoSaveTimer.stop();
        slotAutoSave();
Laurent Montel's avatar
Laurent Montel committed
637
    } else {
638
639
        m_autoSaveTimer.start(3000); // will trigger slotAutoSave() in 3 seconds
    }
640
641
642
643
}

void ProjectManager::slotAutoSave()
{
644
    prepareSave();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
645
646
647
648
649
650
651
652
    QString saveFolder = m_project->url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toLocalFile();
    QString scene = projectSceneList(saveFolder);
    if (!m_replacementPattern.isEmpty()) {
        QMapIterator<QString, QString> i(m_replacementPattern);
        while (i.hasNext()) {
            i.next();
            scene.replace(i.key(), i.value());
        }
653
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
654
    m_project->slotAutoSave(scene);
655
    m_lastSave.start();
656
657
}

Laurent Montel's avatar
Laurent Montel committed
658
QString ProjectManager::projectSceneList(const QString &outputFolder)
659
{
660
    // Disable multitrack view and overlay
661
    bool isMultiTrack = pCore->monitorManager()->isMultiTrack();
662
    bool hasPreview = pCore->window()->getMainTimeline()->controller()->hasPreviewTrack();
663
664
665
    if (isMultiTrack) {
        pCore->window()->getMainTimeline()->controller()->slotMultitrackView(false, false);
    }
666
667
668
    if (hasPreview) {
        pCore->window()->getMainTimeline()->controller()->updatePreviewConnection(false);
    }
669
    pCore->mixer()->pauseMonitoring(true);
670
    QString scene = pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
671
    pCore->mixer()->pauseMonitoring(false);
672
673
    if (isMultiTrack) {
        pCore->window()->getMainTimeline()->controller()->slotMultitrackView(true, false);
674
    }
675
676
677
    if (hasPreview) {
        pCore->window()->getMainTimeline()->controller()->updatePreviewConnection(true);
    }
678
679
680
    return scene;
}

681
682
683
684
685
686
687
688
689
690
691
692
693
694
void ProjectManager::setDocumentNotes(const QString &notes)
{
    m_notesPlugin->widget()->setHtml(notes);
}

QString ProjectManager::documentNotes() const
{
    QString text = m_notesPlugin->widget()->toPlainText().simplified();
    if (text.isEmpty()) {
        return QString();
    }
    return m_notesPlugin->widget()->toHtml();
}

695
696
void ProjectManager::slotAddProjectNote()
{
697
    m_notesPlugin->showDock();
698
699
700
701
702
    m_notesPlugin->widget()->raise();
    m_notesPlugin->widget()->setFocus();
    m_notesPlugin->widget()->addProjectNote();
}

703
704
void ProjectManager::prepareSave()
{
705
    pCore->projectItemModel()->saveDocumentProperties(pCore->window()->getMainTimeline()->controller()->documentProperties(), m_project->metadata(),
Nicolas Carion's avatar
Nicolas Carion committed
706
                                                      m_project->getGuideModel());
707
708
    pCore->projectItemModel()->saveProperty(QStringLiteral("kdenlive:documentnotes"), documentNotes());
    pCore->projectItemModel()->saveProperty(QStringLiteral("kdenlive:docproperties.groups"), m_mainTimelineModel->groupsData());
709
710
}

711
712
713
714
715
void ProjectManager::slotResetProfiles()
{
    m_project->resetProfile();
    pCore->monitorManager()->updateScopeSource();
}
716

717
718
719
720
721
void ProjectManager::slotResetConsumers(bool fullReset)
{
    pCore->monitorManager()->resetConsumers(fullReset);
}

722
723
void ProjectManager::slotExpandClip()
{
724
725
    // TODO refac
    // m_trackView->projectView()->expandActiveClip();
726
727
}

728
void ProjectManager::disableBinEffects(bool disable)
729
{
730
731
    if (m_project) {
        if (disable) {
Nicolas Carion's avatar
Nicolas Carion committed
732
            m_project->setDocumentProperty(QStringLiteral("disablebineffects"), QString::number((int)true));
733
        } else {
734
            m_project->setDocumentProperty(QStringLiteral("disablebineffects"), QString());
735
        }
736
    }
737
738
    pCore->monitorManager()->refreshProjectMonitor();
    pCore->monitorManager()->refreshClipMonitor();
739
740
}

741
742
743
void ProjectManager::slotDisableTimelineEffects(bool disable)
{
    if (disable) {
Nicolas Carion's avatar
Nicolas Carion committed
744
        m_project->setDocumentProperty(QStringLiteral("disabletimelineeffects"), QString::number((int)true));
745
    } else {
746
        m_project->setDocumentProperty(QStringLiteral("disabletimelineeffects"), QString());
747
    }
748
749
    m_mainTimelineModel->setTimelineEffectsEnabled(!disable);
    pCore->monitorManager()->refreshProjectMonitor();
750
}
751

752
753
void ProjectManager::slotSwitchTrackLock()
{
754
    pCore->window()->getMainTimeline()->controller()->switchTrackLock();
755
756
}

757
758
759
760
761
void ProjectManager::slotSwitchTrackActive()
{
    pCore->window()->getMainTimeline()->controller()->switchTrackActive();
}

762
763
void ProjectManager::slotSwitchAllTrackLock()
{
764
    pCore->window()->getMainTimeline()->controller()->switchTrackLock(true);
765
766
}

767
768
void ProjectManager::slotSwitchTrackTarget()
{
769
    pCore->window()->getMainTimeline()->controller()->switchTargetTrack();
770
771
}

772
773
QString ProjectManager::getDefaultProjectFormat()
{
Nicolas Carion's avatar
Nicolas Carion committed
774
775
    // On first run, lets use an HD1080p profile with fps related to timezone country. Then, when the first video is added to a project, if it does not match
    // our profile, propose a new default.
776
777
778
    QTimeZone zone;
    zone = QTimeZone::systemTimeZone();

Laurent Montel's avatar
Laurent Montel committed
779
    QList<int> ntscCountries;
780
    ntscCountries << QLocale::Canada << QLocale::Chile << QLocale::CostaRica << QLocale::Cuba << QLocale::DominicanRepublic << QLocale::Ecuador;
Nicolas Carion's avatar
Nicolas Carion committed
781
782
    ntscCountries << QLocale::Japan << QLocale::Mexico << QLocale::Nicaragua << QLocale::Panama << QLocale::Peru << QLocale::Philippines;
    ntscCountries << QLocale::PuertoRico << QLocale::SouthKorea << QLocale::Taiwan << QLocale::UnitedStates;
783
    bool ntscProject = ntscCountries.contains(zone.country());
Laurent Montel's avatar
Laurent Montel committed
784
785
786
    if (!ntscProject) {
        return QStringLiteral("atsc_1080p_25");
    }
787
788
789
    return QStringLiteral("atsc_1080p_2997");
}

Laurent Montel's avatar
Laurent Montel committed
790
void ProjectManager::saveZone(const QStringList &info, const QDir &dir)
791
792
793
{
    pCore->bin()->saveZone(info, dir);
}
794

795
796
797
void ProjectManager::moveProjectData(const QString &src, const QString &dest)
{
    // Move tmp folder (thumbnails, timeline preview)
Laurent Montel's avatar
Laurent Montel committed
798
    KIO::CopyJob *copyJob = KIO::move(QUrl::fromLocalFile(src), QUrl::fromLocalFile(dest));
Laurent Montel's avatar
Laurent Montel committed
799
    connect(copyJob, &KJob::result, this, &ProjectManager::slotMoveFinished);
Laurent Montel's avatar
Laurent Montel committed
800
    connect(copyJob, SIGNAL(percent(KJob *, ulong)), this, SLOT(slotMoveProgress(KJob *, ulong)));
801
802
803
    m_project->moveProjectData(src, dest);
}

804
805
void ProjectManager::slotMoveProgress(KJob *, unsigned long progress)
{
806
    pCore->displayMessage(i18n("Moving project folder"), ProcessingJobMessage, static_cast<int>(progress));
807
808
809
810
811
}

void ProjectManager::slotMoveFinished(KJob *job)
{
    if (job->error() == 0) {
812
        pCore->displayMessage(QString(), OperationCompletedMessage, 100);
Nicolas Carion's avatar
Nicolas Carion committed
813
        auto *copyJob = static_cast<KIO::CopyJob *>(job);
814
        QString newFolder = copyJob->destUrl().toLocalFile();
815
816
        // Check if project folder is inside document folder, in which case, paths will be relative
        QDir projectDir(m_project->url().toString(QUrl::RemoveFilename | QUrl::RemoveScheme));