projectmanager.cpp 43.5 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
82
83
84
    QAction *saveCopyAction = new QAction(QIcon::fromTheme(QStringLiteral("document-save-as")), i18n("Save Copy…"), this);
    pCore->window()->addAction(QStringLiteral("file_save_copy"), saveCopyAction);
    connect(saveCopyAction,  &QAction::triggered, this, [this]{ saveFileAs(true); });

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

    m_notesPlugin = new NotesPlugin(this);
90
91

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

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
125
void ProjectManager::init(const QUrl &projectUrl, const QString &clipList)
126
127
128
{
    m_startUrl = projectUrl;
    m_loadClipsOnOpen = clipList;
Till Theato's avatar
Till Theato committed
129
130
}

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

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
239
bool ProjectManager::closeCurrentDocument(bool saveChanges, bool quit)
Till Theato's avatar
Till Theato committed
240
{
Nicolas Carion's avatar
Nicolas Carion committed
241
    if ((m_project != nullptr) && m_project->isModified() && saveChanges) {
Till Theato's avatar
Till Theato committed
242
243
244
245
246
247
248
249
        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
250
        case KMessageBox::Yes:
Till Theato's avatar
Till Theato committed
251
            // save document here. If saving fails, return false;
Nicolas Carion's avatar
Nicolas Carion committed
252
            if (!saveFile()) {
Till Theato's avatar
Till Theato committed
253
254
                return false;
            }
Till Theato's avatar
Till Theato committed
255
            break;
Nicolas Carion's avatar
Nicolas Carion committed
256
        case KMessageBox::Cancel:
Till Theato's avatar
Till Theato committed
257
258
259
260
261
262
            return false;
            break;
        default:
            break;
        }
    }
263
    pCore->jobManager()->slotCancelJobs();
264
    disconnect(pCore->window()->getMainTimeline()->controller(), &TimelineController::durationChanged, this, &ProjectManager::adjustProjectDuration);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
265
    pCore->window()->getMainTimeline()->controller()->clipActions.clear();
266
    pCore->window()->getMainTimeline()->controller()->prepareClose();
