projectmanager.cpp 38.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>
Till Theato's avatar
Till Theato committed
53

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

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

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

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

    m_notesPlugin = new NotesPlugin(this);
76
77

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

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

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

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

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

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

117
118
119
120
121
122
123
124
125
126
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
127
{
128
    // fix mantis#3160
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();
205
206
    bool disabled = m_project->getDocumentProperty(QStringLiteral("disabletimelineeffects")) == QLatin1String("1");
    QAction *disableEffects = pCore->window()->actionCollection()->action(QStringLiteral("disable_timeline_effects"));
207
208
209
210
211
212
213
    if (disableEffects) {
        if (disabled != disableEffects->isChecked()) {
            disableEffects->blockSignals(true);
            disableEffects->setChecked(disabled);
            disableEffects->blockSignals(false);
        }
    }
214
    emit docOpened(m_project);
215
    m_lastSave.start();
Till Theato's avatar
Till Theato committed
216
217
}

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

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

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

    return true;
}

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

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

350
#if KXMLGUI_VERSION_MINOR < 23 && KXMLGUI_VERSION_MAJOR == 5
Laurent Montel's avatar
Laurent Montel committed
351
    // Since Plasma 5.7 (release at same time as KF 5.23,
352
353
    // the file dialog manages the overwrite check
    if (QFile::exists(outputFile)) {
Till Theato's avatar
Till Theato committed
354
355
356
357
        // Show the file dialog again if the user does not want to overwrite the file
        if (KMessageBox::questionYesNo(pCore->window(), i18n("File %1 already exists.\nDo you want to overwrite it?", outputFile)) == KMessageBox::No) {
            return saveFileAs();
        }
358
359
360
    }
#endif

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

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

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

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

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

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

    if (orphanedFile) {
Nicolas Carion's avatar
Nicolas Carion committed
447
        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
448
                                       KGuiItem(i18n("Recover")), KGuiItem(i18n("Do not recover"))) == KMessageBox::Yes) {
449
            doOpenFile(url, orphanedFile);
450
            return true;
Nicolas Carion's avatar
Nicolas Carion committed
451
452
        }
        // remove the stale files
Nicolas Carion's avatar
Nicolas Carion committed
453
        for (KAutoSaveFile *stale : staleFiles) {
Nicolas Carion's avatar
Nicolas Carion committed
454
455
456
457
            stale->open(QIODevice::ReadWrite);
            delete stale;
        }

458
459
460
461
462
        return false;
    }
    return false;
}

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

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

Nicolas Carion's avatar
Nicolas Carion committed
492
    if ((m_project != nullptr) && m_project->url() == url) {
Till Theato's avatar
Till Theato committed
493
494
495
        return;
    }

Till Theato's avatar
Till Theato committed
496
497
    if (!closeCurrentDocument()) {
        return;
Till Theato's avatar
Till Theato committed
498
    }
499
500
    if (checkForBackupFile(url)) {
        return;
Till Theato's avatar
Till Theato committed
501
    }
502
    pCore->window()->slotGotProgressInfo(i18n("Opening file %1", url.toLocalFile()), 100, InformationMessage);
Laurent Montel's avatar
Laurent Montel committed
503
    doOpenFile(url, nullptr);
Till Theato's avatar
Till Theato committed
504
505
}

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

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

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

    // Set default target tracks to upper audio / lower video tracks
553
    m_project = doc;
554

555
    updateTimeline(m_project->getDocumentProperty(QStringLiteral("position")).toInt());
556
    pCore->window()->connectDocument();
557
    QDateTime documentDate = QFileInfo(m_project->url().toLocalFile()).lastModified();
558
559
560
    pCore->window()->getMainTimeline()->controller()->loadPreview(m_project->getDocumentProperty(QStringLiteral("previewchunks")),
                                                                  m_project->getDocumentProperty(QStringLiteral("dirtypreviewchunks")), documentDate,
                                                                  m_project->getDocumentProperty(QStringLiteral("disablepreview")).toInt());
561

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

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

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

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

Laurent Montel's avatar
Laurent Montel committed
600
void ProjectManager::slotOpenBackup(const QUrl &url)
601
{
602
603
    QUrl projectFile;
    QUrl projectFolder;
604
    QString projectId;
605
    if (url.isValid()) {
606
        // we could not open the project file, guess where the backups are
607
        projectFolder = QUrl::fromLocalFile(KdenliveSettings::defaultprojectfolder());
608
609
        projectFile = url;
    } else {
610
        projectFolder = QUrl::fromLocalFile(m_project->projectTempFolder());
611
        projectFile = m_project->url();
612
        projectId = m_project->getDocumentProperty(QStringLiteral("documentid"));
613
614
615
616
617
    }

    QPointer<BackupWidget> dia = new BackupWidget(projectFile, projectFolder, projectId, pCore->window());
    if (dia->exec() == QDialog::Accepted) {
        QString requestedBackup = dia->selectedFile();
618
        m_project->backupLastSavedVersion(projectFile.toLocalFile());
619
        closeCurrentDocument(false);
Laurent Montel's avatar
Laurent Montel committed
620
        doOpenFile(QUrl::fromLocalFile(requestedBackup), nullptr);
Vincent Pinon's avatar
Vincent Pinon committed
621
622
623
624
625
        if (m_project) {
            m_project->setUrl(projectFile);
            m_project->setModified(true);
            pCore->window()->setWindowTitle(m_project->description());
        }
626
627
628
629
    }
    delete dia;
}

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
{
Nicolas Carion's avatar
Nicolas Carion committed
664
    // TODO: re-implement overlay and all
665
    // TODO refac: repair this
666
    return pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
667
    /*bool multitrackEnabled = m_trackView->multitrackView;
668
669
670
671
    if (multitrackEnabled) {
        // Multitrack view was enabled, disable for auto save
        m_trackView->slotMultitrackView(false);
    }
672
    m_trackView->connectOverlayTrack(false);
673
    QString scene = pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
674
    m_trackView->connectOverlayTrack(true);
675
676
677
678
679
    if (multitrackEnabled) {
        // Multitrack view was enabled, re-enable for auto save
        m_trackView->slotMultitrackView(true);
    }
    return scene;
680
    */
681
682
}

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)
{
808
    pCore->window()->slotGotProgressInfo(i18n("Moving project folder"), static_cast<int>(progress), ProcessingJobMessage);
809
810
811
812
813
814
}

void ProjectManager::slotMoveFinished(KJob *job)
{
    if (job->error() == 0) {
        pCore->window()->slotGotProgressInfo(QString(), 100, InformationMessage);
Nicolas Carion's avatar
Nicolas Carion committed
815
        auto *copyJob = static_cast<KIO::CopyJob *>(job);
816
        QString newFolder = copyJob->destUrl().toLocalFile();
817
818
        // 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));
819
        QDir srcDir(m_project->projectTempFolder());
820
821
822
        if (srcDir.absolutePath().startsWith(projectDir.absolutePath())) {
            m_replacementPattern.insert(QStringLiteral(">proxy/"), QStringLiteral(">") + newFolder + QStringLiteral("/proxy/"));
        } else {
823
            m_replacementPattern.insert(m_project->projectTempFolder() + QStringLiteral("/proxy/"), newFolder + QStringLiteral("/proxy/"));
824
825
826
827
828
829
830
831
832
        }
        m_project->setProjectFolder(QUrl::fromLocalFile(newFolder));
        saveFile();
        m_replacementPattern<