projectmanager.cpp 41.7 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

Nicolas Carion's avatar
Nicolas Carion committed
55
ProjectManager::ProjectManager(QObject *parent)
56
    : QObject(parent)
57
    , m_mainTimelineModel(nullptr)
Nicolas Carion's avatar
Nicolas Carion committed
58

Till Theato's avatar
Till Theato committed
59
60
{
    m_fileRevert = KStandardAction::revert(this, SLOT(slotRevert()), pCore->window()->actionCollection());
61
    m_fileRevert->setIcon(QIcon::fromTheme(QStringLiteral("document-revert")));
Till Theato's avatar
Till Theato committed
62
63
    m_fileRevert->setEnabled(false);

Nicolas Carion's avatar
Nicolas Carion committed
64
    QAction *a = KStandardAction::open(this, SLOT(openFile()), pCore->window()->actionCollection());
65
    a->setIcon(QIcon::fromTheme(QStringLiteral("document-open")));
Nicolas Carion's avatar
Nicolas Carion committed
66
    a = KStandardAction::saveAs(this, SLOT(saveFileAs()), pCore->window()->actionCollection());
67
    a->setIcon(QIcon::fromTheme(QStringLiteral("document-save-as")));
Nicolas Carion's avatar
Nicolas Carion committed
68
    a = KStandardAction::openNew(this, SLOT(newFile()), pCore->window()->actionCollection());
69
    a->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));
70
    m_recentFilesAction = KStandardAction::openRecent(this, SLOT(openFile(QUrl)), pCore->window()->actionCollection());
71

72
    QAction *backupAction = new QAction(QIcon::fromTheme(QStringLiteral("edit-undo")), i18n("Open Backup File"), this);
73
    pCore->window()->addAction(QStringLiteral("open_backup"), backupAction);
74
    connect(backupAction, SIGNAL(triggered(bool)), SLOT(slotOpenBackup()));
75
76

    m_notesPlugin = new NotesPlugin(this);
77
78

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

81
82
    // Ensure the default data folder exist
    QDir dir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation));
83
    dir.mkpath(QStringLiteral(".backup"));
84
    dir.mkdir(QStringLiteral("titles"));
Till Theato's avatar
Till Theato committed
85
86
}

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

89
void ProjectManager::slotLoadOnOpen()
Till Theato's avatar
Till Theato committed
90
{
91
92
    if (m_startUrl.isValid()) {
        openFile();
Laurent Montel's avatar
Laurent Montel committed
93
    } else if (KdenliveSettings::openlastproject()) {
94
        openLastFile();
Laurent Montel's avatar
Laurent Montel committed
95
96
    } else {
        newFile(false);
Till Theato's avatar
Till Theato committed
97
98
    }

Nicolas Carion's avatar
Nicolas Carion committed
99
    if (!m_loadClipsOnOpen.isEmpty() && (m_project != nullptr)) {
Laurent Montel's avatar
Laurent Montel committed
100
        const QStringList list = m_loadClipsOnOpen.split(QLatin1Char(','));
Laurent Montel's avatar
Laurent Montel committed
101
        QList<QUrl> urls;
Laurent Montel's avatar
Laurent Montel committed
102
103
        urls.reserve(list.count());
        for (const QString &path : list) {
Nicolas Carion's avatar
Nicolas Carion committed
104
            // qCDebug(KDENLIVE_LOG) << QDir::current().absoluteFilePath(path);
Till Theato's avatar
Till Theato committed
105
106
            urls << QUrl::fromLocalFile(QDir::current().absoluteFilePath(path));
        }
107
        pCore->bin()->droppedUrls(urls);
Till Theato's avatar
Till Theato committed
108
    }
109
110
111
    m_loadClipsOnOpen.clear();
}

Laurent Montel's avatar
Laurent Montel committed
112
void ProjectManager::init(const QUrl &projectUrl, const QString &clipList)
113
114
115
{
    m_startUrl = projectUrl;
    m_loadClipsOnOpen = clipList;
Till Theato's avatar
Till Theato committed
116
117
}

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

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
220
bool ProjectManager::closeCurrentDocument(bool saveChanges, bool quit)
Till Theato's avatar
Till Theato committed
221
{
Nicolas Carion's avatar
Nicolas Carion committed
222
    if ((m_project != nullptr) && m_project->isModified() && saveChanges) {
Till Theato's avatar
Till Theato committed
223
224
225
226
227
228
229
230
        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
231
        case KMessageBox::Yes:
Till Theato's avatar
Till Theato committed
232
            // save document here. If saving fails, return false;
Nicolas Carion's avatar
Nicolas Carion committed
233
            if (!saveFile()) {
Till Theato's avatar
Till Theato committed
234
235
                return false;
            }
Till Theato's avatar
Till Theato committed
236
            break;
Nicolas Carion's avatar
Nicolas Carion committed
237
        case KMessageBox::Cancel:
Till Theato's avatar
Till Theato committed
238
239
240
241
242
243
            return false;
            break;
        default:
            break;
        }
    }
