This repository was archived by the owner on Dec 9, 2022. It is now read-only.
forked from MrKepzie/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAppManager.cpp
More file actions
4278 lines (3650 loc) · 141 KB
/
AppManager.cpp
File metadata and controls
4278 lines (3650 loc) · 141 KB
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 <http://www.natron.fr/>,
* Copyright (C) 2015 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 "AppManager.h"
#if defined(Q_OS_UNIX)
#include <sys/time.h> // for getrlimit on linux
#include <sys/resource.h> // for getrlimit
#endif
#include <clocale>
#include <cstddef>
#include <stdexcept>
#include <QDebug>
#include <QTextCodec>
#include <QProcess>
#include <QAbstractSocket>
#include <QCoreApplication>
#include <QLocalServer>
#include <QLocalSocket>
#include <QThread>
#include <QTemporaryFile>
#include <QThreadPool>
#include <QtCore/QAtomicInt>
#ifdef NATRON_USE_BREAKPAD
#if defined(Q_OS_MAC)
#include "client/mac/handler/exception_handler.h"
#elif defined(Q_OS_LINUX)
#include "client/linux/handler/exception_handler.h"
#elif defined(Q_OS_WIN32)
#include "client/windows/handler/exception_handler.h"
#endif
#endif
#include "Global/MemoryInfo.h"
#include "Global/QtCompat.h" // for removeRecursively
#include "Global/GlobalDefines.h" // for removeRecursively
#include "Global/Enums.h"
#include "Global/GitVersion.h"
#include "Engine/AppInstance.h"
#include "Engine/BackDrop.h"
#include "Engine/Cache.h"
#include "Engine/DiskCacheNode.h"
#include "Engine/Dot.h"
#include "Engine/Format.h"
#include "Engine/FrameEntry.h"
#include "Engine/GroupInput.h"
#include "Engine/GroupOutput.h"
#include "Engine/Image.h"
#include "Engine/Knob.h"
#include "Engine/LibraryBinary.h"
#include "Engine/Log.h"
#include "Engine/Node.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxHost.h"
#include "Engine/OutputSchedulerThread.h"
#include "Engine/ProcessHandler.h"
#include "Engine/Project.h"
#include "Engine/RectISerialization.h"
#include "Engine/RectDSerialization.h"
#include "Engine/RotoContext.h"
#include "Engine/RotoPaint.h"
#include "Engine/RotoSmear.h"
#include "Engine/Settings.h"
#include "Engine/StandardPaths.h"
#include "Engine/Transform.h"
#include "Engine/Variant.h"
#include "Engine/ViewerInstance.h"
BOOST_CLASS_EXPORT(Natron::FrameParams)
BOOST_CLASS_EXPORT(Natron::ImageParams)
#define NATRON_CACHE_VERSION 2
using namespace Natron;
AppManager* AppManager::_instance = 0;
struct AppManagerPrivate
{
AppManager::AppTypeEnum _appType; //< the type of app
std::map<int,AppInstanceRef> _appInstances; //< the instances mapped against their ID
int _availableID; //< the ID for the next instance
int _topLevelInstanceID; //< the top level app ID
boost::shared_ptr<Settings> _settings; //< app settings
std::vector<Format*> _formats; //<a list of the "base" formats available in the application
PluginsMap _plugins; //< list of the plugins
boost::scoped_ptr<Natron::OfxHost> ofxHost; //< OpenFX host
boost::scoped_ptr<KnobFactory> _knobFactory; //< knob maker
boost::shared_ptr<Natron::Cache<Natron::Image> > _nodeCache; //< Images cache
boost::shared_ptr<Natron::Cache<Natron::Image> > _diskCache; //< Images disk cache (used by DiskCache nodes)
boost::shared_ptr<Natron::Cache<Natron::FrameEntry> > _viewerCache; //< Viewer textures cache
mutable QMutex diskCachesLocationMutex;
QString diskCachesLocation;
ProcessInputChannel* _backgroundIPC; //< object used to communicate with the main app
//if this app is background, see the ProcessInputChannel def
bool _loaded; //< true when the first instance is completly loaded.
QString _binaryPath; //< the path to the application's binary
mutable QMutex _wasAbortCalledMutex;
bool _wasAbortAnyProcessingCalled; // < has abortAnyProcessing() called at least once ?
U64 _nodesGlobalMemoryUse; //< how much memory all the nodes are using (besides the cache)
mutable QMutex _ofxLogMutex;
QString _ofxLog;
size_t maxCacheFiles; //< the maximum number of files the application can open for caching. This is the hard limit * 0.9
size_t currentCacheFilesCount; //< the number of cache files currently opened in the application
mutable QMutex currentCacheFilesCountMutex; //< protects currentCacheFilesCount
std::string currentOCIOConfigPath; //< the currentOCIO config path
int idealThreadCount; // return value of QThread::idealThreadCount() cached here
int nThreadsToRender; // the value held by the corresponding Knob in the Settings, stored here for faster access (3 RW lock vs 1 mutex here)
int nThreadsPerEffect; // the value held by the corresponding Knob in the Settings, stored here for faster access (3 RW lock vs 1 mutex here)
bool useThreadPool; // whether the multi-thread suite should use the global thread pool (of QtConcurrent) or not
mutable QMutex nThreadsMutex; // protects nThreadsToRender & nThreadsPerEffect & useThreadPool
//The idea here is to keep track of the number of threads launched by Natron (except the ones of the global thread pool of QtConcurrent)
//So that we can properly have an estimation of how much the cores of the CPU are used.
//This method has advantages and drawbacks:
// Advantages:
// - This is quick and fast
// - This very well describes the render activity of Natron
//
// Disadvantages:
// - This only takes into account the current Natron process and disregard completly CPU activity.
// - We might count a thread that is actually waiting in a mutex as a running thread
// Another method could be to analyse all cores running, but this is way more expensive and would impair performances.
QAtomicInt runningThreadsCount;
//To by-pass a bug introduced in RC2 / RC3 with the serialization of bezier curves
bool lastProjectLoadedCreatedDuringRC2Or3;
///Python needs wide strings as from Python 3.x onwards everything is unicode based
#ifndef IS_PYTHON_2
std::vector<wchar_t*> args;
#else
std::vector<char*> args;
#endif
PyObject* mainModule;
PyThreadState* mainThreadState;
#ifdef NATRON_USE_BREAKPAD
boost::shared_ptr<google_breakpad::ExceptionHandler> breakpadHandler;
boost::shared_ptr<QProcess> crashReporter;
QString crashReporterBreakpadPipe;
boost::shared_ptr<QLocalServer> crashClientServer;
QLocalSocket* crashServerConnection;
#endif
QMutex natronPythonGIL;
#ifdef Q_OS_WIN32
//On Windows only, track the UNC path we came across because the WIN32 API does not provide any function to map
//from UNC path to path with drive letter.
std::map<QChar,QString> uncPathMapping;
#endif
AppManagerPrivate();
~AppManagerPrivate()
{
for (U32 i = 0; i < args.size() ; ++i) {
free(args[i]);
}
args.clear();
}
void initProcessInputChannel(const QString & mainProcessServerName);
void loadBuiltinFormats();
void saveCaches();
void restoreCaches();
bool checkForCacheDiskStructure(const QString & cachePath);
void cleanUpCacheDiskStructure(const QString & cachePath);
/**
* @brief Called on startup to initialize the max opened files
**/
void setMaxCacheFiles();
Natron::Plugin* findPluginById(const QString& oldId,int major, int minor) const;
void declareSettingsToPython();
#ifdef NATRON_USE_BREAKPAD
void initBreakpad();
#endif
};
#ifdef DEBUG
static
void crash_application()
{
#ifdef __NATRON_UNIX__
sleep(2);
#endif
volatile int* a = (int*)(NULL);
// coverity[var_deref_op]
*a = 1;
}
#endif
AppManagerPrivate::AppManagerPrivate()
: _appType(AppManager::eAppTypeBackground)
, _appInstances()
, _availableID(0)
, _topLevelInstanceID(0)
, _settings( new Settings(NULL) )
, _formats()
, _plugins()
, ofxHost( new Natron::OfxHost() )
, _knobFactory( new KnobFactory() )
, _nodeCache()
, _diskCache()
, _viewerCache()
, diskCachesLocationMutex()
, diskCachesLocation()
,_backgroundIPC(0)
,_loaded(false)
,_binaryPath()
,_wasAbortAnyProcessingCalled(false)
,_nodesGlobalMemoryUse(0)
,_ofxLogMutex()
,_ofxLog()
,maxCacheFiles(0)
,currentCacheFilesCount(0)
,currentCacheFilesCountMutex()
,idealThreadCount(0)
,nThreadsToRender(0)
,nThreadsPerEffect(0)
,useThreadPool(true)
,nThreadsMutex()
,runningThreadsCount()
,lastProjectLoadedCreatedDuringRC2Or3(false)
,args()
,mainModule(0)
,mainThreadState(0)
#ifdef NATRON_USE_BREAKPAD
,breakpadHandler()
,crashReporter()
,crashReporterBreakpadPipe()
,crashClientServer()
,crashServerConnection(0)
#endif
,natronPythonGIL(QMutex::Recursive)
{
setMaxCacheFiles();
runningThreadsCount = 0;
}
void
AppManager::saveCaches() const
{
_imp->saveCaches();
}
int
AppManager::getHardwareIdealThreadCount()
{
return _imp->idealThreadCount;
}
static bool tryParseFrameRange(const QString& arg,std::pair<int,int>& range)
{
bool frameRangeFound = true;
QStringList strRange = arg.split('-');
if (strRange.size() != 2) {
frameRangeFound = false;
}
for (int i = 0; i < strRange.size(); ++i) {
strRange[i] = strRange[i].trimmed();
}
if (frameRangeFound) {
bool ok;
range.first = strRange[0].toInt(&ok);
if (!ok) {
frameRangeFound = false;
}
if (frameRangeFound) {
range.second = strRange[1].toInt(&ok);
if (!ok) {
frameRangeFound = false;
}
}
}
return frameRangeFound;
}
AppManager::AppManager()
: QObject()
, _imp( new AppManagerPrivate() )
{
assert(!_instance);
_instance = this;
QObject::connect(this, SIGNAL(s_requestOFXDialogOnMainThread(void*)), this, SLOT(onOFXDialogOnMainThreadReceived(void*)));
}
void
AppManager::takeNatronGIL()
{
_imp->natronPythonGIL.lock();
}
void
AppManager::releaseNatronGIL()
{
_imp->natronPythonGIL.unlock();
}
struct CLArgsPrivate
{
QStringList args;
QString filename;
bool isPythonScript;
QString defaultOnProjectLoadedScript;
std::list<CLArgs::WriterArg> writers;
bool isBackground;
QString ipcPipe;
int error;
bool isInterpreterMode;
std::pair<int,int> range;
bool rangeSet;
bool enableRenderStats;
bool isEmpty;
CLArgsPrivate()
: args()
, filename()
, isPythonScript(false)
, defaultOnProjectLoadedScript()
, writers()
, isBackground(false)
, ipcPipe()
, error(0)
, isInterpreterMode(false)
, range()
, rangeSet(false)
, enableRenderStats(false)
, isEmpty(true)
{
}
void parse();
QStringList::iterator hasToken(const QString& longName,const QString& shortName);
QStringList::iterator hasOutputToken(QString& indexStr);
QStringList::iterator findFileNameWithExtension(const QString& extension);
};
CLArgs::CLArgs()
: _imp(new CLArgsPrivate())
{
}
CLArgs::CLArgs(int& argc,char* argv[],bool forceBackground)
: _imp(new CLArgsPrivate())
{
_imp->isEmpty = false;
if (forceBackground) {
_imp->isBackground = true;
}
for (int i = 0; i < argc; ++i) {
QString str = argv[i];
if (str.size() >= 2 && str[0] == '"' && str[str.size() - 1] == '"') {
str.remove(0, 1);
str.remove(str.size() - 1, 1);
}
#ifdef DEBUG
std::cout << "argv[" << i << "] = " << str.toStdString() << std::endl;
#endif
_imp->args.push_back(str);
}
_imp->parse();
}
CLArgs::CLArgs(const QStringList &arguments, bool forceBackground)
: _imp(new CLArgsPrivate())
{
_imp->isEmpty = false;
if (forceBackground) {
_imp->isBackground = true;
}
for (int i = 0; i < arguments.size(); ++i) {
QString str = arguments[i];
if (str.size() >= 2 && str[0] == '"' && str[str.size() - 1] == '"') {
str.remove(0, 1);
str.remove(str.size() - 1, 1);
}
_imp->args.push_back(str);
}
_imp->parse();
}
// GCC 4.2 requires the copy constructor
CLArgs::CLArgs(const CLArgs& other)
: _imp(new CLArgsPrivate())
{
*this = other;
}
CLArgs::~CLArgs()
{
}
void
CLArgs::operator=(const CLArgs& other)
{
_imp->args = other._imp->args;
_imp->filename = other._imp->filename;
_imp->isPythonScript = other._imp->isPythonScript;
_imp->defaultOnProjectLoadedScript = other._imp->defaultOnProjectLoadedScript;
_imp->writers = other._imp->writers;
_imp->isBackground = other._imp->isBackground;
_imp->ipcPipe = other._imp->ipcPipe;
_imp->error = other._imp->error;
_imp->isInterpreterMode = other._imp->isInterpreterMode;
_imp->range = other._imp->range;
_imp->rangeSet = other._imp->rangeSet;
_imp->enableRenderStats = other._imp->enableRenderStats;
_imp->isEmpty = other._imp->isEmpty;
}
bool
CLArgs::isEmpty() const
{
return _imp->isEmpty;
}
void
CLArgs::printBackGroundWelcomeMessage()
{
QString msg = QObject::tr("%1 Version %2\n"
"Copyright (C) 2015 the %1 developers\n"
">>>Use the --help or -h option to print usage.<<<").arg(NATRON_APPLICATION_NAME).arg(NATRON_VERSION_STRING);
std::cout << msg.toStdString() << std::endl;
}
void
CLArgs::printUsage(const std::string& programName)
{
QString msg = QObject::tr(/* Text must hold in 80 columns ************************************************/
"%3 usage:\n"
"Three distinct execution modes exist in background mode:\n"
"- The execution of %1 projects (.%2)\n"
"- The execution of Python scripts that contain commands for %1\n"
"- An interpreter mode where commands can be given directly to the Python\n"
" interpreter\n"
"\n"
"General options:\n"
" -h [ --help ] :\n"
" Produce help message.\n"
" -v [ --version ] :\n"
" Print informations about %1 version.\n"
" -b [ --background ] :\n"
" Enable background rendering mode. No graphical interface is shown.\n"
" When using %1Renderer or the -t option, this argument is implicit\n"
" and does not have to be given.\n"
" If using %1 and this option is not specified, the project is loaded\n"
" as if opened from the file menu.\n"
" -t [ --interpreter ] <python script file path> :\n"
" Enable Python interpreter mode.\n"
" Python commands can be given to the interpreter and executed on the fly.\n"
" An optional Python script filename can be specified to source a script\n"
" before the interpreter is made accessible.\n"
" Note that %1 will not start rendering any Write node of the sourced\n"
" script: it must be started explicitely.\n"
" %1Renderer and %1 do the same thing in this mode, only the\n"
" init.py script is loaded.\n"
"\n"
/* Text must hold in 80 columns ************************************************/
"Options for the execution of %1 projects:\n"
" %3 <project file path> [options]\n"
" -w [ --writer ] <Writer node script name> [<filename>] [<frameRange>] :\n"
" Specify a Write node to render.\n"
" When in background mode, the renderer only renders the node script name\n"
" following this argument. If no such node exists in the project file, the\n"
" process aborts.\n"
" Note that if there is no --writer option, it renders all the writers in\n"
" the project.\n"
" After the writer node script name you can pass an optional output\n"
" filename and pass an optional frame range in the format:\n"
" <firstFrame>-<lastFrame> (e.g: 10-40).\n"
" Note that several -w options can be set to specify multiple Write nodes\n"
" to render.\n"
" Note that if specified, the frame range is the same for all Write nodes\n"
" to render.\n"
" -l [ --onload ] <python script file path> :\n"
" Specify a Python script to be executed after a project is created or\n"
" loaded.\n"
" Note that this is executed in GUI mode or with NatronRenderer, after\n"
" executing the callbacks onProjectLoaded and onProjectCreated.\n"
" The rules on the execution of Python scripts (see below) also apply to\n"
" this script.\n"
" -s [ --render-stats] Enables render statistics that will be produced for\n"
" each frame in form of a file located next to the image produced by\n"
" the Writer node, with the same name and a -stats.txt extension. The\n"
" breakdown contains informations about each nodes, render times etc...\n"
" This option is useful for debugging purposes or to control that a render\n"
" is working correctly.\n"
" **Please note** that it does not work when writing video files."
"Sample uses:\n"
" %1 /Users/Me/MyNatronProjects/MyProject.ntp\n"
" %1 -b -w MyWriter /Users/Me/MyNatronProjects/MyProject.ntp\n"
" %1Renderer -w MyWriter /Users/Me/MyNatronProjects/MyProject.ntp\n"
" %1Renderer -w MyWriter /FastDisk/Pictures/sequence'###'.exr 1-100 /Users/Me/MyNatronProjects/MyProject.ntp\n"
" %1Renderer -w MyWriter -w MySecondWriter 1-10 /Users/Me/MyNatronProjects/MyProject.ntp\n"
" %1Renderer -w MyWriter 1-10 -l /Users/Me/Scripts/onProjectLoaded.py /Users/Me/MyNatronProjects/MyProject.ntp\n"
"\n"
/* Text must hold in 80 columns ************************************************/
"Options for the execution of Python scripts:\n"
" %3 <Python script path> [options]\n"
" [Note that the following does not apply if the -t option was given.]\n"
" The script argument can either be the script of a Group that was exported\n"
" from the graphical user interface, or an exported project, or a script\n"
" written by hand.\n"
" When executing a script, %1 first looks for a function with the\n"
" following signature:\n"
" def createInstance(app,group):\n"
" If this function is found, it is executed, otherwise the whole content of\n"
" the script is interpreted as though it were given to Python natively.\n"
" In either case, the \"app\" variable is always defined and points to the\n"
" correct application instance.\n"
" Note that the GUI version of the program (%1) sources the script before\n"
" creating the graphical user interface and does not start rendering.\n"
" If in background mode, the nodes to render have to be given using the -w\n"
" option (as described above) or with the following option:\n"
" -o [ --output ] <filename> <frameRange> :\n"
" Specify an Output node in the script that should be replaced with a\n"
" Write node.\n"
" The option looks for a node named Output1 in the script and replaces it\n"
" by a Write node (like when creating a Write node in interactive GUI mode).\n"
" <filename> is a pattern for the output file names.\n"
" <frameRange> must be specified if it was not specified earlier on the\n"
" command line.\n"
" This option can also be used to render out multiple Output nodes, in\n"
" which case it has to be used like this:\n"
" -o1 [ --output1 ] : look for a node named Output1.\n"
" -o2 [ --output2 ] : look for a node named Output2 \n"
" etc...\n"
"Sample uses:\n"
" %1 /Users/Me/MyNatronScripts/MyScript.py\n"
" %1 -b -w MyWriter /Users/Me/MyNatronScripts/MyScript.py\n"
" %1Renderer -w MyWriter /Users/Me/MyNatronScripts/MyScript.py\n"
" %1Renderer -o /FastDisk/Pictures/sequence'###'.exr 1-100 /Users/Me/MyNatronScripts/MyScript.py\n"
" %1Renderer -o1 /FastDisk/Pictures/sequence'###'.exr -o2 /FastDisk/Pictures/test'###'.exr 1-100 /Users/Me/MyNatronScripts/MyScript.py\n"
" %1Renderer -w MyWriter -o /FastDisk/Pictures/sequence'###'.exr 1-100 /Users/Me/MyNatronScripts/MyScript.py\n"
"\n"
/* Text must hold in 80 columns ************************************************/
"Options for the execution of the interpreter mode:\n"
" %3 -t [<Python script path>]\n"
" %1 sources the optional script given as argument, if any, and then reads\n"
" Python commands from the standard input, which are interpreted by Python.\n"
"Sample uses:\n"
" %1 -t\n"
" %1Renderer -t\n"
" %1Renderer -t /Users/Me/MyNatronScripts/MyScript.py\n")
.arg(/*%1=*/NATRON_APPLICATION_NAME).arg(/*%2=*/NATRON_PROJECT_FILE_EXT).arg(/*%3=*/programName.c_str());
std::cout << msg.toStdString() << std::endl;
}
int
CLArgs::getError() const
{
return _imp->error;
}
const std::list<CLArgs::WriterArg>&
CLArgs::getWriterArgs() const
{
return _imp->writers;
}
bool
CLArgs::hasFrameRange() const
{
return _imp->rangeSet;
}
const std::pair<int,int>&
CLArgs::getFrameRange() const
{
return _imp->range;
}
bool
CLArgs::isBackgroundMode() const
{
return _imp->isBackground;
}
bool
CLArgs::isInterpreterMode() const
{
return _imp->isInterpreterMode;
}
const QString&
CLArgs::getFilename() const
{
return _imp->filename;
}
const QString&
CLArgs::getDefaultOnProjectLoadedScript() const
{
return _imp->defaultOnProjectLoadedScript;
}
const QString&
CLArgs::getIPCPipeName() const
{
return _imp->ipcPipe;
}
bool
CLArgs::areRenderStatsEnabled() const
{
return _imp->enableRenderStats;
}
bool
CLArgs::isPythonScript() const
{
return _imp->isPythonScript;
}
QStringList::iterator
CLArgsPrivate::findFileNameWithExtension(const QString& extension)
{
bool isPython = extension == "py";
for (QStringList::iterator it = args.begin(); it != args.end() ; ++it) {
if (isPython) {
//Check that we do not take the python script specified for the --onload argument as the file to execute
if (it == args.begin()) {
continue;
}
QStringList::iterator prev = it;
--prev;
if (*prev == "--onload" || *prev == "-l") {
continue;
}
}
if (it->endsWith("." + extension)) {
return it;
}
}
return args.end();
}
QStringList::iterator
CLArgsPrivate::hasToken(const QString& longName,const QString& shortName)
{
QString longToken = "--" + longName;
QString shortToken = !shortName.isEmpty() ? "-" + shortName : QString();
for (QStringList::iterator it = args.begin(); it != args.end() ; ++it) {
if (*it == longToken || (!shortToken.isEmpty() && *it == shortToken)) {
return it;
}
}
return args.end();
}
QStringList::iterator
CLArgsPrivate::hasOutputToken(QString& indexStr)
{
QString outputLong("--output");
QString outputShort("-o");
for (QStringList::iterator it = args.begin(); it != args.end(); ++it) {
int indexOf = it->indexOf(outputLong);
if (indexOf != -1) {
indexOf += outputLong.size();
if (indexOf < it->size()) {
indexStr = it->mid(indexOf);
bool ok;
indexStr.toInt(&ok);
if (!ok) {
error = 1;
std::cout << QObject::tr("Wrong formating for the -o option").toStdString() << std::endl;
return args.end();
}
} else {
indexStr = "1";
}
return it;
} else {
indexOf = it->indexOf(outputShort);
if (indexOf != -1) {
if (it->size() > 2 && !it->at(2).isDigit()) {
//This is probably the --onload option
return args.end();
}
indexOf += outputShort.size();
if (indexOf < it->size()) {
indexStr = it->mid(indexOf);
bool ok;
indexStr.toInt(&ok);
if (!ok) {
error = 1;
std::cout << QObject::tr("Wrong formating for the -o option").toStdString() << std::endl;
return args.end();
}
} else {
indexStr = "1";
}
return it;
}
}
}
return args.end();
}
void
CLArgsPrivate::parse()
{
{
QStringList::iterator it = hasToken("version", "v");
if (it != args.end()) {
QString msg = QObject::tr("%1 version %2 at commit %3 on branch %4 built on %4").arg(NATRON_APPLICATION_NAME).arg(NATRON_VERSION_STRING).arg(GIT_COMMIT).arg(GIT_BRANCH).arg(__DATE__);
std::cout << msg.toStdString() << std::endl;
error = 1;
return;
}
}
{
QStringList::iterator it = hasToken("help", "h");
if (it != args.end()) {
CLArgs::printUsage(args[0].toStdString());
error = 1;
return;
}
}
{
QStringList::iterator it = hasToken("background", "b");
if (it != args.end()) {
isBackground = true;
args.erase(it);
}
}
{
QStringList::iterator it = hasToken("interpreter", "t");
if (it != args.end()) {
isInterpreterMode = true;
isBackground = true;
std::cout << QObject::tr("Note: -t argument given, loading in command-line interpreter mode, only Python commands / scripts are accepted").toStdString()
<< std::endl;
args.erase(it);
}
}
{
QStringList::iterator it = hasToken("render-stats", "s");
if (it != args.end()) {
enableRenderStats = true;
args.erase(it);
}
}
{
QStringList::iterator it = hasToken("IPCpipe", "");
if (it != args.end()) {
++it;
if (it != args.end()) {
ipcPipe = *it;
args.erase(it);
} else {
std::cout << QObject::tr("You must specify the IPC pipe filename").toStdString() << std::endl;
error = 1;
return;
}
}
}
{
QStringList::iterator it = hasToken("onload", "l");
if (it != args.end()) {
++it;
if (it != args.end()) {
defaultOnProjectLoadedScript = *it;
#ifdef __NATRON_UNIX__
defaultOnProjectLoadedScript = AppManager::qt_tildeExpansion(defaultOnProjectLoadedScript);
#endif
args.erase(it);
if (!defaultOnProjectLoadedScript.endsWith(".py")) {
std::cout << QObject::tr("The optional on project load script must be a Python script (.py).").toStdString() << std::endl;
error = 1;
return;
}
if (!QFile::exists(defaultOnProjectLoadedScript)) {
std::cout << QObject::tr("WARNING: --onload %1 ignored because the file does not exist.").arg(defaultOnProjectLoadedScript).toStdString() << std::endl;
}
} else {
std::cout << QObject::tr("--onload or -l specified, you must enter a script filename afterwards.").toStdString() << std::endl;
error = 1;
return;
}
}
}
{
QStringList::iterator it = findFileNameWithExtension(NATRON_PROJECT_FILE_EXT);
if (it == args.end()) {
it = findFileNameWithExtension("py");
if (it == args.end() && !isInterpreterMode && isBackground) {
std::cout << QObject::tr("You must specify the filename of a script or %1 project. (.%2)").arg(NATRON_APPLICATION_NAME).arg(NATRON_PROJECT_FILE_EXT).toStdString() << std::endl;
error = 1;
return;
}
isPythonScript = true;
}
if (it != args.end()) {
filename = *it;
#if defined(Q_OS_UNIX)
filename = AppManager::qt_tildeExpansion(filename);
#endif
args.erase(it);
}
}
//Parse frame range
for (int i = 0; i < args.size(); ++i) {
if (tryParseFrameRange(args[i], range)) {
if (rangeSet) {
std::cout << QObject::tr("Only a single frame range can be specified").toStdString() << std::endl;
error = 1;
return;
}
rangeSet = true;
}
}
//Parse writers
for (;;) {
QStringList::iterator it = hasToken("writer", "w");
if (it == args.end()) {
break;
}
if (!isBackground || isInterpreterMode) {
std::cout << QObject::tr("You cannot use the -w option in interactive or interpreter mode").toStdString() << std::endl;
error = 1;
return;
}
QStringList::iterator next = it;
if (next != args.end()) {
++next;
}
if (next == args.end()) {
std::cout << QObject::tr("You must specify the name of a Write node when using the -w option").toStdString() << std::endl;
error = 1;
return;
}
//Check that the name is conform to a Python acceptable script name
std::string pythonConform = Natron::makeNameScriptFriendly(next->toStdString());
if (next->toStdString() != pythonConform) {
std::cout << QObject::tr("The name of the Write node specified is not valid: it cannot contain non alpha-numerical "
"characters and must not start with a digit.").toStdString() << std::endl;
error = 1;
return;
}
CLArgs::WriterArg w;
w.name = *next;
QStringList::iterator nextNext = next;
if (nextNext != args.end()) {
++nextNext;
}
if (nextNext != args.end()) {
//Check for an optional filename
if (!nextNext->startsWith("-") && !nextNext->startsWith("--")) {
w.filename = *nextNext;
#if defined(Q_OS_UNIX)
w.filename = AppManager::qt_tildeExpansion(w.filename);
#endif
}
}
writers.push_back(w);
if (nextNext != args.end()) {
++nextNext;
}
args.erase(it,nextNext);
} // for (;;)
bool atLeastOneOutput = false;
///Parse outputs
for (;;) {
QString indexStr;
QStringList::iterator it = hasOutputToken(indexStr);
if (error > 0) {
return;
}
if (it == args.end()) {
break;
}
if (!isBackground) {
std::cout << QObject::tr("You cannot use the -o option in interactive or interpreter mode").toStdString() << std::endl;
error = 1;
return;
}
CLArgs::WriterArg w;
w.name = QString("Output%1").arg(indexStr);
w.mustCreate = true;
atLeastOneOutput = true;
//Check for a mandatory file name
QStringList::iterator next = it;
if (next != args.end()) {
++next;
}
if (next == args.end()) {
std::cout << QObject::tr("Filename is not optional with the -o option").toStdString() << std::endl;
error = 1;
return;
}
//Check for an optional filename
if (!next->startsWith("-") && !next->startsWith("--")) {
w.filename = *next;