267
268
269
    if (m_mainTimelineModel) {
        m_mainTimelineModel->prepareClose();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
270
    if (!quit && !qApp->isSavingSession()) {
Laurent Montel's avatar
Laurent Montel committed
271
        m_autoSaveTimer.stop();
272
        if (m_project) {
273
            pCore->jobManager()->slotCancelJobs();
274
            pCore->bin()->abortOperations();
Laurent Montel's avatar
Laurent Montel committed
275
            pCore->monitorManager()->clipMonitor()->slotOpenClip(nullptr);
276
            pCore->window()->clearAssetPanel();
277
            delete m_project;
Laurent Montel's avatar
Laurent Montel committed
278
            m_project = nullptr;
279
        }
280
    }
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    /*  // 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
302
303
304
    return true;
}

305
bool ProjectManager::saveFileAs(const QString &outputFileName, bool saveACopy)
Till Theato's avatar
Till Theato committed
306
{
307
    pCore->monitorManager()->pauseActiveMonitor();
308
309
    // Sync document properties
    prepareSave();
310
311
    QString saveFolder = QFileInfo(outputFileName).absolutePath();
    QString scene = projectSceneList(saveFolder);
312
313
314
315
316
317
318
    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
319
    if (!m_project->saveSceneList(outputFileName, scene)) {
Till Theato's avatar
Till Theato committed
320
321
        return false;
    }
322
    QUrl url = QUrl::fromLocalFile(outputFileName);
Till Theato's avatar
Till Theato committed
323
    // Save timeline thumbnails
324
325
    QStringList thumbKeys = pCore->window()->getMainTimeline()->controller()->getThumbKeys();
    ThumbnailCache::get()->saveCachedThumbs(thumbKeys);
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
    if (!saveACopy) {
        m_project->setUrl(url);
        // setting up autosave file in ~/.kde/data/stalefiles/kdenlive/
        // saved under file name
        // actual saving by KdenliveDoc::slotAutoSave() called by a timer 3 seconds after the document has been edited
        // This timer is set by KdenliveDoc::setModified()
        const QString projectId = QCryptographicHash::hash(url.fileName().toUtf8(), QCryptographicHash::Md5).toHex();
        QUrl autosaveUrl = QUrl::fromLocalFile(QFileInfo(outputFileName).absoluteDir().absoluteFilePath(projectId + QStringLiteral(".kdenlive")));
        if (m_project->m_autosave == nullptr) {
            // 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).
            m_project->m_autosave = new KAutoSaveFile(autosaveUrl, m_project);
        } else {
            m_project->m_autosave->setManagedFile(autosaveUrl);
        }
Till Theato's avatar
Till Theato committed
341

342
343
344
        pCore->window()->setWindowTitle(m_project->description());
        m_project->setModified(false);
    }
345
346
    m_recentFilesAction->addUrl(url);
    // remember folder for next project opening
347
    KRecentDirs::add(QStringLiteral(":KdenliveProjectsFolder"), saveFolder);
348
    saveRecentFiles();
349
350
351
352
    if (!saveACopy) {
        m_fileRevert->setEnabled(true);
        pCore->window()->m_undoView->stack()->setClean();
    }
Till Theato's avatar
Till Theato committed
353
354
355
356

    return true;
}

357
358
359
360
361
362
363
void ProjectManager::saveRecentFiles()
{
    KSharedConfigPtr config = KSharedConfig::openConfig();
    m_recentFilesAction->saveEntries(KConfigGroup(config, "Recent Files"));
    config->sync();
}

364
bool ProjectManager::saveFileAs(bool saveACopy)
Till Theato's avatar
Till Theato committed
365
{
366
    QFileDialog fd(pCore->window());
367
368
369
    if (saveACopy) {
        fd.setWindowTitle(i18n("Save Copy"));
    }
370
    fd.setDirectory(m_project->url().isValid() ? m_project->url().adjusted(QUrl::RemoveFilename).toLocalFile() : KdenliveSettings::defaultprojectfolder());
371
    fd.setNameFilter(getProjectNameFilters(false));
372
    fd.setAcceptMode(QFileDialog::AcceptSave);
373
    fd.setFileMode(QFileDialog::AnyFile);
374
    fd.setDefaultSuffix(QStringLiteral("kdenlive"));
375
    if (fd.exec() != QDialog::Accepted || fd.selectedFiles().isEmpty()) {
376
        return false;
377
    }
378
    
Laurent Montel's avatar
Laurent Montel committed
379
    QString outputFile = fd.selectedFiles().constFirst();
Till Theato's avatar
Till Theato committed
380

381
382
383
    bool ok = false;
    QDir cacheDir = m_project->getCacheDir(CacheBase, &ok);
    if (ok) {
Laurent Montel's avatar
Laurent Montel committed
384
        QFile file(cacheDir.absoluteFilePath(QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral(".") + outputFile))));
385
386
387
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        file.close();
    }
388
    return saveFileAs(outputFile, saveACopy);
Till Theato's avatar
Till Theato committed
389
390
391
392
}

bool ProjectManager::saveFile()
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
393
394
    if (!m_project) {
        // Calling saveFile before a project was created, something is wrong
Laurent Montel's avatar
Laurent Montel committed
395
        qCDebug(KDENLIVE_LOG) << "SaveFile called without project";
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
396
397
        return false;
    }
Till Theato's avatar
Till Theato committed
398
399
    if (m_project->url().isEmpty()) {
        return saveFileAs();
Nicolas Carion's avatar
Nicolas Carion committed
400
401
402
403
    }
    bool result = saveFileAs(m_project->url().toLocalFile());
    m_project->m_autosave->resize(0);
    return result;
Till Theato's avatar
Till Theato committed
404
405
406
407
}

void ProjectManager::openFile()
{
408
    if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
409
        openFile(m_startUrl);
410
        m_startUrl.clear();
Till Theato's avatar
Till Theato committed
411
412
        return;
    }
Nicolas Carion's avatar
Nicolas Carion committed
413
    QUrl url = QFileDialog::getOpenFileUrl(pCore->window(), QString(), QUrl::fromLocalFile(KRecentDirs::dir(QStringLiteral(":KdenliveProjectsFolder"))),
414
                                           getProjectNameFilters());
415
    if (!url.isValid()) {
Till Theato's avatar
Till Theato committed
416
417
        return;
    }
418
    KRecentDirs::add(QStringLiteral(":KdenliveProjectsFolder"), url.adjusted(QUrl::RemoveFilename).toLocalFile());
419
    m_recentFilesAction->addUrl(url);
420
    saveRecentFiles();
Till Theato's avatar
Till Theato committed
421
422
423
424
425
    openFile(url);
}

void ProjectManager::openLastFile()
{
426
    if (m_recentFilesAction->selectableActionGroup()->actions().isEmpty()) {
Till Theato's avatar
Till Theato committed
427
428
429
430
431
        // No files in history
        newFile(false);
        return;
    }

432
    QAction *firstUrlAction = m_recentFilesAction->selectableActionGroup()->actions().last();
Till Theato's avatar
Till Theato committed
433
434
435
436
437
438
439
    if (firstUrlAction) {
        firstUrlAction->trigger();
    } else {
        newFile(false);
    }
}

440
// fix mantis#3160 separate check from openFile() so we can call it from newFile()
441
// to find autosaved files (in ~/.local/share/stalefiles/kdenlive) and recover it
442
bool ProjectManager::checkForBackupFile(const QUrl &url, bool newFile)
443
{
444
    // Check for autosave file that belong to the url we passed in.
445
446
447
    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
448
    KAutoSaveFile *orphanedFile = nullptr;
Laurent Montel's avatar
Laurent Montel committed
449
    // Check if we can have a lock on one of the file,
450
    // meaning it is not handled by any Kdenlive instance
451
    if (!staleFiles.isEmpty()) {
Nicolas Carion's avatar
Nicolas Carion committed
452
        for (KAutoSaveFile *stale : staleFiles) {
453
            if (stale->open(QIODevice::QIODevice::ReadWrite)) {
Laurent Montel's avatar
Laurent Montel committed
454
455
456
                // Found orphaned autosave file
                orphanedFile = stale;
                break;
457
458
459
460
461
            }
        }
    }

    if (orphanedFile) {
Nicolas Carion's avatar
Nicolas Carion committed
462
        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
463
                                       KGuiItem(i18n("Recover")), KGuiItem(i18n("Do not recover"))) == KMessageBox::Yes) {
464
            doOpenFile(url, orphanedFile);
465
            return true;
Nicolas Carion's avatar
Nicolas Carion committed
466
        }
467
    }
468
469
470
471
472
    // remove the stale files
    for (KAutoSaveFile *stale : staleFiles) {
        stale->open(QIODevice::ReadWrite);
        delete stale;
    }
473
474
475
    return false;
}

476
void ProjectManager::openFile(const QUrl &url)
Till Theato's avatar
Till Theato committed
477
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
478
    QMimeDatabase db;
Till Theato's avatar
Till Theato committed
479
    // Make sure the url is a Kdenlive project file
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
480
    QMimeType mime = db.mimeTypeForUrl(url);
481
    if (mime.inherits(QStringLiteral("application/x-compressed-tar"))) {
Till Theato's avatar
Till Theato committed
482
        // Opening a compressed project file, we need to process it
Nicolas Carion's avatar
Nicolas Carion committed
483
        // qCDebug(KDENLIVE_LOG)<<"Opening archive, processing";
Till Theato's avatar
Till Theato committed
484
485
        QPointer<ArchiveWidget> ar = new ArchiveWidget(url);
        if (ar->exec() == QDialog::Accepted) {
486
            openFile(QUrl::fromLocalFile(ar->extractedProjectFile()));
487
        } else if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
488
489
490
491
492
493
494
            // we tried to open an invalid file from command line, init new project
            newFile(false);
        }
        delete ar;
        return;
    }

495
    /*if (!url.fileName().endsWith(".kdenlive")) {
Till Theato's avatar
Till Theato committed
496
        // This is not a Kdenlive project file, abort loading
497
        KMessageBox::sorry(pCore->window(), i18n("File %1 is not a Kdenlive project file", url.toLocalFile()));
498
        if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
499
500
501
502
            // we tried to open an invalid file from command line, init new project
            newFile(false);
        }
        return;
503
    }*/
Till Theato's avatar
Till Theato committed
504

Nicolas Carion's avatar
Nicolas Carion committed
505
    if ((m_project != nullptr) && m_project->url() == url) {
Till Theato's avatar
Till Theato committed
506
507
508
        return;
    }

Till Theato's avatar
Till Theato committed
509
510
    if (!closeCurrentDocument()) {
        return;
Till Theato's avatar
Till Theato committed
511
    }
512
513
    if (checkForBackupFile(url)) {
        return;
Till Theato's avatar
Till Theato committed
514
    }
515
    pCore->displayMessage(i18n("Opening file %1", url.toLocalFile()), OperationCompletedMessage, 100);
Laurent Montel's avatar
Laurent Montel committed
516
    doOpenFile(url, nullptr);
Till Theato's avatar
Till Theato committed
517
518
}