244
    pCore->jobManager()->slotCancelJobs();
245
    disconnect(pCore->window()->getMainTimeline()->controller(), &TimelineController::durationChanged, this, &ProjectManager::adjustProjectDuration);
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
246
    pCore->window()->getMainTimeline()->controller()->clipActions.clear();
247
    pCore->window()->getMainTimeline()->controller()->prepareClose();
248
249
250
    if (m_mainTimelineModel) {
        m_mainTimelineModel->prepareClose();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
251
    if (!quit && !qApp->isSavingSession()) {
Laurent Montel's avatar
Laurent Montel committed
252
        m_autoSaveTimer.stop();
253
        if (m_project) {
254
            pCore->jobManager()->slotCancelJobs();
255
            pCore->bin()->abortOperations();
Laurent Montel's avatar
Laurent Montel committed
256
            pCore->monitorManager()->clipMonitor()->slotOpenClip(nullptr);
257
            pCore->window()->clearAssetPanel();
258
            delete m_project;
Laurent Montel's avatar
Laurent Montel committed
259
            m_project = nullptr;
260
        }
261
    }
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    /*  // 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
283
284
285
286
287
    return true;
}

bool ProjectManager::saveFileAs(const QString &outputFileName)
{
288
    pCore->monitorManager()->pauseActiveMonitor();
289
290
    // Sync document properties
    prepareSave();
291
292
    QString saveFolder = QFileInfo(outputFileName).absolutePath();
    QString scene = projectSceneList(saveFolder);
293
294
295
296
297
298
299
    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
300
    if (!m_project->saveSceneList(outputFileName, scene)) {
Till Theato's avatar
Till Theato committed
301
302
        return false;
    }
303
    QUrl url = QUrl::fromLocalFile(outputFileName);
Till Theato's avatar
Till Theato committed
304
    // Save timeline thumbnails
305
306
    QStringList thumbKeys = pCore->window()->getMainTimeline()->controller()->getThumbKeys();
    ThumbnailCache::get()->saveCachedThumbs(thumbKeys);
307
    m_project->setUrl(url);
308
    // setting up autosave file in ~/.kde/data/stalefiles/kdenlive/
309
    // saved under file name
310
311
    // actual saving by KdenliveDoc::slotAutoSave() called by a timer 3 seconds after the document has been edited
    // This timer is set by KdenliveDoc::setModified()
312
313
    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
314
    if (m_project->m_autosave == nullptr) {
315
316
        // 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).
317
        m_project->m_autosave = new KAutoSaveFile(autosaveUrl, m_project);
Till Theato's avatar
Till Theato committed
318
    } else {
319
        m_project->m_autosave->setManagedFile(autosaveUrl);
Till Theato's avatar
Till Theato committed
320
321
    }

Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
322
    pCore->window()->setWindowTitle(m_project->description());
Till Theato's avatar
Till Theato committed
323
    m_project->setModified(false);
324
325
    m_recentFilesAction->addUrl(url);
    // remember folder for next project opening
326
    KRecentDirs::add(QStringLiteral(":KdenliveProjectsFolder"), saveFolder);
327
    saveRecentFiles();
Till Theato's avatar
Till Theato committed
328
    m_fileRevert->setEnabled(true);
329
    pCore->window()->m_undoView->stack()->setClean();
Till Theato's avatar
Till Theato committed
330
331
332
333

    return true;
}

334
335
336
337
338
339
340
void ProjectManager::saveRecentFiles()
{
    KSharedConfigPtr config = KSharedConfig::openConfig();
    m_recentFilesAction->saveEntries(KConfigGroup(config, "Recent Files"));
    config->sync();
}

Till Theato's avatar
Till Theato committed
341
342
bool ProjectManager::saveFileAs()
{
343
    QFileDialog fd(pCore->window());
344
    fd.setDirectory(m_project->url().isValid() ? m_project->url().adjusted(QUrl::RemoveFilename).toLocalFile() : KdenliveSettings::defaultprojectfolder());
Laurent Montel's avatar
Laurent Montel committed
345
    fd.setMimeTypeFilters(QStringList() << QStringLiteral("application/x-kdenlive"));
346
    fd.setAcceptMode(QFileDialog::AcceptSave);
347
    fd.setFileMode(QFileDialog::AnyFile);
348
    fd.setDefaultSuffix(QStringLiteral("kdenlive"));
349
    if (fd.exec() != QDialog::Accepted || fd.selectedFiles().isEmpty()) {
350
        return false;
351
    }
Laurent Montel's avatar
Laurent Montel committed
352
    QString outputFile = fd.selectedFiles().constFirst();
Till Theato's avatar
Till Theato committed
353

354
355
356
    bool ok = false;
    QDir cacheDir = m_project->getCacheDir(CacheBase, &ok);
    if (ok) {
Laurent Montel's avatar
Laurent Montel committed
357
        QFile file(cacheDir.absoluteFilePath(QString::fromLatin1(QUrl::toPercentEncoding(QStringLiteral(".") + outputFile))));
358
359
360
        file.open(QIODevice::ReadWrite | QIODevice::Text);
        file.close();
    }
Till Theato's avatar
Till Theato committed
361
362
363
364
365
    return saveFileAs(outputFile);
}

bool ProjectManager::saveFile()
{
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
366
367
    if (!m_project) {
        // Calling saveFile before a project was created, something is wrong
Laurent Montel's avatar
Laurent Montel committed
368
        qCDebug(KDENLIVE_LOG) << "SaveFile called without project";
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
369
370
        return false;
    }
Till Theato's avatar
Till Theato committed
371
372
    if (m_project->url().isEmpty()) {
        return saveFileAs();
Nicolas Carion's avatar
Nicolas Carion committed
373
374
375
376
    }
    bool result = saveFileAs(m_project->url().toLocalFile());
    m_project->m_autosave->resize(0);
    return result;
Till Theato's avatar
Till Theato committed
377
378
379
380
}

void ProjectManager::openFile()
{
381
    if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
382
        openFile(m_startUrl);
383
        m_startUrl.clear();
Till Theato's avatar
Till Theato committed
384
385
        return;
    }
Nicolas Carion's avatar
Nicolas Carion committed
386
387
    QUrl url = QFileDialog::getOpenFileUrl(pCore->window(), QString(), QUrl::fromLocalFile(KRecentDirs::dir(QStringLiteral(":KdenliveProjectsFolder"))),
                                           getMimeType());
388
    if (!url.isValid()) {
Till Theato's avatar
Till Theato committed
389
390
        return;
    }
391
    KRecentDirs::add(QStringLiteral(":KdenliveProjectsFolder"), url.adjusted(QUrl::RemoveFilename).toLocalFile());
392
    m_recentFilesAction->addUrl(url);
393
    saveRecentFiles();
Till Theato's avatar
Till Theato committed
394
395
396
397
398
    openFile(url);
}

void ProjectManager::openLastFile()
{
399
    if (m_recentFilesAction->selectableActionGroup()->actions().isEmpty()) {
Till Theato's avatar
Till Theato committed
400
401
402
403
404
        // No files in history
        newFile(false);
        return;
    }

405
    QAction *firstUrlAction = m_recentFilesAction->selectableActionGroup()->actions().last();
Till Theato's avatar
Till Theato committed
406
407
408
409
410
411
412
    if (firstUrlAction) {
        firstUrlAction->trigger();
    } else {
        newFile(false);
    }
}

413
// fix mantis#3160 separate check from openFile() so we can call it from newFile()
414
// to find autosaved files (in ~/.local/share/stalefiles/kdenlive) and recover it
415
bool ProjectManager::checkForBackupFile(const QUrl &url, bool newFile)
416
{
417
    // Check for autosave file that belong to the url we passed in.
418
419
420
    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
421
    KAutoSaveFile *orphanedFile = nullptr;
Laurent Montel's avatar
Laurent Montel committed
422
    // Check if we can have a lock on one of the file,
423
    // meaning it is not handled by any Kdenlive instance
424
    if (!staleFiles.isEmpty()) {
Nicolas Carion's avatar
Nicolas Carion committed
425
        for (KAutoSaveFile *stale : staleFiles) {
426
            if (stale->open(QIODevice::QIODevice::ReadWrite)) {
Laurent Montel's avatar
Laurent Montel committed
427
428
429
                // Found orphaned autosave file
                orphanedFile = stale;
                break;
430
431
432
433
434
            }
        }
    }

    if (orphanedFile) {
Nicolas Carion's avatar
Nicolas Carion committed
435
        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
436
                                       KGuiItem(i18n("Recover")), KGuiItem(i18n("Do not recover"))) == KMessageBox::Yes) {
437
            doOpenFile(url, orphanedFile);
438
            return true;
Nicolas Carion's avatar
Nicolas Carion committed
439
        }
440
    }
441
442
443
444
445
446
    // remove the stale files
    for (KAutoSaveFile *stale : staleFiles) {
        stale->open(QIODevice::ReadWrite);
        delete stale;
    }
    
447
448
449
    return false;
}

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

469
    /*if (!url.fileName().endsWith(".kdenlive")) {
Till Theato's avatar
Till Theato committed
470
        // This is not a Kdenlive project file, abort loading
471
        KMessageBox::sorry(pCore->window(), i18n("File %1 is not a Kdenlive project file", url.toLocalFile()));
472
        if (m_startUrl.isValid()) {
Till Theato's avatar
Till Theato committed
473
474
475
476
            // we tried to open an invalid file from command line, init new project
            newFile(false);
        }
        return;
477
    }*/
Till Theato's avatar
Till Theato committed
478

Nicolas Carion's avatar
Nicolas Carion committed
479
    if ((m_project != nullptr) && m_project->url() == url) {
Till Theato's avatar
Till Theato committed
480
481
482
        return;
    }

Till Theato's avatar
Till Theato committed
483
484
    if (!closeCurrentDocument()) {
        return;
Till Theato's avatar
Till Theato committed
485
    }
486
487
    if (checkForBackupFile(url)) {
        return;
Till Theato's avatar
Till Theato committed
488
    }
489
    pCore->displayMessage(i18n("Opening file %1", url.toLocalFile()), OperationCompletedMessage, 100);
Laurent Montel's avatar
Laurent Montel committed
490
    doOpenFile(url, nullptr);
Till Theato's avatar
Till Theato committed
491
492
}

