Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TRint.cxx
Go to the documentation of this file.
1// @(#)root/rint:$Id$
2// Author: Rene Brun 17/02/95
3
4/*************************************************************************
5 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12//////////////////////////////////////////////////////////////////////////
13// //
14// Rint //
15// //
16// Rint is the ROOT Interactive Interface. It allows interactive access //
17// to the ROOT system via the Cling C/C++ interpreter. //
18// //
19//////////////////////////////////////////////////////////////////////////
20
21#include "TROOT.h"
22#include "TClass.h"
23#include "TClassEdit.h"
24#include "TVirtualX.h"
25#include "TObjectTable.h"
26#include "TClassTable.h"
27#include "TStopwatch.h"
28#include "TBenchmark.h"
29#include "TRint.h"
30#include "TSystem.h"
31#include "TEnv.h"
32#include "TSysEvtHandler.h"
33#include "TSystemDirectory.h"
34#include "TError.h"
35#include "TException.h"
36#include "TInterpreter.h"
37#include "TObjString.h"
38#include "TObjArray.h"
39#include "TStorage.h" // ROOT::Internal::gMmallocDesc
40#include "ThreadLocalStorage.h"
41#include "TTabCom.h"
42#include <cstdlib>
43#include <algorithm>
44#include <iostream>
45#include "Getline.h"
46#include "strlcpy.h"
47#include "snprintf.h"
48
49#ifdef R__UNIX
50#include <signal.h>
51#include <unistd.h>
52#endif
53
54////////////////////////////////////////////////////////////////////////////////
55
57{
59 return 0;
60}
61
62////////////////////////////////////////////////////////////////////////////////
63
65{
66 if (!gSystem) return 0;
67 gSystem->Beep();
68 return 1;
69}
70
71////////////////////////////////////////////////////////////////////////////////
72/// Restore terminal to non-raw mode.
73
74static void ResetTermAtExit()
75{
76 Getlinem(kCleanUp, nullptr);
77}
78
79
80//----- Interrupt signal handler -----------------------------------------------
81////////////////////////////////////////////////////////////////////////////////
82
84public:
86 Bool_t Notify() override;
87};
88
89////////////////////////////////////////////////////////////////////////////////
90/// TRint interrupt handler.
91
93{
94 if (fDelay) {
95 fDelay++;
96 return kTRUE;
97 }
98
99 // make sure we use the sbrk heap (in case of mapped files)
101
102 if (TROOT::Initialized() && gROOT->IsLineProcessing()) {
103 Break("TInterruptHandler::Notify", "keyboard interrupt");
104 Getlinem(kInit, "Root > ");
105 gCling->Reset();
106#ifndef WIN32
107 if (gException)
108 Throw(GetSignal());
109#endif
110 } else {
111 // Reset input.
112 Getlinem(kClear, ((TRint*)gApplication)->GetPrompt());
113 }
114
115 return kTRUE;
116}
117
118//----- Terminal Input file handler --------------------------------------------
119////////////////////////////////////////////////////////////////////////////////
120
122public:
124 Bool_t Notify() override;
125 Bool_t ReadNotify() override { return Notify(); }
126};
127
128////////////////////////////////////////////////////////////////////////////////
129/// Notify implementation. Call the application interupt handler.
130
132{
134}
135
136
138
139
140namespace {
141static int SetExtraClingArgsBeforeTAppCtor(Int_t *argc, char **argv)
142{
143 bool forcePtrCheck = false;
144 if (argc != nullptr) {
145 for (int iarg = 1; iarg < *argc; ++iarg) {
146 if (!strcmp(argv[iarg], "--ptrcheck")) {
147 // Hide this, by moving all other args one down...
148 for (int jarg = iarg + 1; jarg < *argc; ++jarg)
149 argv[jarg - 1] = argv[jarg];
150 // ... and updating argc accordingly.
151 --*argc;
152 forcePtrCheck = true;
153 break;
154 }
155 }
156 }
157#ifdef R__UNIX
158 if (forcePtrCheck || isatty(0) || isatty(1))
159#endif
160 TROOT::AddExtraInterpreterArgs({"--ptrcheck"});
161 return 0;
162}
163}
164
165////////////////////////////////////////////////////////////////////////////////
166/// Create an application environment. The TRint environment provides an
167/// interface to the WM manager functionality and eventloop via inheritance
168/// of TApplication and in addition provides interactive access to
169/// the Cling C++ interpreter via the command line.
170
171TRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options, Int_t numOptions, Bool_t noLogo,
172 Bool_t exitOnUnknownArgs)
173 : TApplication(appClassName, argc, argv, options, numOptions + SetExtraClingArgsBeforeTAppCtor(argc, argv)),
174 fCaughtSignal(-1)
175{
176
177 if (exitOnUnknownArgs && argc != nullptr && *argc > 1) {
178 // Early exit if there are remaining unrecognized options
179 // This branch supposes that TRint is created as a result of using the `root` command
180 for (auto n = 1; n < *argc; n++) {
181 std::cerr << "root: unrecognized option '" << argv[n] << "'\n";
182 }
183 std::cerr << "Try 'root --help' for more information.\n";
185 }
186
187 fNcmd = 0;
188 fDefaultPrompt = "root [%d] ";
190
191 gBenchmark = new TBenchmark();
192
193 if (!noLogo && !NoLogoOpt()) {
194 Bool_t lite = (Bool_t) gEnv->GetValue("Rint.WelcomeLite", 0);
195 PrintLogo(lite);
196 }
197
198 // Explicitly load libMathCore it cannot be auto-loaded it when using one
199 // of its freestanding functions. Once functions can trigger autoloading we
200 // can get rid of this.
201 if (!gClassTable->GetDict("TRandom"))
202 gSystem->Load("libMathCore");
203
204 if (!gInterpreter->HasPCMForLibrary("std")) {
205 // Load some frequently used includes
206 Int_t includes = gEnv->GetValue("Rint.Includes", 1);
207 // When the interactive ROOT starts, it can automatically load some frequently
208 // used includes. However, this introduces several overheads
209 // -The initialisation takes more time
210 // -Memory overhead when including <vector>
211 // In $ROOTSYS/etc/system.rootrc, you can set the variable Rint.Includes to 0
212 // to disable the loading of these includes at startup.
213 // You can set the variable to 1 (default) to load only <iostream>, <string> and <DllImport.h>
214 // You can set it to 2 to load in addition <vector> and <utility>
215 // We strongly recommend setting the variable to 2 if your scripts include <vector>
216 // and you execute your scripts multiple times.
217 if (includes > 0) {
218 TString code;
219 code = "#include <iostream>\n"
220 "#include <string>\n" // for std::string std::iostream.
221 "#include <DllImport.h>\n";// Defined R__EXTERN
222 if (includes > 1) {
223 code += "#include <vector>\n"
224 "#include <utility>";
225 }
226 ProcessLine(code, kTRUE);
227 }
228 }
229
230 // Load user functions
231 const char *logon;
232 logon = gEnv->GetValue("Rint.Load", (char*)nullptr);
233 if (logon) {
234 char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
235 if (mac)
236 ProcessLine(Form(".L %s",logon), kTRUE);
237 delete [] mac;
238 }
239
240 // Execute logon macro
241 ExecLogon();
242
243 // Save current interpreter context
246
247 // Install interrupt and terminal input handlers
249 ih->Add();
251
252 // Handle stdin events
255
256 // Goto into raw terminal input mode
257 char defhist[kMAXPATHLEN];
258 snprintf(defhist, sizeof(defhist), "%s/.root_hist", gSystem->HomeDirectory());
259 logon = gEnv->GetValue("Rint.History", defhist);
260 // In the code we had HistorySize and HistorySave, in the rootrc and doc
261 // we have HistSize and HistSave. Keep the doc as it is and check
262 // now also for HistSize and HistSave in case the user did not use
263 // the History versions
264 int hist_size = gEnv->GetValue("Rint.HistorySize", 500);
265 if (hist_size == 500)
266 hist_size = gEnv->GetValue("Rint.HistSize", 500);
267 int hist_save = gEnv->GetValue("Rint.HistorySave", 400);
268 if (hist_save == 400)
269 hist_save = gEnv->GetValue("Rint.HistSave", 400);
270 const char *envHist = gSystem->Getenv("ROOT_HIST");
271 if (envHist) {
272 hist_size = atoi(envHist);
273 envHist = strchr(envHist, ':');
274 if (envHist)
275 hist_save = atoi(envHist+1);
276 }
277 Gl_histsize(hist_size, hist_save);
278 Gl_histinit((char *)logon);
279
280 // black on white or white on black?
281 static const char* defaultColorsBW[] = {
282 "bold blue", "magenta", "bold green", "bold red underlined", "default"
283 };
284 static const char* defaultColorsWB[] = {
285 "yellow", "magenta", "bold green", "bold red underlined", "default"
286 };
287
288 const char** defaultColors = defaultColorsBW;
289 TString revColor = gEnv->GetValue("Rint.ReverseColor", "no");
290 if (revColor.Contains("yes", TString::kIgnoreCase)) {
291 defaultColors = defaultColorsWB;
292 }
293 TString colorType = gEnv->GetValue("Rint.TypeColor", defaultColors[0]);
294 TString colorTabCom = gEnv->GetValue("Rint.TabComColor", defaultColors[1]);
295 TString colorBracket = gEnv->GetValue("Rint.BracketColor", defaultColors[2]);
296 TString colorBadBracket = gEnv->GetValue("Rint.BadBracketColor", defaultColors[3]);
297 TString colorPrompt = gEnv->GetValue("Rint.PromptColor", defaultColors[4]);
298 Gl_setColors(colorType, colorTabCom, colorBracket, colorBadBracket, colorPrompt);
299
300 Gl_windowchanged();
301
302 atexit(ResetTermAtExit);
303
304 // Setup for tab completion
305 gTabCom = new TTabCom;
306 Gl_in_key = &Key_Pressed;
307 Gl_beep_hook = &BeepHook;
308
309 // tell Cling to use our getline
310 gCling->SetGetline(Getline, Gl_histadd);
311}
312
313////////////////////////////////////////////////////////////////////////////////
314/// Destructor.
315
317{
318 delete gTabCom;
319 gTabCom = nullptr;
320 Gl_in_key = nullptr;
321 Gl_beep_hook = nullptr;
323 delete fInputHandler;
324 // We can't know where the signal handler was changed since we started ...
325 // so for now let's not delete it.
326// TSignalHandler *ih = GetSignalHandler();
327// ih->Remove();
328// SetSignalHandler(0);
329// delete ih;
330}
331
332////////////////////////////////////////////////////////////////////////////////
333/// Execute logon macro's. There are three levels of logon macros that
334/// will be executed: the system logon etc/system.rootlogon.C, the global
335/// user logon ~/.rootlogon.C and the local ./.rootlogon.C. For backward
336/// compatibility also the logon macro as specified by the Rint.Logon
337/// environment setting, by default ./rootlogon.C, will be executed.
338/// No logon macros will be executed when the system is started with
339/// the -n option.
340
342{
343 if (NoLogOpt()) return;
344
345 TString name = ".rootlogon.C";
346 TString sname = "system";
347 sname += name;
348 char *s = gSystem->ConcatFileName(TROOT::GetEtcDir(), sname);
350 ProcessFile(s);
351 }
352 delete [] s;
355 ProcessFile(s);
356 }
357 delete [] s;
358 // avoid executing ~/.rootlogon.C twice
359 if (strcmp(gSystem->HomeDirectory(), gSystem->WorkingDirectory())) {
362 }
363
364 // execute also the logon macro specified by "Rint.Logon"
365 const char *logon = gEnv->GetValue("Rint.Logon", (char*)nullptr);
366 if (logon) {
367 char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
368 if (mac)
369 ProcessFile(logon);
370 delete [] mac;
371 }
372}
373
374////////////////////////////////////////////////////////////////////////////////
375/// Main application eventloop. First process files given on the command
376/// line and then go into the main application event loop, unless the -q
377/// command line option was specified in which case the program terminates.
378/// When return is true this method returns even when -q was specified.
379///
380/// When QuitOpt is true and return is false, terminate the application with
381/// an error code equal to either the ProcessLine error (if any) or the
382/// return value of the command casted to a long.
383
385{
386 if (!QuitOpt()) {
387 // Prompt prompt only if we are expecting / allowing input.
388 Getlinem(kInit, GetPrompt());
389 }
390
391 Longptr_t retval = 0;
392 Int_t error = 0;
393 volatile Bool_t needGetlinemInit = kFALSE;
394
395 if (strlen(WorkingDirectory())) {
396 // if directory specified as argument make it the working directory
398 TSystemDirectory *workdir = new TSystemDirectory("workdir", gSystem->WorkingDirectory());
399 TObject *w = gROOT->GetListOfBrowsables()->FindObject("workdir");
400 TObjLink *lnk = gROOT->GetListOfBrowsables()->FirstLink();
401 while (lnk) {
402 if (lnk->GetObject() == w) {
403 lnk->SetObject(workdir);
405 break;
406 }
407 lnk = lnk->Next();
408 }
409 delete w;
410 }
411
412 // Process shell command line input files
413 if (InputFiles()) {
414 // Make sure that calls into the event loop
415 // ignore end-of-file on the terminal.
417 TIter next(InputFiles());
418 RETRY {
419 retval = 0; error = 0;
420 Int_t nfile = 0;
421 while (TObject *fileObj = next()) {
422 if (dynamic_cast<TNamed*>(fileObj)) {
423 // A file that TApplication did not find. Note the error.
424 retval = 1;
425 continue;
426 }
427 TObjString *file = (TObjString *)fileObj;
428 char cmd[kMAXPATHLEN+50];
429 if (!fNcmd)
430 printf("\n");
431 Bool_t rootfile = kFALSE;
432
433 if (file->TestBit(kExpression)) {
434 snprintf(cmd, kMAXPATHLEN+50, "%s", (const char*)file->String());
435 } else {
436 if (file->String().EndsWith(".root") || file->String().BeginsWith("file:")) {
437 rootfile = kTRUE;
438 } else {
439 rootfile = gROOT->IsRootFile(file->String());
440 }
441 if (rootfile) {
442 // special trick to be able to open files using UNC path names
443 if (file->String().BeginsWith("\\\\"))
444 file->String().Prepend("\\\\");
445 file->String().ReplaceAll("\\","/");
446 const char *rfile = (const char*)file->String();
447 Printf("Attaching file %s as _file%d...", rfile, nfile);
448 snprintf(cmd, kMAXPATHLEN+50, "TFile *_file%d = TFile::Open(\"%s\")", nfile++, rfile);
449 } else {
450 Printf("Processing %s...", (const char*)file->String());
451 snprintf(cmd, kMAXPATHLEN+50, ".x %s", (const char*)file->String());
452 }
453 }
454 Getlinem(kCleanUp, nullptr);
455 Gl_histadd(cmd);
456
457 // The ProcessLine might throw an 'exception'. In this case,
458 // GetLinem(kInit,"Root >") is called and we are jump back
459 // to RETRY ... and we have to avoid the Getlinem(kInit, GetPrompt());
460 needGetlinemInit = kFALSE;
461 retval = ProcessLineNr("ROOT_cli_", cmd, &error);
463 fNcmd++;
464
465 // The ProcessLine has successfully completed and we need
466 // to call Getlinem(kInit, GetPrompt());
467 needGetlinemInit = kTRUE;
468
469 if (error != 0 || fCaughtSignal != -1) break;
470 }
471 } ENDTRY;
472
473 if (QuitOpt()) {
474 if (retrn) return;
475 if (error) {
476 retval = error;
477 } else if (fCaughtSignal != -1) {
478 retval = fCaughtSignal + 128;
479 }
480 // Bring retval into sensible range, 0..255.
481 if (retval < 0 || retval > 255)
482 retval = 255;
483 Terminate(retval);
484 }
485
486 // Allow end-of-file on the terminal to be noticed
487 // after we finish processing the command line input files.
489
491
492 if (needGetlinemInit) Getlinem(kInit, GetPrompt());
493 }
494
495 if (QuitOpt()) {
496 printf("\n");
497 if (retrn) return;
498 Terminate(fCaughtSignal != -1 ? fCaughtSignal + 128 : 0);
499 }
500
501 TApplication::Run(retrn);
502
503 // Reset to happiness.
504 fCaughtSignal = -1;
505
506 Getlinem(kCleanUp, nullptr);
507}
508
509////////////////////////////////////////////////////////////////////////////////
510/// Print the ROOT logo on standard output.
511
513{
514 if (!lite) {
515 // Fancy formatting: the content of lines are format strings; their %s is
516 // replaced by spaces needed to make all lines as long as the longest line.
517 std::vector<TString> lines;
518 // Here, %%s results in %s after TString::Format():
519 lines.emplace_back(TString::Format("Welcome to ROOT %s%%shttps://root.cern",
520 gROOT->GetVersion()));
521 lines.emplace_back(TString::Format("(c) 1995-2024, The ROOT Team; conception: R. Brun, F. Rademakers%%s"));
522 lines.emplace_back(TString::Format("Built for %s on %s%%s", gSystem->GetBuildArch(), gROOT->GetGitDate()));
523 if (!strcmp(gROOT->GetGitBranch(), gROOT->GetGitCommit())) {
524 static const char *months[] = {"January","February","March","April","May",
525 "June","July","August","September","October",
526 "November","December"};
527 Int_t idatqq = gROOT->GetVersionDate();
528 Int_t iday = idatqq%100;
529 Int_t imonth = (idatqq/100)%100;
530 Int_t iyear = (idatqq/10000);
531
532 lines.emplace_back(TString::Format("From tag %s, %d %s %4d%%s",
533 gROOT->GetGitBranch(),
534 iday,months[imonth-1],iyear));
535 } else {
536 // If branch and commit are identical - e.g. "v5-34-18" - then we have
537 // a release build. Else specify the git hash this build was made from.
538 lines.emplace_back(TString::Format("From %s@%s %%s",
539 gROOT->GetGitBranch(),
540 gROOT->GetGitCommit()));
541 }
542 lines.emplace_back(TString::Format("With %s %%s",
544 lines.emplace_back(TString("Try '.help'/'.?', '.demo', '.license', '.credits', '.quit'/'.q'%s"));
545
546 // Find the longest line and its length:
547 auto itLongest = std::max_element(lines.begin(), lines.end(),
548 [](const TString& left, const TString& right) {
549 return left.Length() < right.Length(); });
550 Ssiz_t lenLongest = itLongest->Length();
551
552
553 Printf(" %s", TString('-', lenLongest).Data());
554 for (const auto& line: lines) {
555 // Print the line, expanded with the necessary spaces at %s, and
556 // surrounded by some ASCII art.
557 Printf(" | %s |",
558 TString::Format(line.Data(),
559 TString(' ', lenLongest - line.Length()).Data()).Data());
560 }
561 Printf(" %s\n", TString('-', lenLongest).Data());
562 }
563
564#ifdef R__UNIX
565 // Popdown X logo, only if started with -splash option
566 for (int i = 0; i < Argc(); i++)
567 if (!strcmp(Argv(i), "-splash"))
568 kill(getppid(), SIGUSR1);
569#endif
570}
571
572////////////////////////////////////////////////////////////////////////////////
573/// Get prompt from interpreter. Either "root [n]" or "end with '}'".
574
576{
577 char *s = gCling->GetPrompt();
578 if (s[0])
579 strlcpy(fPrompt, s, sizeof(fPrompt));
580 else
582
583 return fPrompt;
584}
585
586////////////////////////////////////////////////////////////////////////////////
587/// Set a new default prompt. It returns the previous prompt.
588/// The prompt may contain a %d which will be replaced by the commend
589/// number. The default prompt is "root [%d] ". The maximum length of
590/// the prompt is 55 characters. To set the prompt in an interactive
591/// session do:
592/// root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
593/// aap>
594
595const char *TRint::SetPrompt(const char *newPrompt)
596{
597 static TString op;
598 op = fDefaultPrompt;
599
600 if (newPrompt && strlen(newPrompt) <= 55)
601 fDefaultPrompt = newPrompt;
602 else
603 Error("SetPrompt", "newPrompt too long (> 55 characters)");
604
605 return op.Data();
606}
607
608////////////////////////////////////////////////////////////////////////////////
609/// Handle input coming from terminal.
610
612{
613 static TStopwatch timer;
614 const char *line;
615
616 if ((line = Getlinem(kOneChar, nullptr))) {
617 if (line[0] == 0 && Gl_eof())
618 Terminate(0);
619
620 gVirtualX->SetKeyAutoRepeat(kTRUE);
621
622 Gl_histadd(line);
623
624 TString sline = line;
625
626 // strip off '\n' and leading and trailing blanks
627 sline = sline.Chop();
628 sline = sline.Strip(TString::kBoth);
629 ReturnPressed((char*)sline.Data());
630
632
633 // prevent recursive calling of this input handler
635
636 if (gROOT->Timer()) timer.Start();
637
638 TTHREAD_TLS(Bool_t) added;
639 added = kFALSE; // reset on each call.
640
641 // This is needed when working with remote sessions
643
644 try {
645 TRY {
646 if (!sline.IsNull())
647 LineProcessed(sline);
648 ProcessLineNr("ROOT_prompt_", sline);
649 } CATCH(excode) {
650 // enable again input handler
652 added = kTRUE;
653 Throw(excode);
654 } ENDTRY;
655 }
656 // handle every exception
657 catch (std::exception& e) {
658 // enable again intput handler
659 if (!added) fInputHandler->Activate();
660
661 int err;
662 char *demangledType_c = TClassEdit::DemangleTypeIdName(typeid(e), err);
663 const char* demangledType = demangledType_c;
664 if (err) {
665 demangledType_c = nullptr;
666 demangledType = "<UNKNOWN>";
667 }
668 Error("HandleTermInput()", "%s caught: %s", demangledType, e.what());
669 free(demangledType_c);
670 }
671 catch (...) {
672 // enable again intput handler
673 if (!added) fInputHandler->Activate();
674 Error("HandleTermInput()", "Exception caught!");
675 }
676
677 // `ProcessLineNr()` only prepends a `#line` directive if the previous
678 // input line was not terminated by a '\' (backslash-newline).
679 // Thus, to match source locations included in cling diagnostics, we only
680 // increment `fNcmd` if the next call to `ProcessLineNr()` will issue
681 // a new `#line`.
682 if (!fBackslashContinue && !sline.IsNull())
683 fNcmd++;
684
685 if (gROOT->Timer()) timer.Print("u");
686
687 // enable again intput handler
689
690 if (!sline.BeginsWith(".reset"))
692
693 gTabCom->ClearAll();
694 Getlinem(kInit, GetPrompt());
695 }
696 return kTRUE;
697}
698
699////////////////////////////////////////////////////////////////////////////////
700/// Handle signals (kSigBus, kSigSegmentationViolation,
701/// kSigIllegalInstruction and kSigFloatingException) trapped in TSystem.
702/// Specific TApplication implementations may want something different here.
703
705{
706 fCaughtSignal = sig;
707 if (TROOT::Initialized()) {
708 if (gException) {
709 Getlinem(kCleanUp, nullptr);
710 Getlinem(kInit, "Root > ");
711 }
712 }
714}
715
716////////////////////////////////////////////////////////////////////////////////
717/// Terminate the application. Reset the terminal to sane mode and call
718/// the logoff macro defined via Rint.Logoff environment variable.
719/// @note The function does not return, unless the class has
720/// been told to return from Run(), by a call to SetReturnFromRun().
721
723{
724 Getlinem(kCleanUp, nullptr);
725
726 if (ReturnFromRun()) {
727 gSystem->ExitLoop();
728 } else {
729 delete gTabCom;
730 gTabCom = nullptr;
731
732 //Execute logoff macro
733 const char *logoff;
734 logoff = gEnv->GetValue("Rint.Logoff", (char*)nullptr);
735 if (logoff && !NoLogOpt()) {
736 char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
737 if (mac)
738 ProcessFile(logoff);
739 delete [] mac;
740 }
741
743 }
744}
745
746////////////////////////////////////////////////////////////////////////////////
747/// Set console mode:
748///
749/// mode = kTRUE - echo input symbols
750/// mode = kFALSE - noecho input symbols
751
753{
754 Gl_config("noecho", mode ? 0 : 1);
755}
756
757////////////////////////////////////////////////////////////////////////////////
758/// Process the content of a line starting with ".R" (already stripped-off)
759/// The format is
760/// [user@]host[:dir] [-l user] [-d dbg] [script]
761/// The variable 'dir' is the remote directory to be used as working dir.
762/// The username can be specified in two ways, "-l" having the priority
763/// (as in ssh).
764/// A 'dbg' value > 0 gives increasing verbosity.
765/// The last argument 'script' allows to specify an alternative script to
766/// be executed remotely to startup the session.
767
769{
771
772 if (ret == 1) {
773 if (fAppRemote) {
774 TString prompt; prompt.Form("%s:root [%%d] ", fAppRemote->ApplicationName());
775 SetPrompt(prompt);
776 } else {
777 SetPrompt("root [%d] ");
778 }
779 }
780
781 return ret;
782}
783
784
785////////////////////////////////////////////////////////////////////////////////
786/// Calls TRint::ProcessLine() possibly prepending a `#line` directive for
787/// better diagnostics.
788/// The user is responsible for incrementing `fNcmd`, where appropriate, after
789/// a call to this function.
790
791Longptr_t TRint::ProcessLineNr(const char* filestem, const char *line, Int_t *error /*= 0*/)
792{
793 Int_t err;
794 if (!error)
795 error = &err;
796 if (line && line[0] != '.') {
799 input += TString::Format("#line 1 \"%s%d\"\n", filestem, fNcmd);
800 input += line;
801 int res = ProcessLine(input, kFALSE, error);
802 if (gCling->GetMore()) {
805 SetPrompt("root (cont'ed, cancel with .@) [%d]");
806 } else if (fNonContinuePrompt.Length()) {
809 }
810 std::string_view sv(line);
811 auto lastNonSpace = sv.find_last_not_of(" \t");
812 fBackslashContinue = (lastNonSpace != std::string_view::npos
813 && sv[lastNonSpace] == '\\');
814 return res;
815 }
816 if (line && line[0] == '.' && line[1] == '@') {
817 ProcessLine(line, kFALSE, error);
818 SetPrompt("root [%d] ");
819 }
820 return ProcessLine(line, kFALSE, error);
821}
822
823
824////////////////////////////////////////////////////////////////////////////////
825/// Forward tab completion request to our TTabCom::Hook().
826
827Int_t TRint::TabCompletionHook(char *buf, int *pLoc, std::ostream& out)
828{
829 if (gTabCom)
830 return gTabCom->Hook(buf, pLoc, out);
831
832 return -1;
833}
#define e(i)
Definition RSha256.hxx:103
bool Bool_t
Definition RtypesCore.h:63
int Int_t
Definition RtypesCore.h:45
long Longptr_t
Definition RtypesCore.h:82
constexpr Bool_t kFALSE
Definition RtypesCore.h:101
constexpr Bool_t kTRUE
Definition RtypesCore.h:100
#define ClassImp(name)
Definition Rtypes.h:377
R__EXTERN TApplication * gApplication
R__EXTERN TBenchmark * gBenchmark
Definition TBenchmark.h:59
R__EXTERN TClassTable * gClassTable
Definition TClassTable.h:97
R__EXTERN TEnv * gEnv
Definition TEnv.h:170
void Break(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:207
#define CATCH(n)
Definition TException.h:58
#define ENDTRY
Definition TException.h:64
#define RETRY
Definition TException.h:44
#define TRY
Definition TException.h:51
R__EXTERN ExceptionContext_t * gException
Definition TException.h:69
R__EXTERN void Throw(int code)
If an exception context has been set (using the TRY and RETRY macros) jump back to where it was set.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:110
R__EXTERN TInterpreter * gCling
#define gInterpreter
#define gROOT
Definition TROOT.h:406
static void ResetTermAtExit()
Restore terminal to non-raw mode.
Definition TRint.cxx:74
static Int_t Key_Pressed(Int_t key)
Definition TRint.cxx:56
static Int_t BeepHook()
Definition TRint.cxx:64
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2503
@ kSigInterrupt
@ kReadPermission
Definition TSystem.h:45
R__EXTERN TSystem * gSystem
Definition TSystem.h:555
R__EXTERN TTabCom * gTabCom
Definition TTabCom.h:229
#define gVirtualX
Definition TVirtualX.h:337
#define free
Definition civetweb.c:1539
#define snprintf
Definition civetweb.c:1540
This class creates the ROOT Application Environment that interfaces to the windowing system eventloop...
virtual void KeyPressed(Int_t key)
Emit signal when console keyboard key was pressed.
virtual Longptr_t ProcessLine(const char *line, Bool_t sync=kFALSE, Int_t *error=nullptr)
Process a single command line, either a C++ statement or an interpreter command starting with a "....
virtual Bool_t HandleTermInput()
TObjArray * InputFiles() const
virtual void LineProcessed(const char *line)
Emit signal when a line has been processed.
void ClearInputFiles()
Clear list containing macro files passed as program arguments.
Bool_t ReturnFromRun() const
virtual void Run(Bool_t retrn=kFALSE)
Main application eventloop. Calls system dependent eventloop via gSystem.
virtual void HandleException(Int_t sig)
Handle exceptions (kSigBus, kSigSegmentationViolation, kSigIllegalInstruction and kSigFloatingExcepti...
char ** Argv() const
virtual void Terminate(Int_t status=0)
Terminate the application by call TSystem::Exit() unless application has been told to return from Run...
virtual const char * ApplicationName() const
virtual Longptr_t ProcessFile(const char *file, Int_t *error=nullptr, Bool_t keep=kFALSE)
Process a file containing a C++ macro.
virtual void ReturnPressed(char *text)
Emit signal when return key was pressed.
Bool_t NoLogOpt() const
Bool_t NoLogoOpt() const
const char * WorkingDirectory() const
Bool_t QuitOpt() const
Int_t Argc() const
virtual Longptr_t ProcessRemote(const char *line, Int_t *error=nullptr)
Process the content of a line starting with ".R" (already stripped-off) The format is.
TApplication * fAppRemote
void SetSignalHandler(TSignalHandler *sh)
This class is a ROOT utility to help benchmarking applications.
Definition TBenchmark.h:29
static DictFuncPtr_t GetDict(const char *cname)
Given the class name returns the Dictionary() function of a class (uses hash of name).
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:491
void Remove() override
Remove file event handler from system file handler list.
void Add() override
Add file event handler to system file handler list.
virtual char * GetPrompt()=0
virtual void SaveGlobalsContext()=0
virtual void EndOfLineAction()=0
virtual void Reset()=0
virtual void SetGetline(const char *(*getlineFunc)(const char *prompt), void(*histaddFunc)(const char *line))=0
virtual void SaveContext()=0
virtual Int_t GetMore() const =0
Returns whether the interpreter is waiting for more input, i.e.
Bool_t Notify() override
TRint interrupt handler.
Definition TRint.cxx:92
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
Collectable string class.
Definition TObjString.h:28
TString & String()
Definition TObjString.h:48
Mother of all ROOT objects.
Definition TObject.h:41
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:199
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:403
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:780
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:987
static const char * GetMacroPath()
Get macro search path. Static utility function.
Definition TROOT.cxx:2762
static Bool_t Initialized()
Return kTRUE if the TROOT object has been initialized.
Definition TROOT.cxx:2906
static const std::vector< std::string > & AddExtraInterpreterArgs(const std::vector< std::string > &args)
Provide command line arguments to the interpreter construction.
Definition TROOT.cxx:2952
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3052
Definition TRint.h:31
void SetEchoMode(Bool_t mode) override
Set console mode:
Definition TRint.cxx:752
Bool_t HandleTermInput() override
Handle input coming from terminal.
Definition TRint.cxx:611
Bool_t fInterrupt
Definition TRint.h:38
void Run(Bool_t retrn=kFALSE) override
Main application eventloop.
Definition TRint.cxx:384
Longptr_t ProcessLineNr(const char *filestem, const char *line, Int_t *error=nullptr)
Calls TRint::ProcessLine() possibly prepending a #line directive for better diagnostics.
Definition TRint.cxx:791
virtual const char * SetPrompt(const char *newPrompt)
Set a new default prompt.
Definition TRint.cxx:595
virtual void Terminate(int status) override
Terminate the application.
Definition TRint.cxx:722
char fPrompt[64]
Definition TRint.h:37
Int_t TabCompletionHook(char *buf, int *pLoc, std::ostream &out) override
Forward tab completion request to our TTabCom::Hook().
Definition TRint.cxx:827
virtual char * GetPrompt()
Get prompt from interpreter. Either "root [n]" or "end with '}'".
Definition TRint.cxx:575
void HandleException(Int_t sig) override
Handle signals (kSigBus, kSigSegmentationViolation, kSigIllegalInstruction and kSigFloatingException)...
Definition TRint.cxx:704
virtual ~TRint()
Destructor.
Definition TRint.cxx:316
virtual void PrintLogo(Bool_t lite=kFALSE)
Print the ROOT logo on standard output.
Definition TRint.cxx:512
void ExecLogon()
Execute logon macro's.
Definition TRint.cxx:341
Longptr_t ProcessRemote(const char *line, Int_t *error=nullptr) override
Process the content of a line starting with ".R" (already stripped-off) The format is [user@]host[:di...
Definition TRint.cxx:768
Bool_t fBackslashContinue
Definition TRint.h:41
TString fDefaultPrompt
Definition TRint.h:35
TString fNonContinuePrompt
Definition TRint.h:36
Int_t fCaughtSignal
Definition TRint.h:39
Int_t fNcmd
Definition TRint.h:34
TRint(const TRint &)=delete
TFileHandler * fInputHandler
Definition TRint.h:40
void Add() override
Add signal handler to system signal handler list.
ESignals GetSignal() const
Stopwatch class.
Definition TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void Print(Option_t *option="") const override
Print the real and cpu time passed between the start and stop events.
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:417
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
Return true if string ends with the specified string.
Definition TString.cxx:2244
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Definition TString.cxx:1163
void Clear()
Clear string without changing its capacity.
Definition TString.cxx:1235
const char * Data() const
Definition TString.h:376
TString & Chop()
Definition TString.h:691
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:704
@ kBoth
Definition TString.h:276
@ kIgnoreCase
Definition TString.h:277
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Definition TString.h:623
TString & Prepend(const char *cs)
Definition TString.h:673
Bool_t IsNull() const
Definition TString.h:414
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2378
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2356
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:632
void DeActivate()
De-activate a system event handler.
void Activate()
Activate a system event handler.
Describes an Operating System directory for the browser.
void Beep(Int_t freq=-1, Int_t duration=-1, Bool_t setDefault=kFALSE)
Beep for duration milliseconds with a tone of frequency freq.
Definition TSystem.cxx:324
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1665
virtual char * ConcatFileName(const char *dir, const char *name)
Concatenate a directory and a file name. User must delete returned string.
Definition TSystem.cxx:1071
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1857
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1296
virtual void ExitLoop()
Exit from event loop.
Definition TSystem.cxx:392
virtual Bool_t ChangeDirectory(const char *path)
Change directory.
Definition TSystem.cxx:862
virtual const char * GetBuildCompilerVersionStr() const
Return the build compiler version identifier string.
Definition TSystem.cxx:3899
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:871
virtual char * Which(const char *search, const char *file, EAccessMode mode=kFileExists)
Find location of file in a search path.
Definition TSystem.cxx:1548
virtual const char * GetBuildArch() const
Return the build architecture.
Definition TSystem.cxx:3875
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:887
Int_t Hook(char *buf, int *pLoc, std::ostream &out)
[private]
Definition TTabCom.cxx:1567
void ClearAll()
clears all lists except for user names and system include files.
Definition TTabCom.cxx:319
TTermInputHandler(Int_t fd)
Definition TRint.cxx:123
Bool_t ReadNotify() override
Notify when something can be read from the descriptor associated with this handler.
Definition TRint.cxx:125
Bool_t Notify() override
Notify implementation. Call the application interupt handler.
Definition TRint.cxx:131
TLine * line
const Int_t n
Definition legend1.C:16
R__EXTERN void * gMmallocDesc
Definition TStorage.h:143
char * DemangleTypeIdName(const std::type_info &ti, int &errorCode)
Demangle in a portable way the type id name.
#define kMAXPATHLEN