519
void ProjectManager::doOpenFile(const QUrl &url, KAutoSaveFile *stale)
Till Theato's avatar
Till Theato committed
520
{
Laurent Montel's avatar
Laurent Montel committed
521
    Q_ASSERT(m_project == nullptr);
Till Theato's avatar
Till Theato committed
522
523
    m_fileRevert->setEnabled(true);

524
    delete m_progressDialog;
525
    ThumbnailCache::get()->clearCache();
526
    pCore->monitorManager()->resetDisplay();
527
    pCore->monitorManager()->activateMonitor(Kdenlive::ProjectMonitor);
528
529
    m_progressDialog = new QProgressDialog(pCore->window());
    m_progressDialog->setWindowTitle(i18n("Loading project"));
Laurent Montel's avatar
Laurent Montel committed
530
    m_progressDialog->setCancelButton(nullptr);
531
    m_progressDialog->setLabelText(i18n("Loading project"));
532
533
    m_progressDialog->setMaximum(0);
    m_progressDialog->show();
Till Theato's avatar
Till Theato committed
534
    bool openBackup;
535
    m_notesPlugin->clear();
536
537
538
539
540
541
    int audioChannels = 2;
    if (KdenliveSettings::audio_channels() == 1) {
        audioChannels = 4;
    } else if (KdenliveSettings::audio_channels() == 2) {
        audioChannels = 6;
    }
542

Nicolas Carion's avatar
linting    
Nicolas Carion committed
543
544
545
    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>(),
546
                                       {KdenliveSettings::videotracks(), KdenliveSettings::audiotracks()}, audioChannels, &openBackup, pCore->window());