493
void ProjectManager::doOpenFile(const QUrl &url, KAutoSaveFile *stale)
Till Theato's avatar
Till Theato committed
494
{
Laurent Montel's avatar
Laurent Montel committed
495
    Q_ASSERT(m_project == nullptr);
Till Theato's avatar
Till Theato committed
496
497
    m_fileRevert->setEnabled(true);

498
    delete m_progressDialog;
499
    ThumbnailCache::get()->clearCache();
500
    pCore->monitorManager()->resetDisplay();
501
    pCore->monitorManager()->activateMonitor(Kdenlive::ProjectMonitor);
502
503
    m_progressDialog = new QProgressDialog(pCore->window());
    m_progressDialog->setWindowTitle(i18n("Loading project"));
Laurent Montel's avatar
Laurent Montel committed
504
    m_progressDialog->setCancelButton(nullptr);
505
    m_progressDialog->setLabelText(i18n("Loading project"));
506
507
    m_progressDialog->setMaximum(0);
    m_progressDialog->show();
Till Theato's avatar
Till Theato committed
508
    bool openBackup;
509
    m_notesPlugin->clear();
Nicolas Carion's avatar
linting    
Nicolas Carion committed
510
511
512
513
    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
514
    if (stale == nullptr) {
515
516
517
        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
518
519
520
        doc->m_autosave = stale;
    } else {
        doc->m_autosave = stale;
521
        stale->setParent(doc);
522
        // if loading from an autosave of unnamed file then keep unnamed
Laurent Montel's avatar
Laurent Montel committed
523
        if (url.fileName().contains(QStringLiteral("_untitled.kdenlive"))) {
524
            doc->setUrl(QUrl());
Laurent Montel's avatar
Laurent Montel committed
525
        } else {
526
            doc->setUrl(url);
Laurent Montel's avatar
Laurent Montel committed
527
        }
Till Theato's avatar
Till Theato committed
528
529
530
        doc->setModified(true);
        stale->setParent(doc);
    }
531
    m_progressDialog->setLabelText(i18n("Loading clips"));
532
    m_progressDialog->setMaximum(doc->clipsCount());
533
534

    // TODO refac delete this
535
    pCore->bin()->setDocument(doc);
Laurent Montel's avatar
Laurent Montel committed
536
    QList<QAction *> rulerActions;
537
538
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("set_render_timeline_zone"));
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("unset_render_timeline_zone"));
539
    rulerActions << pCore->window()->actionCollection()->action(QStringLiteral("clear_render_timeline_zone"));
