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

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
    pCore->bin()->setDocument(doc);
201
    m_project = doc;
202
203
    pCore->monitorManager()->activateMonitor(Kdenlive::ProjectMonitor);
    updateTimeline(0);
204
    pCore->window()->connectDocument();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
205
    pCore->mixer()->setModel(m_mainTimelineModel);
206
207
    bool disabled = m_project->getDocumentProperty(QStringLiteral("disabletimelineeffects")) == QLatin1String("1");
    QAction *disableEffects = pCore->window()->actionCollection()->action(QStringLiteral("disable_timeline_effects"));
208
209
210
211
212
213
214
    if (disableEffects) {
        if (disabled != disableEffects->isChecked()) {
            disableEffects->blockSignals(true);
            disableEffects->setChecked(disabled);
            disableEffects->blockSignals(false);
        }
    }
215
    emit docOpened(m_project);
216
    m_lastSave.start();
Till Theato's avatar
Till Theato committed
217
218
}

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

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

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

    return true;
}

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

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

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

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

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

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

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

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

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

450
451
452
453
454
        return false;
    }
    return false;
}

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

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

Nicolas Carion's avatar
Nicolas Carion committed
484
    if ((m_project != nullptr) && m_project->url() == url) {
Till Theato's avatar
Till Theato committed
485
486
487
        return;
    }

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

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

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

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

    // Set default target tracks to upper audio / lower video tracks
546
    m_project = doc;
547

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
593
KdenliveDoc *ProjectManager::current()
Till Theato's avatar
Till Theato committed
594
595
596
597
{
    return m_project;
}

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

Laurent Montel's avatar
Laurent Montel committed
630
KRecentFilesAction *ProjectManager::recentFilesAction()
631
632
633
634
{
    return m_recentFilesAction;
}

635
636
void ProjectManager::slotStartAutoSave()
{
637
638
639
640
    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
641
    } else {
642
643
        m_autoSaveTimer.start(3000); // will trigger slotAutoSave() in 3 seconds
    }
644
645
646
647
}

void ProjectManager::slotAutoSave()
{
648
    prepareSave();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
649
650
651
652
653
654
655
656
    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());
        }
657
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
658
    m_project->slotAutoSave(scene);
659
    m_lastSave.start();
660
661
}

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

683
684
685
686
687
688
689
690
691
692
693
694
695
696
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();
}

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

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

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

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

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

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

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

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

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

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

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

774
775
QString ProjectManager::getDefaultProjectFormat()
{
Nicolas Carion's avatar
Nicolas Carion committed
776
777
    // 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.
778
779
780
    QTimeZone zone;
    zone = QTimeZone::systemTimeZone();

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

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

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

806
807
void ProjectManager::slotMoveProgress(KJob *, unsigned long progress)
{