Laurent Montel's avatar
Laurent Montel committed
547
    if (stale == nullptr) {
548
549
550
        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
551
552
553
        doc->m_autosave = stale;
    } else {
        doc->m_autosave = stale;
554
        stale->setParent(doc);
555
556
        // if loading from an autosave of unnamed file, or restor failed then keep unnamed
        bool loadingFailed = doc->url().isEmpty();
Laurent Montel's avatar
Laurent Montel committed
557
        if (url.fileName().contains(QStringLiteral("_untitled.kdenlive"))) {
558
            doc->setUrl(QUrl());
559
560
            doc->setModified(true);
        } else if (!loadingFailed) {
561
            doc->setUrl(url);
Laurent Montel's avatar
Laurent Montel committed
562
        }
563
        doc->setModified(!loadingFailed);
Till Theato's avatar
Till Theato committed
564
565
        stale->setParent(doc);
    }
566
    m_progressDialog->setLabelText(i18n("Loading clips"));
567
    m_progressDialog->setMaximum(doc->clipsCount());
568
569

    // TODO refac delete this
570
    pCore->bin()->setDocument(doc);
Laurent Montel's avatar
Laurent Montel committed
571
    QList<QAction *> rulerActions;
572
573
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("set_render_timeline_zone"));
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("unset_render_timeline_zone"));
574
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("clear_render_timeline_zone"));
575
576

    // Set default target tracks to upper audio / lower video tracks
