forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProject.cpp
2914 lines (2516 loc) · 100 KB
/
Project.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <https://natrongithub.github.io/>,
* (C) 2018-2021 The Natron developers
* (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat
*
* Natron 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 2 of the License, or
* (at your option) any later version.
*
* Natron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
// ***** BEGIN PYTHON BLOCK *****
// from <https://docs.python.org/3/c-api/intro.html#include-files>:
// "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included."
#include <Python.h>
// ***** END PYTHON BLOCK *****
#include "Project.h"
#include <fstream>
#include <algorithm> // min, max
#include <ios>
#include <cstdlib> // strtoul
#include <cerrno> // errno
#include <cassert>
#include <stdexcept>
#if !defined(SBK_RUN) && !defined(Q_MOC_RUN)
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF
#include <boost/algorithm/string/predicate.hpp>
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_ON
#endif
#ifdef __NATRON_WIN32__
#include <stdio.h> //for _snprintf
#include <windows.h> //for GetUserName
#include <Lmcons.h> //for UNLEN
#define snprintf _snprintf
#elif defined(__NATRON_UNIX__)
#include <pwd.h> //for getpwuid
#endif
#include <QtCore/QCoreApplication>
#include <QtCore/QTimer>
#include <QtCore/QThread>
#include <QtCore/QDir>
#include <QtCore/QDirIterator>
#include <QtCore/QTemporaryFile>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtNetwork/QHostInfo>
#include <QtConcurrentRun> // QtCore on Qt4, QtConcurrent on Qt5
#include <ofxhXml.h> // OFX::XML::escape
#include "Global/StrUtils.h"
#include "Global/FStreamsSupport.h"
#ifdef DEBUG
#include "Global/FloatingPointExceptions.h"
#endif
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/CreateNodeArgs.h"
#include "Engine/BezierCPSerialization.h"
#include "Engine/EffectInstance.h"
#include "Engine/FormatSerialization.h"
#include "Engine/Hash64.h"
#include "Engine/KnobFile.h"
#include "Engine/Node.h"
#include "Engine/OutputSchedulerThread.h"
#include "Engine/ProjectPrivate.h"
#include "Engine/ProjectSerialization.h"
#include "Engine/RectDSerialization.h"
#include "Engine/RectISerialization.h"
#include "Engine/RotoLayer.h"
#include "Engine/Settings.h"
#include "Engine/StandardPaths.h"
#include "Engine/ViewerInstance.h"
#include "Engine/ViewIdx.h"
NATRON_NAMESPACE_ENTER
using std::cout; using std::endl;
using std::make_pair;
static std::string
getUserName()
{
#ifdef __NATRON_WIN32__
wchar_t user_name[UNLEN + 1];
DWORD user_name_size = sizeof(user_name);
GetUserNameW(user_name, &user_name_size);
std::wstring wUserName(user_name);
std::string sUserName = StrUtils::utf16_to_utf8(wUserName);
return sUserName;
#elif defined(__NATRON_UNIX__)
struct passwd *passwd;
passwd = getpwuid( getuid() );
return passwd->pw_name;
#endif
}
static std::string
generateGUIUserName()
{
return getUserName() + '@' + QHostInfo::localHostName().toStdString();
}
static std::string
generateUserFriendlyNatronVersionName()
{
std::string ret(NATRON_APPLICATION_NAME);
ret.append(" v");
ret.append(NATRON_VERSION_STRING);
const std::string status(NATRON_DEVELOPMENT_STATUS);
ret.append(" " NATRON_DEVELOPMENT_STATUS);
if (status == NATRON_DEVELOPMENT_RELEASE_CANDIDATE) {
ret.append( QString::number(NATRON_BUILD_NUMBER).toStdString() );
}
return ret;
}
Project::Project(const AppInstancePtr& appInstance)
: KnobHolder(appInstance)
, NodeCollection(appInstance)
, _imp( new ProjectPrivate(this) )
{
QObject::connect( _imp->autoSaveTimer.get(), SIGNAL(timeout()), this, SLOT(onAutoSaveTimerTriggered()) );
}
// make_shared enabler (because make_shared needs access to the private constructor)
// see https://stackoverflow.com/a/20961251/2607517
struct Project::MakeSharedEnabler: public Project
{
MakeSharedEnabler(const AppInstancePtr& appInstance) : Project(appInstance) {
}
};
ProjectPtr
Project::create(const AppInstancePtr& appInstance)
{
return boost::make_shared<Project::MakeSharedEnabler>(appInstance);
}
Project::~Project()
{
///wait for all autosaves to finish
for (std::list<boost::shared_ptr<QFutureWatcher<void> > >::iterator it = _imp->autoSaveFutures.begin(); it != _imp->autoSaveFutures.end(); ++it) {
(*it)->waitForFinished();
}
///Don't clear autosaves if the program is shutting down by user request.
///Even if the user replied she/he didn't want to save the current work, we keep an autosave of it.
//removeAutoSaves();
}
NATRON_NAMESPACE_ANONYMOUS_ENTER
class LoadProjectSplashScreen_RAII
{
AppInstanceWPtr app;
public:
LoadProjectSplashScreen_RAII(const AppInstancePtr& app,
const QString& filename)
: app(app)
{
if (app) {
app->createLoadProjectSplashScreen(filename);
}
}
~LoadProjectSplashScreen_RAII()
{
AppInstancePtr a = app.lock();
if (a) {
a->closeLoadProjectSplashScreen();
}
}
};
NATRON_NAMESPACE_ANONYMOUS_EXIT
bool
Project::loadProject(const QString & path,
const QString & name,
bool isUntitledAutosave,
bool attemptToLoadAutosave)
{
reset(false, true);
try {
QString realPath = path;
StrUtils::ensureLastPathSeparator(realPath);
QString realName = name;
bool isAutoSave = isUntitledAutosave;
if (!getApp()->isBackground() && !isUntitledAutosave) {
// In Gui mode, attempt to load an auto-save for this project if there's one.
QString autosaveFileName;
bool hasAutoSave = findAutoSaveForProject(realPath, name, &autosaveFileName);
if (hasAutoSave) {
StandardButtonEnum ret = eStandardButtonNo;
if (attemptToLoadAutosave) {
QString text = tr("A recent auto-save of %1 was found.\n"
"Would you like to use it instead? "
"Clicking No will remove this auto-save.").arg(name);
ret = Dialogs::questionDialog(tr("Auto-save").toStdString(),
text.toStdString(), false, StandardButtons(eStandardButtonYes | eStandardButtonNo),
eStandardButtonYes);
}
if ( (ret == eStandardButtonNo) || (ret == eStandardButtonEscape) ) {
QFile::remove(realPath + autosaveFileName);
} else {
realName = autosaveFileName;
isAutoSave = true;
{
QMutexLocker k(&_imp->projectLock);
_imp->lastAutoSaveFilePath = realPath + realName;
}
}
}
}
bool mustSave = false;
if ( !loadProjectInternal(realPath, realName, isAutoSave, isUntitledAutosave, &mustSave) ) {
appPTR->showErrorLog();
} else if (mustSave) {
saveProject(realPath, realName, 0);
}
} catch (const std::exception & e) {
Dialogs::errorDialog( tr("Project loader").toStdString(), tr("Error while loading project: %1").arg( QString::fromUtf8( e.what() ) ).toStdString() );
if ( !getApp()->isBackground() ) {
CreateNodeArgs args(PLUGINID_NATRON_VIEWER, shared_from_this() );
args.setProperty<bool>(kCreateNodeArgsPropAutoConnect, false);
args.setProperty<bool>(kCreateNodeArgsPropAddUndoRedoCommand, false);
getApp()->createNode(args);
}
return false;
} catch (...) {
Dialogs::errorDialog( tr("Project loader").toStdString(), tr("Unknown error while loading project.").toStdString() );
if ( !getApp()->isBackground() ) {
CreateNodeArgs args(PLUGINID_NATRON_VIEWER, shared_from_this() );
args.setProperty<bool>(kCreateNodeArgsPropAutoConnect, false);
args.setProperty<bool>(kCreateNodeArgsPropAddUndoRedoCommand, false);
getApp()->createNode(args);
}
return false;
}
refreshViewersAndPreviews();
return true;
} // loadProject
bool
Project::loadProjectInternal(const QString & path,
const QString & name,
bool isAutoSave,
bool isUntitledAutosave,
bool* mustSave)
{
FlagSetter loadingProjectRAII(true, &_imp->isLoadingProject, &_imp->isLoadingProjectMutex);
QString filePath = path + name;
std::cout << tr("Loading project: %1").arg(filePath).toStdString() << std::endl;
if ( !QFile::exists(filePath) ) {
throw std::invalid_argument( QString( filePath + QString::fromUtf8(" : no such file.") ).toStdString() );
}
bool ret = false;
FStreamsSupport::ifstream ifile;
FStreamsSupport::open( &ifile, filePath.toStdString() );
if (!ifile) {
throw std::runtime_error( tr("Failed to open %1").arg(filePath).toStdString() );
}
if ( (NATRON_VERSION_MAJOR == 1) && (NATRON_VERSION_MINOR == 0) && (NATRON_VERSION_REVISION == 0) ) {
///Try to determine if the project was made during Natron v1.0.0 - RC2 or RC3 to detect a bug we introduced at that time
///in the BezierCP class serialisation
bool foundV = false;
QFile f(filePath);
f.open(QIODevice::ReadOnly);
QTextStream fs(&f);
while ( !fs.atEnd() ) {
QString line = fs.readLine();
if ( (line.indexOf( QString::fromUtf8("Natron v1.0.0 RC2") ) != -1) || (line.indexOf( QString::fromUtf8("Natron v1.0.0 RC3") ) != -1) ) {
appPTR->setProjectCreatedDuringRC2Or3(true);
foundV = true;
break;
}
}
if (!foundV) {
appPTR->setProjectCreatedDuringRC2Or3(false);
}
}
LoadProjectSplashScreen_RAII __raii_splashscreen__(getApp(), name);
try {
bool bgProject;
boost::archive::xml_iarchive iArchive(ifile);
{
FlagSetter __raii_loadingProjectInternal__(true, &_imp->isLoadingProjectInternal, &_imp->isLoadingProjectMutex);
iArchive >> boost::serialization::make_nvp("Background_project", bgProject);
ProjectSerialization projectSerializationObj( getApp() );
iArchive >> boost::serialization::make_nvp("Project", projectSerializationObj);
ret = load(projectSerializationObj, name, path, mustSave);
} // __raii_loadingProjectInternal__
if (!bgProject) {
getApp()->loadProjectGui(isAutoSave, iArchive);
}
} catch (const std::exception &e) {
const ProjectBeingLoadedInfo& pInfo = getApp()->getProjectBeingLoadedInfo();
if (pInfo.vMajor > NATRON_VERSION_MAJOR ||
(pInfo.vMajor == NATRON_VERSION_MAJOR && pInfo.vMinor > NATRON_VERSION_MINOR) ||
(pInfo.vMajor == NATRON_VERSION_MAJOR && pInfo.vMinor == NATRON_VERSION_MINOR && pInfo.vRev > NATRON_VERSION_REVISION)) {
QString message = tr("This project was saved with a more recent version (%1.%2.%3) of %4. Projects are not forward compatible and may only be opened in a version of %4 equal or more recent than the version that saved it.").arg(pInfo.vMajor).arg(pInfo.vMinor).arg(pInfo.vRev).arg(QString::fromUtf8(NATRON_APPLICATION_NAME));
throw std::runtime_error(message.toStdString());
}
throw std::runtime_error( tr("Unrecognized or damaged project file:").toStdString() + ' ' + e.what());
} catch (...) {
const ProjectBeingLoadedInfo& pInfo = getApp()->getProjectBeingLoadedInfo();
if (pInfo.vMajor > NATRON_VERSION_MAJOR ||
(pInfo.vMajor == NATRON_VERSION_MAJOR && pInfo.vMinor > NATRON_VERSION_MINOR) ||
(pInfo.vMajor == NATRON_VERSION_MAJOR && pInfo.vMinor == NATRON_VERSION_MINOR && pInfo.vRev > NATRON_VERSION_REVISION)) {
QString message = tr("This project was saved with a more recent version (%1.%2.%3) of %4. Projects are not forward compatible and may only be opened in a version of %4 equal or more recent than the version that saved it.").arg(pInfo.vMajor).arg(pInfo.vMinor).arg(pInfo.vRev).arg(QString::fromUtf8(NATRON_APPLICATION_NAME));
throw std::runtime_error(message.toStdString());
}
throw std::runtime_error( tr("Unrecognized or damaged project file").toStdString() );
}
Format f;
getProjectDefaultFormat(&f);
Q_EMIT formatChanged(f);
_imp->natronVersion->setValue( generateUserFriendlyNatronVersionName() );
if (isAutoSave) {
_imp->autoSetProjectFormat = false;
if (!isUntitledAutosave) {
QString projectFilename = QString::fromUtf8( _imp->getProjectFilename().c_str() );
int found = projectFilename.lastIndexOf( QString::fromUtf8(".autosave") );
if (found != -1) {
_imp->setProjectFilename( projectFilename.left(found).toStdString() );
}
_imp->hasProjectBeenSavedByUser = true;
} else {
_imp->hasProjectBeenSavedByUser = false;
_imp->setProjectFilename(NATRON_PROJECT_UNTITLED);
_imp->setProjectPath("");
}
_imp->lastAutoSave = QDateTime::currentDateTime();
_imp->ageSinceLastSave = QDateTime();
_imp->lastAutoSaveFilePath = filePath;
QString projectPath = QString::fromUtf8( _imp->getProjectPath().c_str() );
QString projectFilename = QString::fromUtf8( _imp->getProjectFilename().c_str() );
Q_EMIT projectNameChanged(projectPath + projectFilename, true);
} else {
Q_EMIT projectNameChanged(path + name, false);
}
///Try to take the project lock by creating a lock file
if (!isAutoSave) {
QString lockFilePath = getLockAbsoluteFilePath();
if ( !QFile::exists(lockFilePath) ) {
createLockFile();
}
}
_imp->runOnProjectLoadCallback();
///Process all events before flagging that we're no longer loading the project
///to avoid multiple renders being called because of reshape events of viewers
{
#ifdef DEBUG
boost_adaptbx::floating_point::exception_trapping trap(0);
#endif
QCoreApplication::processEvents();
}
return ret;
} // Project::loadProjectInternal
bool
Project::saveProject(const QString & path,
const QString & name,
QString* newFilePath)
{
return saveProject_imp(path, name, false, true, newFilePath);
}
bool
Project::saveProject_imp(const QString & path,
const QString & name,
bool autoS,
bool updateProjectProperties,
QString* newFilePath)
{
{
QMutexLocker l(&_imp->isLoadingProjectMutex);
if (_imp->isLoadingProject) {
return false;
}
}
{
QMutexLocker l(&_imp->isSavingProjectMutex);
if (_imp->isSavingProject) {
return false;
} else {
_imp->isSavingProject = true;
}
}
QString ret;
try {
if (!autoS) {
//if (!isSaveUpToDate() || !QFile::exists(path+name)) {
//We are saving, do not autosave.
_imp->autoSaveTimer->stop();
ret = saveProjectInternal(path, name, false, updateProjectProperties);
///We just saved, remove the last auto-save which is now obsolete
removeLastAutosave();
//}
} else {
if (updateProjectProperties) {
///Replace the last auto-save with a more recent one
removeLastAutosave();
}
ret = saveProjectInternal(path, name, true, updateProjectProperties);
}
} catch (const std::exception & e) {
if (!autoS) {
Dialogs::errorDialog( tr("Save").toStdString(), e.what() );
} else {
qDebug() << "Save failure: " << e.what();
}
}
{
QMutexLocker l(&_imp->isSavingProjectMutex);
_imp->isSavingProject = false;
}
///Save caches ToC
appPTR->saveCaches();
if (newFilePath) {
*newFilePath = ret;
}
return true;
} // Project::saveProject_imp
static bool
fileCopy(const QString & source,
const QString & dest)
{
QFile sourceFile(source);
QFile destFile(dest);
bool success = true;
success &= sourceFile.open( QFile::ReadOnly );
success &= destFile.open( QFile::WriteOnly | QFile::Truncate );
success &= destFile.write( sourceFile.readAll() ) >= 0;
sourceFile.close();
destFile.close();
return success;
}
static QStringList
findBackups(const QString & filePath)
{
QStringList ret;
if ( QFile::exists(filePath) ) {
ret.append(filePath);
}
// find files matching filePath.~[0-9]+~
QRegExp rx(QString::fromUtf8("\\.~(\\d+)~$"));
QFileInfo fileInfo(filePath);
QString fileName = fileInfo.fileName();
QDirIterator it(fileInfo.dir());
while (it.hasNext()) {
QString filename = it.next();
QFileInfo file(filename);
if (file.isDir()) { // Check if it's a dir
continue;
}
// If the filename contains target string - put it in the hitlist
QString fn = file.fileName();
if (fn.startsWith(fileName) && rx.lastIndexIn(fn) == fileName.size()) {
ret.append(file.filePath());
}
}
ret.sort();
return ret;
}
// if filePath matches .*\.~[0-9]+~, increment the backup number
// else append .~1~
static QString
nextBackup(const QString & filePath)
{
QRegExp rx(QString::fromUtf8("\\.~(\\d+)~$"));
int pos = rx.lastIndexIn(filePath);
if (pos >= 0) {
int i = rx.cap(1).toInt();
return filePath.left(pos) + QString::fromUtf8(".~%1~").arg(i+1);
} else {
return filePath + QString::fromUtf8(".~1~");
}
}
QString
Project::saveProjectInternal(const QString & path,
const QString & name,
bool autoSave,
bool updateProjectProperties)
{
bool isRenderSave = name.contains( QString::fromUtf8("RENDER_SAVE") );
QDateTime time = QDateTime::currentDateTime();
QString timeStr = time.toString();
QString filePath;
if (autoSave) {
bool appendTimeHash = false;
if ( path.isEmpty() ) {
filePath = autoSavesDir();
//If the auto-save is saved in the AutoSaves directory, there will be other autosaves for other opened
//projects. We uniquely identity it with the time hash of the current time
appendTimeHash = true;
} else {
filePath = path;
}
filePath.append( QLatin1Char('/') );
filePath.append(name);
if (!isRenderSave) {
filePath.append( QString::fromUtf8(".autosave") );
}
if (!isRenderSave) {
if (appendTimeHash) {
Hash64 timeHash;
Q_FOREACH(QChar ch, timeStr) {
timeHash.append<unsigned short>( ch.unicode() );
}
timeHash.computeHash();
QString timeHashStr = QString::number( timeHash.value() );
filePath.append(QLatin1Char('.') + timeHashStr);
}
}
if (updateProjectProperties) {
QMutexLocker l(&_imp->projectLock);
_imp->lastAutoSaveFilePath = filePath;
}
} else {
filePath = path + name;
}
std::string newFilePath = _imp->runOnProjectSaveCallback(filePath.toStdString(), autoSave);
filePath = QString::fromUtf8( newFilePath.c_str() );
///Use a temporary file to save, so if Natron crashes it doesn't corrupt the user save.
QString tmpFilename = StandardPaths::writableLocation(StandardPaths::eStandardLocationTemp);
StrUtils::ensureLastPathSeparator(tmpFilename);
tmpFilename.append( QString::number( time.toMSecsSinceEpoch() ) );
{
FStreamsSupport::ofstream ofile;
FStreamsSupport::open( &ofile, tmpFilename.toStdString() );
if (!ofile) {
throw std::runtime_error( tr("Failed to open file ").toStdString() + tmpFilename.toStdString() );
}
///Fix file paths before saving.
QString oldProjectPath = QString::fromUtf8( _imp->getProjectPath().c_str() );
if (!autoSave && updateProjectProperties) {
_imp->autoSetProjectDirectory(path);
_imp->saveDate->setValue( timeStr.toStdString() );
_imp->lastAuthorName->setValue( generateGUIUserName() );
_imp->natronVersion->setValue( generateUserFriendlyNatronVersionName() );
}
try {
boost::archive::xml_oarchive oArchive(ofile);
bool bgProject = getApp()->isBackground();
oArchive << boost::serialization::make_nvp("Background_project", bgProject);
ProjectSerialization projectSerializationObj( getApp() );
save(&projectSerializationObj);
oArchive << boost::serialization::make_nvp("Project", projectSerializationObj);
if (!bgProject) {
AppInstancePtr app = getApp();
if (app) {
app->saveProjectGui(oArchive);
}
}
} catch (...) {
if (!autoSave && updateProjectProperties) {
///Reset the old project path in case of failure.
_imp->autoSetProjectDirectory(oldProjectPath);
}
throw;
}
} // ofile
if (!autoSave) {
// rotate backups
int saveVersions = appPTR->getCurrentSettings()->saveVersions();
// find the list of ordered backups (including the file itself if it exists)
QStringList backups = findBackups(filePath);
// remove extra backups
for (int i = backups.size() - 1; i >= saveVersions; --i) {
if ( QFile::exists(backups.last()) ) {
QFile::remove(backups.last());
}
backups.removeLast();
}
// rename existing backups
for (int i = backups.size() - 1; i >= 0; --i) {
QFile::rename(backups.at(i), nextBackup(backups.at(i)));
}
}
if (!QFile::rename(tmpFilename, filePath)) {
// QFile::rename() may fail, e.g. if tmpFilename and filePath are not on the same partition
if (!QFile::copy(tmpFilename, filePath)) {
int nAttemps = 0;
while ( nAttemps < 10 && !fileCopy(tmpFilename, filePath) ) {
++nAttemps;
}
if (nAttemps >= 10) {
throw std::runtime_error( "Failed to save to " + filePath.toStdString() );
}
}
QFile::remove(tmpFilename);
}
if (!autoSave && updateProjectProperties) {
QString lockFilePath = getLockAbsoluteFilePath();
if ( QFile::exists(lockFilePath) ) {
///Remove the previous lock file if there was any
removeLockFile();
}
{
_imp->setProjectFilename( name.toStdString() );
_imp->setProjectPath( path.toStdString() );
QMutexLocker l(&_imp->projectLock);
_imp->hasProjectBeenSavedByUser = true;
_imp->ageSinceLastSave = time;
}
Q_EMIT projectNameChanged(path + name, false); //< notify the gui so it can update the title
//Create the lock file corresponding to the project
createLockFile();
} else if (updateProjectProperties) {
if (!isRenderSave) {
QString projectPath = QString::fromUtf8( _imp->getProjectPath().c_str() );
QString projectFilename = QString::fromUtf8( _imp->getProjectFilename().c_str() );
Q_EMIT projectNameChanged(projectPath + projectFilename, true);
}
}
if (updateProjectProperties) {
_imp->lastAutoSave = time;
}
return filePath;
} // saveProjectInternal
void
Project::autoSave()
{
///don't autosave in background mode...
if ( getApp()->isBackground() ) {
return;
}
QString path = QString::fromUtf8( _imp->getProjectPath().c_str() );
QString name = QString::fromUtf8( _imp->getProjectFilename().c_str() );
saveProject_imp(path, name, true, true, 0);
}
void
Project::triggerAutoSave()
{
///Should only be called in the main-thread, that is upon user interaction.
assert( QThread::currentThread() == qApp->thread() );
if ( getApp()->isBackground() || !appPTR->isLoaded() || isProjectClosing() ) {
return;
}
if ( !hasProjectBeenSavedByUser() && !appPTR->getCurrentSettings()->isAutoSaveEnabledForUnsavedProjects() ) {
return;
}
{
QMutexLocker l(&_imp->isLoadingProjectMutex);
if (_imp->isLoadingProject) {
return;
}
}
_imp->autoSaveTimer->start( appPTR->getCurrentSettings()->getAutoSaveDelayMS() );
}
void
Project::onAutoSaveTimerTriggered()
{
assert( !getApp()->isBackground() );
if ( !getApp() ) {
return;
}
///check that all schedulers are not working.
///If so launch an auto-save, otherwise, restart the timer.
bool canAutoSave = !hasNodeRendering() && !getApp()->isShowingDialog();
if (canAutoSave) {
boost::shared_ptr<QFutureWatcher<void> > watcher = boost::make_shared<QFutureWatcher<void> >();
QObject::connect( watcher.get(), SIGNAL(finished()), this, SLOT(onAutoSaveFutureFinished()) );
watcher->setFuture( QtConcurrent::run(this, &Project::autoSave) );
_imp->autoSaveFutures.push_back(watcher);
} else {
///If the auto-save failed because a render is in progress, try every 2 seconds to auto-save.
///We don't use the user-provided timeout interval here because it could be an inapropriate value.
_imp->autoSaveTimer->start(2000);
}
}
void
Project::onAutoSaveFutureFinished()
{
QFutureWatcherBase* future = qobject_cast<QFutureWatcherBase*>( sender() );
assert(future);
for (std::list<boost::shared_ptr<QFutureWatcher<void> > >::iterator it = _imp->autoSaveFutures.begin(); it != _imp->autoSaveFutures.end(); ++it) {
if (it->get() == future) {
_imp->autoSaveFutures.erase(it);
break;
}
}
}
bool
Project::findAutoSaveForProject(const QString& projectPath,
const QString& projectName,
QString* autoSaveFileName)
{
QString projectAbsFilePath = projectPath + projectName;
QDir savesDir(projectPath);
QStringList entries = savesDir.entryList(QDir::Files | QDir::NoDotAndDotDot);
Q_FOREACH(const QString &entry, entries) {
QString ntpExt( QLatin1Char('.') );
ntpExt.append( QString::fromUtf8(NATRON_PROJECT_FILE_EXT) );
QString searchStr(ntpExt);
QString autosaveSuffix( QString::fromUtf8(".autosave") );
searchStr.append(autosaveSuffix);
int suffixPos = entry.indexOf(searchStr);
if ( (suffixPos == -1) || entry.contains( QString::fromUtf8("RENDER_SAVE") ) ) {
continue;
}
QString filename = projectPath + entry.left( suffixPos + ntpExt.size() );
if ( (filename == projectAbsFilePath) && QFile::exists(filename) ) {
*autoSaveFileName = entry;
return true;
}
}
return false;
}
void
Project::initializeKnobs()
{
KnobPagePtr page = AppManager::createKnob<KnobPage>( this, tr("Settings") );
_imp->envVars = AppManager::createKnob<KnobPath>( this, tr("Project Paths") );
_imp->envVars->setName("projectPaths");
_imp->envVars->setHintToolTip( tr("Specify here project paths. Any path can be used "
"in file paths and can be used between brackets, for example: \n"
"[%1]MyProject.ntp \n"
"You can add as many project paths as you want and can name them as you want. This way it "
"makes it easy to share your projects and move files around."
" You can chain up paths, like so:\n "
"[%1] = <PathToProject> \n"
"[Scene1] = [%1]/Rush/S_01 \n"
"[Shot1] = [Scene1]/Shot001 \n"
"By default if a file-path is NOT absolute (i.e: not starting with '/' "
" on Unix or a drive name on Windows) "
"then it will be expanded using the [%1] path. "
"Absolute paths are treated as normal."
" The [%1] path will be set automatically to "
" the location of the project file when saving and loading a project."
" The [%2] path will also be set automatically for better sharing of projects with reader nodes.").arg( QString::fromUtf8(NATRON_PROJECT_ENV_VAR_NAME) ).arg( QString::fromUtf8(NATRON_OCIO_ENV_VAR_NAME) ) );
_imp->envVars->setSecret(false);
_imp->envVars->setMultiPath(true);
///Initialize the OCIO Config
onOCIOConfigPathChanged(appPTR->getOCIOConfigPath(), false);
page->addKnob(_imp->envVars);
_imp->formatKnob = AppManager::createKnob<KnobChoice>( this, tr("Project Format") );
_imp->formatKnob->setHintToolTip( tr("The project format is used as the default workspace size for viewers, the default format for generators, and the default output format for writers. In most cases this should match your plate resolution.") );
_imp->formatKnob->setName("outputFormat");
const std::vector<Format> & appFormats = appPTR->getFormats();
std::vector<ChoiceOption> entries;
for (U32 i = 0; i < appFormats.size(); ++i) {
const Format& f = appFormats[i];
QString formatStr = ProjectPrivate::generateStringFromFormat(f);
if ( (f.width() == 1920) && (f.height() == 1080) && (f.getPixelAspectRatio() == 1) ) {
_imp->formatKnob->setDefaultValue(i, 0);
}
if ( !f.getName().empty() ) {
entries.push_back( ChoiceOption(f.getName(), formatStr.toStdString(), "") );
} else {
entries.push_back( ChoiceOption( formatStr.toStdString() ) );
}
_imp->builtinFormats.push_back(f);
}
_imp->formatKnob->setAddNewLine(false);
_imp->formatKnob->populateChoices(entries);
_imp->formatKnob->setAnimationEnabled(false);
page->addKnob(_imp->formatKnob);
QObject::connect( _imp->formatKnob.get(), SIGNAL(populated()), this, SLOT(onProjectFormatPopulated()) );
_imp->addFormatKnob = AppManager::createKnob<KnobButton>( this, tr("New Format...") );
_imp->addFormatKnob->setName("newFormat");
page->addKnob(_imp->addFormatKnob);
_imp->previewMode = AppManager::createKnob<KnobBool>( this, tr("Auto Previews") );
_imp->previewMode->setName("autoPreviews");
_imp->previewMode->setHintToolTip( tr("When checked, preview images in the node graph will be "
"refreshed automatically. Disabling this will improve performance.") );
_imp->previewMode->setAnimationEnabled(false);
_imp->previewMode->setEvaluateOnChange(false);
page->addKnob(_imp->previewMode);
bool autoPreviewEnabled = appPTR->getCurrentSettings()->isAutoPreviewOnForNewProjects();
_imp->previewMode->setDefaultValue(autoPreviewEnabled, 0);
_imp->frameRange = AppManager::createKnob<KnobInt>(this, tr("Frame Range"), 2);
_imp->frameRange->setDefaultValue(1, 0);
_imp->frameRange->setDefaultValue(250, 1);
_imp->frameRange->setDimensionName(0, "first");
_imp->frameRange->setDimensionName(1, "last");
_imp->frameRange->setEvaluateOnChange(false);
_imp->frameRange->setName("frameRange");
_imp->frameRange->setHintToolTip( tr("The frame range of the project as seen by plug-ins. New viewers are created automatically "
"with this frame-range. By default when the first Read node is created, this range "
"will be set to the "
"sequence legnth, unless the Lock Range parameter is checked.") );
_imp->frameRange->setAnimationEnabled(false);
_imp->frameRange->setAddNewLine(false);
page->addKnob(_imp->frameRange);
_imp->lockFrameRange = AppManager::createKnob<KnobBool>( this, tr("Lock Range") );
_imp->lockFrameRange->setName("lockRange");
_imp->lockFrameRange->setDefaultValue(false);
_imp->lockFrameRange->setAnimationEnabled(false);
_imp->lockFrameRange->setHintToolTip( tr("By default when the first Read node is created, this range will be set to the "
"sequence length, unless this parameter is checked.") );
_imp->lockFrameRange->setEvaluateOnChange(false);
page->addKnob(_imp->lockFrameRange);
_imp->frameRate = AppManager::createKnob<KnobDouble>( this, tr("Frame Rate") );
_imp->frameRate->setName("frameRate");
_imp->frameRate->setHintToolTip( tr("The frame rate of the project. This will serve as a default value for all effects that don't produce "
"special frame rates.") );
_imp->frameRate->setAnimationEnabled(false);
_imp->frameRate->setDefaultValue(24);
_imp->frameRate->setDisplayMinimum(0.);
_imp->frameRate->setDisplayMaximum(50.);
page->addKnob(_imp->frameRate);
_imp->gpuSupport = AppManager::createKnob<KnobChoice>( this, tr("GPU Rendering") );
_imp->gpuSupport->setName("gpuRendering");
{
std::vector<ChoiceOption> entries;
entries.push_back(ChoiceOption("Enabled","",tr("Enable GPU rendering if required resources are available and the plugin supports it.").toStdString()));
entries.push_back(ChoiceOption("Disabled", "", tr("Disable GPU rendering for all plug-ins.").toStdString()));
entries.push_back(ChoiceOption("Disabled if background","",tr("Disable GPU rendering when rendering with NatronRenderer but not in GUI mode.").toStdString()));
_imp->gpuSupport->populateChoices(entries);
}
_imp->gpuSupport->setAnimationEnabled(false);
_imp->gpuSupport->setHintToolTip( tr("Select when to activate GPU rendering for plug-ins. Note that if the OpenGL Rendering parameter in the Preferences/GPU Rendering is set to disabled then GPU rendering will not be activated regardless of that value.") );
_imp->gpuSupport->setEvaluateOnChange(false);
if (!appPTR->getCurrentSettings()->isOpenGLRenderingEnabled()) {
_imp->gpuSupport->setAllDimensionsEnabled(false);
}
page->addKnob(_imp->gpuSupport);
KnobPagePtr viewsPage = AppManager::createKnob<KnobPage>( this, tr("Views") );
_imp->viewsList = AppManager::createKnob<KnobPath>( this, tr("Views List") );
_imp->viewsList->setName("viewsList");
_imp->viewsList->setHintToolTip( tr("The list of the views in the project") );
_imp->viewsList->setAnimationEnabled(false);
_imp->viewsList->setEvaluateOnChange(false);
_imp->viewsList->setAsStringList(true);
std::list<std::string> defaultViews;
defaultViews.push_back("Main");
std::string encodedDefaultViews = _imp->viewsList->encodeToKnobTableFormatSingleCol(defaultViews);
_imp->viewsList->setDefaultValue(encodedDefaultViews);
viewsPage->addKnob(_imp->viewsList);
_imp->setupForStereoButton = AppManager::createKnob<KnobButton>( this, tr("Setup views for stereo") );
_imp->setupForStereoButton->setName("setupForStereo");
_imp->setupForStereoButton->setHintToolTip( tr("Quickly setup the views list for stereo") );
_imp->setupForStereoButton->setEvaluateOnChange(false);
viewsPage->addKnob(_imp->setupForStereoButton);
KnobPagePtr LayersPage = AppManager::createKnob<KnobPage>( this, tr("Layers") );
_imp->defaultLayersList = AppManager::createKnob<KnobLayers>( this, tr("Default Layers") );
_imp->defaultLayersList->setName("defaultLayers");
_imp->defaultLayersList->setHintToolTip( tr("The list of the default layers available in layers menus on nodes.") );
_imp->defaultLayersList->setAnimationEnabled(false);
_imp->defaultLayersList->setEvaluateOnChange(false);
std::list<std::vector<std::string> > defaultLayers;
{
std::vector<ImagePlaneDesc> defaultComponents;
defaultComponents.push_back(ImagePlaneDesc::getRGBAComponents());
defaultComponents.push_back(ImagePlaneDesc::getDisparityLeftComponents());
defaultComponents.push_back(ImagePlaneDesc::getDisparityRightComponents());
defaultComponents.push_back(ImagePlaneDesc::getBackwardMotionComponents());
defaultComponents.push_back(ImagePlaneDesc::getForwardMotionComponents());
for (std::size_t i = 0; i < defaultComponents.size(); ++i) {
const ImagePlaneDesc& comps = defaultComponents[i];
std::vector<std::string> row(3);
row[0] = comps.getPlaneLabel();
std::string channelsStr;
const std::vector<std::string>& channels = comps.getChannels();
for (std::size_t c = 0; c < channels.size(); ++c) {
if (c > 0) {
channelsStr += ' ';
}
channelsStr += channels[c];
}
row[1] = channelsStr;
row[2] = comps.getChannelsLabel();
defaultLayers.push_back(row);
}
}
std::string encodedDefaultLayers = _imp->defaultLayersList->encodeToKnobTableFormat(defaultLayers);
_imp->defaultLayersList->setDefaultValue(encodedDefaultLayers);