540
541

    // Set default target tracks to upper audio / lower video tracks
542
    m_project = doc;
543

544
545
546
547
548
    if (!updateTimeline(m_project->getDocumentProperty(QStringLiteral("position")).toInt())) {
        delete m_progressDialog;
        m_progressDialog = nullptr;
        return;
    }
549
    pCore->window()->connectDocument();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
550
    pCore->mixer()->setModel(m_mainTimelineModel);
551
    QDateTime documentDate = QFileInfo(m_project->url().toLocalFile()).lastModified();
552
553
554
    pCore->window()->getMainTimeline()->controller()->loadPreview(m_project->getDocumentProperty(QStringLiteral("previewchunks")),
                                                                  m_project->getDocumentProperty(QStringLiteral("dirtypreviewchunks")), documentDate,
                                                                  m_project->getDocumentProperty(QStringLiteral("disablepreview")).toInt());
555

556
    emit docOpened(m_project);
557
    pCore->displayMessage(QString(), OperationCompletedMessage, 100);
Till Theato's avatar
Till Theato committed
558
    if (openBackup) {
559
        slotOpenBackup(url);
Till Theato's avatar
Till Theato committed
560
    }
561
    m_lastSave.start();
562
    delete m_progressDialog;
Laurent Montel's avatar
Laurent Montel committed
563
    m_progressDialog = nullptr;