577
    m_project = doc;
578

579
580
581
582
583
    if (!updateTimeline(m_project->getDocumentProperty(QStringLiteral("position")).toInt())) {
        delete m_progressDialog;
        m_progressDialog = nullptr;
        return;
    }
584
    pCore->window()->connectDocument();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
585
    pCore->mixer()->setModel(m_mainTimelineModel);
586
    QDateTime documentDate = QFileInfo(m_project->url().toLocalFile()).lastModified();
587
588
589
    pCore->window()->getMainTimeline()->controller()->loadPreview(m_project->getDocumentProperty(QStringLiteral("previewchunks")),
                                                                  m_project->getDocumentProperty(QStringLiteral("dirtypreviewchunks")), documentDate,
                                                                  m_project->getDocumentProperty(QStringLiteral("disablepreview")).toInt());
590

591
    emit docOpened(m_project);
592
    pCore->displayMessage(QString(), OperationCompletedMessage, 100);
Till Theato's avatar
Till Theato committed
593
    if (openBackup) {
594
        slotOpenBackup(url);
Till Theato's avatar
Till Theato committed
595
    }
596
    m_lastSave.start();
597
    delete m_progressDialog;
Laurent Montel's avatar
Laurent Montel committed
598
    m_progressDialog = nullptr;
Till Theato's avatar
Till Theato committed
599
600
601
602
}

void ProjectManager::slotRevert()
{
Nicolas Carion's avatar
Nicolas Carion committed
603
604
605
606
    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
607
608
        return;
    }
609
    QUrl url = m_project->url();
Laurent Montel's avatar
Laurent Montel committed
610
    if (closeCurrentDocument(false)) {
Laurent Montel's avatar
Laurent Montel committed
611
        doOpenFile(url, nullptr);
Laurent Montel's avatar
Laurent Montel committed
612
    }
Till Theato's avatar
Till Theato committed
613
614
}

Laurent Montel's avatar
Laurent Montel committed
615
KdenliveDoc *ProjectManager::current()
Till Theato's avatar
Till Theato committed
616
617
618
619
{
    return m_project;
}

620
bool ProjectManager::slotOpenBackup(const QUrl &url)
621
{
622
623
    QUrl projectFile;
    QUrl projectFolder;
624
    QString projectId;
625
    if (url.isValid()) {
626
        // we could not open the project file, guess where the backups are
627
        projectFolder = QUrl::fromLocalFile(KdenliveSettings::defaultprojectfolder());
628
629
        projectFile = url;
    } else {
630
        projectFolder = QUrl::fromLocalFile(m_project->projectTempFolder());
631
        projectFile = m_project->url();
632
        projectId = m_project->getDocumentProperty(QStringLiteral("documentid"));
633
    }
634
    bool result = false;
635
636
637
    QPointer<BackupWidget> dia = new BackupWidget(projectFile, projectFolder, projectId, pCore->window());
    if (dia->exec() == QDialog::Accepted) {
        QString requestedBackup = dia->selectedFile();
638
        m_project->backupLastSavedVersion(projectFile.toLocalFile());
639
        closeCurrentDocument(false);
Laurent Montel's avatar
Laurent Montel committed
640
        doOpenFile(QUrl::fromLocalFile(requestedBackup), nullptr);
Vincent Pinon's avatar
Vincent Pinon committed
641
        if (m_project) {
642
643
644
645
646
            if (!m_project->url().isEmpty()) {
                // Only update if restore succeeded
                m_project->setUrl(projectFile);
                m_project->setModified(true);
            }
Vincent Pinon's avatar
Vincent Pinon committed
647
            pCore->window()->setWindowTitle(m_project->description());
648
            result = true;
Vincent Pinon's avatar
Vincent Pinon committed
649
        }
650
651
    }
    delete dia;
652
    return result;
653
654
}

