projectmanager.cpp 41.2 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
    pCore->window()->getMainTimeline()->controller()->prepareClose();
244
245
246
    if (m_mainTimelineModel) {
        m_mainTimelineModel->prepareClose();
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
247
    if (!quit && !qApp->isSavingSession()) {
Laurent Montel's avatar
Laurent Montel committed
248
        m_autoSaveTimer.stop();
249
        if (m_project) {
250
            pCore->jobManager()->slotCancelJobs();
251
            pCore->bin()->abortOperations();
Laurent Montel's avatar
Laurent Montel committed
252
            pCore->monitorManager()->clipMonitor()->slotOpenClip(nullptr);
253
            pCore->window()->clearAssetPanel();
254
            delete m_project;
Laurent Montel's avatar
Laurent Montel committed
255
            m_project = nullptr;
256
        }
Laurent Montel's avatar
Laurent Montel committed
257
        pCore->monitorManager()->setDocument(m_project);
258
    }
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    /*  // 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
280
281
282
283
284
    return true;
}

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

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

    return true;
}

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

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

351
#if KXMLGUI_VERSION_MINOR < 23 && KXMLGUI_VERSION_MAJOR == 5
Laurent Montel's avatar
Laurent Montel committed
352
    // Since Plasma 5.7 (release at same time as KF 5.23,
353
354
    // the file dialog manages the overwrite check
    if (QFile::exists(outputFile)) {
Till Theato's avatar
Till Theato committed
355
356
357
358
        // 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();
        }
359
360
361
    }
#endif

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

556
557
558
559
560
    if (!updateTimeline(m_project->getDocumentProperty(QStringLiteral("position")).toInt())) {
        delete m_progressDialog;
        m_progressDialog = nullptr;
        return;
    }
561
    pCore->window()->connectDocument();
562
    QDateTime documentDate = QFileInfo(m_project->url().toLocalFile()).lastModified();
563
564
565
    pCore->window()->getMainTimeline()->controller()->loadPreview(m_project->getDocumentProperty(QStringLiteral("previewchunks")),
                                                                  m_project->getDocumentProperty(QStringLiteral("dirtypreviewchunks")), documentDate,
                                                                  m_project->getDocumentProperty(QStringLiteral("disablepreview")).toInt());
566

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

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

QString ProjectManager::getMimeType(bool open)
{
593
    QString mimetype = i18n("Kdenlive project (*.kdenlive)");
Laurent Montel's avatar
Laurent Montel committed
594
    if (open) {
Laurent Montel's avatar
Laurent Montel committed
595
        mimetype.append(QStringLiteral(";;") + i18n("Archived project (*.tar.gz)"));
Laurent Montel's avatar
Laurent Montel committed
596
    }
Till Theato's avatar
Till Theato committed
597
598
599
    return mimetype;
}

Laurent Montel's avatar
Laurent Montel committed
600
KdenliveDoc *ProjectManager::current()
Till Theato's avatar
Till Theato committed
601
602
603
604
{
    return m_project;
}

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

Laurent Montel's avatar
Laurent Montel committed
637
KRecentFilesAction *ProjectManager::recentFilesAction()
638
639
640
641
{
    return m_recentFilesAction;
}

642
643
void ProjectManager::slotStartAutoSave()
{
644
645
646
647
    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
648
    } else {
649
650
        m_autoSaveTimer.start(3000); // will trigger slotAutoSave() in 3 seconds
    }
651
652
653
654
}

void ProjectManager::slotAutoSave()
{
655
    prepareSave();
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
656
657
658
659
660
661
662
663
    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());
        }
664
    }
Jean-Baptiste Mardelle's avatar
Jean-Baptiste Mardelle committed
665
    m_project->slotAutoSave(scene);
666
    m_lastSave.start();
667
668
}

Laurent Montel's avatar
Laurent Montel committed
669
QString ProjectManager::projectSceneList(const QString &outputFolder)
670
{
Nicolas Carion's avatar
Nicolas Carion committed
671
    // TODO: re-implement overlay and all
672
    // TODO refac: repair this
673
    return pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
674
    /*bool multitrackEnabled = m_trackView->multitrackView;
675
676
677
678
    if (multitrackEnabled) {
        // Multitrack view was enabled, disable for auto save
        m_trackView->slotMultitrackView(false);
    }
679
    m_trackView->connectOverlayTrack(false);
680
    QString scene = pCore->monitorManager()->projectMonitor()->sceneList(outputFolder);
681
    m_trackView->connectOverlayTrack(true);
682
683
684
685
686
    if (multitrackEnabled) {
        // Multitrack view was enabled, re-enable for auto save
        m_trackView->slotMultitrackView(true);
    }
    return scene;
687
    */
688
689
}

690
691
692
693
694
695
696
697
698
699
700
701
702
703
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();
}

704
705
706
707
708
709
710
void ProjectManager::slotAddProjectNote()
{
    m_notesPlugin->widget()->raise();
    m_notesPlugin->widget()->setFocus();
    m_notesPlugin->widget()->addProjectNote();
}

