forked from root-project/root
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTApplication.cxx
More file actions
2141 lines (1910 loc) · 77.9 KB
/
Copy pathTApplication.cxx
File metadata and controls
2141 lines (1910 loc) · 77.9 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
// @(#)root/base:$Id$
// Author: Fons Rademakers 22/12/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TApplication
\ingroup Base
This class creates the ROOT Application Environment that interfaces
to the windowing system eventloop and eventhandlers.
This class must be instantiated exactly once in any given
application. Normally the specific application class inherits from
TApplication (see TRint).
*/
#include "RConfigure.h"
#include "TApplication.h"
#include "TException.h"
#include "TGuiFactory.h"
#include "TVirtualX.h"
#include "TROOT.h"
#include "TSystem.h"
#include "TString.h"
#include "TError.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TTimer.h"
#include "TInterpreter.h"
#include "TStyle.h"
#include "TVirtualPad.h"
#include "TEnv.h"
#include "TColor.h"
#include "TPluginManager.h"
#include "TClassTable.h"
#include "TBrowser.h"
#include "TUrl.h"
#include "TVirtualMutex.h"
#include "TClassEdit.h"
#include "TMethod.h"
#include "TDataMember.h"
#include "TApplicationCommandLineOptionsHelp.h"
#include "TPRegexp.h"
#include <cstdlib>
#include <iostream>
#include <fstream>
TApplication *gApplication = nullptr;
Bool_t TApplication::fgGraphNeeded = kFALSE;
Bool_t TApplication::fgGraphInit = kFALSE;
TList *TApplication::fgApplications = nullptr; // List of available applications
////////////////////////////////////////////////////////////////////////////////
class TIdleTimer : public TTimer {
public:
TIdleTimer(Long_t ms) : TTimer(ms, kTRUE) {}
Bool_t Notify() override;
};
////////////////////////////////////////////////////////////////////////////////
/// Notify handler.
Bool_t TIdleTimer::Notify()
{
gApplication->HandleIdleTimer();
Reset();
return kFALSE;
}
static void CallEndOfProcessCleanups()
{
// Insure that the files, canvases and sockets are closed.
// If we get here, the tear down has started. We have no way to know what
// has or has not yet been done. In particular on Ubuntu, this was called
// after the function static in TSystem.cxx has been destructed. So we
// set gROOT in its end-of-life mode which prevents executing code, like
// autoloading libraries (!) that is pointless ...
if (gROOT) {
gROOT->SetBit(kInvalidObject);
gROOT->EndOfProcessCleanups();
}
}
////////////////////////////////////////////////////////////////////////////////
/// Default ctor. Can be used by classes deriving from TApplication.
TApplication::TApplication() :
fArgc(0), fArgv(nullptr), fAppImp(nullptr), fIsRunning(kFALSE), fReturnFromRun(kFALSE),
fNoLog(kFALSE), fNoLogo(kFALSE), fQuit(kFALSE),
fFiles(nullptr), fIdleTimer(nullptr), fSigHandler(nullptr), fExitOnException(kDontExit),
fAppRemote(nullptr)
{
ResetBit(kProcessRemotely);
}
////////////////////////////////////////////////////////////////////////////////
/// Create an application environment. The application environment
/// provides an interface to the graphics system and eventloop
/// (be it X, Windows, macOS or BeOS). After creating the application
/// object start the eventloop by calling its Run() method. The command
/// line options recognized by TApplication are described in the GetOptions()
/// method. The recognized options are removed from the argument array.
/// The original list of argument options can be retrieved via the Argc()
/// and Argv() methods. The "options" and "numOptions" arguments are not used,
/// except if you want to by-pass the argv processing by GetOptions()
/// in which case you should specify numOptions<0. All options will
/// still be available via the Argv() method for later use.
TApplication::TApplication(const char *appClassName, Int_t *argc, char **argv,
void * /*options*/, Int_t numOptions) :
fArgc(0), fArgv(nullptr), fAppImp(nullptr), fIsRunning(kFALSE), fReturnFromRun(kFALSE),
fNoLog(kFALSE), fNoLogo(kFALSE), fQuit(kFALSE),
fFiles(nullptr), fIdleTimer(nullptr), fSigHandler(nullptr), fExitOnException(kDontExit),
fAppRemote(nullptr)
{
R__LOCKGUARD(gInterpreterMutex);
// Create the list of applications the first time
if (!fgApplications)
fgApplications = new TList;
// Add the new TApplication early, so that the destructor of the
// default TApplication (if it is called in the block of code below)
// will not destroy the files, socket or TColor that have already been
// created.
fgApplications->Add(this);
if (gApplication && gApplication->TestBit(kDefaultApplication)) {
// allow default TApplication to be replaced by a "real" TApplication
delete gApplication;
gApplication = nullptr;
gROOT->SetBatch(kFALSE);
fgGraphInit = kFALSE;
}
if (gApplication) {
Error("TApplication", "only one instance of TApplication allowed");
fgApplications->Remove(this);
return;
}
if (!gROOT)
::Fatal("TApplication::TApplication", "ROOT system not initialized");
if (!gSystem)
::Fatal("TApplication::TApplication", "gSystem not initialized");
static Bool_t hasRegisterAtExit(kFALSE);
if (!hasRegisterAtExit) {
// If we are the first TApplication register the atexit)
atexit(CallEndOfProcessCleanups);
hasRegisterAtExit = kTRUE;
}
gROOT->SetName(appClassName);
// copy command line arguments, can be later accessed via Argc() and Argv()
if (argc && *argc > 0) {
fArgc = *argc;
fArgv = (char **)new char*[fArgc];
}
for (int i = 0; i < fArgc; i++)
fArgv[i] = StrDup(argv[i]);
if (numOptions >= 0)
GetOptions(argc, argv);
if (fArgv)
gSystem->SetProgname(fArgv[0]);
// Alternative to '-b' command line switch (i.e. for pyROOT)
if (gSystem->Getenv("ROOT_BATCH"))
MakeBatch();
// Tell TSystem the TApplication has been created
gSystem->NotifyApplicationCreated();
fAppImp = gGuiFactory->CreateApplicationImp(appClassName, argc, argv);
ResetBit(kProcessRemotely);
// Initialize the graphics environment
if (gClassTable->GetDict("TPad")) {
fgGraphNeeded = kTRUE;
InitializeGraphics(gROOT->IsWebDisplay());
}
// Save current interpreter context
gInterpreter->SaveContext();
gInterpreter->SaveGlobalsContext();
// to allow user to interact with TCanvas's under WIN32
gROOT->SetLineHasBeenProcessed();
//Needs to be done last
gApplication = this;
gROOT->SetApplication(this);
}
////////////////////////////////////////////////////////////////////////////////
/// TApplication dtor.
TApplication::~TApplication()
{
for (int i = 0; i < fArgc; i++)
if (fArgv[i]) delete [] fArgv[i];
delete [] fArgv;
if (fgApplications)
fgApplications->Remove(this);
// Reduce the risk of the files or sockets being closed after the
// end of 'main' (or more exactly before the library start being
// unloaded).
if (fgApplications == nullptr || fgApplications->FirstLink() == nullptr ) {
TROOT::ShutDown();
}
// Now that all the canvases and files have been closed we can
// delete the implementation.
SafeDelete(fAppImp);
}
////////////////////////////////////////////////////////////////////////////////
/// Static method. This method should be called from static library
/// initializers if the library needs the low level graphics system.
void TApplication::NeedGraphicsLibs()
{
fgGraphNeeded = kTRUE;
}
////////////////////////////////////////////////////////////////////////////////
/// Initialize the graphics environment.
/// If @param only_web is specified, only web-related part of graphics is loaded
void TApplication::InitializeGraphics(Bool_t only_web)
{
if (fgGraphInit || !fgGraphNeeded)
return;
if (!only_web) {
// Load the graphics related libraries
LoadGraphicsLibs();
// Try to load TrueType font renderer. Only try to load if not in batch
// mode and Root.UseTTFonts is true and Root.TTFontPath exists. Abort silently
// if libttf or libGX11TTF are not found in $ROOTSYS/lib or $ROOTSYS/ttf/lib.
const char *ttpath = gEnv->GetValue("Root.TTFontPath",
TROOT::GetTTFFontDir());
char *ttfont = gSystem->Which(ttpath, "arialbd.ttf", kReadPermission);
// Check for use of DFSG - fonts
if (!ttfont)
ttfont = gSystem->Which(ttpath, "FreeSansBold.ttf", kReadPermission);
#if !defined(R__WIN32)
if (!gROOT->IsBatch() && !strcmp(gVirtualX->GetName(), "X11") &&
ttfont && gEnv->GetValue("Root.UseTTFonts", 1)) {
if (gClassTable->GetDict("TGX11TTF")) {
// in principle we should not have linked anything against libGX11TTF
// but with ACLiC this can happen, initialize TGX11TTF by hand
// (normally this is done by the static library initializer)
ProcessLine("TGX11TTF::Activate();");
} else {
TPluginHandler *h;
if ((h = gROOT->GetPluginManager()->FindHandler("TVirtualX", "x11ttf")))
if (h->LoadPlugin() == -1)
Info("InitializeGraphics", "no TTF support");
}
}
#endif
delete [] ttfont;
}
if (!only_web || !fAppImp) {
// Create WM dependent application environment
if (fAppImp)
delete fAppImp;
fAppImp = gGuiFactory->CreateApplicationImp(gROOT->GetName(), &fArgc, fArgv);
if (!fAppImp) {
MakeBatch();
fAppImp = gGuiFactory->CreateApplicationImp(gROOT->GetName(), &fArgc, fArgv);
}
}
// Create the canvas colors early so they are allocated before
// any color table expensive bitmaps get allocated in GUI routines (like
// creation of XPM bitmaps).
TColor::InitializeColors();
// Hook for further initializing the WM dependent application environment
Init();
// Set default screen factor (if not disabled in rc file)
if (!only_web && gEnv->GetValue("Canvas.UseScreenFactor", 1)) {
Int_t x, y;
UInt_t w, h;
if (gVirtualX) {
gVirtualX->GetGeometry(-1, x, y, w, h);
if (h > 0)
gStyle->SetScreenFactor(0.001 * h);
}
}
}
////////////////////////////////////////////////////////////////////////////////
/// Clear list containing macro files passed as program arguments.
/// This method is called from TRint::Run() to ensure that the macro
/// files are only executed the first time Run() is called.
void TApplication::ClearInputFiles()
{
if (fFiles) {
fFiles->Delete();
SafeDelete(fFiles);
}
}
////////////////////////////////////////////////////////////////////////////////
/// Return specified argument.
char *TApplication::Argv(Int_t index) const
{
if (fArgv) {
if (index >= fArgc) {
Error("Argv", "index (%d) >= number of arguments (%d)", index, fArgc);
return nullptr;
}
return fArgv[index];
}
return nullptr;
}
////////////////////////////////////////////////////////////////////////////////
/// Get and handle command line options. Arguments handled are removed
/// from the argument array. See CommandLineOptionsHelp.h for options.
void TApplication::GetOptions(Int_t *argc, char **argv)
{
static char null[1] = { "" };
fNoLog = kFALSE;
fQuit = kFALSE;
fFiles = nullptr;
if (!argc)
return;
int i, j;
TString pwd;
for (i = 1; i < *argc; i++) {
if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
!strncmp(argv[i], "--help", 6)) {
fprintf(stderr, kCommandLineOptionsHelp);
Terminate(0);
} else if (!strncmp(argv[i], "--version", 9)) {
fprintf(stderr, "ROOT Version: %s\n", gROOT->GetVersion());
fprintf(stderr, "Built for %s on %s\n",
gSystem->GetBuildArch(),
gROOT->GetGitDate());
fprintf(stderr, "From %s@%s\n",
gROOT->GetGitBranch(),
gROOT->GetGitCommit());
Terminate(0);
} else if (!strcmp(argv[i], "-config")) {
fprintf(stderr, "ROOT ./configure options:\n%s\n", gROOT->GetConfigOptions());
Terminate(0);
} else if (!strcmp(argv[i], "-a")) {
fprintf(stderr, "ROOT splash screen is not visible with root.exe, use root instead.\n");
Terminate(0);
} else if (!strcmp(argv[i], "-b")) {
MakeBatch();
argv[i] = null;
} else if (!strcmp(argv[i], "-n")) {
fNoLog = kTRUE;
argv[i] = null;
} else if (!strcmp(argv[i], "-t")) {
ROOT::EnableImplicitMT();
// EnableImplicitMT() only enables thread safety if IMT was configured;
// enable thread safety even with IMT off:
ROOT::EnableThreadSafety();
argv[i] = null;
} else if (!strcmp(argv[i], "-q")) {
fQuit = kTRUE;
argv[i] = null;
} else if (!strcmp(argv[i], "-l")) {
// used by front-end program to not display splash screen
fNoLogo = kTRUE;
argv[i] = null;
} else if (!strcmp(argv[i], "-x")) {
fExitOnException = kExit;
argv[i] = null;
} else if (!strcmp(argv[i], "-splash")) {
// used when started by front-end program to signal that
// splash screen can be popped down (TRint::PrintLogo())
argv[i] = null;
} else if (strncmp(argv[i], "--web", 5) == 0) {
// the web mode is requested
const char *opt = argv[i] + 5;
argv[i] = null;
gROOT->SetWebDisplay((*opt == '=') ? opt + 1 : "");
} else if (!strcmp(argv[i], "-e")) {
argv[i] = null;
++i;
if ( i < *argc ) {
if (!fFiles) fFiles = new TObjArray;
TObjString *expr = new TObjString(argv[i]);
expr->SetBit(kExpression);
fFiles->Add(expr);
argv[i] = null;
} else {
Warning("GetOptions", "-e must be followed by an expression.");
}
} else if (!strcmp(argv[i], "--")) {
TObjString* macro = nullptr;
bool warnShown = false;
if (fFiles) {
for (auto f: *fFiles) {
TObjString *file = dynamic_cast<TObjString *>(f);
if (!file) {
if (!dynamic_cast<TNamed*>(f)) {
Error("GetOptions()", "Inconsistent file entry (not a TObjString)!");
if (f)
f->Dump();
} // else we did not find the file.
continue;
}
if (file->TestBit(kExpression))
continue;
if (file->String().EndsWith(".root"))
continue;
if (file->String().Contains('('))
continue;
if (macro && !warnShown && (warnShown = true))
Warning("GetOptions", "-- is used with several macros. "
"The arguments will be passed to the last one.");
macro = file;
}
}
if (macro) {
argv[i] = null;
++i;
TString& str = macro->String();
str += '(';
for (; i < *argc; i++) {
str += argv[i];
str += ',';
argv[i] = null;
}
str.EndsWith(",") ? str[str.Length() - 1] = ')' : str += ')';
} else {
Warning("GetOptions", "no macro to pass arguments to was provided. "
"Everything after the -- will be ignored.");
for (; i < *argc; i++)
argv[i] = null;
}
} else if (argv[i][0] != '-' && argv[i][0] != '+') {
Long64_t size;
Long_t id, flags, modtime;
char *arg = strchr(argv[i], '(');
if (arg) *arg = '\0';
TString expandedDir(argv[i]);
if (gSystem->ExpandPathName(expandedDir)) {
// ROOT-9959: we do not continue if we could not expand the path
continue;
}
TUrl udir(expandedDir, kTRUE);
// remove options and anchor to check the path
TString sfx = udir.GetFileAndOptions();
TString fln = udir.GetFile();
sfx.Replace(sfx.Index(fln), fln.Length(), "");
TString path = udir.GetFile();
if (strcmp(udir.GetProtocol(), "file")) {
path = udir.GetUrl();
path.Replace(path.Index(sfx), sfx.Length(), "");
}
// 'path' is the full URL without suffices (options and/or anchor)
if (arg) *arg = '(';
if (!arg && !gSystem->GetPathInfo(path.Data(), &id, &size, &flags, &modtime)) {
if ((flags & 2)) {
// if directory set it in fWorkDir
if (pwd == "") {
pwd = gSystem->WorkingDirectory();
fWorkDir = expandedDir;
gSystem->ChangeDirectory(expandedDir);
argv[i] = null;
} else if (!strcmp(gROOT->GetName(), "Rint")) {
Warning("GetOptions", "only one directory argument can be specified (%s)", expandedDir.Data());
}
} else if (size > 0) {
// if file add to list of files to be processed
if (!fFiles) fFiles = new TObjArray;
fFiles->Add(new TObjString(path.Data()));
argv[i] = null;
} else {
Warning("GetOptions", "file %s has size 0, skipping", expandedDir.Data());
}
} else {
if (TString(udir.GetFile()).EndsWith(".root")) {
if (!strcmp(udir.GetProtocol(), "file")) {
// file ending on .root but does not exist, likely a typo
// warn user if plain root...
if (!strcmp(gROOT->GetName(), "Rint"))
Warning("GetOptions", "file %s not found", expandedDir.Data());
} else {
// remote file, give it the benefit of the doubt and add it to list of files
if (!fFiles) fFiles = new TObjArray;
fFiles->Add(new TObjString(argv[i]));
argv[i] = null;
}
} else {
TString mode,fargs,io;
TString fname = gSystem->SplitAclicMode(expandedDir,mode,fargs,io);
char *mac;
if (!fFiles) fFiles = new TObjArray;
if ((mac = gSystem->Which(TROOT::GetMacroPath(), fname,
kReadPermission))) {
// if file add to list of files to be processed
fFiles->Add(new TObjString(argv[i]));
argv[i] = null;
delete [] mac;
} else {
// if file add an invalid entry to list of files to be processed
fFiles->Add(new TNamed("NOT FOUND!", argv[i]));
// only warn if we're plain root,
// other progs might have their own params
if (!strcmp(gROOT->GetName(), "Rint")) {
Error("GetOptions", "macro %s not found", fname.Data());
// Return 2 as the Python interpreter does in case the macro
// is not found.
Terminate(2);
}
}
}
}
}
// ignore unknown options
}
// go back to startup directory
if (pwd != "")
gSystem->ChangeDirectory(pwd);
// remove handled arguments from argument array
j = 0;
for (i = 0; i < *argc; i++) {
if (strcmp(argv[i], "")) {
argv[j] = argv[i];
j++;
}
}
*argc = j;
}
////////////////////////////////////////////////////////////////////////////////
/// Handle idle timeout. When this timer expires the registered idle command
/// will be executed by this routine and a signal will be emitted.
void TApplication::HandleIdleTimer()
{
if (!fIdleCommand.IsNull())
ProcessLine(GetIdleCommand());
Emit("HandleIdleTimer()");
}
////////////////////////////////////////////////////////////////////////////////
/// Handle exceptions (kSigBus, kSigSegmentationViolation,
/// kSigIllegalInstruction and kSigFloatingException) trapped in TSystem.
/// Specific TApplication implementations may want something different here.
void TApplication::HandleException(Int_t sig)
{
if (TROOT::Initialized()) {
if (gException) {
gInterpreter->RewindDictionary();
gInterpreter->ClearFileBusy();
}
if (fExitOnException == kExit)
gSystem->Exit(128 + sig);
else if (fExitOnException == kAbort)
gSystem->Abort();
else
Throw(sig);
}
gSystem->Exit(128 + sig);
}
////////////////////////////////////////////////////////////////////////////////
/// Set the exit on exception option. Setting this option determines what
/// happens in HandleException() in case an exception (kSigBus,
/// kSigSegmentationViolation, kSigIllegalInstruction or kSigFloatingException)
/// is trapped. Choices are: kDontExit (default), kExit or kAbort.
/// Returns the previous value.
TApplication::EExitOnException TApplication::ExitOnException(TApplication::EExitOnException opt)
{
EExitOnException old = fExitOnException;
fExitOnException = opt;
return old;
}
/////////////////////////////////////////////////////////////////////////////////
/// The function generates and executes a command that loads the Doxygen URL in
/// a browser. It works for Mac, Windows and Linux. In the case of Linux, the
/// function also checks if the DISPLAY is set. If it isn't, a warning message
/// and the URL will be displayed on the terminal. In all OS, if the system command
/// fails, the URL will be also displayed on the terminal.
///
/// \param[in] url web page to be displayed in a browser
void TApplication::OpenInBrowser(const TString &url)
{
// We check what operating system the user has.
#ifdef R__MACOSX
// Command for opening a browser on Mac.
TString cMac("open ");
// We generate the full command and execute it.
cMac.Append(url);
auto res = gSystem->Exec(cMac);
#elif defined(R__WIN32)
// Command for opening a browser on Windows.
TString cWindows("start \"\" ");
cWindows.Append(url);
auto res = gSystem->Exec(cWindows);
#else
// For Linux we check first if the DISPLAY is set.
if (!gSystem->Getenv("DISPLAY")) {
// The user will have a warning and the URL in the terminal.
Warning("OpenInBrowser", "The $DISPLAY is not set! Please manually open (e.g. Ctrl-click) %s\n", url.Data());
return;
}
// Command for opening a browser in Linux. Since the DISPLAY is set, it will open the browser.
TString cLinux("xdg-open ");
cLinux.Append(url);
auto res = gSystem->Exec(cLinux);
#endif
if (res != EXIT_SUCCESS) {
Warning("OpenInBrowser", "Could not automatically open web browser (e.g. due to missing X11)! Please manually open (e.g. Ctrl-click) %s\n", url.Data());
return;
}
Info("OpenInBrowser", "A new tab should have opened in your browser.");
}
namespace {
enum EUrl { kURLforClass, kURLforNameSpace, kURLforStruct };
////////////////////////////////////////////////////////////////////////////////
/// The function generates a URL address for class or namespace (scopeName).
/// This is the URL to the online reference guide, generated by Doxygen.
/// With the enumeration "EUrl" we pick which case we need - the one for
/// class (kURLforClass) or the one for namespace (kURLforNameSpace).
///
/// \param[in] scopeName the name of the class or the namespace
/// \param[in] scopeType the enumerator for class or namespace
static TString UrlGenerator(TString scopeName, EUrl scopeType)
{
// We start the URL with a static part, the same for all scopes and members.
TString url = "https://root.cern/doc/";
// Then we check the ROOT version used.
TPRegexp re4(R"(.*/(v\d)-(\d\d)-00-patches)");
const char *branchName = gROOT->GetGitBranch();
TObjArray *objarr = re4.MatchS(branchName);
TString version;
// We extract the correct version name for the URL.
if (objarr && objarr->GetEntries() == 3) {
// We have a valid version of ROOT and we will extract the correct name for the URL.
version = ((TObjString *)objarr->At(1))->GetString() + ((TObjString *)objarr->At(2))->GetString();
} else {
// If it's not a supported version, we will go to "master" branch.
version = "master";
}
delete objarr;
url.Append(version);
url.Append("/");
// We will replace all "::" with "_1_1" and all "_" with "__" in the
// classes definitions, due to Doxygen syntax requirements.
scopeName.ReplaceAll("_", "__");
scopeName.ReplaceAll("::", "_1_1");
// We build the URL for the correct scope type and name.
if (scopeType == kURLforClass) {
url.Append("class");
} else if (scopeType == kURLforStruct) {
url.Append("struct");
} else {
url.Append("namespace");
}
url.Append(scopeName);
url.Append(".html");
return url;
}
} // namespace
namespace {
////////////////////////////////////////////////////////////////////////////////
/// The function returns a TString with the arguments of a method from the
/// scope (scopeName), but modified with respect to Doxygen syntax - spacing
/// around special symbols and adding the missing scopes ("std::").
/// "FormatMethodArgsForDoxygen" works for functions defined inside namespaces
/// as well. We avoid looking up twice for the TFunction by passing "func".
///
/// \param[in] scopeName the name of the class/namespace/struct
/// \param[in] func pointer to the method
static TString FormatMethodArgsForDoxygen(const TString &scopeName, TFunction *func)
{
// With "GetSignature" we get the arguments of the method and put them in a TString.
TString methodArguments = func->GetSignature();
// "methodArguments" is modified with respect of Doxygen requirements.
methodArguments.ReplaceAll(" = ", "=");
methodArguments.ReplaceAll("* ", " *");
methodArguments.ReplaceAll("*=", " *=");
methodArguments.ReplaceAll("*)", " *)");
methodArguments.ReplaceAll("*,", " *,");
methodArguments.ReplaceAll("*& ", " *&");
methodArguments.ReplaceAll("& ", " &");
// TODO: prepend "std::" to all stdlib classes!
methodArguments.ReplaceAll("ostream", "std::ostream");
methodArguments.ReplaceAll("istream", "std::istream");
methodArguments.ReplaceAll("map", "std::map");
methodArguments.ReplaceAll("vector", "std::vector");
// We need to replace the "currentClass::foo" with "foo" in the arguments.
// TODO: protect the global functions.
TString scopeNameRE("\\b");
scopeNameRE.Append(scopeName);
scopeNameRE.Append("::\\b");
TPRegexp argFix(scopeNameRE);
argFix.Substitute(methodArguments, "");
return methodArguments;
}
} // namespace
namespace {
////////////////////////////////////////////////////////////////////////////////
/// The function returns a TString with the text as an encoded url so that it
/// can be passed to the function OpenInBrowser
///
/// \param[in] text the input text
/// \return the text appropriately escaped
static TString FormatHttpUrl(TString text)
{
text.ReplaceAll("\n","%0A");
text.ReplaceAll("#","%23");
text.ReplaceAll(";","%3B");
text.ReplaceAll("\"","%22");
text.ReplaceAll("`","%60");
text.ReplaceAll("+","%2B");
text.ReplaceAll("/","%2F");
return text;
}
} // namespace
namespace {
////////////////////////////////////////////////////////////////////////////////
/// The function checks if a member function of a scope is defined as inline.
/// If so, it also checks if it is virtual. Then the return type of "func" is
/// modified for the need of Doxygen and with respect to the function
/// definition. We pass pointer to the method (func) to not re-do the
/// TFunction lookup.
///
/// \param[in] scopeName the name of the class/namespace/struct
/// \param[in] func pointer to the method
static TString FormatReturnTypeForDoxygen(const TString &scopeName, TFunction *func)
{
// We put the return type of "func" in a TString "returnType".
TString returnType = func->GetReturnTypeName();
// If the return type is a type nested in the current class, it will appear scoped (Class::Enumeration).
// Below we make sure to remove the current class, because the syntax of Doxygen requires it.
TString scopeNameRE("\\b");
scopeNameRE.Append(scopeName);
scopeNameRE.Append("::\\b");
TPRegexp returnFix(scopeNameRE);
returnFix.Substitute(returnType, "");
// We check is if the method is defined as inline.
if (func->ExtraProperty() & kIsInlined) {
// We check if the function is defined as virtual.
if (func->Property() & kIsVirtual) {
// If the function is virtual, we append "virtual" before the return type.
returnType.Prepend("virtual ");
}
returnType.ReplaceAll(" *", "*");
} else {
// If the function is not inline we only change the spacing in "returnType"
returnType.ReplaceAll("*", " *");
}
// In any case (with no respect to virtual/inline check) we need to change
// the return type as following.
// TODO: prepend "std::" to all stdlib classes!
returnType.ReplaceAll("istream", "std::istream");
returnType.ReplaceAll("ostream", "std::ostream");
returnType.ReplaceAll("map", "std::map");
returnType.ReplaceAll("vector", "std::vector");
returnType.ReplaceAll("&", " &");
return returnType;
}
} // namespace
namespace {
////////////////////////////////////////////////////////////////////////////////
/// The function generates a URL for "dataMemberName" defined in "scopeName".
/// It returns a TString with the URL used in the online reference guide,
/// generated with Doxygen. For data members the URL consist of 2 parts -
/// URL for "scopeName" and a part for "dataMemberName".
/// For enumerator, the URL could be separated into 3 parts - URL for
/// "scopeName", part for the enumeration and a part for the enumerator.
///
/// \param[in] scopeName the name of the class/namespace/struct
/// \param[in] dataMemberName the name of the data member/enumerator
/// \param[in] dataMember pointer to the data member/enumerator
/// \param[in] scopeType enumerator to the scope type
static TString
GetUrlForDataMember(const TString &scopeName, const TString &dataMemberName, TDataMember *dataMember, EUrl scopeType)
{
// We first check if the data member is not enumerator.
if (!dataMember->IsEnum()) {
// If we work with data members, we have to append a hashed with MD5 text, consisting of:
// "Type ClassName::DataMemberNameDataMemberName(arguments)".
// We first get the type of the data member.
TString md5DataMember(dataMember->GetFullTypeName());
md5DataMember.Append(" ");
// We append the scopeName and "::".
md5DataMember.Append(scopeName);
md5DataMember.Append("::");
// We append the dataMemberName twice.
md5DataMember.Append(dataMemberName);
md5DataMember.Append(dataMemberName);
// We call UrlGenerator for the scopeName.
TString urlForDataMember = UrlGenerator(scopeName, scopeType);
// Then we append "#a" and the hashed text.
urlForDataMember.Append("#a");
urlForDataMember.Append(md5DataMember.MD5());
return urlForDataMember;
}
// If the data member is enumerator, then we first have to check if the enumeration is anonymous.
// Doxygen requires different syntax for anonymous enumeration ("scopeName::@1@1").
// We create a TString with the name of the scope and the enumeration from which the enumerator is.
TString scopeEnumeration = dataMember->GetTrueTypeName();
TString md5EnumClass;
if (scopeEnumeration.Contains("(unnamed)")) {
// FIXME: need to investigate the numbering scheme.
md5EnumClass.Append(scopeName);
md5EnumClass.Append("::@1@1");
} else {
// If the enumeration is not anonymous we put "scopeName::Enumeration" in a TString,
// which will be hashed with MD5 later.
md5EnumClass.Append(scopeEnumeration);
// We extract the part after "::" (this is the enumerator name).
TString enumOnlyName = TClassEdit::GetUnqualifiedName(scopeEnumeration);
// The syntax is "Class::EnumeratorEnumerator
md5EnumClass.Append(enumOnlyName);
}
// The next part of the URL is hashed "@ scopeName::EnumeratorEnumerator".
TString md5Enumerator("@ ");
md5Enumerator.Append(scopeName);
md5Enumerator.Append("::");
md5Enumerator.Append(dataMemberName);
md5Enumerator.Append(dataMemberName);
// We make the URL for the "scopeName".
TString url = UrlGenerator(scopeName, scopeType);
// Then we have to append the hashed text for the enumerator.
url.Append("#a");
url.Append(md5EnumClass.MD5());
// We append "a" and then the next hashed text.
url.Append("a");
url.Append(md5Enumerator.MD5());
return url;
}
} // namespace
namespace {
////////////////////////////////////////////////////////////////////////////////
/// The function generates URL for enumeration. The hashed text consist of:
/// "Class::EnumerationEnumeration".
///
/// \param[in] scopeName the name of the class/namespace/struct
/// \param[in] enumeration the name of the enumeration
/// \param[in] scopeType enumerator for class/namespace/struct
static TString GetUrlForEnumeration(TString scopeName, const TString &enumeration, EUrl scopeType)
{
// The URL consists of URL for the "scopeName", "#a" and hashed as MD5 text.
// The text is "Class::EnumerationEnumeration.
TString md5Enumeration(scopeName);
md5Enumeration.Append("::");
md5Enumeration.Append(enumeration);
md5Enumeration.Append(enumeration);
// We make the URL for the scope "scopeName".
TString url(UrlGenerator(scopeName, scopeType));
// Then we have to append "#a" and the hashed text.
url.Append("#a");
url.Append(md5Enumeration.MD5());
return url;
}
} // namespace
namespace {
enum EMethodKind { kURLforMethod, kURLforStructor };
////////////////////////////////////////////////////////////////////////////////
/// The function generates URL for any member function (including Constructor/
/// Destructor) of "scopeName". Doxygen first generates the URL for the scope.
/// We do that with the help of "UrlGenerator". Then we append "#a" and a
/// hashed with MD5 text. It consists of:
/// "ReturnType ScopeName::MethodNameMethodName(Method arguments)".
/// For constructor/destructor of a class, the return type is not appended.
///
/// \param[in] scopeName the name of the class/namespace/struct
/// \param[in] methodName the name of the method from the scope
/// \param[in] func pointer to the method
/// \param[in] methodType enumerator for method or constructor
/// \param[in] scopeType enumerator for class/namespace/struct
static TString GetUrlForMethod(const TString &scopeName, const TString &methodName, TFunction *func,
EMethodKind methodType, EUrl scopeType)
{
TString md5Text;
if (methodType == kURLforMethod) {
// In the case of method, we append the return type too.
// "FormatReturnTypeForDoxygen" modifies the return type with respect to Doxygen's requirement.
md5Text.Append((FormatReturnTypeForDoxygen(scopeName, func)));
if (scopeType == kURLforNameSpace) {
// We need to append "constexpr" if we work with constexpr functions in namespaces.
if (func->Property() & kIsConstexpr) {
md5Text.Prepend("constexpr ");
}
}
md5Text.Append(" ");
}
// We append ScopeName::MethodNameMethodName.
md5Text.Append(scopeName);
md5Text.Append("::");
md5Text.Append(methodName);
md5Text.Append(methodName);
// We use "FormatMethodArgsForDoxygen" to modify the arguments of Method with respect of Doxygen.
md5Text.Append(FormatMethodArgsForDoxygen(scopeName, func));
// We generate the URL for the class/namespace/struct.
TString url = UrlGenerator(scopeName, scopeType);
url.Append("#a");
// We append the hashed text.
url.Append(md5Text.MD5());
return url;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
/// It gets the ROOT installation setup as TString
///
/// \return a string with several lines
///
TString TApplication::GetSetup()
{
std::vector<TString> lines;
lines.emplace_back("```");
lines.emplace_back(TString::Format("ROOT v%s",
gROOT->GetVersion()));
lines.emplace_back(TString::Format("Built for %s on %s", gSystem->GetBuildArch(), gROOT->GetGitDate()));
if (!strcmp(gROOT->GetGitBranch(), gROOT->GetGitCommit())) {
static const char *months[] = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
Int_t idatqq = gROOT->GetVersionDate();
Int_t iday = idatqq%100;
Int_t imonth = (idatqq/100)%100;
Int_t iyear = (idatqq/10000);
lines.emplace_back(TString::Format("From tag %s, %d %s %4d",
gROOT->GetGitBranch(),
iday,months[imonth-1],iyear));
} else {
// If branch and commit are identical - e.g. "v5-34-18" - then we have
// a release build. Else specify the git hash this build was made from.
lines.emplace_back(TString::Format("From %s@%s",
gROOT->GetGitBranch(),
gROOT->GetGitCommit()));
}
lines.emplace_back(TString::Format("With %s std%ld",
gSystem->GetBuildCompilerVersionStr(), __cplusplus));
lines.emplace_back("Binary directory: "+ gROOT->GetBinDir());