Laurent Montel's avatar
Laurent Montel committed
655
KRecentFilesAction *ProjectManager::recentFilesAction()
656
657
658
659
{
    return m_recentFilesAction;
}

660
661
void ProjectManager::slotStartAutoSave()
{
662
663
664
665
    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
666
    } else {
667
668
        m_autoSaveTimer.start(3000); // will trigger slotAutoSave() in 3 seconds
    }
669
670
671
672
}

void ProjectManager::slotAutoSave()
{
673
    prepareSave();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
674
675
676
677
678
679
680
681
    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());
        }
682
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
683
    m_project->slotAutoSave(scene);
684
    m_lastSave.start();
685
686
}

Laurent Montel's avatar
Laurent Montel committed
687
QString ProjectManager::projectSceneList(const QString &outputFolder)
688
{
689
    // Disable multitrack view and overlay
690
    bool isMultiTrack = pCore->monitorManager()->isMultiTrack();
691
    bool hasPreview = pCore->window()->getMainTimeline()->controller()->hasPreviewTrack();
692
693
694
    if (isMultiTrack) {
        pCore->window()->getMainTimeline()->controller()->slotMultitrackView(false, false);
    }
695
696
697
    if (hasPreview) {
        pCore->window()->getMainTimeline()->controller()->updatePreviewConnection(false);
    }
698
    pCore->mixer()->pauseMonitoring(true);
699
    QString scene = pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
700
    pCore->mixer()->pauseMonitoring(false);
701
702
    if (isMultiTrack) {
        pCore->window()->getMainTimeline()->controller()->slotMultitrackView(true, false);
703
    }
704
705
706
    if (hasPreview) {
        pCore->window()->getMainTimeline()->controller()->updatePreviewConnection(true);
    }
707
708
709
    return scene;
}

710
711
712
713
714
715
716
717
718
719
720
721
722
723
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();
}

724
725
void ProjectManager::slotAddProjectNote()
{
726
    m_notesPlugin->showDock();
727
728
729
730
731
    m_notesPlugin->widget()->raise();
    m_notesPlugin->widget()->setFocus();
    m_notesPlugin->widget()->addProjectNote();
}

732
733
void ProjectManager::prepareSave()
{
734
    pCore->projectItemModel()->saveDocumentProperties(pCore->window()->getMainTimeline()->controller()->documentProperties(), m_project->metadata(),
Nicolas Carion's avatar
Nicolas Carion committed
735
                                                      m_project->getGuideModel());
736
737
    pCore->projectItemModel()->saveProperty(QStringLiteral("kdenlive:documentnotes"), documentNotes());
    pCore->projectItemModel()->saveProperty(QStringLiteral("kdenlive:docproperties.groups"), m_mainTimelineModel->groupsData());
738
739
}

740
void ProjectManager::slotResetProfiles(bool reloadThumbs)
741
{
742
    m_project->resetProfile(reloadThumbs);
743
744
    pCore->monitorManager()->updateScopeSource();
}
745

746
747
748
749
750
void ProjectManager::slotResetConsumers(bool fullReset)
{
    pCore->monitorManager()->resetConsumers(fullReset);
}