711
712
void ProjectManager::prepareSave()
{
713
    pCore->projectItemModel()->saveDocumentProperties(pCore->window()->getMainTimeline()->controller()->documentProperties(), m_project->metadata(),
Nicolas Carion's avatar
Nicolas Carion committed
714
                                                      m_project->getGuideModel());
715
716
    pCore->projectItemModel()->saveProperty(QStringLiteral("kdenlive:documentnotes"), documentNotes());
    pCore->projectItemModel()->saveProperty(QStringLiteral("kdenlive:docproperties.groups"), m_mainTimelineModel->groupsData());
717
718
}

719
720
721
void ProjectManager::slotResetProfiles()
{
    m_project->resetProfile();
722
    pCore->monitorManager()->resetProfiles(m_project->timecode());
723
724
    pCore->monitorManager()->updateScopeSource();
}
725

726
727
728
729
730
void ProjectManager::slotResetConsumers(bool fullReset)
{
    pCore->monitorManager()->resetConsumers(fullReset);
}

731
732
void ProjectManager::slotExpandClip()
{
733
734
    // TODO refac
    // m_trackView->projectView()->expandActiveClip();
735
736
}

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

750
751
752
void ProjectManager::slotDisableTimelineEffects(bool disable)
{
    if (disable) {
Nicolas Carion's avatar
Nicolas Carion committed
753
        m_project->setDocumentProperty(QStringLiteral("disabletimelineeffects"), QString::number((int)true));
754
    } else {
755
        m_project->setDocumentProperty(QStringLiteral("disabletimelineeffects"), QString());
756
    }
757
758
    m_mainTimelineModel->setTimelineEffectsEnabled(!disable);
    pCore->monitorManager()->refreshProjectMonitor();
759
}
760

761
762
void ProjectManager::slotSwitchTrackLock()
{
763
    pCore->window()->getMainTimeline()->controller()->switchTrackLock();
764
765
}

766
767
768
769
770
void ProjectManager::slotSwitchTrackActive()
{
    pCore->window()->getMainTimeline()->controller()->switchTrackActive();
}

771
772
void ProjectManager::slotSwitchAllTrackLock()
{
773
    pCore->window()->getMainTimeline()->controller()->switchTrackLock(true);
774
775
}

776
777
void ProjectManager::slotSwitchTrackTarget()
{
778
    pCore->window()->getMainTimeline()->controller()->switchTargetTrack();
779
780
}

781
782
QString ProjectManager::getDefaultProjectFormat()
{
Nicolas Carion's avatar
Nicolas Carion committed
783
784
    // 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.
785
786
787
    QTimeZone zone;
    zone = QTimeZone::systemTimeZone();

Laurent Montel's avatar
Laurent Montel committed
788
    QList<int> ntscCountries;
789
    ntscCountries << QLocale::Canada << QLocale::Chile << QLocale::CostaRica << QLocale::Cuba << QLocale::DominicanRepublic << QLocale::Ecuador;
Nicolas Carion's avatar
Nicolas Carion committed
790
791
    ntscCountries << QLocale::Japan << QLocale::Mexico << QLocale::Nicaragua << QLocale::Panama << QLocale::Peru << QLocale::Philippines;
    ntscCountries << QLocale::PuertoRico << QLocale::SouthKorea << QLocale::Taiwan << QLocale::UnitedStates;
792
    bool ntscProject = ntscCountries.contains(zone.country());
Laurent Montel's avatar
Laurent Montel committed
793
794
795
    if (!ntscProject) {
        return QStringLiteral("atsc_1080p_25");
    }
796
797
798
    return QStringLiteral("atsc_1080p_2997");
}

Laurent Montel's avatar
Laurent Montel committed
799
void ProjectManager::saveZone(const QStringList &info, const QDir &dir)
800
801
802
{
    pCore->bin()->saveZone(info, dir);
}
803

804
805
806
void ProjectManager::moveProjectData(const QString &src, const QString &dest)
{
    // Move tmp folder (thumbnails, timeline preview)
Laurent Montel's avatar
Laurent Montel committed
807
    KIO::CopyJob *copyJob = KIO::move(QUrl::fromLocalFile(src), QUrl::fromLocalFile(dest));
Laurent Montel's avatar
Laurent Montel committed
808
    connect(copyJob, &KJob::result, this, &ProjectManager::slotMoveFinished);
Laurent Montel's avatar
Laurent Montel committed
809
    connect(copyJob, SIGNAL(percent(KJob *, ulong)), this, SLOT(slotMoveProgress(KJob *, ulong)));
810
811
812
    m_project->moveProjectData(src, dest);
}

813
814
void ProjectManager::slotMoveProgress(KJob *, unsigned long progress)
{
815
    pCore->window()->slotGotProgressInfo(i18n("Moving project folder"), static_cast<int>(progress), ProcessingJobMessage);
816
817
818
819
820
821
}

void ProjectManager::slotMoveFinished(KJob *job)
{
    if (job->error() == 0) {
        pCore->window()->slotGotProgressInfo(QString(), 100, InformationMessage);
Nicolas Carion's avatar
Nicolas Carion committed
822
        auto *copyJob = static_cast<KIO::CopyJob *>(job);
823
        QString newFolder = copyJob->destUrl().toLocalFile();