forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AppManager.cpp
4622 lines (3964 loc) · 154 KB
/
AppManager.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 "AppManager.h"
//#include "AppManagerPrivate.h" // include breakpad after Engine, because it includes /usr/include/AssertMacros.h on OS X which defines a check(x) macro, which conflicts with boost
#if defined(__APPLE__) && defined(_LIBCPP_VERSION)
#include <AvailabilityMacros.h>
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 1090
// Disable availability macros on macOS
// because we may be using libc++ on an older macOS,
// so that std::locale::numeric may be available
// even on macOS < 10.9.
// see _LIBCPP_AVAILABILITY_LOCALE_CATEGORY
// in /opt/local/libexec/llvm-5.0/include/c++/v1/__config
// and /opt/local/libexec/llvm-5.0/include/c++/v1/__locale
#if defined(_LIBCPP_USE_AVAILABILITY_APPLE)
#error "this must be compiled with _LIBCPP_DISABLE_AVAILABILITY defined"
#else
#ifndef _LIBCPP_DISABLE_AVAILABILITY
#define _LIBCPP_DISABLE_AVAILABILITY
#endif
#endif
#endif
#endif
#include <clocale>
#include <csignal>
#include <cstddef>
#include <cassert>
#include <stdexcept>
#include <cstring> // for std::memcpy
#include <sstream> // stringstream
#include <locale>
#include <QtCore/QtGlobal> // for Q_OS_*
#if defined(Q_OS_LINUX)
#include <sys/signal.h>
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <ucontext.h>
#include <execinfo.h>
#endif
#ifdef Q_OS_UNIX
#include <stdio.h>
#include <stdlib.h>
#ifdef Q_OS_MAC
#include <sys/sysctl.h>
#include <libproc.h>
#endif
#endif
#ifdef Q_OS_WIN
#include <shlobj.h>
#endif
#include <cairo/cairo.h>
#include <boost/version.hpp>
#include <libs/hoedown/src/version.h>
#include <ceres/version.h>
#include <openMVG/version.hpp>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QTextCodec>
#include <QtCore/QCoreApplication>
#include <QtCore/QSettings>
#include <QtCore/QThreadPool>
#include <QtCore/QTextStream>
#include <QtNetwork/QAbstractSocket>
#include <QtNetwork/QLocalServer>
#include <QtNetwork/QLocalSocket>
#include "Global/ProcInfo.h"
#include "Global/GLIncludes.h"
#include "Global/StrUtils.h"
#ifdef DEBUG
#include "Global/FloatingPointExceptions.h"
#endif
#include "Engine/AppInstance.h"
#include "Engine/Backdrop.h"
#include "Engine/CLArgs.h"
#include "Engine/DiskCacheNode.h"
#include "Engine/Dot.h"
#include "Engine/ExistenceCheckThread.h"
#include "Engine/FileSystemModel.h"
#include "Engine/GroupInput.h"
#include "Engine/GroupOutput.h"
#include "Engine/JoinViewsNode.h"
#include "Engine/LibraryBinary.h"
#include "Engine/Log.h"
#include "Engine/MemoryInfo.h" // getSystemTotalRAM, printAsRAM
#include "Engine/Node.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxHost.h"
#include "Engine/OSGLContext.h"
#include "Engine/OneViewNode.h"
#include "Engine/ProcessHandler.h" // ProcessInputChannel
#include "Engine/Project.h"
#include "Engine/PrecompNode.h"
#include "Engine/ReadNode.h"
#include "Engine/RotoPaint.h"
#include "Engine/RotoSmear.h"
#include "Engine/StandardPaths.h"
#include "Engine/TrackerNode.h"
#include "Engine/ThreadPool.h"
#include "Engine/Utils.h"
#include "Engine/ViewIdx.h"
#include "Engine/ViewerInstance.h" // RenderStatsMap
#include "Engine/WriteNode.h"
#include "sbkversion.h" // shiboken/pyside version
#include "AppManagerPrivate.h" // include breakpad after Engine, because it includes /usr/include/AssertMacros.h on OS X which defines a check(x) macro, which conflicts with boost
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
Q_DECLARE_METATYPE(QAbstractSocket::SocketState)
#endif
NATRON_NAMESPACE_ENTER
AppManager* AppManager::_instance = 0;
#ifdef __NATRON_UNIX__
//namespace {
static void
handleShutDownSignal( int /*signalId*/ )
{
if (appPTR) {
std::cerr << "\nCaught termination signal, exiting!" << std::endl;
appPTR->quitApplication();
}
}
static void
setShutDownSignal(int signalId)
{
#if defined(__NATRON_UNIX__)
struct sigaction sa;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = handleShutDownSignal;
if (sigaction(signalId, &sa, NULL) == -1) {
std::perror("setting up termination signal");
std::exit(1);
}
#else
std::signal(signalId, handleShutDownSignal);
#endif
}
#endif
#if defined(__NATRON_LINUX__) && !defined(__FreeBSD__)
#define NATRON_UNIX_BACKTRACE_STACK_DEPTH 16
static void
backTraceSigSegvHandler(int sig,
siginfo_t *info,
void *secret)
{
void *trace[NATRON_UNIX_BACKTRACE_STACK_DEPTH];
char **messages = (char **)NULL;
int i, trace_size = 0;
ucontext_t *uc = (ucontext_t *)secret;
/* Do something useful with siginfo_t */
if (sig == SIGSEGV) {
QThread* curThread = QThread::currentThread();
std::string threadName;
if (curThread) {
threadName = (qApp && qApp->thread() == curThread) ? "Main" : curThread->objectName().toStdString();
}
std::cerr << "Caught segmentation fault (SIGSEGV) from thread " << threadName << "(" << curThread << "), faulty address is " <<
#ifndef __x86_64__
(void*)uc->uc_mcontext.gregs[REG_EIP]
#else
(void*) uc->uc_mcontext.gregs[REG_RIP]
#endif
<< " from " << info->si_addr << std::endl;
} else {
printf("Got signal %d#92;n", sig);
}
trace_size = backtrace(trace, NATRON_UNIX_BACKTRACE_STACK_DEPTH);
/* overwrite sigaction with caller's address */
#ifndef __x86_64__
trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];
#else
trace[1] = (void *) uc->uc_mcontext.gregs[REG_RIP];
#endif
messages = backtrace_symbols(trace, trace_size);
/* skip first stack frame (points here) */
std::cerr << "Backtrace:" << std::endl;
for (i = 1; i < trace_size; ++i) {
std::cerr << "[Frame " << i << "]: " << messages[i] << std::endl;
}
exit(1);
}
static void
setSigSegvSignal()
{
struct sigaction sa;
sigemptyset (&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_SIGINFO;
/* if SA_SIGINFO is set, sa_sigaction is to be used instead of sa_handler. */
sa.sa_sigaction = backTraceSigSegvHandler;
if (sigaction(SIGSEGV, &sa, NULL) == -1) {
std::perror("setting up sigsegv signal");
std::exit(1);
}
}
#endif // if defined(__NATRON_LINUX__) && !defined(__FreeBSD__)
#if PY_MAJOR_VERSION >= 3
// Python 3
//Borrowed from https://github.com/python/cpython/blob/634cb7aa2936a09e84c5787d311291f0e042dba3/Python/fileutils.c
//Somehow Python 3 dev forced every C application embedding python to have their own code to convert char** to wchar_t**
static wchar_t*
char2wchar(char* arg)
{
wchar_t *res = NULL;
#ifdef HAVE_BROKEN_MBSTOWCS
/* Some platforms have a broken implementation of
* mbstowcs which does not count the characters that
* would result from conversion. Use an upper bound.
*/
size_t argsize = strlen(arg);
#else
size_t argsize = mbstowcs(NULL, arg, 0);
#endif
size_t count;
unsigned char *in;
wchar_t *out;
#ifdef HAVE_MBRTOWC
mbstate_t mbs;
#endif
if (argsize != (size_t)-1) {
res = (wchar_t *)malloc( (argsize + 1) * sizeof(wchar_t) );
if (!res) {
goto oom;
}
count = mbstowcs(res, arg, argsize + 1);
if (count != (size_t)-1) {
wchar_t *tmp;
/* Only use the result if it contains no
surrogate characters. */
for (tmp = res; *tmp != 0 &&
(*tmp < 0xd800 || *tmp > 0xdfff); tmp++) {
;
}
if (*tmp == 0) {
return res;
}
}
free(res);
}
/* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
/* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
/* Overallocate; as multi-byte characters are in the argument, the
actual output could use less memory. */
argsize = strlen(arg) + 1;
res = (wchar_t*)malloc( argsize * sizeof(wchar_t) );
if (!res) {
goto oom;
}
in = (unsigned char*)arg;
out = res;
std::memset(&mbs, 0, sizeof mbs);
while (argsize) {
size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
if (converted == 0) {
/* Reached end of string; null char stored. */
break;
}
if (converted == (size_t)-2) {
/* Incomplete character. This should never happen,
since we provide everything that we have -
unless there is a bug in the C library, or I
misunderstood how mbrtowc works. */
fprintf(stderr, "unexpected mbrtowc result -2\n");
free(res);
return NULL;
}
if (converted == (size_t)-1) {
/* Conversion error. Escape as UTF-8b, and start over
in the initial shift state. */
*out++ = 0xdc00 + *in++;
argsize--;
std::memset(&mbs, 0, sizeof mbs);
continue;
}
if ( (*out >= 0xd800) && (*out <= 0xdfff) ) {
/* Surrogate character. Escape the original
byte sequence with surrogateescape. */
argsize -= converted;
while (converted--) {
*out++ = 0xdc00 + *in++;
}
continue;
}
/* successfully converted some bytes */
in += converted;
argsize -= converted;
out++;
}
#else
/* Cannot use C locale for escaping; manually escape as if charset
is ASCII (i.e. escape all bytes > 128. This will still roundtrip
correctly in the locale's charset, which must be an ASCII superset. */
res = (wchar_t*)malloc( (strlen(arg) + 1) * sizeof(wchar_t) );
if (!res) {
goto oom;
}
in = (unsigned char*)arg;
out = res;
while (*in) {
if (*in < 128) {
*out++ = *in++;
} else {
*out++ = 0xdc00 + *in++;
}
}
*out = 0;
#endif // ifdef HAVE_MBRTOWC
return res;
oom:
fprintf(stderr, "out of memory\n");
free(res);
return NULL;
} // char2wchar
#endif // if PY_MAJOR_VERSION >= 3
//} // anon namespace
void
AppManager::saveCaches() const
{
_imp->saveCaches();
}
int
AppManager::getHardwareIdealThreadCount()
{
return _imp->idealThreadCount;
}
int
AppManager::getMaxThreadCount()
{
return QThreadPool::globalInstance()->maxThreadCount();
}
AppManager::AppManager()
: QObject()
, _imp( new AppManagerPrivate() )
{
assert(!_instance);
_instance = this;
QObject::connect( this, SIGNAL(s_requestOFXDialogOnMainThread(OfxImageEffectInstance*,void*)), this, SLOT(onOFXDialogOnMainThreadReceived(OfxImageEffectInstance*,void*)) );
#ifdef __NATRON_WIN32__
FileSystemModel::initDriveLettersToNetworkShareNamesMapping();
#endif
}
#ifdef USE_NATRON_GIL
void
AppManager::takeNatronGIL()
{
_imp->natronPythonGIL.lock();
}
void
AppManager::releaseNatronGIL()
{
_imp->natronPythonGIL.unlock();
}
#endif
void
StrUtils::ensureLastPathSeparator(QString& path)
{
static const QChar separator( QLatin1Char('/') );
if ( !path.endsWith(separator) ) {
path += separator;
}
}
bool
AppManager::loadFromArgs(const CLArgs& cl)
{
#ifdef DEBUG
for (std::size_t i = 0; i < _imp->commandLineArgsUtf8.size(); ++i) {
std::cout << "argv[" << i << "] = " << _imp->commandLineArgsUtf8[i] << std::endl;
}
#endif
// Ensure Qt knows C-strings are UTF-8 before creating the QApplication for argv
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
// be forward compatible: source code is UTF-8, and Qt5 assumes UTF-8 by default
QTextCodec::setCodecForCStrings( QTextCodec::codecForName("UTF-8") );
QTextCodec::setCodecForTr( QTextCodec::codecForName("UTF-8") );
#endif
// This needs to be done BEFORE creating qApp because
// on Linux, X11 will create a context that would corrupt
// the XUniqueContext created by Qt
// scoped_ptr
_imp->renderingContextPool.reset( new GPUContextPool() );
initializeOpenGLFunctionsOnce(true);
// QCoreApplication will hold a reference to that appManagerArgc integer until it dies.
// Thus ensure that the QCoreApplication is destroyed when returning this function.
initializeQApp(_imp->nArgs, &_imp->commandLineArgsUtf8.front()); // calls QCoreApplication::QCoreApplication(), which calls setlocale()
// see C++ standard 23.2.4.2 vector capacity [lib.vector.capacity]
// resizing to a smaller size doesn't free/move memory, so the data pointer remains valid
assert(_imp->nArgs <= (int)_imp->commandLineArgsUtf8.size());
_imp->commandLineArgsUtf8.resize(_imp->nArgs); // Qt may have reduced the numlber of args
#ifdef QT_CUSTOM_THREADPOOL
// Set the global thread pool (pointed is owned and deleted by QThreadPool at exit)
QThreadPool::setGlobalInstance(new ThreadPool);
#endif
// set fontconfig path on all platforms
if ( qgetenv("FONTCONFIG_PATH").isNull() ) {
// set FONTCONFIG_PATH to Natron/Resources/etc/fonts (required by plugins using fontconfig)
QString path = QCoreApplication::applicationDirPath() + QString::fromUtf8("/../Resources/etc/fonts");
QFileInfo fileInfo(path);
if ( !fileInfo.exists() ) {
std::cerr << "Fontconfig configuration file " << path.toStdString() << " does not exist, not setting FONTCONFIG_PATH "<< std::endl;
} else {
QString fcPath = fileInfo.canonicalFilePath();
std::string stdFcPath = fcPath.toStdString();
// qputenv on minw will just call putenv, but we want to keep the utf16 info, so we need to call _wputenv
qDebug() << "Setting FONTCONFIG_PATH to" << stdFcPath.c_str();
#if 0 //def __NATRON_WIN32__
_wputenv_s(L"FONTCONFIG_PATH", StrUtils::utf8_to_utf16(stdFcPath).c_str());
#else
qputenv( "FONTCONFIG_PATH", stdFcPath.c_str() );
#endif
}
}
try {
initPython(); // calls Py_InitializeEx(), which calls setlocale()
} catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
return false;
}
_imp->idealThreadCount = QThread::idealThreadCount();
QThreadPool::globalInstance()->setExpiryTimeout(-1); //< make threads never exit on their own
//otherwise it might crash with thread-local storage
///the QCoreApplication must have been created so far.
assert(qApp);
bool ret = false;
try {
ret = loadInternal(cl);
} catch (const std::runtime_error& e) {
std::cerr << e.what() << std::endl;
}
return ret;
} // loadFromArgs
bool
AppManager::load(int argc,
char **argv,
const CLArgs& cl)
{
// Ensure application has correct locale before doing anything
// Warning: Qt resets it in the QCoreApplication constructor
// see http://doc.qt.io/qt-4.8/qcoreapplication.html#locale-settings
setApplicationLocale();
_imp->handleCommandLineArgs(argc, argv);
return loadFromArgs(cl);
}
bool
AppManager::loadW(int argc,
wchar_t **argv,
const CLArgs& cl)
{
// Ensure application has correct locale before doing anything
// Warning: Qt resets it in the QCoreApplication constructor
// see http://doc.qt.io/qt-4.8/qcoreapplication.html#locale-settings
setApplicationLocale();
_imp->handleCommandLineArgsW(argc, argv);
return loadFromArgs(cl);
}
AppManager::~AppManager()
{
#ifdef NATRON_USE_BREAKPAD
if (_imp->breakpadAliveThread) {
_imp->breakpadAliveThread->quitThread();
}
#endif
bool appsEmpty;
{
QMutexLocker k(&_imp->_appInstancesMutex);
appsEmpty = _imp->_appInstances.empty();
}
while (!appsEmpty) {
AppInstancePtr front;
{
QMutexLocker k(&_imp->_appInstancesMutex);
front = _imp->_appInstances.front();
}
if (front) {
front->quitNow();
}
{
QMutexLocker k(&_imp->_appInstancesMutex);
appsEmpty = _imp->_appInstances.empty();
}
}
for (PluginsMap::iterator it = _imp->_plugins.begin(); it != _imp->_plugins.end(); ++it) {
for (PluginVersionsOrdered::reverse_iterator itver = it->second.rbegin(); itver != it->second.rend(); ++itver) {
delete *itver;
}
}
_imp->_backgroundIPC.reset();
try {
_imp->saveCaches();
} catch (std::runtime_error&) {
// ignore errors
}
///Caches may have launched some threads to delete images, wait for them to be done
QThreadPool::globalInstance()->waitForDone();
///Kill caches now because decreaseNCacheFilesOpened can be called
_imp->_nodeCache->waitForDeleterThread();
_imp->_diskCache->waitForDeleterThread();
_imp->_viewerCache->waitForDeleterThread();
_imp->_nodeCache.reset();
_imp->_viewerCache.reset();
_imp->_diskCache.reset();
tearDownPython();
_imp->tearDownGL();
_instance = 0;
// After this line, everything is cleaned-up (should be) and the process may resume in the main and could in theory be able to re-create a new AppManager
_imp->_qApp.reset();
}
class QuitInstanceArgs
: public GenericWatcherCallerArgs
{
public:
AppInstanceWPtr instance;
QuitInstanceArgs()
: GenericWatcherCallerArgs()
, instance()
{
}
virtual ~QuitInstanceArgs() {}
};
typedef boost::shared_ptr<QuitInstanceArgs> QuitInstanceArgsPtr;
void
AppManager::afterQuitProcessingCallback(const GenericWatcherCallerArgsPtr& args)
{
QuitInstanceArgs* inArgs = dynamic_cast<QuitInstanceArgs*>( args.get() );
if (!inArgs) {
return;
}
AppInstancePtr instance = inArgs->instance.lock();
instance->aboutToQuit();
appPTR->removeInstance( instance->getAppID() );
int nbApps = getNumInstances();
///if we exited the last instance, exit the event loop, this will make
/// the exec() function return.
if (nbApps == 0) {
assert(qApp);
qApp->quit();
}
// This should kill the AppInstance
instance.reset();
}
void
AppManager::quitNow(const AppInstancePtr& instance)
{
NodesList nodesToWatch;
instance->getProject()->getNodes_recursive(nodesToWatch, false);
if ( !nodesToWatch.empty() ) {
for (NodesList::iterator it = nodesToWatch.begin(); it != nodesToWatch.end(); ++it) {
(*it)->quitAnyProcessing_blocking(false);
}
}
QuitInstanceArgsPtr args = boost::make_shared<QuitInstanceArgs>();
args->instance = instance;
afterQuitProcessingCallback(args);
}
void
AppManager::quit(const AppInstancePtr& instance)
{
QuitInstanceArgsPtr args = boost::make_shared<QuitInstanceArgs>();
args->instance = instance;
if ( !instance->getProject()->quitAnyProcessingForAllNodes(this, args) ) {
afterQuitProcessingCallback(args);
}
}
void
AppManager::quitApplication()
{
bool appsEmpty;
{
QMutexLocker k(&_imp->_appInstancesMutex);
appsEmpty = _imp->_appInstances.empty();
}
while (!appsEmpty) {
AppInstancePtr app;
{
QMutexLocker k(&_imp->_appInstancesMutex);
app = _imp->_appInstances.front();
}
if (app) {
quitNow(app);
}
{
QMutexLocker k(&_imp->_appInstancesMutex);
appsEmpty = _imp->_appInstances.empty();
}
}
}
void
AppManager::initializeQApp(int &argc,
char **argv)
{
assert(!_imp->_qApp);
// scoped_ptr
_imp->_qApp.reset( new QCoreApplication(argc, argv) );
}
// setApplicationLocale is called twice:
// - before parsing the command-line arguments
// - after the QCoreApplication was constructed, because the QCoreApplication
// constructor resets the locale to the system locale
// see http://doc.qt.io/qt-4.8/qcoreapplication.html#locale-settings
void
AppManager::setApplicationLocale()
{
// Natron is not yet internationalized, so it is better for now to use the "C" locale,
// until it is tested for robustness against locale choice.
// The locale affects numerics printing and scanning, date and time.
// Note that with other locales (e.g. "de" or "fr"), the floating-point numbers may have
// a comma (",") as the decimal separator instead of a point (".").
// There is also an OpenCOlorIO issue with non-C numeric locales:
// https://github.com/imageworks/OpenColorIO/issues/297
//
// this must be done after initializing the QCoreApplication, see
// https://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings
// Set the C and C++ locales
// see http://en.cppreference.com/w/cpp/locale/locale/global
// Maybe this can also workaround the OSX crash in loadlocale():
// https://discussions.apple.com/thread/3479591
// https://github.com/cth103/dcpomatic/blob/master/src/lib/safe_stringstream.h
// stringstreams don't seem to be thread-safe on OSX because the change the locale.
// We also set explicitly the LC_NUMERIC locale to "C" to avoid juggling
// between locales when using stringstreams.
// See function __convert_from_v(...) in
// /usr/include/c++/4.2.1/x86_64-apple-darwin10/bits/c++locale.h
// https://www.opensource.apple.com/source/libstdcxx/libstdcxx-104.1/include/c++/4.2.1/bits/c++locale.h
// See also https://stackoverflow.com/questions/22753707/is-ostream-operator-in-libstdc-thread-hostile
// set the C++ locale first
#if defined(__APPLE__) && defined(_LIBCPP_VERSION) && (defined(_LIBCPP_USE_AVAILABILITY_APPLE) || !defined(_LIBCPP_DISABLE_AVAILABILITY)) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 1090)
try {
std::locale::global( std::locale("C") );
} catch (std::runtime_error&) {
qDebug() << "Could not set C++ locale!";
}
#else
try {
std::locale::global( std::locale(std::locale("en_US.UTF-8"), "C", std::locale::numeric) );
} catch (std::runtime_error&) {
try {
std::locale::global( std::locale(std::locale("C.UTF-8"), "C", std::locale::numeric) );
} catch (std::runtime_error&) {
try {
std::locale::global( std::locale(std::locale("UTF-8"), "C", std::locale::numeric) );
} catch (std::runtime_error&) {
try {
std::locale::global( std::locale("C") );
} catch (std::runtime_error&) {
qDebug() << "Could not set C++ locale!";
}
}
}
}
#endif
// set the C locale second, because it will not overwrite the changes you made to the C++ locale
// see https://stackoverflow.com/questions/12373341/does-stdlocaleglobal-make-affect-to-printf-function
char *category = std::setlocale(LC_ALL, "en_US.UTF-8");
if (category == NULL) {
category = std::setlocale(LC_ALL, "C.UTF-8");
}
if (category == NULL) {
category = std::setlocale(LC_ALL, "UTF-8");
}
if (category == NULL) {
category = std::setlocale(LC_ALL, "C");
}
if (category == NULL) {
qDebug() << "Could not set C locale!";
}
std::setlocale(LC_NUMERIC, "C"); // set the locale for LC_NUMERIC only
QLocale::setDefault( QLocale(QLocale::English, QLocale::UnitedStates) );
}
bool
AppManager::loadInternal(const CLArgs& cl)
{
assert(!_imp->_loaded);
_imp->_binaryPath = QCoreApplication::applicationDirPath();
assert(StrUtils::is_utf8(_imp->_binaryPath.toStdString().c_str()));
registerEngineMetaTypes();
registerGuiMetaTypes();
qApp->setOrganizationName( QString::fromUtf8(NATRON_ORGANIZATION_NAME) );
qApp->setOrganizationDomain( QString::fromUtf8(NATRON_ORGANIZATION_DOMAIN) );
qApp->setApplicationName( QString::fromUtf8(NATRON_APPLICATION_NAME) );
//Set it once setApplicationName is set since it relies on it
refreshDiskCacheLocation();
// Set the locale AGAIN, because Qt resets it in the QCoreApplication constructor and in Py_InitializeEx
// see http://doc.qt.io/qt-4.8/qcoreapplication.html#locale-settings
setApplicationLocale();
Log::instance(); //< enable logging
bool mustSetSignalsHandlers = true;
#ifdef NATRON_USE_BREAKPAD
//Enabled breakpad only if the process was spawned from the crash reporter
const QString& breakpadProcessExec = cl.getBreakpadProcessExecutableFilePath();
if ( !breakpadProcessExec.isEmpty() && QFile::exists(breakpadProcessExec) ) {
_imp->breakpadProcessExecutableFilePath = breakpadProcessExec;
_imp->breakpadProcessPID = (Q_PID)cl.getBreakpadProcessPID();
const QString& breakpadPipePath = cl.getBreakpadPipeFilePath();
const QString& breakpadComPipePath = cl.getBreakpadComPipeFilePath();
int breakpad_client_fd = cl.getBreakpadClientFD();
_imp->initBreakpad(breakpadPipePath, breakpadComPipePath, breakpad_client_fd);
mustSetSignalsHandlers = false;
}
#endif
# ifdef __NATRON_UNIX__
if (mustSetSignalsHandlers) {
setShutDownSignal(SIGINT); // shut down on ctrl-c
setShutDownSignal(SIGTERM); // shut down on killall
# if defined(__NATRON_LINUX__) && !defined(__FreeBSD__)
//Catch SIGSEGV only when google-breakpad is not active
setSigSegvSignal();
# endif
}
# else
Q_UNUSED(mustSetSignalsHandlers);
# endif
_imp->_settings = boost::make_shared<Settings>();
_imp->_settings->initializeKnobsPublic();
bool hasGLForRendering = hasOpenGLForRequirements(eOpenGLRequirementsTypeRendering, 0);
if (_imp->hasInitializedOpenGLFunctions && hasGLForRendering) {
OSGLContext::getGPUInfos(_imp->openGLRenderers);
for (std::list<OpenGLRendererInfo>::iterator it = _imp->openGLRenderers.begin(); it != _imp->openGLRenderers.end(); ++it) {
qDebug() << "Found OpenGL Renderer:" << it->rendererName.c_str() << ", Vendor:" << it->vendorName.c_str()
<< ", OpenGL Version:" << it->glVersionString.c_str() << ", Max. Texture Size" << it->maxTextureSize <<
",Max GPU Memory:" << printAsRAM(it->maxMemBytes);;
}
}
_imp->_settings->populateOpenGLRenderers(_imp->openGLRenderers);
// Settings: we must load these and set the custom settings (using python) ASAP, before creating the OFX Plugin Cache
// Settings: always call restoreSettings, but call restoreKnobsFromSettings conditionally
// Call restore after initializing knobs
_imp->_settings->restoreSettings( cl.isLoadedUsingDefaultSettings() );
if (cl.isLoadedUsingDefaultSettings()) {
_imp->_settings->setSaveSettings(false);
}
_imp->declareSettingsToPython();
// executeCommandLineSettingCommands
{
const std::list<std::string>& commands = cl.getSettingCommands();
// do not save settings if there is a --setting option
if ( !commands.empty() ) {
_imp->_settings->setSaveSettings(false);
}
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;
}
}
}
///basically show a splashScreen load fonts etc...
return initGui(cl);
} // loadInternal
const std::list<OpenGLRendererInfo>&
AppManager::getOpenGLRenderers() const
{
return _imp->openGLRenderers;
}
bool
AppManager::isSpawnedFromCrashReporter() const
{
#ifdef NATRON_USE_BREAKPAD
return _imp->breakpadHandler.get() != 0;
#else
return false;
#endif
}
void
AppManager::setPluginsUseInputImageCopyToRender(bool b)
{
_imp->pluginsUseInputImageCopyToRender = b;
}
bool
AppManager::isCopyInputImageForPluginRenderEnabled() const
{
return _imp->pluginsUseInputImageCopyToRender;
}
bool
AppManager::isOpenGLLoaded() const
{
QMutexLocker k(&_imp->openGLFunctionsMutex);
return _imp->hasInitializedOpenGLFunctions;
}
bool
AppManager::isTextureFloatSupported() const
{
return _imp->glHasTextureFloat;
}
bool
AppManager::hasOpenGLForRequirements(OpenGLRequirementsTypeEnum type, QString* missingOpenGLError ) const
{
std::map<OpenGLRequirementsTypeEnum,AppManagerPrivate::OpenGLRequirementsData>::const_iterator found = _imp->glRequirements.find(type);
assert(found != _imp->glRequirements.end());
if (found == _imp->glRequirements.end()) {
return false;
}
if (missingOpenGLError && !found->second.hasRequirements) {
*missingOpenGLError = found->second.error;
}
return found->second.hasRequirements;
}
bool
AppManager::initializeOpenGLFunctionsOnce(bool createOpenGLContext)
{
QMutexLocker k(&_imp->openGLFunctionsMutex);
if (!_imp->hasInitializedOpenGLFunctions) {
OSGLContextPtr glContext;
bool checkRenderingReq = true;
if (createOpenGLContext) {
try {
_imp->initGLAPISpecific();
glContext = _imp->renderingContextPool->attachGLContextToRender(false /*checkIfGLLoaded*/);
if (glContext) {
// Make the context current and check its version
glContext->setContextCurrentNoRender();
} else {
AppManagerPrivate::OpenGLRequirementsData& vdata = _imp->glRequirements[eOpenGLRequirementsTypeViewer];
AppManagerPrivate::OpenGLRequirementsData& rdata = _imp->glRequirements[eOpenGLRequirementsTypeRendering];
rdata.error = tr("Error creating OpenGL context.");
vdata.error = rdata.error;
rdata.hasRequirements = false;
vdata.hasRequirements = false;
AppManagerPrivate::addOpenGLRequirementsString(rdata.error, eOpenGLRequirementsTypeRendering);
AppManagerPrivate::addOpenGLRequirementsString(vdata.error, eOpenGLRequirementsTypeViewer);
}
} catch (const std::exception& e) {
std::cerr << "Error while loading OpenGL: " << e.what() << std::endl;
std::cerr << "OpenGL rendering is disabled. " << std::endl;
AppManagerPrivate::OpenGLRequirementsData& vdata = _imp->glRequirements[eOpenGLRequirementsTypeViewer];
AppManagerPrivate::OpenGLRequirementsData& rdata = _imp->glRequirements[eOpenGLRequirementsTypeRendering];
rdata.hasRequirements = false;
vdata.hasRequirements = false;
vdata.error = tr("Error while creating OpenGL context: %1").arg(QString::fromUtf8(e.what()));