forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppInstance.cpp
2369 lines (2026 loc) · 85.9 KB
/
AppInstance.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 "AppInstance.h"
#include <fstream>
#include <list>
#include <cassert>
#include <stdexcept>
#include <sstream> // stringstream
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QTextStream>
#include <QtConcurrentMap> // QtCore on Qt4, QtConcurrent on Qt5
#include <QtCore/QUrl>
#include <QtCore/QFileInfo>
#include <QtCore/QEventLoop>
#include <QtCore/QSettings>
#include <QtNetwork/QNetworkReply>
#if !defined(SBK_RUN) && !defined(Q_MOC_RUN)
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_OFF
// /usr/local/include/boost/bind/arg.hpp:37:9: warning: unused typedef 'boost_static_assert_typedef_37' [-Wunused-local-typedef]
#include <boost/bind/bind.hpp>
#include <boost/algorithm/string/predicate.hpp>
GCC_DIAG_UNUSED_LOCAL_TYPEDEFS_ON
#endif
// ofxhPropertySuite.h:565:37: warning: 'this' pointer cannot be null in well-defined C++ code; comparison may be assumed to always evaluate to true [-Wtautological-undefined-compare]
CLANG_DIAG_OFF(unknown-pragmas)
CLANG_DIAG_OFF(tautological-undefined-compare) // appeared in clang 3.5
#include <ofxhImageEffect.h>
CLANG_DIAG_ON(tautological-undefined-compare)
CLANG_DIAG_ON(unknown-pragmas)
#include "Global/QtCompat.h" // removeFileExtension
#include "Engine/BlockingBackgroundRender.h"
#include "Engine/CLArgs.h"
#include "Engine/CreateNodeArgs.h"
#include "Engine/FileDownloader.h"
#include "Engine/GroupOutput.h"
#include "Engine/DiskCacheNode.h"
#include "Engine/ProjectSerialization.h"
#include "Engine/Node.h"
#include "Engine/NodeSerialization.h"
#include "Engine/Plugin.h"
#include "Engine/Project.h"
#include "Engine/ProcessHandler.h"
#include "Engine/ReadNode.h"
#include "Engine/Settings.h"
#include "Engine/WriteNode.h"
using namespace boost::placeholders;
NATRON_NAMESPACE_ENTER
FlagSetter::FlagSetter(bool initialValue,
bool* p)
: p(p)
, lock(0)
{
*p = initialValue;
}
FlagSetter::FlagSetter(bool initialValue,
bool* p,
QMutex* mutex)
: p(p)
, lock(mutex)
{
lock->lock();
*p = initialValue;
lock->unlock();
}
FlagSetter::~FlagSetter()
{
if (lock) {
lock->lock();
}
*p = !*p;
if (lock) {
lock->unlock();
}
}
FlagIncrementer::FlagIncrementer(int* p)
: p(p)
, lock(0)
{
*p = *p + 1;
}
FlagIncrementer::FlagIncrementer(int* p,
QMutex* mutex)
: p(p)
, lock(mutex)
{
lock->lock();
*p = *p + 1;
lock->unlock();
}
FlagIncrementer::~FlagIncrementer()
{
if (lock) {
lock->lock();
}
*p = *p - 1;
if (lock) {
lock->unlock();
}
}
struct RenderQueueItem
{
AppInstance::RenderWork work;
QString sequenceName;
QString savePath;
ProcessHandlerPtr process;
};
struct AppInstancePrivate
{
Q_DECLARE_TR_FUNCTIONS(AppInstance)
public:
AppInstance* _publicInterface;
ProjectPtr _currentProject; //< ptr to the project
int _appID; //< the unique ID of this instance (or window)
bool _projectCreatedWithLowerCaseIDs;
mutable QMutex creatingGroupMutex;
//When a pyplug is created
int _creatingGroup;
// True when a pyplug is being created internally without being shown to the user
bool _creatingInternalNode;
//When a node is created, it gets appended to this list (since for a PyPlug more than 1 node can be created)
std::list<NodePtr> _creatingNodeQueue;
//When a node tree is created
int _creatingTree;
mutable QMutex renderQueueMutex;
std::list<RenderQueueItem> renderQueue, activeRenders;
mutable QMutex invalidExprKnobsMutex;
std::list<KnobIWPtr> invalidExprKnobs;
ProjectBeingLoadedInfo projectBeingLoaded;
AppInstancePrivate(int appID,
AppInstance* app)
: _publicInterface(app)
, _currentProject()
, _appID(appID)
, _projectCreatedWithLowerCaseIDs(false)
, creatingGroupMutex()
, _creatingGroup(0)
, _creatingInternalNode(false)
, _creatingNodeQueue()
, _creatingTree(0)
, renderQueueMutex()
, renderQueue()
, activeRenders()
, invalidExprKnobsMutex()
, invalidExprKnobs()
, projectBeingLoaded()
{
}
void declareCurrentAppVariable_Python();
void executeCommandLinePythonCommands(const CLArgs& args);
bool validateRenderOptions(const AppInstance::RenderWork& w,
int* firstFrame,
int* lastFrame,
int* frameStep);
void getSequenceNameFromWriter(const OutputEffectInstance* writer, QString* sequenceName);
void startRenderingFullSequence(bool blocking, const RenderQueueItem& writerWork);
};
AppInstance::AppInstance(int appID)
: QObject()
, _imp( new AppInstancePrivate(appID, this) )
{
}
AppInstance::~AppInstance()
{
_imp->_currentProject->clearNodesBlocking();
}
const ProjectBeingLoadedInfo&
AppInstance::getProjectBeingLoadedInfo() const
{
assert(QThread::currentThread() == qApp->thread());
return _imp->projectBeingLoaded;
}
void
AppInstance::setProjectBeingLoadedInfo(const ProjectBeingLoadedInfo& info)
{
assert(QThread::currentThread() == qApp->thread());
_imp->projectBeingLoaded = info;
}
const std::list<NodePtr>&
AppInstance::getNodesBeingCreated() const
{
assert( QThread::currentThread() == qApp->thread() );
return _imp->_creatingNodeQueue;
}
bool
AppInstance::isCreatingNodeTree() const
{
QMutexLocker k(&_imp->creatingGroupMutex);
return _imp->_creatingTree;
}
void
AppInstance::setIsCreatingNodeTree(bool b)
{
QMutexLocker k(&_imp->creatingGroupMutex);
if (b) {
++_imp->_creatingTree;
} else {
if (_imp->_creatingTree >= 1) {
--_imp->_creatingTree;
} else {
_imp->_creatingTree = 0;
}
}
}
void
AppInstance::checkForNewVersion() const
{
FileDownloader* downloader = new FileDownloader( QUrl( QString::fromUtf8(NATRON_LATEST_VERSION_URL) ), false );
QObject::connect( downloader, SIGNAL(downloaded()), this, SLOT(newVersionCheckDownloaded()) );
QObject::connect( downloader, SIGNAL(error()), this, SLOT(newVersionCheckError()) );
///make the call blocking
QEventLoop loop;
connect( downloader->getReply(), SIGNAL(finished()), &loop, SLOT(quit()) );
loop.exec();
}
//return -1 if a < b, 0 if a == b and 1 if a > b
//Returns -2 if not understood
static
int
compareDevStatus(const QString& a,
const QString& b)
{
if ( ( a == QString::fromUtf8(NATRON_DEVELOPMENT_DEVEL) ) || ( a == QString::fromUtf8(NATRON_DEVELOPMENT_SNAPSHOT) ) ) {
//Do not try updates when update available is a dev build
return -1;
} else if ( ( b == QString::fromUtf8(NATRON_DEVELOPMENT_DEVEL) ) || ( b == QString::fromUtf8(NATRON_DEVELOPMENT_SNAPSHOT) ) ) {
//This is a dev build, do not try updates
return -1;
} else if ( a == QString::fromUtf8(NATRON_DEVELOPMENT_ALPHA) ) {
if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_ALPHA) ) {
return 0;
} else {
return -1;
}
} else if ( a == QString::fromUtf8(NATRON_DEVELOPMENT_BETA) ) {
if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_ALPHA) ) {
return 1;
} else if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_BETA) ) {
return 0;
} else {
return -1;
}
} else if ( a == QString::fromUtf8(NATRON_DEVELOPMENT_RELEASE_CANDIDATE) ) {
if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_ALPHA) ) {
return 1;
} else if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_BETA) ) {
return 1;
} else if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_RELEASE_CANDIDATE) ) {
return 0;
} else {
return -1;
}
} else if ( a == QString::fromUtf8(NATRON_DEVELOPMENT_RELEASE_STABLE) ) {
if ( b == QString::fromUtf8(NATRON_DEVELOPMENT_RELEASE_STABLE) ) {
return 0;
} else {
return 1;
}
}
assert(false);
return -2;
}
void
AppInstance::newVersionCheckDownloaded()
{
FileDownloader* downloader = qobject_cast<FileDownloader*>( sender() );
assert(downloader);
QString extractedFileVersionStr, extractedSoftwareVersionStr, extractedDevStatusStr, extractedBuildNumberStr;
QString fileVersionTag( QString::fromUtf8("File version: ") );
QString softwareVersionTag( QString::fromUtf8("Software version: ") );
QString devStatusTag( QString::fromUtf8("Development status: ") );
QString buildNumberTag( QString::fromUtf8("Build number: ") );
QString data( QString::fromUtf8( downloader->downloadedData() ) );
QTextStream ts(&data);
while ( !ts.atEnd() ) {
QString line = ts.readLine();
if ( line.startsWith( QChar::fromLatin1('#') ) || line.startsWith( QChar::fromLatin1('\n') ) ) {
continue;
}
if ( line.startsWith(fileVersionTag) ) {
int i = fileVersionTag.size();
while ( i < line.size() && !line.at(i).isSpace() ) {
extractedFileVersionStr.push_back( line.at(i) );
++i;
}
} else if ( line.startsWith(softwareVersionTag) ) {
int i = softwareVersionTag.size();
while ( i < line.size() && !line.at(i).isSpace() ) {
extractedSoftwareVersionStr.push_back( line.at(i) );
++i;
}
} else if ( line.startsWith(devStatusTag) ) {
int i = devStatusTag.size();
while ( i < line.size() && !line.at(i).isSpace() ) {
extractedDevStatusStr.push_back( line.at(i) );
++i;
}
} else if ( line.startsWith(buildNumberTag) ) {
int i = buildNumberTag.size();
while ( i < line.size() && !line.at(i).isSpace() ) {
extractedBuildNumberStr.push_back( line.at(i) );
++i;
}
}
}
downloader->deleteLater();
if ( extractedFileVersionStr.isEmpty() || (extractedFileVersionStr.toInt() < NATRON_LAST_VERSION_FILE_VERSION) ) {
//The file cannot be decoded here
return;
}
QStringList versionDigits = extractedSoftwareVersionStr.split( QChar::fromLatin1('.') );
///we only understand 3 digits formed version numbers
if (versionDigits.size() != 3) {
return;
}
int buildNumber = extractedBuildNumberStr.toInt();
int major = versionDigits[0].toInt();
int minor = versionDigits[1].toInt();
int revision = versionDigits[2].toInt();
const QString currentDevStatus = QString::fromUtf8(NATRON_DEVELOPMENT_STATUS);
int devStatCompare = compareDevStatus(extractedDevStatusStr, currentDevStatus);
int versionEncoded = NATRON_VERSION_ENCODE(major, minor, revision);
bool hasUpdate = false;
if ( (versionEncoded > NATRON_VERSION_ENCODED) ||
( ( versionEncoded == NATRON_VERSION_ENCODED) &&
( ( devStatCompare > 0) || ( ( devStatCompare == 0) && ( buildNumber > NATRON_BUILD_NUMBER) ) ) ) ) {
if (devStatCompare == 0) {
if ( ( buildNumber > NATRON_BUILD_NUMBER) && ( versionEncoded == NATRON_VERSION_ENCODED) ) {
hasUpdate = true;
} else if (versionEncoded > NATRON_VERSION_ENCODED) {
hasUpdate = true;
}
} else {
hasUpdate = true;
}
}
if (hasUpdate) {
const QString popen = QString::fromUtf8("<p>");
const QString pclose = QString::fromUtf8("</p>");
QString text = popen
+ tr("Updates for %1 are now available for download.")
.arg( QString::fromUtf8(NATRON_APPLICATION_NAME) )
+ pclose
+ popen
+ tr("You are currently using %1 version %2 - %3.")
.arg( QString::fromUtf8(NATRON_APPLICATION_NAME) )
.arg( QString::fromUtf8(NATRON_VERSION_STRING) )
.arg( QString::fromUtf8(NATRON_DEVELOPMENT_STATUS) )
+ pclose
+ popen
+ tr("The latest version of %1 is version %4 - %5.")
.arg( QString::fromUtf8(NATRON_APPLICATION_NAME) )
.arg(extractedSoftwareVersionStr)
.arg(extractedDevStatusStr)
+ pclose
+ popen
+ tr("You can download it from %1.")
.arg( QString::fromUtf8("<a href=\"https://natrongithub.github.io/#download\">"
"natrongithub.github.io</a>") )
+ pclose;
Dialogs::informationDialog( tr("New version").toStdString(), text.toStdString(), true );
}
} // AppInstance::newVersionCheckDownloaded
void
AppInstance::newVersionCheckError()
{
///Nothing to do,
FileDownloader* downloader = qobject_cast<FileDownloader*>( sender() );
assert(downloader);
downloader->deleteLater();
}
void
AppInstance::getWritersWorkForCL(const CLArgs& cl,
std::list<AppInstance::RenderWork>& requests)
{
const std::list<CLArgs::WriterArg>& writers = cl.getWriterArgs();
for (std::list<CLArgs::WriterArg>::const_iterator it = writers.begin(); it != writers.end(); ++it) {
NodePtr writerNode;
if (!it->mustCreate) {
std::string writerName = it->name.toStdString();
writerNode = getNodeByFullySpecifiedName(writerName);
if (!writerNode) {
QString s = tr("%1 does not belong to the project file. Please enter a valid Write node script-name.").arg(it->name);
throw std::invalid_argument( s.toStdString() );
} else {
if ( !writerNode->isOutputNode() ) {
QString s = tr("%1 is not an output node! It cannot render anything.").arg(it->name);
throw std::invalid_argument( s.toStdString() );
}
}
if ( !it->filename.isEmpty() ) {
KnobIPtr fileKnob = writerNode->getKnobByName(kOfxImageEffectFileParamName);
if (fileKnob) {
KnobOutputFile* outFile = dynamic_cast<KnobOutputFile*>( fileKnob.get() );
if (outFile) {
outFile->setValue( it->filename.toStdString() );
}
}
}
} else {
CreateNodeArgs args(PLUGINID_NATRON_WRITE, getProject());
args.setProperty<bool>(kCreateNodeArgsPropAddUndoRedoCommand, false);
args.setProperty<bool>(kCreateNodeArgsPropSettingsOpened, false);
args.setProperty<bool>(kCreateNodeArgsPropAutoConnect, false);
writerNode = createWriter( it->filename.toStdString(), args );
if (!writerNode) {
throw std::runtime_error( tr("Failed to create writer for %1.").arg(it->filename).toStdString() );
}
//Connect the writer to the corresponding Output node input
NodePtr output = getProject()->getNodeByFullySpecifiedName( it->name.toStdString() );
if (!output) {
throw std::invalid_argument( tr("%1 is not the name of a valid Output node of the script").arg(it->name).toStdString() );
}
GroupOutput* isGrpOutput = dynamic_cast<GroupOutput*>( output->getEffectInstance().get() );
if (!isGrpOutput) {
throw std::invalid_argument( tr("%1 is not the name of a valid Output node of the script").arg(it->name).toStdString() );
}
NodePtr outputInput = output->getRealInput(0);
if (outputInput) {
writerNode->connectInput(outputInput, 0);
}
}
assert(writerNode);
OutputEffectInstance* effect = dynamic_cast<OutputEffectInstance*>( writerNode->getEffectInstance().get() );
if ( cl.hasFrameRange() ) {
const std::list<std::pair<int, std::pair<int, int> > >& frameRanges = cl.getFrameRanges();
for (std::list<std::pair<int, std::pair<int, int> > >::const_iterator it2 = frameRanges.begin(); it2 != frameRanges.end(); ++it2) {
AppInstance::RenderWork r( effect, it2->second.first, it2->second.second, it2->first, cl.areRenderStatsEnabled() );
requests.push_back(r);
}
} else {
AppInstance::RenderWork r( effect, INT_MIN, INT_MAX, INT_MIN, cl.areRenderStatsEnabled() );
requests.push_back(r);
}
}
} // AppInstance::getWritersWorkForCL
void
AppInstancePrivate::executeCommandLinePythonCommands(const CLArgs& args)
{
const std::list<std::string>& commands = args.getPythonCommands();
for (std::list<std::string>::const_iterator it = commands.begin(); it != commands.end(); ++it) {
std::string err;
std::string output;
bool ok = NATRON_PYTHON_NAMESPACE::interpretPythonScript(*it, &err, &output);
if (!ok) {
const QString sp( QString::fromUtf8(" ") );
QString m = tr("Failed to execute the following Python command:") + sp +
QString::fromUtf8( it->c_str() ) + sp +
tr("Error:") + sp +
QString::fromUtf8( err.c_str() );
throw std::runtime_error( m.toStdString() );
} else if ( !output.empty() ) {
std::cout << output << std::endl;
}
}
}
void
AppInstance::executeCommandLinePythonCommands(const CLArgs& args)
{
_imp->executeCommandLinePythonCommands(args);
}
void
AppInstance::load(const CLArgs& cl,
bool makeEmptyInstance)
{
// Initialize the knobs of the project before loading anything else.
assert(!_imp->_currentProject); // < This function may only be called once per AppInstance
_imp->_currentProject = Project::create( shared_from_this() );
_imp->_currentProject->initializeKnobsPublic();
loadInternal(cl, makeEmptyInstance);
}
void
AppInstance::loadInternal(const CLArgs& cl,
bool makeEmptyInstance)
{
try {
declareCurrentAppVariable_Python();
} catch (const std::exception& e) {
throw std::runtime_error( e.what() );
}
if (makeEmptyInstance) {
return;
}
executeCommandLinePythonCommands(cl);
QString exportDocPath = cl.getExportDocsPath();
if ( !exportDocPath.isEmpty() ) {
exportDocs(exportDocPath);
return;
}
///if the app is a background project autorun and the project name is empty just throw an exception.
if ( ( (appPTR->getAppType() == AppManager::eAppTypeBackgroundAutoRun) ||
( appPTR->getAppType() == AppManager::eAppTypeBackgroundAutoRunLaunchedFromGui) ) ) {
const QString& scriptFilename = cl.getScriptFilename();
if ( scriptFilename.isEmpty() ) {
// cannot start a background process without a file
throw std::invalid_argument( tr("Project file name is empty.").toStdString() );
}
QFileInfo info(scriptFilename);
if ( !info.exists() ) {
throw std::invalid_argument( tr("%1: No such file.").arg(scriptFilename).toStdString() );
}
std::list<AppInstance::RenderWork> writersWork;
if ( info.suffix() == QString::fromUtf8(NATRON_PROJECT_FILE_EXT) ) {
///Load the project
if ( !_imp->_currentProject->loadProject( info.path(), info.fileName() ) ) {
throw std::invalid_argument( tr("Project file loading failed.").toStdString() );
}
} else if ( info.suffix() == QString::fromUtf8("py") ) {
///Load the python script
loadPythonScript(info);
} else {
throw std::invalid_argument( tr("%1 only accepts python scripts or .ntp project files.").arg( QString::fromUtf8(NATRON_APPLICATION_NAME) ).toStdString() );
}
// exec the python script specified via --onload
const QString& extraOnProjectCreatedScript = cl.getDefaultOnProjectLoadedScript();
if ( !extraOnProjectCreatedScript.isEmpty() ) {
QFileInfo cbInfo(extraOnProjectCreatedScript);
if ( cbInfo.exists() ) {
loadPythonScript(cbInfo);
}
}
getWritersWorkForCL(cl, writersWork);
///Set reader parameters if specified from the command-line
const std::list<CLArgs::ReaderArg>& readerArgs = cl.getReaderArgs();
for (std::list<CLArgs::ReaderArg>::const_iterator it = readerArgs.begin(); it != readerArgs.end(); ++it) {
std::string readerName = it->name.toStdString();
NodePtr readNode = getNodeByFullySpecifiedName(readerName);
if (!readNode) {
std::string exc( tr("%1 does not belong to the project file. Please enter a valid Read node script-name.").arg( QString::fromUtf8( readerName.c_str() ) ).toStdString() );
throw std::invalid_argument(exc);
} else {
if ( !readNode->getEffectInstance()->isReader() ) {
std::string exc( tr("%1 is not a Read node! It cannot render anything.").arg( QString::fromUtf8( readerName.c_str() ) ).toStdString() );
throw std::invalid_argument(exc);
}
}
if ( it->filename.isEmpty() ) {
std::string exc( tr("%1: Filename specified is empty but [-i] or [--reader] was passed to the command-line.").arg( QString::fromUtf8( readerName.c_str() ) ).toStdString() );
throw std::invalid_argument(exc);
}
KnobIPtr fileKnob = readNode->getKnobByName(kOfxImageEffectFileParamName);
if (fileKnob) {
KnobFile* outFile = dynamic_cast<KnobFile*>( fileKnob.get() );
if (outFile) {
outFile->setValue( it->filename.toStdString() );
}
}
}
///launch renders
if ( !writersWork.empty() ) {
startWritersRendering(false, writersWork);
} else {
std::list<std::string> writers;
startWritersRenderingFromNames( cl.areRenderStatsEnabled(), false, writers, cl.getFrameRanges() );
}
} else if (appPTR->getAppType() == AppManager::eAppTypeInterpreter) {
QFileInfo info( cl.getScriptFilename() );
if ( info.exists() ) {
if ( info.suffix() == QString::fromUtf8("py") ) {
loadPythonScript(info);
} else if ( info.suffix() == QString::fromUtf8(NATRON_PROJECT_FILE_EXT) ) {
if ( !_imp->_currentProject->loadProject( info.path(), info.fileName() ) ) {
throw std::invalid_argument( tr("Project file loading failed.").toStdString() );
}
}
}
// exec the python script specified via --onload
const QString& extraOnProjectCreatedScript = cl.getDefaultOnProjectLoadedScript();
if ( !extraOnProjectCreatedScript.isEmpty() ) {
QFileInfo cbInfo(extraOnProjectCreatedScript);
if ( cbInfo.exists() ) {
loadPythonScript(cbInfo);
}
}
appPTR->launchPythonInterpreter();
} else {
execOnProjectCreatedCallback();
// exec the python script specified via --onload
const QString& extraOnProjectCreatedScript = cl.getDefaultOnProjectLoadedScript();
if ( !extraOnProjectCreatedScript.isEmpty() ) {
QFileInfo cbInfo(extraOnProjectCreatedScript);
if ( cbInfo.exists() ) {
loadPythonScript(cbInfo);
}
}
}
} // AppInstance::load
bool
AppInstance::loadPythonScript(const QFileInfo& file)
{
std::string addToPythonPath("sys.path.append(\"");
addToPythonPath += file.path().toStdString();
addToPythonPath += "\")\n";
std::string err;
bool ok = NATRON_PYTHON_NAMESPACE::interpretPythonScript(addToPythonPath, &err, 0);
assert(ok);
if (!ok) {
throw std::runtime_error("AppInstance::loadPythonScript(" + file.path().toStdString() + "): interpretPythonScript(" + addToPythonPath + " failed!");
}
std::string s = "app = app1\n";
ok = NATRON_PYTHON_NAMESPACE::interpretPythonScript(s, &err, 0);
assert(ok);
if (!ok) {
throw std::runtime_error("AppInstance::loadPythonScript(" + file.path().toStdString() + "): interpretPythonScript(" + s + " failed!");
}
QFile f( file.absoluteFilePath() );
if ( !f.open(QIODevice::ReadOnly) ) {
return false;
}
QTextStream ts(&f);
QString content = ts.readAll();
bool hasCreateInstance = content.contains( QString::fromUtf8("def createInstance") );
/*
The old way of doing it was
QString hasCreateInstanceScript = QString("import sys\n"
"import %1\n"
"ret = True\n"
"if not hasattr(%1,\"createInstance\") or not hasattr(%1.createInstance,\"__call__\"):\n"
" ret = False\n").arg(filename);
ok = interpretPythonScript(hasCreateInstanceScript.toStdString(), &err, 0);
which is wrong because it will try to import the script first.
But we in the case of regular scripts, we allow the user to access externally declared variables such as "app", "app1" etc...
and this would not be possible if the script was imported. Importing the module would then fail because it could not
find the variables and the script could not be executed.
*/
if (hasCreateInstance) {
QString moduleName = file.fileName();
int lastDotPos = moduleName.lastIndexOf( QChar::fromLatin1('.') );
if (lastDotPos != -1) {
moduleName = moduleName.left(lastDotPos);
}
std::stringstream ss;
ss << "import " << moduleName.toStdString() << '\n';
ss << moduleName.toStdString() << ".createInstance(app,app)";
std::string output;
FlagIncrementer flag(&_imp->_creatingGroup, &_imp->creatingGroupMutex);
CreatingNodeTreeFlag_RAII createNodeTree( shared_from_this() );
if ( !NATRON_PYTHON_NAMESPACE::interpretPythonScript(ss.str(), &err, &output) ) {
if ( !err.empty() ) {
Dialogs::errorDialog(tr("Python").toStdString(), err);
}
return false;
} else {
if ( !output.empty() ) {
if ( appPTR->isBackground() ) {
std::cout << output << std::endl;
} else {
appendToScriptEditor(output);
}
}
}
getProject()->forceComputeInputDependentDataOnAllTrees();
} else {
PythonGILLocker pgl;
PyRun_SimpleString( content.toStdString().c_str() );
PyObject* mainModule = NATRON_PYTHON_NAMESPACE::getMainModule();
std::string error;
///Gui session, do stdout, stderr redirection
PyObject *errCatcher = 0;
if ( PyObject_HasAttrString(mainModule, "catchErr") ) {
errCatcher = PyObject_GetAttrString(mainModule, "catchErr"); //get our catchOutErr created above, new ref
}
PyErr_Print(); //make python print any errors
PyObject *errorObj = 0;
if (errCatcher) {
errorObj = PyObject_GetAttrString(errCatcher, "value"); //get the stderr from our catchErr object, new ref
assert(errorObj);
error = NATRON_PYTHON_NAMESPACE::PyStringToStdString(errorObj);
PyObject* unicode = PyUnicode_FromString("");
PyObject_SetAttrString(errCatcher, "value", unicode);
Py_DECREF(errorObj);
Py_DECREF(errCatcher);
}
if ( !error.empty() ) {
QString message( QString::fromUtf8("Failed to load ") );
message.append( file.absoluteFilePath() );
message.append( QString::fromUtf8(": ") );
message.append( QString::fromUtf8( error.c_str() ) );
appendToScriptEditor( message.toStdString() );
}
}
return true;
} // AppInstance::loadPythonScript
class AddCreateNode_RAII
{
AppInstancePrivate* _imp;
NodePtr _node;
public:
AddCreateNode_RAII(AppInstancePrivate* imp,
const NodePtr& node)
: _imp(imp)
, _node(node)
{
if (node) {
_imp->_creatingNodeQueue.push_back(node);
}
}
virtual ~AddCreateNode_RAII()
{
std::list<NodePtr>::iterator found = std::find(_imp->_creatingNodeQueue.begin(), _imp->_creatingNodeQueue.end(), _node);
if ( found != _imp->_creatingNodeQueue.end() ) {
_imp->_creatingNodeQueue.erase(found);
}
}
};
NodePtr
AppInstance::createNodeFromPythonModule(Plugin* plugin,
const CreateNodeArgs& args)
{
/*If the plug-in is a toolset, execute the toolset script and don't actually create a node*/
bool istoolsetScript = plugin->getToolsetScript();
NodePtr node;
NodeSerializationPtr serialization = args.getProperty<NodeSerializationPtr>(kCreateNodeArgsPropNodeSerialization);
NodeCollectionPtr group = args.getProperty<NodeCollectionPtr>(kCreateNodeArgsPropGroupContainer);
{
FlagIncrementer fs(&_imp->_creatingGroup, &_imp->creatingGroupMutex);
if (_imp->_creatingGroup == 1) {
bool createGui = !args.getProperty<bool>(kCreateNodeArgsPropNoNodeGUI) && !args.getProperty<bool>(kCreateNodeArgsPropOutOfProject);
_imp->_creatingInternalNode = !createGui;
}
CreatingNodeTreeFlag_RAII createNodeTree( shared_from_this() );
NodePtr containerNode;
if (!istoolsetScript) {
CreateNodeArgs groupArgs = args;
groupArgs.setProperty<std::string>(kCreateNodeArgsPropPluginID,PLUGINID_NATRON_GROUP);
groupArgs.setProperty<bool>(kCreateNodeArgsPropNodeGroupDisableCreateInitialNodes, true);
containerNode = createNode(groupArgs);
if (!containerNode) {
return containerNode;
}
if (!serialization && args.getProperty<std::string>(kCreateNodeArgsPropNodeInitialName).empty()) {
std::string containerName;
try {
if (group) {
group->initNodeName(plugin->getLabelWithoutSuffix().toStdString(), &containerName);
}
containerNode->setScriptName(containerName);
containerNode->setLabel(containerName);
} catch (...) {
}
}
}
AddCreateNode_RAII creatingNode_raii(_imp.get(), containerNode);
std::string containerFullySpecifiedName;
if (containerNode) {
containerFullySpecifiedName = containerNode->getFullyQualifiedName();
}
QString moduleName;
QString modulePath;
plugin->getPythonModuleNameAndPath(&moduleName, &modulePath);
if ( containerNode && !moduleName.isEmpty() ) {
setGroupLabelIDAndVersion(containerNode, modulePath, moduleName);
}
int appID = getAppID() + 1;
std::stringstream ss;
ss << moduleName.toStdString();
ss << ".createInstance(app" << appID;
if (istoolsetScript) {
ss << ",\"\"";
} else {
ss << ", app" << appID << "." << containerFullySpecifiedName;
}
ss << ")\n";
std::string err;
std::string output;
if ( !NATRON_PYTHON_NAMESPACE::interpretPythonScript(ss.str(), &err, &output) ) {
Dialogs::errorDialog(tr("Group plugin creation error").toStdString(), err);
if (containerNode) {
containerNode->destroyNode(false, false);
}
return node;
} else {
if ( !output.empty() ) {
appendToScriptEditor(output);
}
node = containerNode;
}
if (istoolsetScript) {
return NodePtr();
}
// If there's a serialization, restore the serialization of the group node because the Python script probably overridden any state
if (serialization) {
containerNode->loadKnobs(*serialization);
}
} //FlagSetter fs(true,&_imp->_creatingGroup,&_imp->creatingGroupMutex);
///Now that the group is created and all nodes loaded, autoconnect the group like other nodes.
bool autoConnect = args.getProperty<bool>(kCreateNodeArgsPropAutoConnect);
onGroupCreationFinished(node, serialization, autoConnect);
return node;
} // AppInstance::createNodeFromPythonModule
void
AppInstance::setGroupLabelIDAndVersion(const NodePtr& node,
const QString& pythonModulePath,
const QString &pythonModule)
{
assert(node);
if (!node) {
throw std::logic_error(__func__);
}
std::string pluginID, pluginLabel, iconFilePath, pluginGrouping, description;
unsigned int version;
bool istoolset;
if ( NATRON_PYTHON_NAMESPACE::getGroupInfos(pythonModulePath.toStdString(), pythonModule.toStdString(), &pluginID, &pluginLabel, &iconFilePath, &pluginGrouping, &description, &istoolset, &version) ) {
QString groupingStr = QString::fromUtf8( pluginGrouping.c_str() );
QStringList groupingSplits = groupingStr.split( QLatin1Char('/') );
std::list<std::string> stdGrouping;
for (QStringList::iterator it = groupingSplits.begin(); it != groupingSplits.end(); ++it) {
stdGrouping.push_back( it->toStdString() );
}
node->setPluginIDAndVersionForGui(stdGrouping, pluginLabel, pluginID, description, iconFilePath, version);
node->setPluginPythonModule( QString( pythonModulePath + pythonModule + QString::fromUtf8(".py") ).toStdString() );
}
}
NodePtr
AppInstance::createReader(const std::string& filename,
CreateNodeArgs& args)
{
std::string pluginID;
#ifndef NATRON_ENABLE_IO_META_NODES
std::map<std::string, std::string> readersForFormat;
appPTR->getCurrentSettings()->getFileFormatsForReadingAndReader(&readersForFormat);
QString fileCpy = QString::fromUtf8( filename.c_str() );
QString extq = QtCompat::removeFileExtension(fileCpy).toLower();
std::string ext = extq.toStdString();
std::map<std::string, std::string>::iterator found = readersForFormat.find(ext);
if ( found == readersForFormat.end() ) {
Dialogs::errorDialog( tr("Reader").toStdString(),
tr("No plugin capable of decoding %1 was found").arg(extq).toStdString(), false );
return NodePtr();
}
pluginID = found->second;
CreateNodeArgs args(QString::fromUtf8( found->second.c_str() ), reason, group);
#endif