-
Notifications
You must be signed in to change notification settings - Fork 459
/
qSlicerCoreApplication.cxx
1747 lines (1544 loc) · 58 KB
/
qSlicerCoreApplication.cxx
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
/*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http:https://www.slicer.org/copyright/copyright.txt for details.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
// standard library includes
#include <clocale>
// Qt includes
#include <QDebug>
#include <QDesktopServices>
#include <QDir>
#include <QLocale>
#include <QMessageBox>
#include <QTimer>
#include <QNetworkProxyFactory>
#include <QResource>
#include <QSettings>
#include <QTranslator>
// For:
// - Slicer_QTLOADABLEMODULES_LIB_DIR
// - Slicer_CLIMODULES_BIN_DIR
// - Slicer_LIB_DIR
// - Slicer_SHARE_DIR
// - Slicer_USE_PYTHONQT
// - Slicer_BUILD_EXTENSIONMANAGER_SUPPORT
// - Slicer_BUILD_WIN32_CONSOLE
// - Slicer_BUILD_CLI_SUPPORT
// - Slicer_BUILD_I18N_SUPPORT
// - Slicer_ORGANIZATION_DOMAIN
// - Slicer_ORGANIZATION_NAME
// - SLICER_REVISION_SPECIFIC_USER_SETTINGS_FILEBASENAME
#include "vtkSlicerConfigure.h"
#ifdef Slicer_USE_PYTHONQT
// PythonQt includes
#include <PythonQt.h>
#endif
#ifdef Slicer_USE_PYTHONQT_WITH_OPENSSL
#include <QSslCertificate>
#include <QSslSocket>
#endif
// SlicerQt includes
#include "qSlicerCoreApplication_p.h"
#include "qSlicerCoreCommandOptions.h"
#include "qSlicerCoreIOManager.h"
#ifdef Slicer_USE_PYTHONQT
# include "qSlicerCorePythonManager.h"
# include "ctkPythonConsole.h"
#endif
#ifdef Slicer_BUILD_EXTENSIONMANAGER_SUPPORT
# include "qSlicerExtensionsManagerModel.h"
#endif
#include "qSlicerLoadableModuleFactory.h"
#include "qSlicerModuleFactoryManager.h"
#include "qSlicerModuleManager.h"
#include "qSlicerUtils.h"
// SlicerLogic includes
#include "vtkDataIOManagerLogic.h"
// MRMLDisplayable includes
#include <vtkMRMLThreeDViewDisplayableManagerFactory.h>
#include <vtkMRMLSliceViewDisplayableManagerFactory.h>
// MRMLLogic includes
#include <vtkMRMLRemoteIOLogic.h>
// MRML includes
#include <vtkCacheManager.h>
#include <vtkMRMLCrosshairNode.h>
#ifdef Slicer_BUILD_CLI_SUPPORT
# include <vtkMRMLCommandLineModuleNode.h>
#endif
#include <vtkMRMLScene.h>
// VTK includes
#include <vtkNew.h>
#include <vtksys/SystemTools.hxx>
// Slicer includes
#include "vtkSlicerVersionConfigure.h" // For Slicer_VERSION_{MINOR, MAJOR}, Slicer_VERSION_FULL
#ifdef Slicer_BUILD_DICOM_SUPPORT
// XXX Avoid warning: "HAVE_XXXX" redefined
#undef HAVE_STAT
#undef HAVE_FTIME
#undef HAVE_GETPID
#undef HAVE_IO_H
#undef HAVE_STRERROR
#undef HAVE_SYS_UTIME_H
#undef HAVE_TEMPNAM
#undef HAVE_TMPNAM
#undef HAVE_LONG_LONG
// XXX Fix windows build error
#undef HAVE_INT64_T
#include <ctkDICOMDatabase.h>
#endif
//-----------------------------------------------------------------------------
// qSlicerCoreApplicationPrivate methods
//-----------------------------------------------------------------------------
qSlicerCoreApplicationPrivate::qSlicerCoreApplicationPrivate(
qSlicerCoreApplication& object,
qSlicerCoreCommandOptions * coreCommandOptions,
qSlicerCoreIOManager * coreIOManager) : q_ptr(&object)
{
qRegisterMetaType<qSlicerCoreApplication::ReturnCode>("qSlicerCoreApplication::ReturnCode");
this->DefaultSettings = 0;
this->UserSettings = 0;
this->RevisionUserSettings = 0;
this->ReturnCode = qSlicerCoreApplication::ExitNotRequested;
this->CoreCommandOptions = QSharedPointer<qSlicerCoreCommandOptions>(coreCommandOptions);
this->CoreIOManager = QSharedPointer<qSlicerCoreIOManager>(coreIOManager);
#ifdef Slicer_BUILD_DICOM_SUPPORT
this->DICOMDatabase = 0;
#endif
this->NextResourceHandle = 0;
}
//-----------------------------------------------------------------------------
qSlicerCoreApplicationPrivate::~qSlicerCoreApplicationPrivate()
{
// - The ModuleManager deals with scripted module which internally work with
// python references. (I.e calling Py_DECREF, ...)
// - The PythonManager takes care of initializing and terminating the
// python embedded interpreter
// => Di facto, it's important to make sure PythonManager is destructed
// after the ModuleManager.
// To do so, the associated SharedPointer are cleared in the appropriate order
this->ModuleManager->factoryManager()->unloadModules();
this->ModuleManager.clear();
this->CoreIOManager.clear();
#ifdef Slicer_USE_PYTHONQT
this->CorePythonManager.clear();
#endif
this->AppLogic->TerminateProcessingThread();
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::init()
{
Q_Q(qSlicerCoreApplication);
// Minimize the number of call to 'systemEnvironment()' by keeping
// a reference to 'Environment'. Indeed, re-creating QProcessEnvironment is a non-trivial
// operation. See http:https://doc.qt.nokia.com/4.7/qprocessenvironment.html#systemEnvironment
// Note also that since environment variables are set using 'setEnvironmentVariable()',
// 'Environment' is maintained 'up-to-date'. Nevertheless, if the environment
// is udpated solely using 'putenv(...)' function, 'Environment' won't be updated.
this->Environment = QProcessEnvironment::systemEnvironment();
// Set the locale to be "C" to avoid issues related to reading and writing
// of floating point numbers. For example, when the decimal point is set to be
// a comma instead of a period, there can be truncation of data.
// See these previous commits and the bug report.
// http:https://viewvc.slicer.org/viewvc.cgi/Slicer4?view=revision&revision=21856
// http:https://viewvc.slicer.org/viewvc.cgi/Slicer4?view=revision&revision=21865
// http:https://slicer-devel.65872.n3.nabble.com/Re-Rounding-to-integer-tt4027985.html
// http:https://slicer-devel.65872.n3.nabble.com/Re-slicer-users-Slicer4-can-t-really-use-it-yet-td4028040.html
// http:https://slicer-users.65878.n3.nabble.com/Slicer4-DICOM-many-problems-td4025919.html
// and issue #3029
// Set both the Qt locale, and the standard library locale to cover
// all supported read and write methods.
QLocale::setDefault(QLocale::C);
setlocale(LC_ALL, "C");
// allow a debugger to be attached during startup
if(qApp->arguments().contains("--attach-process"))
{
QString msg("This message box is here to give you time to attach "
"your debugger to process [PID %1]");
QMessageBox::information(0, "Attach process", msg.arg(QCoreApplication::applicationPid()));
}
QCoreApplication::setOrganizationDomain(Slicer_ORGANIZATION_DOMAIN);
QCoreApplication::setOrganizationName(Slicer_ORGANIZATION_NAME);
QSettings::setDefaultFormat(QSettings::IniFormat);
if (q->arguments().isEmpty())
{
qDebug() << "qSlicerCoreApplication must be given the True argc/argv";
}
this->parseArguments();
this->SlicerHome = this->discoverSlicerHomeDirectory();
this->setEnvironmentVariable("SLICER_HOME", this->SlicerHome);
#ifdef Slicer_USE_PYTHONQT_WITH_OPENSSL
if (!QSslSocket::supportsSsl())
{
qWarning() << "[SSL] SSL support disabled - Failed to load SSL library !";
}
if (!qSlicerCoreApplication::loadCaCertificates(this->SlicerHome))
{
qWarning() << "[SSL] Failed to load Slicer.crt";
}
# ifdef Q_OS_MAC
if (this->isInstalled(this->SlicerHome))
{
this->setEnvironmentVariable(
"SSL_CERT_FILE",
this->SlicerHome + "/" Slicer_SHARE_DIR "/Slicer.crt");
}
# endif
#endif
// Add 'SLICER_SHARE_DIR' to the environment so that Tcl scripts can reference
// their dependencies.
this->setEnvironmentVariable("SLICER_SHARE_DIR", Slicer_SHARE_DIR);
this->ITKFactoriesDir = this->discoverITKFactoriesDirectory();
this->setEnvironmentVariable("ITK_AUTOLOAD_PATH", this->ITKFactoriesDir);
this->setPythonEnvironmentVariables();
this->setTclEnvironmentVariables();
// Load default settings if any.
if (q->defaultSettings())
{
foreach(const QString& key, q->defaultSettings()->allKeys())
{
if (!q->userSettings()->contains(key))
{
q->userSettings()->setValue(key, q->defaultSettings()->value(key));
}
}
}
// Create the application Logic object,
this->AppLogic = vtkSmartPointer<vtkSlicerApplicationLogic>::New();
this->AppLogic->SetTemporaryPath(q->temporaryPath().toLatin1());
q->qvtkConnect(this->AppLogic, vtkCommand::ModifiedEvent,
q, SLOT(onSlicerApplicationLogicModified()));
q->qvtkConnect(this->AppLogic, vtkSlicerApplicationLogic::RequestInvokeEvent,
q, SLOT(requestInvokeEvent(vtkObject*,void*)), 0.0, Qt::DirectConnection);
q->connect(q, SIGNAL(invokeEventRequested(unsigned int,void*,unsigned long,void*)),
q, SLOT(scheduleInvokeEvent(unsigned int,void*,unsigned long,void*)), Qt::AutoConnection);
q->qvtkConnect(this->AppLogic, vtkSlicerApplicationLogic::RequestModifiedEvent,
q, SLOT(onSlicerApplicationLogicRequest(vtkObject*,void*,ulong)));
q->qvtkConnect(this->AppLogic, vtkSlicerApplicationLogic::RequestReadDataEvent,
q, SLOT(onSlicerApplicationLogicRequest(vtkObject*,void*,ulong)));
q->qvtkConnect(this->AppLogic, vtkSlicerApplicationLogic::RequestWriteDataEvent,
q, SLOT(onSlicerApplicationLogicRequest(vtkObject*,void*,ulong)));
vtkMRMLThreeDViewDisplayableManagerFactory::GetInstance()->SetMRMLApplicationLogic(
this->AppLogic.GetPointer());
vtkMRMLSliceViewDisplayableManagerFactory::GetInstance()->SetMRMLApplicationLogic(
this->AppLogic.GetPointer());
// pass through event handling once without observing the scene
// -- allows any dependent nodes to be created
// Note that Interaction and Selection Node are now created
// in MRMLApplicationLogic.
//this->AppLogic->ProcessMRMLEvents(scene, vtkCommand::ModifiedEvent, NULL);
//this->AppLogic->SetAndObserveMRMLScene(scene);
this->AppLogic->CreateProcessingThread();
// Set up Slicer to use the system proxy
QNetworkProxyFactory::setUseSystemConfiguration(true);
// Set up Data IO
this->initDataIO();
// Create MRML scene
vtkNew<vtkMRMLScene> scene;
q->setMRMLScene(scene.GetPointer());
// Instantiate moduleManager
this->ModuleManager = QSharedPointer<qSlicerModuleManager>(new qSlicerModuleManager);
this->ModuleManager->factoryManager()->setAppLogic(this->AppLogic.GetPointer());
this->ModuleManager->factoryManager()->setMRMLScene(scene.GetPointer());
q->connect(q, SIGNAL(mrmlSceneChanged(vtkMRMLScene*)),
this->ModuleManager->factoryManager(), SLOT(setMRMLScene(vtkMRMLScene*)));
q->handlePreApplicationCommandLineArguments();
#ifdef Slicer_USE_PYTHONQT
if (!qSlicerCoreApplication::testAttribute(qSlicerCoreApplication::AA_DisablePython))
{
if (q->corePythonManager())
{
q->corePythonManager()->mainContext(); // Initialize python
q->corePythonManager()->setSystemExitExceptionHandlerEnabled(true);
q->connect(q->corePythonManager(), SIGNAL(systemExitExceptionRaised(int)),
q, SLOT(terminate(int)));
}
# ifdef Q_WS_WIN
// HACK - Since on windows setting an environment variable using putenv doesn't propagate
// to the environment initialized in python, let's make sure 'os.environ' is updated.
this->updatePythonOsEnviron();
# endif
}
#endif
#ifdef Slicer_BUILD_EXTENSIONMANAGER_SUPPORT
qSlicerExtensionsManagerModel * model = new qSlicerExtensionsManagerModel(q);
model->setExtensionsSettingsFilePath(q->slicerRevisionUserSettingsFilePath());
model->setSlicerRequirements(q->repositoryRevision(), q->os(), q->arch());
q->setExtensionsManagerModel(model);
# ifdef Q_OS_MAC
this->createDirectory(this->defaultExtensionsInstallPathForMacOSX(), "extensions"); // Make sure the path exists
q->addLibraryPath(this->defaultExtensionsInstallPathForMacOSX());
q->setExtensionsInstallPath(this->defaultExtensionsInstallPathForMacOSX());
# endif
this->createDirectory(q->extensionsInstallPath(), "extensions"); // Make sure the path exists
model->updateModel();
QStringList updatedExtensions;
model->updateScheduledExtensions(updatedExtensions);
foreach(const QString& extensionName, updatedExtensions)
{
qDebug() << "Successfully updated extension" << extensionName;
}
QStringList uninstalledExtensions;
model->uninstallScheduledExtensions(uninstalledExtensions);
foreach(const QString& extensionName, uninstalledExtensions)
{
qDebug() << "Successfully uninstalled extension" << extensionName;
}
#endif
if (q->userSettings()->value("Internationalization/Enabled").toBool())
{
// We load the language selected for the application
qSlicerCoreApplication::loadLanguage();
}
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::initDataIO()
{
Q_Q(qSlicerCoreApplication);
// Create MRMLRemoteIOLogic
this->MRMLRemoteIOLogic = vtkSmartPointer<vtkMRMLRemoteIOLogic>::New();
// Default cache location, can be changed in settings.
this->MRMLRemoteIOLogic->GetCacheManager()->SetRemoteCacheDirectory(
QFileInfo(q->temporaryPath(), "RemoteIO").
absoluteFilePath().toLatin1());
this->DataIOManagerLogic = vtkSmartPointer<vtkDataIOManagerLogic>::New();
this->DataIOManagerLogic->SetMRMLApplicationLogic(this->AppLogic);
this->DataIOManagerLogic->SetAndObserveDataIOManager(
this->MRMLRemoteIOLogic->GetDataIOManager());
}
//-----------------------------------------------------------------------------
QSettings* qSlicerCoreApplicationPrivate::newSettings()
{
Q_Q(qSlicerCoreApplication);
return new QSettings(q);
}
//-----------------------------------------------------------------------------
QSettings* qSlicerCoreApplicationPrivate::instantiateSettings(bool useTmp)
{
Q_Q(qSlicerCoreApplication);
if (useTmp)
{
q->setApplicationName(q->applicationName() + "-tmp");
}
QSettings* settings = this->newSettings();
if (useTmp && !q->coreCommandOptions()->keepTemporarySettings())
{
settings->clear();
}
return settings;
}
//-----------------------------------------------------------------------------
bool qSlicerCoreApplicationPrivate::isInstalled(const QString& slicerHome)const
{
return !QFile::exists(slicerHome + "/CMakeCache.txt");
}
//-----------------------------------------------------------------------------
QString qSlicerCoreApplicationPrivate::discoverSlicerHomeDirectory()
{
// Since some standalone executable (i.e EMSegmentCommandLine) can create
// an instance of qSlicer(Core)Application so that the environment and the
// python manager are properly initialized. This executable will have
// to set SLICER_HOME. If not, the current directory associated with that
// executable will be considered and initialization code expecting SLICER_HOME
// to be properly set will fail.
QString slicerHome = this->Environment.value("SLICER_HOME");
if (slicerHome.isEmpty())
{
QString slicerBin = this->discoverSlicerBinDirectory();
QDir slicerBinDir(slicerBin);
bool cdUpRes = slicerBinDir.cdUp();
Q_ASSERT(cdUpRes);
(void)cdUpRes;
slicerHome = slicerBinDir.canonicalPath();
}
#ifdef Q_OS_WIN32
Q_Q(qSlicerCoreApplication);
if (!this->isInstalled(slicerHome))
{
foreach(const QString& subDir,
QStringList() << Slicer_BIN_DIR << Slicer_CLIMODULES_BIN_DIR << "Cxx")
{
qSlicerUtils::pathWithoutIntDir(q->applicationDirPath(), subDir, this->IntDir);
if (!this->IntDir.isEmpty())
{
break;
}
}
}
Q_ASSERT(this->isInstalled(slicerHome) ? this->IntDir.isEmpty() : !this->IntDir.isEmpty());
#endif
return slicerHome;
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::setEnvironmentVariable(const QString& key, const QString& value)
{
Q_Q(qSlicerCoreApplication);
q->setEnvironmentVariable(key, value);
#if defined(Slicer_USE_PYTHONQT) && defined(Q_WS_WIN)
// Cache environment variable
this->EnvironmentVariablesCache[key] = value;
#endif
}
//-----------------------------------------------------------------------------
#ifdef Slicer_USE_PYTHONQT
void qSlicerCoreApplicationPrivate::setPythonOsEnviron(const QString& key, const QString& value)
{
if(!this->CorePythonManager->isPythonInitialized())
{
return;
}
this->CorePythonManager->executeString(
QString("import os; os.environ['%1']='%2'; del os").arg(key).arg(value));
}
#endif
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::updateEnvironmentVariable(const QString& key, const QString& value,
QChar separator, bool prepend)
{
Q_Q(qSlicerCoreApplication);
if(q->isEnvironmentVariableValueSet(key, value))
{
return;
}
std::string currentValue;
vtksys::SystemTools::GetEnv(key.toLatin1(), currentValue);
if(currentValue.size() > 0)
{
QString updatedValue(value);
if(prepend)
{
q->setEnvironmentVariable(key, updatedValue.prepend(separator).prepend(QString::fromStdString(currentValue)));
}
else
{
q->setEnvironmentVariable(key, updatedValue.append(separator).append(QString::fromStdString(currentValue)));
}
}
else
{
q->setEnvironmentVariable(key, value);
}
}
//-----------------------------------------------------------------------------
QString qSlicerCoreApplicationPrivate::discoverSlicerBinDirectory()
{
Q_Q(qSlicerCoreApplication);
QString slicerBin;
// Note: On Linux, QCoreApplication::applicationDirPath() will attempt
// to get the path using the "/proc" filesystem.
if (!QFile::exists(q->applicationDirPath()))
{
qCritical() << "Cannot find Slicer executable" << q->applicationDirPath();
return slicerBin;
}
#ifndef Q_OS_MAC
slicerBin =
qSlicerUtils::pathWithoutIntDir(q->applicationDirPath(), Slicer_BIN_DIR, this->IntDir);
#else
// There are two cases to consider, the application could be started from:
// 1) Install tree
// Application location: /path/to/Foo.app/Contents/MacOSX/myapp
// Binary directory: /path/to/Foo.app/Contents/bin
// 2) Build tree
// Application location: /path/to/build-dir/bin/Foo.app/Contents/MacOSX/myapp
// Binary directory: /path/to/build-dir/bin
//
QDir slicerBinAsDir(q->applicationDirPath());
slicerBinAsDir.cdUp(); // Move from /path/to/Foo.app/Contents/MacOSX to /path/to/Foo.app/Contents
if(!slicerBinAsDir.cd(Slicer_BIN_DIR))
{
slicerBinAsDir.cdUp(); // Move from /path/to/build-dir/bin/Foo.app/Contents to /path/to/build-dir/bin/Foo.app
slicerBinAsDir.cdUp(); // Move from /path/to/build-dir/bin/Foo.app to /path/to/build-dir/bin
slicerBinAsDir.cd(Slicer_BIN_DIR);
}
slicerBin = slicerBinAsDir.path();
#endif
Q_ASSERT(qSlicerUtils::pathEndsWith(slicerBin, Slicer_BIN_DIR));
return slicerBin;
}
//-----------------------------------------------------------------------------
QString qSlicerCoreApplicationPrivate::discoverITKFactoriesDirectory()
{
QDir itkFactoriesDir(this->SlicerHome);
itkFactoriesDir.cd(Slicer_ITKFACTORIES_DIR);
if (!this->IntDir.isEmpty())
{
itkFactoriesDir.cd(this->IntDir);
}
if (!itkFactoriesDir.exists())
{
qWarning() << "ITK_AUTOLOAD_PATH doesn't exists:"<< this->ITKFactoriesDir;
}
return itkFactoriesDir.absolutePath();
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::setPythonEnvironmentVariables()
{
#ifdef Slicer_USE_PYTHONQT
Q_Q(qSlicerCoreApplication);
// Set PYTHONHOME if not already done
if (this->Environment.value("PYTHONHOME").isEmpty())
{
if (!q->isInstalled())
{
// TODO
}
else
{
qSlicerCoreApplication * app = qSlicerCoreApplication::application();
this->setEnvironmentVariable("PYTHONHOME", app->slicerHome() + "/lib/Python");
}
}
// Set PYTHONPATH if not already done
if (this->Environment.value("PYTHONPATH").isEmpty())
{
this->setEnvironmentVariable(
"PYTHONPATH", qSlicerCorePythonManager().pythonPaths().join(":"));
}
#endif
}
//-----------------------------------------------------------------------------
#if defined(Slicer_USE_PYTHONQT) && defined(Q_WS_WIN)
void qSlicerCoreApplicationPrivate::updatePythonOsEnviron()
{
foreach(const QString& key, this->EnvironmentVariablesCache.keys())
{
this->setPythonOsEnviron(key, this->EnvironmentVariablesCache.value(key));
}
}
#endif
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::setTclEnvironmentVariables()
{
#ifdef Slicer_USE_PYTHONQT_WITH_TCL
Q_Q(qSlicerCoreApplication);
qSlicerCoreApplication * app = qSlicerCoreApplication::application();
if (this->Environment.value("TCL_LIBRARY").isEmpty())
{
if (!q->isInstalled())
{
// TODO
}
else
{
this->setEnvironmentVariable(
"TCL_LIBRARY", app->slicerHome() + "/lib/TclTk/lib/tcl" Slicer_TCL_TK_VERSION_DOT);
}
}
if (this->Environment.value("TK_LIBRARY").isEmpty())
{
if (!q->isInstalled())
{
// TODO
}
else
{
this->setEnvironmentVariable(
"TK_LIBRARY", app->slicerHome() + "/lib/TclTk/lib/tk" Slicer_TCL_TK_VERSION_DOT);
}
}
if (this->Environment.value("TCLLIBPATH").isEmpty())
{
if (!q->isInstalled())
{
// TODO
}
else
{
QStringList tclLibPaths;
tclLibPaths << app->slicerHome() + "/lib/TclTk/lib/itcl" Slicer_INCR_TCL_VERSION_DOT;
tclLibPaths << app->slicerHome() + "/lib/TclTk/lib/itk" Slicer_INCR_TCL_VERSION_DOT;
this->setEnvironmentVariable("TCLLIBPATH", tclLibPaths.join(" "));
}
}
#endif
}
#ifdef Slicer_BUILD_EXTENSIONMANAGER_SUPPORT
//-----------------------------------------------------------------------------
QString qSlicerCoreApplicationPrivate::defaultExtensionsInstallPathForMacOSX()const
{
Q_Q(const qSlicerCoreApplication);
if (q->isInstalled())
{
QDir slicerHomeDir(q->slicerHome());
slicerHomeDir.cdUp();
return slicerHomeDir.absolutePath() + "/Contents/" Slicer_EXTENSIONS_DIRNAME;
}
else
{
return q->slicerHome() + "/bin/" Slicer_BUNDLE_LOCATION "/" Slicer_EXTENSIONS_DIRNAME;
}
}
#endif
//-----------------------------------------------------------------------------
bool qSlicerCoreApplicationPrivate::createDirectory(const QString& path, const QString& description) const
{
if (path.isEmpty())
{
return false;
}
if (QDir(path).exists())
{
return true;
}
if (!QDir::root().mkpath(path))
{
qCritical() << QObject::tr("Failed to create %1 directory").arg(description) << path;
return false;
}
return true;
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplicationPrivate::parseArguments()
{
Q_Q(qSlicerCoreApplication);
qSlicerCoreCommandOptions* options = this->CoreCommandOptions.data();
if (!options)
{
qWarning() << "Failed to parse arguments - "
"it seems you forgot to call setCoreCommandOptions()";
q->terminate(EXIT_FAILURE);
return;
}
if (!options->parse(q->arguments()))
{
qCritical("Problem parsing command line arguments. Try with --help.");
q->terminate(EXIT_FAILURE);
return;
}
}
//-----------------------------------------------------------------------------
// qSlicerCoreApplication methods
//-----------------------------------------------------------------------------
qSlicerCoreApplication::qSlicerCoreApplication(int &_argc, char **_argv):Superclass(_argc, _argv)
, d_ptr(new qSlicerCoreApplicationPrivate(*this, new qSlicerCoreCommandOptions, new qSlicerCoreIOManager))
{
Q_D(qSlicerCoreApplication);
d->init();
}
//-----------------------------------------------------------------------------
qSlicerCoreApplication::qSlicerCoreApplication(
qSlicerCoreApplicationPrivate* pimpl, int &argc, char **argv)
: Superclass(argc, argv), d_ptr(pimpl)
{
// Note: You are responsible to call init() in the constructor of derived class.
}
//-----------------------------------------------------------------------------
qSlicerCoreApplication::~qSlicerCoreApplication()
{
}
//-----------------------------------------------------------------------------
qSlicerCoreApplication* qSlicerCoreApplication::application()
{
qSlicerCoreApplication* app = qobject_cast<qSlicerCoreApplication*>(QApplication::instance());
return app;
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::setAttribute(qSlicerCoreApplication::ApplicationAttribute attribute, bool on)
{
QCoreApplication::setAttribute(static_cast<Qt::ApplicationAttribute>(attribute), on);
}
//-----------------------------------------------------------------------------
bool qSlicerCoreApplication::testAttribute(qSlicerCoreApplication::ApplicationAttribute attribute)
{
return QCoreApplication::testAttribute(static_cast<Qt::ApplicationAttribute>(attribute));
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::setEnvironmentVariable(const QString& key, const QString& value)
{
Q_D(qSlicerCoreApplication);
d->Environment.insert(key, value);
// Since QProcessEnvironment can't be used to update the environment of the
// current process, let's use 'putenv()'.
// See http:https://doc.qt.nokia.com/4.6/qprocessenvironment.html#details
vtksys::SystemTools::PutEnv(QString("%1=%2").arg(key).arg(value).toLatin1().constData());
#ifdef Slicer_USE_PYTHONQT
d->setPythonOsEnviron(key, value);
#endif
}
//-----------------------------------------------------------------------------
bool qSlicerCoreApplication::isEnvironmentVariableValueSet(const QString& key, const QString& value)
{
std::string currentValue;
vtksys::SystemTools::GetEnv(key.toLatin1(), currentValue);
return QString::fromStdString(currentValue).contains(value);
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::prependEnvironmentVariable(const QString& key, const QString& value, QChar separator)
{
Q_D(qSlicerCoreApplication);
d->updateEnvironmentVariable(key, value, separator, true);
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::appendEnvironmentVariable(const QString& key, const QString& value, QChar separator)
{
Q_D(qSlicerCoreApplication);
d->updateEnvironmentVariable(key, value, separator, false);
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::parseArguments(bool& exitWhenDone)
{
Q_D(qSlicerCoreApplication);
d->parseArguments();
exitWhenDone = (d->ReturnCode != ExitNotRequested);
}
//-----------------------------------------------------------------------------
int qSlicerCoreApplication::returnCode()const
{
Q_D(const qSlicerCoreApplication);
return d->ReturnCode;
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::handlePreApplicationCommandLineArguments()
{
qSlicerCoreCommandOptions* options = this->coreCommandOptions();
Q_ASSERT(options);
if (options->displayHelpAndExit())
{
if (this->launcherSettingsFilePath().isEmpty())
{
std::cout << "Usage\n"
<< " " << qPrintable(this->applicationName()) << " [options]\n\n"
<< "Options\n";
}
std::cout << qPrintable(options->helpText()) << std::endl;
this->terminate(EXIT_SUCCESS);
return;
}
if (options->displayVersionAndExit())
{
std::cout << qPrintable(this->applicationName() + " " +
this->applicationVersion()) << std::endl;
this->terminate(EXIT_SUCCESS);
return;
}
if (options->displayProgramPathAndExit())
{
std::cout << qPrintable(this->arguments().at(0)) << std::endl;
this->terminate(EXIT_SUCCESS);
return;
}
if (options->displayHomePathAndExit())
{
std::cout << qPrintable(this->slicerHome()) << std::endl;
this->terminate(EXIT_SUCCESS);
return;
}
if (options->displaySettingsPathAndExit())
{
std::cout << qPrintable(this->userSettings()->fileName()) << std::endl;
this->terminate(EXIT_SUCCESS);
return;
}
if (options->displayTemporaryPathAndExit())
{
std::cout << qPrintable(this->temporaryPath()) << std::endl;
this->terminate(EXIT_SUCCESS);
return;
}
if (options->ignoreRest())
{
qDebug() << "Ignored arguments:" << options->unparsedArguments();
return;
}
if (!options->settingsDisabled() && options->keepTemporarySettings())
{
qWarning() << "Argument '--keep-temporary-settings' requires "
"'--settings-disabled' to be specified.";
}
if (options->isTestingEnabled())
{
this->setAttribute(AA_EnableTesting);
}
#ifdef Slicer_USE_PYTHONQT
if (options->isPythonDisabled())
{
this->setAttribute(AA_DisablePython);
}
#endif
}
//-----------------------------------------------------------------------------
void qSlicerCoreApplication::handleCommandLineArguments()
{
qSlicerCoreCommandOptions* options = this->coreCommandOptions();
QStringList unparsedArguments = options->unparsedArguments();
if (unparsedArguments.length() > 0 &&
options->pythonScript().isEmpty() &&
options->extraPythonScript().isEmpty())
{
foreach(QString fileName, unparsedArguments)
{
QFileInfo file(fileName);
if (file.exists())
{
qSlicerCoreIOManager* ioManager =this->coreIOManager();
qSlicerIO::IOFileType fileType = ioManager->fileType(fileName);
qSlicerIO::IOProperties fileProperties;
fileProperties.insert("fileName", fileName);
ioManager->loadNodes(fileType, fileProperties);
}
}
}
#ifndef Slicer_USE_PYTHONQT
Q_UNUSED(options);
#else
if (!qSlicerCoreApplication::testAttribute(qSlicerCoreApplication::AA_DisablePython))
{
// Note that 'pythonScript' is ignored if 'extraPythonScript' is specified
QString pythonScript = options->pythonScript();
QString extraPythonScript = options->extraPythonScript();
QStringList scriptArgs = options->unparsedArguments();
// Do not pass "--attach-process", it will avoid some python script to complain about
// unknown argument.
scriptArgs.removeAll("--attach-process");
if(!extraPythonScript.isEmpty())
{
scriptArgs.removeFirst();
pythonScript = extraPythonScript;
}
// Set 'argv' so that python script can retrieve its associated arguments
int pythonArgc = 1 /*scriptname*/ + scriptArgs.count();
char** pythonArgv = new char*[pythonArgc];
pythonArgv[0] = new char[pythonScript.size() + 1];
strcpy(pythonArgv[0], pythonScript.toLatin1());
for(int i = 0; i < scriptArgs.count(); ++i)
{
pythonArgv[i + 1] = new char[scriptArgs.at(i).size() + 1];
strcpy(pythonArgv[i + 1], scriptArgs.at(i).toLatin1());
}
// See http:https://docs.python.org/c-api/init.html
PySys_SetArgvEx(pythonArgc, pythonArgv, /*updatepath=*/false);
// Set 'sys.executable' so that Slicer can be used as a "regular" python interpreter
this->corePythonManager()->executeString(
QString("import sys; sys.executable = '%1'; del sys").arg(this->applicationFilePath()));
// Clean memory
for(int i = 0; i < pythonArgc; ++i){ delete[] pythonArgv[i];}
delete[] pythonArgv;
// Attempt to load Slicer RC file only if 'display...AndExit' options are not True
if (!(options->displayMessageAndExit() ||
options->ignoreSlicerRC()))
{
this->corePythonManager()->executeString("loadSlicerRCFile()");
}
if (this->testAttribute(AA_EnableTesting))
{
options->setRunPythonAndExit(true);
}
// Execute python script
if(!pythonScript.isEmpty())
{
if (QFile::exists(pythonScript))
{
qApp->processEvents();
this->corePythonManager()->executeFile(pythonScript);
}
else
{
qWarning() << "Specified python script doesn't exist:" << pythonScript;
}
}
QString pythonCode = options->pythonCode();
if(!pythonCode.isEmpty())
{
qApp->processEvents();
this->corePythonManager()->executeString(pythonCode);
}
if (options->runPythonAndExit())
{
qSlicerCoreApplication::exit(
this->corePythonManager()->pythonErrorOccured() ? EXIT_FAILURE : EXIT_SUCCESS);
}
}
#endif
}
//-----------------------------------------------------------------------------
QSettings* qSlicerCoreApplication::defaultSettings()const
{
Q_D(const qSlicerCoreApplication);
if (!QFile(this->slicerDefaultSettingsFilePath()).exists())
{
return 0;
}
qSlicerCoreApplication* mutable_self =
const_cast<qSlicerCoreApplication*>(this);
qSlicerCoreApplicationPrivate* mutable_d =
const_cast<qSlicerCoreApplicationPrivate*>(d);
// If required, instantiate Settings
if(!mutable_d->DefaultSettings)
{
mutable_d->DefaultSettings =
new QSettings(this->slicerDefaultSettingsFilePath(), QSettings::IniFormat, mutable_self);
}
return mutable_d->DefaultSettings;
}
//-----------------------------------------------------------------------------
QSettings* qSlicerCoreApplication::userSettings()const
{
Q_D(const qSlicerCoreApplication);
qSlicerCoreApplicationPrivate* mutable_d =