Till Theato's avatar
Till Theato committed
564
565
566
567
}

void ProjectManager::slotRevert()
{
Nicolas Carion's avatar
Nicolas Carion committed
568
569
570
571
    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
572
573
        return;
    }
574
    QUrl url = m_project->url();
Laurent Montel's avatar
Laurent Montel committed
575
    if (closeCurrentDocument(false)) {
Laurent Montel's avatar
Laurent Montel committed
576
        doOpenFile(url, nullptr);
Laurent Montel's avatar
Laurent Montel committed
577
    }
Till Theato's avatar
Till Theato committed
578
579
580
581
}

QString ProjectManager::getMimeType(bool open)
{
582
    QString mimetype = i18n("Kdenlive project (*.kdenlive)");
Laurent Montel's avatar
Laurent Montel committed
583
    if (open) {
Laurent Montel's avatar
Laurent Montel committed
584
        mimetype.append(QStringLiteral(";;") + i18n("Archived project (*.tar.gz)"));
Laurent Montel's avatar
Laurent Montel committed
585
    }
Till Theato's avatar
Till Theato committed
586
587
588
    return mimetype;
}

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
    QString scene = pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
670
671
    if (isMultiTrack) {
        pCore->window()->getMainTimeline()->controller()->slotMultitrackView(true, false);
672
    }
673
674
675
    if (hasPreview) {
        pCore->window()->getMainTimeline()->controller()->updatePreviewConnection(true);
    }
676
677
678
    return scene;
}

679
680
681
682
683
684
685
686
687
688
689
690
691
692
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();
}

693
694
695
696
697
698
699
void ProjectManager::slotAddProjectNote()
{
    m_notesPlugin->widget()->raise();
    m_notesPlugin->widget()->setFocus();
    m_notesPlugin->widget()->addProjectNote();
}

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

708
709
710
void ProjectManager::slotResetProfiles()
{
    m_project->resetProfile();
711
    pCore->monitorManager()->resetProfiles(m_project->timecode());
712
713
    pCore->monitorManager()->updateScopeSource();
}
714

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

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

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

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

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

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

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

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

770
771
QString ProjectManager::getDefaultProjectFormat()
{
Nicolas Carion's avatar
Nicolas Carion committed
772
773
    // 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.
774
775
776
    QTimeZone zone;
    zone = QTimeZone::systemTimeZone();

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

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

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

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

void ProjectManager::slotMoveFinished(KJob *job)
{
    if (job->error() == 0) {
810
        pCore->displayMessage(QString(), OperationCompletedMessage, 100);
Nicolas Carion's avatar
Nicolas Carion committed
811
        auto *copyJob = static_cast<KIO::CopyJob *>(job);
812
        QString newFolder = copyJob->destUrl().toLocalFile();
813
814
        // 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));
Jean-Baptiste Mardelle's avatar