751
void ProjectManager::disableBinEffects(bool disable)
752
{
753
754
    if (m_project) {
        if (disable) {
Nicolas Carion's avatar
Nicolas Carion committed
755
            m_project->setDocumentProperty(QStringLiteral("disablebineffects"), QString::number((int)true));
756
        } else {
757
            m_project->setDocumentProperty(QStringLiteral("disablebineffects"), QString());
758
        }
759
    }
760
761
    pCore->monitorManager()->refreshProjectMonitor();
    pCore->monitorManager()->refreshClipMonitor();
762
763
}

764
765
766
void ProjectManager::slotDisableTimelineEffects(bool disable)
{
    if (disable) {
Nicolas Carion's avatar
Nicolas Carion committed
767
        m_project->setDocumentProperty(QStringLiteral("disabletimelineeffects"), QString::number((int)true));
768
    } else {
769
        m_project->setDocumentProperty(QStringLiteral("disabletimelineeffects"), QString());
770
    }
771
772
    m_mainTimelineModel->setTimelineEffectsEnabled(!disable);
    pCore->monitorManager()->refreshProjectMonitor();
773
}
774

775
776
void ProjectManager::slotSwitchTrackLock()
{
777
    pCore->window()->getMainTimeline()->controller()->switchTrackLock();
778
779
}

780
781
782
783
784
void ProjectManager::slotSwitchTrackActive()
{
    pCore->window()->getMainTimeline()->controller()->switchTrackActive();
}

785
786
787
788
789
void ProjectManager::slotSwitchAllTrackActive()
{
    pCore->window()->getMainTimeline()->controller()->switchAllTrackActive();
}

790
791
792
793
794
void ProjectManager::slotMakeAllTrackActive()
{
    pCore->window()->getMainTimeline()->controller()->makeAllTrackActive();
}

795
796
void ProjectManager::slotSwitchAllTrackLock()
{
797
    pCore->window()->getMainTimeline()->controller()->switchTrackLock(true);
798
799
}

800
801
void ProjectManager::slotSwitchTrackTarget()
{
802
    pCore->window()->getMainTimeline()->controller()->switchTargetTrack();
803
804
}

805
806
QString ProjectManager::getDefaultProjectFormat()
{
Nicolas Carion's avatar
Nicolas Carion committed
807
808
    // 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.
809
810
811
    QTimeZone zone;
    zone = QTimeZone::systemTimeZone();

Laurent Montel's avatar
Laurent Montel committed
812
    QList<int> ntscCountries;
813
    ntscCountries << QLocale::Canada << QLocale::Chile << QLocale::CostaRica << QLocale::Cuba << QLocale::DominicanRepublic << QLocale::Ecuador;
Nicolas Carion's avatar
Nicolas Carion committed
814
815
    ntscCountries << QLocale::Japan << QLocale::Mexico << QLocale::Nicaragua << QLocale::Panama << QLocale::Peru << QLocale::Philippines;
    ntscCountries << QLocale::PuertoRico << QLocale::SouthKorea << QLocale::Taiwan << QLocale::UnitedStates;
816
    bool ntscProject = ntscCountries.contains(zone.country());
Laurent Montel's avatar
Laurent Montel committed
817
818
819
    if (!ntscProject) {
        return QStringLiteral("atsc_1080p_25");
    }
820
821
822
    return QStringLiteral("atsc_1080p_2997");
}

Laurent Montel's avatar
Laurent Montel committed
823
void ProjectManager::saveZone(const QStringList &info, const QDir &dir)
824
825
826
{
    pCore->bin()->saveZone(info, dir);
}
827

828
829
830
void ProjectManager::moveProjectData(const QString &src, const QString &dest)
{
    // Move tmp folder (thumbnails, timeline preview)
Laurent Montel's avatar
Laurent Montel committed
831
    KIO::CopyJob *copyJob = KIO::move(QUrl::fromLocalFile(src), QUrl::fromLocalFile(dest));
Laurent Montel's avatar
Laurent Montel committed
832
    connect(copyJob, &KJob::result, this, &ProjectManager::