Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RWebDisplayHandle.cxx
Go to the documentation of this file.
1// Author: Sergey Linev <s.linev@gsi.de>
2// Date: 2018-10-17
3// Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
4
5/*************************************************************************
6 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
14
15#include <ROOT/RLogger.hxx>
16
17#include "RConfigure.h"
18#include "TSystem.h"
19#include "TRandom3.h"
20#include "TString.h"
21#include "TObjArray.h"
22#include "THttpServer.h"
23#include "TEnv.h"
24#include "TError.h"
25#include "TROOT.h"
26#include "TBase64.h"
27#include "TBufferJSON.h"
29
30#include <fstream>
31#include <iostream>
32#include <filesystem>
33#include <memory>
34#include <regex>
35
36#ifdef _MSC_VER
37#include <process.h>
38#else
39#include <unistd.h>
40#include <stdlib.h>
41#include <signal.h>
42#include <spawn.h>
43#ifdef R__MACOSX
44#include <sys/wait.h>
45#include <crt_externs.h>
46#elif defined(__FreeBSD__)
47#include <sys/wait.h>
48#include <dlfcn.h>
49#else
50#include <wait.h>
51#endif
52#endif
53
54using namespace ROOT;
55using namespace std::string_literals;
56
57/** \class ROOT::RWebDisplayHandle
58\ingroup webdisplay
59
60Handle of created web-based display
61Depending from type of web display, holds handle of started browser process or other display-specific information
62to correctly stop and cleanup display.
63*/
64
65
66//////////////////////////////////////////////////////////////////////////////////////////////////
67/// Static holder of registered creators of web displays
68
69std::map<std::string, std::unique_ptr<RWebDisplayHandle::Creator>> &RWebDisplayHandle::GetMap()
70{
71 static std::map<std::string, std::unique_ptr<RWebDisplayHandle::Creator>> sMap;
72 return sMap;
73}
74
75//////////////////////////////////////////////////////////////////////////////////////////////////
76/// Search for specific browser creator
77/// If not found, try to add one
78/// \param name - creator name like ChromeCreator
79/// \param libname - shared library name where creator could be provided
80
81std::unique_ptr<RWebDisplayHandle::Creator> &RWebDisplayHandle::FindCreator(const std::string &name, const std::string &libname)
82{
83 auto &m = GetMap();
84 auto search = m.find(name);
85 if (search == m.end()) {
86
87 if (libname == "ChromeCreator") {
88 m.emplace(name, std::make_unique<ChromeCreator>(name == "edge"));
89 } else if (libname == "FirefoxCreator") {
90 m.emplace(name, std::make_unique<FirefoxCreator>());
91 } else if (libname == "SafariCreator") {
92 m.emplace(name, std::make_unique<SafariCreator>());
93 } else if (libname == "BrowserCreator") {
94 m.emplace(name, std::make_unique<BrowserCreator>(false));
95 } else if (!libname.empty()) {
96 gSystem->Load(libname.c_str());
97 }
98
99 search = m.find(name); // try again
100 }
101
102 if (search != m.end())
103 return search->second;
104
105 static std::unique_ptr<RWebDisplayHandle::Creator> dummy;
106 return dummy;
107}
108
109namespace ROOT {
110
111//////////////////////////////////////////////////////////////////////////////////////////////////
112/// Specialized handle to hold information about running browser process
113/// Used to correctly cleanup all processes and temporary directories
114
116
117#ifdef _MSC_VER
118 typedef int browser_process_id;
119#else
120 typedef pid_t browser_process_id;
121#endif
122 std::string fTmpDir; ///< temporary directory to delete at the end
123 std::string fTmpFile; ///< temporary file to remove
124 bool fHasPid{false};
126
127public:
128 RWebBrowserHandle(const std::string &url, const std::string &tmpdir, const std::string &tmpfile,
129 const std::string &dump)
131 {
132 SetContent(dump);
133 }
134
135 RWebBrowserHandle(const std::string &url, const std::string &tmpdir, const std::string &tmpfile,
138 {
139 }
140
142 {
143#ifdef _MSC_VER
144 if (fHasPid)
145 gSystem->Exec(("taskkill /F /PID " + std::to_string(fPid) + " >NUL 2>NUL").c_str());
146 std::string rmdir = "rmdir /S /Q ";
147#else
148 if (fHasPid)
149 kill(fPid, SIGKILL);
150 std::string rmdir = "rm -rf ";
151#endif
152 if (!fTmpDir.empty())
153 gSystem->Exec((rmdir + fTmpDir).c_str());
155 }
156
157 void RemoveStartupFiles() override
158 {
159#ifdef _MSC_VER
160 std::string rmfile = "del /F ";
161#else
162 std::string rmfile = "rm -f ";
163#endif
164 if (!fTmpFile.empty()) {
165 gSystem->Exec((rmfile + fTmpFile).c_str());
166 fTmpFile.clear();
167 }
168 }
169};
170
171} // namespace ROOT
172
173//////////////////////////////////////////////////////////////////////////////////////////////////
174/// Class to handle starting of web-browsers like Chrome or Firefox
175
177{
178 if (custom) return;
179
180 if (!exec.empty()) {
181 if (exec.find("$url") == std::string::npos) {
182 fProg = exec;
183#ifdef _MSC_VER
184 fExec = exec + " $url";
185#else
186 fExec = exec + " $url &";
187#endif
188 } else {
189 fExec = exec;
190 auto pos = exec.find(" ");
191 if (pos != std::string::npos)
192 fProg = exec.substr(0, pos);
193 }
194 } else if (gSystem->InheritsFrom("TMacOSXSystem")) {
195 fExec = "open \'$url\'";
196 } else if (gSystem->InheritsFrom("TWinNTSystem")) {
197 fExec = "start $url";
198 } else {
199 fExec = "xdg-open \'$url\' &";
200 }
201}
202
203//////////////////////////////////////////////////////////////////////////////////////////////////
204/// Check if browser executable exists and can be used
205
207{
208 if (nexttry.empty() || !fProg.empty())
209 return;
210
212#ifdef R__MACOSX
213 fProg = std::regex_replace(nexttry, std::regex("%20"), " ");
214#else
215 fProg = nexttry;
216#endif
217 return;
218 }
219
220 if (!check_std_paths)
221 return;
222
223#ifdef _MSC_VER
224 std::string ProgramFiles = gSystem->Getenv("ProgramFiles");
225 auto pos = ProgramFiles.find(" (x86)");
226 if (pos != std::string::npos)
227 ProgramFiles.erase(pos, 6);
228 std::string ProgramFilesx86 = gSystem->Getenv("ProgramFiles(x86)");
229
230 if (!ProgramFiles.empty())
231 TestProg(ProgramFiles + nexttry, false);
232 if (!ProgramFilesx86.empty())
233 TestProg(ProgramFilesx86 + nexttry, false);
234#endif
235}
236
237//////////////////////////////////////////////////////////////////////////////////////////////////
238/// Create temporary file for web display
239/// Normally gSystem->TempFileName() method used to create file in default temporary directory
240/// For snap chromium use of default temp directory is not always possible therefore one switches to home directory
241/// But one checks if default temp directory modified and already points to /home folder
242
244{
245 std::string dirname;
246 if (use_home_dir > 0) {
247 if (use_home_dir == 1) {
248 const char *tmp_dir = gSystem->TempDirectory();
249 if (tmp_dir && (strncmp(tmp_dir, "/home", 5) == 0))
250 use_home_dir = 0;
251 else if (!tmp_dir || (strncmp(tmp_dir, "/tmp", 4) == 0))
252 use_home_dir = 2;
253 }
254
255 if (use_home_dir > 1)
257 }
258 return gSystem->TempFileName(name, use_home_dir > 1 ? dirname.c_str() : nullptr, suffix);
259}
260
261static void DummyTimeOutHandler(int /* Sig */) {}
262
263
264//////////////////////////////////////////////////////////////////////////////////////////////////
265/// Display given URL in web browser
266/// \note See more details related to webdisplay on RWebWindowsManager::ShowWindow
267
268std::unique_ptr<RWebDisplayHandle>
270{
271 std::string url = args.GetFullUrl();
272 if (url.empty())
273 return nullptr;
274
276 std::cout << "New web window: " << url << std::endl;
277 return std::make_unique<RWebBrowserHandle>(url, "", "", "");
278 }
279
280 std::string exec;
281 if (args.IsBatchMode())
282 exec = fBatchExec;
283 else if (args.IsHeadless())
284 exec = fHeadlessExec;
285 else if (args.IsStandalone())
286 exec = fExec;
287 else
288 exec = "$prog $url &";
289
290 if (exec.empty())
291 return nullptr;
292
293 std::string swidth = std::to_string(args.GetWidth() > 0 ? args.GetWidth() : 800),
294 sheight = std::to_string(args.GetHeight() > 0 ? args.GetHeight() : 600),
295 sposx = std::to_string(args.GetX() >= 0 ? args.GetX() : 0),
296 sposy = std::to_string(args.GetY() >= 0 ? args.GetY() : 0);
297
298 ProcessGeometry(exec, args);
299
300 std::string rmdir = MakeProfile(exec, args.IsBatchMode() || args.IsHeadless());
301
302 std::string tmpfile;
303
304 // these are secret parameters, hide them in temp file
305 if (((url.find("token=") != std::string::npos) || (url.find("key=") != std::string::npos)) && !args.IsBatchMode() && !args.IsHeadless()) {
306 TString filebase = "root_start_";
307
308 auto f = TemporaryFile(filebase, IsSnapBrowser() ? 1 : 0, ".html");
309
310 bool ferr = false;
311
312 if (!f) {
313 ferr = true;
314 } else {
315 std::string content = std::regex_replace(
316 "<!DOCTYPE html>\n"
317 "<html lang=\"en\">\n"
318 "<head>\n"
319 " <meta charset=\"utf-8\">\n"
320 " <meta http-equiv=\"refresh\" content=\"0;url=$url\"/>\n"
321 " <title>Opening ROOT widget</title>\n"
322 "</head>\n"
323 "<body>\n"
324 "<p>\n"
325 " This page should redirect you to a ROOT widget. If it doesn't,\n"
326 " <a href=\"$url\">click here to go to ROOT</a>.\n"
327 "</p>\n"
328 "</body>\n"
329 "</html>\n", std::regex("\\$url"), url);
330
331 if (fwrite(content.c_str(), 1, content.length(), f) != content.length())
332 ferr = true;
333
334 if (fclose(f) != 0)
335 ferr = true;
336
337 tmpfile = filebase.Data();
338
339 url = "file://"s + tmpfile;
340 }
341
342 if (ferr) {
343 if (!tmpfile.empty())
344 gSystem->Unlink(tmpfile.c_str());
345 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary HTML file to startup widget";
346 return nullptr;
347 }
348 }
349
350 exec = std::regex_replace(exec, std::regex("\\$rootetcdir"), TROOT::GetEtcDir().Data());
351 exec = std::regex_replace(exec, std::regex("\\$url"), url);
352 exec = std::regex_replace(exec, std::regex("\\$width"), swidth);
353 exec = std::regex_replace(exec, std::regex("\\$height"), sheight);
354 exec = std::regex_replace(exec, std::regex("\\$posx"), sposx);
355 exec = std::regex_replace(exec, std::regex("\\$posy"), sposy);
356
357 if (exec.compare(0,5,"fork:") == 0) {
358 if (fProg.empty()) {
359 if (!tmpfile.empty())
360 gSystem->Unlink(tmpfile.c_str());
361 R__LOG_ERROR(WebGUILog()) << "Fork instruction without executable";
362 return nullptr;
363 }
364
365 exec.erase(0, 5);
366
367 // in case of redirection process will wait until output is produced
368 std::string redirect = args.GetRedirectOutput();
369
370#ifndef _MSC_VER
371
372 std::unique_ptr<TObjArray> fargs(TString(exec.c_str()).Tokenize(" "));
373 if (!fargs || (fargs->GetLast()<=0)) {
374 if (!tmpfile.empty())
375 gSystem->Unlink(tmpfile.c_str());
376 R__LOG_ERROR(WebGUILog()) << "Fork instruction is empty";
377 return nullptr;
378 }
379
380 std::vector<char *> argv;
381 argv.push_back((char *) fProg.c_str());
382 for (Int_t n = 0; n <= fargs->GetLast(); ++n)
383 argv.push_back((char *)fargs->At(n)->GetName());
384 argv.push_back(nullptr);
385
386 R__LOG_DEBUG(0, WebGUILog()) << "Show web window in browser with posix_spawn:\n" << fProg << " " << exec;
387
390 if (redirect.empty())
392 else
395
396#ifdef R__MACOSX
397 char **envp = *_NSGetEnviron();
398#elif defined (__FreeBSD__)
399 //this is needed because the FreeBSD linker does not like to resolve these special symbols
400 //in shared libs with -Wl,--no-undefined
401 char** envp = (char**)dlsym(RTLD_DEFAULT, "environ");
402#else
403 char **envp = environ;
404#endif
405
406 pid_t pid;
407 int status = posix_spawn(&pid, argv[0], &action, nullptr, argv.data(), envp);
408
410
411 if (status != 0) {
412 if (!tmpfile.empty())
413 gSystem->Unlink(tmpfile.c_str());
414 R__LOG_ERROR(WebGUILog()) << "Fail to launch " << argv[0];
415 return nullptr;
416 }
417
418 if (!redirect.empty()) {
419 Int_t batch_timeout = gEnv->GetValue("WebGui.BatchTimeout", 30);
420 struct sigaction Act, Old;
421 int elapsed_time = 0;
422
423 if (batch_timeout) {
424 memset(&Act, 0, sizeof(Act));
425 Act.sa_handler = DummyTimeOutHandler;
426 sigemptyset(&Act.sa_mask);
431 }
432
433 int job_done = 0;
434 std::string dump_content;
435
436 while (!job_done) {
437
438 // wait until output is produced
439 int wait_status = 0;
440
442
443 // try read dump anyway
445
446 if (dump_content.find("<div>###batch###job###done###</div>") != std::string::npos)
447 job_done = 1;
448
449 if (wait_res == -1) {
450 // failure when finish process
452 if ((errno == EINTR) && (alarm_timeout > 0) && !job_done) {
453 if (alarm_timeout > 2) alarm_timeout = 2;
456 } else {
457 // end of timeout - do not try to wait any longer
458 job_done = 1;
459 }
460 } else if (!WIFEXITED(wait_status) && !WIFSIGNALED(wait_status)) {
461 // abnormal end of browser process
462 job_done = 1;
463 } else {
464 // this is normal finish, no need for process kill
465 job_done = 2;
466 }
467 }
468
469 if (job_done != 2) {
470 // kill browser process when no normal end was detected
471 kill(pid, SIGKILL);
472 }
473
474 if (batch_timeout) {
475 alarm(0); // disable alarm
476 sigaction(SIGALRM, &Old, nullptr);
477 }
478
479 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
480 ::Info("RWebDisplayHandle::Display", "Preserve dump file %s", redirect.c_str());
481 else
482 gSystem->Unlink(redirect.c_str());
483
484 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, dump_content);
485 }
486
487 // add processid and rm dir
488
489 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, pid);
490
491#else
492
493 if (fProg.empty()) {
494 if (!tmpfile.empty())
495 gSystem->Unlink(tmpfile.c_str());
496 R__LOG_ERROR(WebGUILog()) << "No Web browser found";
497 return nullptr;
498 }
499
500 // use UnixPathName to simplify handling of backslashes
501 exec = "wmic process call create '"s + gSystem->UnixPathName(fProg.c_str()) + " " + exec + "' | find \"ProcessId\" "s;
502 std::string process_id = gSystem->GetFromPipe(exec.c_str()).Data();
503 std::stringstream ss(process_id);
504 std::string tmp;
505 char c;
506 int pid = 0;
507 ss >> tmp >> c >> pid;
508
509 if (pid <= 0) {
510 if (!tmpfile.empty())
511 gSystem->Unlink(tmpfile.c_str());
512 R__LOG_ERROR(WebGUILog()) << "Fail to launch " << fProg;
513 return nullptr;
514 }
515
516 // add processid and rm dir
517 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, pid);
518#endif
519 }
520
521#ifdef _MSC_VER
522
523 if (exec.rfind("&") == exec.length() - 1) {
524
525 // if last symbol is &, use _spawn to detach execution
526 exec.resize(exec.length() - 1);
527
528 std::vector<char *> argv;
529 std::string firstarg = fProg;
530 auto slashpos = firstarg.find_last_of("/\\");
531 if (slashpos != std::string::npos)
532 firstarg.erase(0, slashpos + 1);
533 argv.push_back((char *)firstarg.c_str());
534
535 std::unique_ptr<TObjArray> fargs(TString(exec.c_str()).Tokenize(" "));
536 for (Int_t n = 1; n <= fargs->GetLast(); ++n)
537 argv.push_back((char *)fargs->At(n)->GetName());
538 argv.push_back(nullptr);
539
540 R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in " << fProg << " with:\n" << exec;
541
542 _spawnv(_P_NOWAIT, gSystem->UnixPathName(fProg.c_str()), argv.data());
543
544 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, ""s);
545 }
546
547 std::string prog = "\""s + gSystem->UnixPathName(fProg.c_str()) + "\""s;
548
549#else
550
551#ifdef R__MACOSX
552 std::string prog = std::regex_replace(fProg, std::regex(" "), "\\ ");
553#else
554 std::string prog = fProg;
555#endif
556
557#endif
558
559 exec = std::regex_replace(exec, std::regex("\\$prog"), prog);
560
561 std::string redirect = args.GetRedirectOutput(), dump_content;
562
563 if (!redirect.empty()) {
564 if (exec.find("$dumpfile") != std::string::npos) {
565 exec = std::regex_replace(exec, std::regex("\\$dumpfile"), redirect);
566 } else {
567 auto p = exec.length();
568 if (exec.rfind("&") == p-1) --p;
569 exec.insert(p, " >"s + redirect + " "s);
570 }
571 }
572
573 R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in browser with:\n" << exec;
574
575 gSystem->Exec(exec.c_str());
576
577 // read content of redirected output
578 if (!redirect.empty()) {
580
581 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
582 ::Info("RWebDisplayHandle::Display", "Preserve dump file %s", redirect.c_str());
583 else
584 gSystem->Unlink(redirect.c_str());
585 }
586
587 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, dump_content);
588}
589
590//////////////////////////////////////////////////////////////////////////////////////////////////
591/// Constructor
592
594{
595 fExec = gEnv->GetValue("WebGui.SafariInteractive", "open -a Safari $url");
596}
597
598//////////////////////////////////////////////////////////////////////////////////////////////////
599/// Returns true if it can be used
600
602{
603#ifdef R__MACOSX
604 return true;
605#else
606 return false;
607#endif
608}
609
610//////////////////////////////////////////////////////////////////////////////////////////////////
611/// Constructor
612
614{
615 fEdge = _edge;
616
617 fEnvPrefix = fEdge ? "WebGui.Edge" : "WebGui.Chrome";
618
619 TestProg(gEnv->GetValue(fEnvPrefix.c_str(), ""));
620
621 if (!fProg.empty() && !fEdge)
622 fChromeVersion = gEnv->GetValue("WebGui.ChromeVersion", -1);
623
624#ifdef _MSC_VER
625 if (fEdge)
626 TestProg("\\Microsoft\\Edge\\Application\\msedge.exe", true);
627 else
628 TestProg("\\Google\\Chrome\\Application\\chrome.exe", true);
629#endif
630#ifdef R__MACOSX
631 TestProg("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
632#endif
633#ifdef R__LINUX
634 TestProg("/snap/bin/chromium"); // test snap before to detect it properly
635 TestProg("/usr/bin/chromium");
636 TestProg("/usr/bin/chromium-browser");
637 TestProg("/usr/bin/chrome-browser");
638 TestProg("/usr/bin/google-chrome-stable");
639 TestProg("/usr/bin/google-chrome");
640#endif
641
642// --no-sandbox is required to run chrome with super-user, but only in headless mode
643// --headless=new was used when both old and new were available, but old was removed from chrome 132, see https://developer.chrome.com/blog/removing-headless-old-from-chrome
644
645#ifdef _MSC_VER
646 // here --headless=old was used to let normally end of Edge process when --dump-dom is used
647 // while on Windows chrome and edge version not tested, just suppose that newest chrome is used
648 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless --no-sandbox $geometry --dump-dom $url");
649 // in interactive headless mode fork used to let stop browser via process id
650 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless --no-sandbox --disable-gpu $geometry \"$url\"");
651 fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=$url &"); // & in windows mean usage of spawn
652#else
653#ifdef R__MACOSX
654 bool use_normal = true; // mac does not like new flag
655#else
656 bool use_normal = (fChromeVersion < 119) || (fChromeVersion > 131);
657#endif
658 if (use_normal) {
659 // old or newest browser with standard headless mode
660 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "fork:--headless --no-sandbox --disable-extensions --disable-audio-output $geometry --dump-dom $url");
661 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless --no-sandbox --disable-extensions --disable-audio-output $geometry $url");
662 } else {
663 // newer version with headless=new mode
664 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "fork:--headless=new --no-sandbox --disable-extensions --disable-audio-output $geometry --dump-dom $url");
665 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless=new --no-sandbox --disable-extensions --disable-audio-output $geometry $url");
666 }
667 fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=\'$url\' >/dev/null 2>/dev/null &");
668#endif
669}
670
671
672//////////////////////////////////////////////////////////////////////////////////////////////////
673/// Replace $geometry placeholder with geometry settings
674/// Also RWebDisplayArgs::GetExtraArgs() are appended
675
677{
678 std::string geometry;
679 if ((args.GetWidth() > 0) && (args.GetHeight() > 0))
680 geometry = "--window-size="s + std::to_string(args.GetWidth())
681 + (args.IsHeadless() ? "x"s : ","s)
682 + std::to_string(args.GetHeight());
683
684 if (((args.GetX() >= 0) || (args.GetY() >= 0)) && !args.IsHeadless()) {
685 if (!geometry.empty()) geometry.append(" ");
686 geometry.append("--window-position="s + std::to_string(args.GetX() >= 0 ? args.GetX() : 0) + ","s +
687 std::to_string(args.GetY() >= 0 ? args.GetY() : 0));
688 }
689
690 if (!args.GetExtraArgs().empty()) {
691 if (!geometry.empty()) geometry.append(" ");
692 geometry.append(args.GetExtraArgs());
693 }
694
695 exec = std::regex_replace(exec, std::regex("\\$geometry"), geometry);
696}
697
698
699//////////////////////////////////////////////////////////////////////////////////////////////////
700/// Handle profile argument
701
702std::string RWebDisplayHandle::ChromeCreator::MakeProfile(std::string &exec, bool)
703{
704 std::string rmdir, profile_arg;
705
706 if (exec.find("$profile") == std::string::npos)
707 return rmdir;
708
709 const char *chrome_profile = gEnv->GetValue((fEnvPrefix + "Profile").c_str(), "");
712 } else {
714 rnd.SetSeed(0);
716 if ((profile_arg.compare(0, 4, "/tmp") == 0) && IsSnapBrowser())
718
719#ifdef _MSC_VER
720 char slash = '\\';
721#else
722 char slash = '/';
723#endif
724 if (!profile_arg.empty() && (profile_arg[profile_arg.length()-1] != slash))
726 profile_arg += "root_chrome_profile_"s + std::to_string(rnd.Integer(0x100000));
727
728 rmdir = profile_arg;
729 }
730
731 exec = std::regex_replace(exec, std::regex("\\$profile"), profile_arg);
732
733 return rmdir;
734}
735
736
737//////////////////////////////////////////////////////////////////////////////////////////////////
738/// Constructor
739
741{
742 TestProg(gEnv->GetValue("WebGui.Firefox", ""));
743
744#ifdef _MSC_VER
745 TestProg("\\Mozilla Firefox\\firefox.exe", true);
746#endif
747#ifdef R__MACOSX
748 TestProg("/Applications/Firefox.app/Contents/MacOS/firefox");
749#endif
750#ifdef R__LINUX
751 TestProg("/snap/bin/firefox");
752 TestProg("/usr/bin/firefox");
753 TestProg("/usr/bin/firefox-bin");
754#endif
755
756#ifdef _MSC_VER
757 // there is a problem when specifying the window size with wmic on windows:
758 // It gives: Invalid format. Hint: <paramlist> = <param> [, <paramlist>].
759 fBatchExec = gEnv->GetValue("WebGui.FirefoxBatch", "$prog -headless -no-remote $profile $url");
760 fHeadlessExec = gEnv->GetValue("WebGui.FirefoxHeadless", "fork:-headless -no-remote $profile \"$url\"");
761 fExec = gEnv->GetValue("WebGui.FirefoxInteractive", "$prog -no-remote $profile $geometry $url &");
762#else
763 fBatchExec = gEnv->GetValue("WebGui.FirefoxBatch", "fork:--headless -no-remote -new-instance $profile $url");
764 fHeadlessExec = gEnv->GetValue("WebGui.FirefoxHeadless", "fork:--headless -no-remote $profile --private-window $url");
765 fExec = gEnv->GetValue("WebGui.FirefoxInteractive", "$rootetcdir/runfirefox.sh __nodump__ $cleanup_profile $prog -no-remote $profile $geometry -url \'$url\' &");
766#endif
767}
768
769//////////////////////////////////////////////////////////////////////////////////////////////////
770/// Process window geometry for Firefox
771
773{
774 std::string geometry;
775 if ((args.GetWidth() > 0) && (args.GetHeight() > 0) && !args.IsHeadless())
776 geometry = "-width="s + std::to_string(args.GetWidth()) + " -height=" + std::to_string(args.GetHeight());
777
778 exec = std::regex_replace(exec, std::regex("\\$geometry"), geometry);
779}
780
781//////////////////////////////////////////////////////////////////////////////////////////////////
782/// Create Firefox profile to run independent browser window
783
785{
786 std::string rmdir, profile_arg;
787
788 if (exec.find("$profile") == std::string::npos)
789 return rmdir;
790
791 const char *ff_profile = gEnv->GetValue("WebGui.FirefoxProfile", "");
792 const char *ff_profilepath = gEnv->GetValue("WebGui.FirefoxProfilePath", "");
793 Int_t ff_randomprofile = RWebWindowWSHandler::GetBoolEnv("WebGui.FirefoxRandomProfile", 1);
794 if (ff_profile && *ff_profile) {
795 profile_arg = "-P "s + ff_profile;
796 } else if (ff_profilepath && *ff_profilepath) {
797 profile_arg = "-profile "s + ff_profilepath;
798 } else if (ff_randomprofile > 0) {
800 rnd.SetSeed(0);
801 std::string profile_dir = gSystem->TempDirectory();
802 if ((profile_dir.compare(0, 4, "/tmp") == 0) && IsSnapBrowser())
804
805#ifdef _MSC_VER
806 char slash = '\\';
807#else
808 char slash = '/';
809#endif
810 if (!profile_dir.empty() && (profile_dir[profile_dir.length()-1] != slash))
812 profile_dir += "root_ff_profile_"s + std::to_string(rnd.Integer(0x100000));
813
814 profile_arg = "-profile "s + profile_dir;
815
816 if (gSystem->mkdir(profile_dir.c_str()) == 0) {
817 rmdir = profile_dir;
818
819 std::ofstream user_js(profile_dir + "/user.js", std::ios::trunc);
820 // workaround for current Firefox, without such settings it fail to close window and terminate it from batch
821 // also disable question about upload of data
822 user_js << "user_pref(\"datareporting.policy.dataSubmissionPolicyAcceptedVersion\", 2);" << std::endl;
823 user_js << "user_pref(\"datareporting.policy.dataSubmissionPolicyNotifiedTime\", \"1635760572813\");" << std::endl;
824
825 // try to ensure that window closes with last tab
826 user_js << "user_pref(\"browser.tabs.closeWindowWithLastTab\", true);" << std::endl;
827 user_js << "user_pref(\"dom.allow_scripts_to_close_windows\", true);" << std::endl;
828 user_js << "user_pref(\"browser.sessionstore.resume_from_crash\", false);" << std::endl;
829
830 if (batch_mode) {
831 // allow to dump messages to std output
832 user_js << "user_pref(\"browser.dom.window.dump.enabled\", true);" << std::endl;
833 } else {
834 // to suppress annoying privacy tab
835 user_js << "user_pref(\"datareporting.policy.firstRunURL\", \"\");" << std::endl;
836 // to use custom userChrome.css files
837 user_js << "user_pref(\"toolkit.legacyUserProfileCustomizations.stylesheets\", true);" << std::endl;
838 // do not put tabs in title
839 user_js << "user_pref(\"browser.tabs.inTitlebar\", 0);" << std::endl;
840
841#ifdef R__LINUX
842 // fix WebGL creation problem on some Linux platforms
843 user_js << "user_pref(\"webgl.out-of-process\", false);" << std::endl;
844#endif
845
846 std::ofstream times_json(profile_dir + "/times.json", std::ios::trunc);
847 times_json << "{" << std::endl;
848 times_json << " \"created\": 1699968480952," << std::endl;
849 times_json << " \"firstUse\": null" << std::endl;
850 times_json << "}" << std::endl;
851 if (gSystem->mkdir((profile_dir + "/chrome").c_str()) == 0) {
852 std::ofstream style(profile_dir + "/chrome/userChrome.css", std::ios::trunc);
853 // do not show tabs
854 style << "#TabsToolbar { visibility: collapse; }" << std::endl;
855 // do not show URL
856 style << "#nav-bar, #urlbar-container, #searchbar { visibility: collapse !important; }" << std::endl;
857 }
858 }
859
860 } else {
861 R__LOG_ERROR(WebGUILog()) << "Cannot create Firefox profile directory " << profile_dir;
862 }
863 }
864
865 exec = std::regex_replace(exec, std::regex("\\$profile"), profile_arg);
866
867 if (exec.find("$cleanup_profile") != std::string::npos) {
868 if (rmdir.empty()) rmdir = "__dummy__";
869 exec = std::regex_replace(exec, std::regex("\\$cleanup_profile"), rmdir);
870 rmdir.clear(); // no need to delete directory - it will be removed by script
871 }
872
873 return rmdir;
874}
875
876///////////////////////////////////////////////////////////////////////////////////////////////////
877/// Check if http server required for display
878/// \param args - defines where and how to display web window
879
881{
884 return false;
885
886 if (!args.IsHeadless() && (args.GetBrowserKind() == RWebDisplayArgs::kOn)) {
887
888#ifdef WITH_QT6WEB
889 auto &qt6 = FindCreator("qt6", "libROOTQt6WebDisplay");
890 if (qt6 && qt6->IsActive())
891 return false;
892#endif
893#ifdef WITH_CEFWEB
894 auto &cef = FindCreator("cef", "libROOTCefDisplay");
895 if (cef && cef->IsActive())
896 return false;
897#endif
898 }
899
900 return true;
901}
902
903
904///////////////////////////////////////////////////////////////////////////////////////////////////
905/// Create web display
906/// \param args - defines where and how to display web window
907/// Returns RWebDisplayHandle, which holds information of running browser application
908/// Can be used fully independent from RWebWindow classes just to show any web page
909
910std::unique_ptr<RWebDisplayHandle> RWebDisplayHandle::Display(const RWebDisplayArgs &args)
911{
912 std::unique_ptr<RWebDisplayHandle> handle;
913
915 return handle;
916
917 auto try_creator = [&](std::unique_ptr<Creator> &creator) {
918 if (!creator || !creator->IsActive())
919 return false;
920 handle = creator->Display(args);
921 return handle ? true : false;
922 };
923
925 (!args.IsHeadless() && (args.GetBrowserKind() == RWebDisplayArgs::kOn)),
926 has_qt6web = false, has_cefweb = false;
927
928#ifdef WITH_QT6WEB
929 has_qt6web = true;
930#endif
931
932#ifdef WITH_CEFWEB
933 has_cefweb = true;
934#endif
935
937 if (try_creator(FindCreator("qt6", "libROOTQt6WebDisplay")))
938 return handle;
939 }
940
942 if (try_creator(FindCreator("cef", "libROOTCefDisplay")))
943 return handle;
944 }
945
946 if (args.IsLocalDisplay()) {
947 R__LOG_ERROR(WebGUILog()) << "Neither Qt5/6 nor CEF libraries were found to provide local display";
948 return handle;
949 }
950
951 bool handleAsNative =
953
955 if (try_creator(FindCreator("chrome", "ChromeCreator")))
956 return handle;
957 }
958
960 if (try_creator(FindCreator("firefox", "FirefoxCreator")))
961 return handle;
962 }
963
964#ifdef _MSC_VER
965 // Edge browser cannot be run headless without registry change, therefore do not try it by default
966 if ((handleAsNative && !args.IsHeadless() && !args.IsBatchMode()) || (args.GetBrowserKind() == RWebDisplayArgs::kEdge)) {
967 if (try_creator(FindCreator("edge", "ChromeCreator")))
968 return handle;
969 }
970#endif
971
974 // R__LOG_ERROR(WebGUILog()) << "Neither Chrome nor Firefox browser cannot be started to provide display";
975 return handle;
976 }
977
979 if (try_creator(FindCreator("safari", "SafariCreator")))
980 return handle;
981 }
982
984 std::unique_ptr<Creator> creator = std::make_unique<BrowserCreator>(false, args.GetCustomExec());
985 try_creator(creator);
986 } else {
987 try_creator(FindCreator("browser", "BrowserCreator"));
988 }
989
990 return handle;
991}
992
993///////////////////////////////////////////////////////////////////////////////////////////////////
994/// Display provided url in configured web browser
995/// \param url - specified URL address like https://root.cern
996/// Browser can specified when starting `root --web=firefox`
997/// Returns true when browser started
998/// It is convenience method, equivalent to:
999/// ~~~
1000/// RWebDisplayArgs args;
1001/// args.SetUrl(url);
1002/// args.SetStandalone(false);
1003/// auto handle = RWebDisplayHandle::Display(args);
1004/// ~~~
1005
1006bool RWebDisplayHandle::DisplayUrl(const std::string &url)
1007{
1008 RWebDisplayArgs args;
1009 args.SetUrl(url);
1010 args.SetStandalone(false);
1011
1012 auto handle = Display(args);
1013
1014 return !!handle;
1015}
1016
1017///////////////////////////////////////////////////////////////////////////////////////////////////
1018/// Checks if configured browser can be used for image production
1019
1021{
1025 bool detected = false;
1026
1027 auto &h1 = FindCreator("chrome", "ChromeCreator");
1028 if (h1 && h1->IsActive()) {
1030 detected = true;
1031 }
1032
1033 if (!detected) {
1034 auto &h2 = FindCreator("firefox", "FirefoxCreator");
1035 if (h2 && h2->IsActive()) {
1037 detected = true;
1038 }
1039 }
1040
1041 return detected;
1042 }
1043
1045 auto &h1 = FindCreator("chrome", "ChromeCreator");
1046 return h1 && h1->IsActive();
1047 }
1048
1050 auto &h2 = FindCreator("firefox", "FirefoxCreator");
1051 return h2 && h2->IsActive();
1052 }
1053
1054#ifdef _MSC_VER
1055 if (args.GetBrowserKind() == RWebDisplayArgs::kEdge) {
1056 auto &h3 = FindCreator("edge", "ChromeCreator");
1057 return h3 && h3->IsActive();
1058 }
1059#endif
1060
1061 return true;
1062}
1063
1064///////////////////////////////////////////////////////////////////////////////////////////////////
1065/// Returns true if image production for specified browser kind is supported
1066/// If browser not specified - use currently configured browser or try to test existing web browsers
1067
1069{
1071
1072 return CheckIfCanProduceImages(args);
1073}
1074
1075///////////////////////////////////////////////////////////////////////////////////////////////////
1076/// Detect image format
1077/// There is special handling of ".screenshot.pdf" and ".screenshot.png" extensions
1078/// Creation of such files relies on headless browser functionality and fully supported only by Chrome browser
1079
1080std::string RWebDisplayHandle::GetImageFormat(const std::string &fname)
1081{
1082 std::string _fname = fname;
1083 std::transform(_fname.begin(), _fname.end(), _fname.begin(), ::tolower);
1084 auto EndsWith = [&_fname](const std::string &suffix) {
1085 return (_fname.length() > suffix.length()) ? (0 == _fname.compare(_fname.length() - suffix.length(), suffix.length(), suffix)) : false;
1086 };
1087
1088 if (EndsWith(".screenshot.pdf"))
1089 return "s.pdf"s;
1090 if (EndsWith(".pdf"))
1091 return "pdf"s;
1092 if (EndsWith(".json"))
1093 return "json"s;
1094 if (EndsWith(".svg"))
1095 return "svg"s;
1096 if (EndsWith(".screenshot.png"))
1097 return "s.png"s;
1098 if (EndsWith(".png"))
1099 return "png"s;
1100 if (EndsWith(".jpg") || EndsWith(".jpeg"))
1101 return "jpeg"s;
1102 if (EndsWith(".webp"))
1103 return "webp"s;
1104
1105 return ""s;
1106}
1107
1108
1109///////////////////////////////////////////////////////////////////////////////////////////////////
1110/// Produce image file using JSON data as source
1111/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1112
1113bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string &json, int width, int height, const char *batch_file)
1114{
1115 return ProduceImages(fname, {json}, {width}, {height}, batch_file);
1116}
1117
1118
1119///////////////////////////////////////////////////////////////////////////////////////////////////
1120/// Produce vector of file names for specified file pattern
1121/// Depending from supported file forma
1122
1123std::vector<std::string> RWebDisplayHandle::ProduceImagesNames(const std::string &fname, unsigned nfiles)
1124{
1125 auto fmt = GetImageFormat(fname);
1126
1127 std::vector<std::string> fnames;
1128
1129 if ((fmt == "s.pdf") || (fmt == "s.png")) {
1130 fnames.emplace_back(fname);
1131 } else {
1132 std::string farg = fname;
1133
1134 bool has_quialifier = farg.find("%") != std::string::npos;
1135
1136 if (!has_quialifier && (nfiles > 1) && (fmt != "pdf")) {
1137 farg.insert(farg.rfind("."), "%d");
1138 has_quialifier = true;
1139 }
1140
1141 for (unsigned n = 0; n < nfiles; n++) {
1142 if(has_quialifier) {
1143 auto expand_name = TString::Format(farg.c_str(), (int) n);
1144 fnames.emplace_back(expand_name.Data());
1145 } else if (n > 0)
1146 fnames.emplace_back(""); // empty name is multiPdf
1147 else
1148 fnames.emplace_back(fname);
1149 }
1150 }
1151
1152 return fnames;
1153}
1154
1155
1156///////////////////////////////////////////////////////////////////////////////////////////////////
1157/// Produce image file(s) using JSON data as source
1158/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1159
1160bool RWebDisplayHandle::ProduceImages(const std::string &fname, const std::vector<std::string> &jsons, const std::vector<int> &widths, const std::vector<int> &heights, const char *batch_file)
1161{
1163}
1164
1165///////////////////////////////////////////////////////////////////////////////////////////////////
1166/// Produce image file(s) using JSON data as source
1167/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1168
1169bool RWebDisplayHandle::ProduceImages(const std::vector<std::string> &fnames, const std::vector<std::string> &jsons, const std::vector<int> &widths, const std::vector<int> &heights, const char *batch_file)
1170{
1171 if (fnames.empty() || jsons.empty())
1172 return false;
1173
1174 std::vector<std::string> fmts;
1175 for (auto& fname : fnames)
1176 fmts.emplace_back(GetImageFormat(fname));
1177
1178 bool is_any_image = false;
1179
1180 for (unsigned n = 0; (n < fmts.size()) && (n < jsons.size()); n++) {
1181 if (fmts[n] == "json") {
1182 std::ofstream ofs(fnames[n]);
1183 ofs << jsons[n];
1184 fmts[n].clear();
1185 } else if (!fmts[n].empty())
1186 is_any_image = true;
1187 }
1188
1189 if (!is_any_image)
1190 return true;
1191
1192 std::string fdebug;
1193 if (fnames.size() == 1)
1194 fdebug = fnames[0];
1195 else
1197
1198 const char *jsrootsys = gSystem->Getenv("JSROOTSYS");
1200 if (!jsrootsys) {
1201 jsrootsysdflt = TROOT::GetDataDir() + "/js";
1203 R__LOG_ERROR(WebGUILog()) << "Fail to locate JSROOT " << jsrootsysdflt;
1204 return false;
1205 }
1206 jsrootsys = jsrootsysdflt.Data();
1207 }
1208
1209 RWebDisplayArgs args; // set default browser kind, only Chrome/Firefox/Edge or CEF/Qt5/Qt6 can be used here
1210 if (!CheckIfCanProduceImages(args)) {
1211 R__LOG_ERROR(WebGUILog()) << "Fail to detect supported browsers for image production";
1212 return false;
1213 }
1214
1218
1219 std::vector<std::string> draw_kinds;
1220 bool use_browser_draw = false, can_optimize_json = false;
1221 int use_home_dir = 0;
1223
1224 // Some Chrome installation do not allow run html code from files, created in /tmp directory
1225 // When during session such failures happened, force usage of home directory from the beginning
1226 static int chrome_tmp_workaround = 0;
1227
1228 if (isChrome) {
1230 auto &h1 = FindCreator("chrome", "ChromeCreator");
1231 if (h1 && h1->IsActive() && h1->IsSnapBrowser() && (use_home_dir == 0))
1232 use_home_dir = 1;
1233 }
1234
1235 if (fmts[0] == "s.png") {
1236 if (!isChromeBased && !isFirefox) {
1237 R__LOG_ERROR(WebGUILog()) << "Direct png image creation supported only by Chrome and Firefox browsers";
1238 return false;
1239 }
1240 use_browser_draw = true;
1241 jsonkind = "1111"; // special mark in canv_batch.htm
1242 } else if (fmts[0] == "s.pdf") {
1243 if (!isChromeBased) {
1244 R__LOG_ERROR(WebGUILog()) << "Direct creation of PDF files supported only by Chrome-based browser";
1245 return false;
1246 }
1247 use_browser_draw = true;
1248 jsonkind = "2222"; // special mark in canv_batch.htm
1249 } else {
1250 draw_kinds = fmts;
1252 can_optimize_json = true;
1253 }
1254
1255 if (!batch_file || !*batch_file)
1256 batch_file = "/js/files/canv_batch.htm";
1257
1260 R__LOG_ERROR(WebGUILog()) << "Fail to find " << origin;
1261 return false;
1262 }
1263
1265 if (filecont.empty()) {
1266 R__LOG_ERROR(WebGUILog()) << "Fail to read content of " << origin;
1267 return false;
1268 }
1269
1270 int max_width = 0, max_height = 0, page_margin = 10;
1271 for (auto &w : widths)
1272 if (w > max_width)
1273 max_width = w;
1274 for (auto &h : heights)
1275 if (h > max_height)
1276 max_height = h;
1277
1280
1281 std::string mains, prev;
1282 for (auto &json : jsons) {
1283 mains.append(mains.empty() ? "[" : ", ");
1284 if (can_optimize_json && (json == prev)) {
1285 mains.append("'same'");
1286 } else {
1287 mains.append(json);
1288 prev = json;
1289 }
1290 }
1291 mains.append("]");
1292
1293 if (strstr(jsrootsys, "http://") || strstr(jsrootsys, "https://") || strstr(jsrootsys, "file://"))
1294 filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), jsrootsys);
1295 else {
1296 static std::string jsroot_include = "<script id=\"jsroot\" src=\"$jsrootsys/build/jsroot.js\"></script>";
1297 auto p = filecont.find(jsroot_include);
1298 if (p != std::string::npos) {
1299 auto jsroot_build = THttpServer::ReadFileContent(std::string(jsrootsys) + "/build/jsroot.js");
1300 if (!jsroot_build.empty()) {
1301 // insert actual jsroot file location
1302 jsroot_build = std::regex_replace(jsroot_build, std::regex("'\\$jsrootsys'"), std::string("'file://") + jsrootsys + "/'");
1303 filecont.erase(p, jsroot_include.length());
1304 filecont.insert(p, "<script id=\"jsroot\">" + jsroot_build + "</script>");
1305 }
1306 }
1307
1308 filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), "file://"s + jsrootsys);
1309 }
1310
1311 filecont = std::regex_replace(filecont, std::regex("\\$page_margin"), std::to_string(page_margin) + "px");
1312 filecont = std::regex_replace(filecont, std::regex("\\$page_width"), std::to_string(max_width + 2*page_margin) + "px");
1313 filecont = std::regex_replace(filecont, std::regex("\\$page_height"), std::to_string(max_height + 2*page_margin) + "px");
1314
1315 filecont = std::regex_replace(filecont, std::regex("\\$draw_kind"), jsonkind.Data());
1316 filecont = std::regex_replace(filecont, std::regex("\\$draw_widths"), jsonw.Data());
1317 filecont = std::regex_replace(filecont, std::regex("\\$draw_heights"), jsonh.Data());
1318 filecont = std::regex_replace(filecont, std::regex("\\$draw_objects"), mains);
1319
1321
1323 dump_name = "canvasdump";
1325 if (!df) {
1326 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary file for dump-dom";
1327 return false;
1328 }
1329 fputs("placeholder", df);
1330 fclose(df);
1331 }
1332
1333try_again:
1334
1336 args.SetUrl(""s);
1338
1339 html_name.Clear();
1340
1341 R__LOG_DEBUG(0, WebGUILog()) << "Using file content_len " << filecont.length() << " to produce batch images ";
1342
1343 } else {
1344 html_name = "canvasbody";
1346 if (!hf) {
1347 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary file for batch job";
1348 return false;
1349 }
1350 fputs(filecont.c_str(), hf);
1351 fclose(hf);
1352
1353 args.SetUrl("file://"s + gSystem->UnixPathName(html_name.Data()));
1354 args.SetPageContent(""s);
1355
1356 R__LOG_DEBUG(0, WebGUILog()) << "Using " << html_name << " content_len " << filecont.length() << " to produce batch images " << fdebug;
1357 }
1358
1360
1361 args.SetStandalone(true);
1362 args.SetHeadless(true);
1363 args.SetBatchMode(true);
1364 args.SetSize(widths[0], heights[0]);
1365
1366 if (use_browser_draw) {
1367
1368 tgtfilename = fnames[0].c_str();
1371
1373
1374 if (fmts[0] == "s.pdf")
1375 args.SetExtraArgs("--print-to-pdf-no-header --print-to-pdf="s + gSystem->UnixPathName(tgtfilename.Data()));
1376 else if (isFirefox) {
1377 args.SetExtraArgs("--screenshot"); // firefox does not let specify output image file
1378 wait_file_name = "screenshot.png";
1379 } else
1380 args.SetExtraArgs("--screenshot="s + gSystem->UnixPathName(tgtfilename.Data()));
1381
1382 // remove target image file - we use it as detection when chrome is ready
1383 gSystem->Unlink(tgtfilename.Data());
1384
1385 } else if (isFirefox) {
1386 // firefox will use window.dump to output produced result
1387 args.SetRedirectOutput(dump_name.Data());
1388 gSystem->Unlink(dump_name.Data());
1389 } else if (isChromeBased) {
1390 // chrome should have --dump-dom args configures
1391 args.SetRedirectOutput(dump_name.Data());
1392 gSystem->Unlink(dump_name.Data());
1393 }
1394
1395 auto handle = RWebDisplayHandle::Display(args);
1396
1397 if (!handle) {
1398 R__LOG_DEBUG(0, WebGUILog()) << "Cannot start " << args.GetBrowserName() << " to produce image " << fdebug;
1399 return false;
1400 }
1401
1402 // delete temporary HTML file
1403 if (html_name.Length() > 0) {
1404 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
1405 ::Info("ProduceImages", "Preserve batch file %s", html_name.Data());
1406 else
1407 gSystem->Unlink(html_name.Data());
1408 }
1409
1410 if (!wait_file_name.IsNull() && gSystem->AccessPathName(wait_file_name.Data())) {
1411 R__LOG_ERROR(WebGUILog()) << "Fail to produce image " << fdebug;
1412 return false;
1413 }
1414
1415 if (use_browser_draw) {
1416 if (fmts[0] == "s.pdf")
1417 ::Info("ProduceImages", "PDF file %s with %d pages has been created", fnames[0].c_str(), (int) jsons.size());
1418 else {
1419 if (isFirefox)
1420 gSystem->Rename("screenshot.png", fnames[0].c_str());
1421 ::Info("ProduceImages", "PNG file %s with %d pages has been created", fnames[0].c_str(), (int) jsons.size());
1422 }
1423 } else {
1424 auto dumpcont = handle->GetContent();
1425
1426 if ((dumpcont.length() > 20) && (dumpcont.length() < 60) && (use_home_dir < 2) && isChrome) {
1427 // chrome creates dummy html file with mostly no content
1428 // problem running chrome from /tmp directory, lets try work from home directory
1429 R__LOG_INFO(WebGUILog()) << "Use home directory for running chrome in batch, set TMPDIR for preferable temp directory";
1431 goto try_again;
1432 }
1433
1434 if (dumpcont.length() < 100) {
1435 R__LOG_ERROR(WebGUILog()) << "Fail to dump HTML code into " << (dump_name.IsNull() ? "CEF" : dump_name.Data());
1436 return false;
1437 }
1438
1439 std::string::size_type p = 0;
1440
1441 for (unsigned n = 0; n < fmts.size(); n++) {
1442 if (fmts[n].empty())
1443 continue;
1444 if (fmts[n] == "svg") {
1445 auto p1 = dumpcont.find("<div><svg", p);
1446 auto p2 = dumpcont.find("</svg></div>", p1 + 8);
1447 p = p2 + 12;
1448 std::ofstream ofs(fnames[n]);
1449 if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) {
1450 if (p2 - p1 > 10) {
1451 ofs << dumpcont.substr(p1 + 5, p2 - p1 + 1);
1452 ::Info("ProduceImages", "Image file %s size %d bytes has been created", fnames[n].c_str(), (int) (p2 - p1 + 1));
1453 } else {
1454 ::Error("ProduceImages", "Failure producing %s", fnames[n].c_str());
1455 }
1456 }
1457 } else {
1458 auto p0 = dumpcont.find("<img src=\"", p);
1459 auto p1 = dumpcont.find(";base64,", p0 + 8);
1460 auto p2 = dumpcont.find("\">", p1 + 8);
1461 p = p2 + 2;
1462
1463 if ((p0 != std::string::npos) && (p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) {
1464 auto base64 = dumpcont.substr(p1+8, p2-p1-8);
1465 if ((base64 == "failure") || (base64.length() < 10)) {
1466 ::Error("ProduceImages", "Failure producing %s", fnames[n].c_str());
1467 } else {
1468 auto binary = TBase64::Decode(base64.c_str());
1469 std::ofstream ofs(fnames[n], std::ios::binary);
1470 ofs.write(binary.Data(), binary.Length());
1471 ::Info("ProduceImages", "Image file %s size %d bytes has been created", fnames[n].c_str(), (int) binary.Length());
1472 }
1473 } else {
1474 ::Error("ProduceImages", "Failure producing %s", fnames[n].c_str());
1475 return false;
1476 }
1477 }
1478 }
1479 }
1480
1481 R__LOG_DEBUG(0, WebGUILog()) << "Create " << (fnames.size() > 1 ? "files " : "file ") << fdebug;
1482
1483 return true;
1484}
1485
nlohmann::json json
#define R__LOG_ERROR(...)
Definition RLogger.hxx:357
#define R__LOG_DEBUG(DEBUGLEVEL,...)
Definition RLogger.hxx:360
#define R__LOG_INFO(...)
Definition RLogger.hxx:359
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define h(i)
Definition RSha256.hxx:106
static void DummyTimeOutHandler(int)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
R__EXTERN TEnv * gEnv
Definition TEnv.h:170
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:241
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t width
Option_t Option_t style
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
char name[80]
Definition TGX11.cxx:110
@ kExecutePermission
Definition TSystem.h:53
R__EXTERN TSystem * gSystem
Definition TSystem.h:572
const_iterator begin() const
const_iterator end() const
Specialized handle to hold information about running browser process Used to correctly cleanup all pr...
RWebBrowserHandle(const std::string &url, const std::string &tmpdir, const std::string &tmpfile, browser_process_id pid)
std::string fTmpDir
temporary directory to delete at the end
void RemoveStartupFiles() override
remove file which was used to startup widget - if possible
RWebBrowserHandle(const std::string &url, const std::string &tmpdir, const std::string &tmpfile, const std::string &dump)
std::string fTmpFile
temporary file to remove
Holds different arguments for starting browser with RWebDisplayHandle::Display() method.
std::string GetBrowserName() const
Returns configured browser name.
EBrowserKind GetBrowserKind() const
returns configured browser kind, see EBrowserKind for supported values
const std::string & GetRedirectOutput() const
get file name to which web browser output should be redirected
void SetStandalone(bool on=true)
Set standalone mode for running browser, default on When disabled, normal browser window (or just tab...
void SetBatchMode(bool on=true)
set batch mode
RWebDisplayArgs & SetSize(int w, int h)
set preferable web window width and height
RWebDisplayArgs & SetUrl(const std::string &url)
set window url
int GetWidth() const
returns preferable web window width
RWebDisplayArgs & SetPageContent(const std::string &cont)
set window url
int GetY() const
set preferable web window y position
std::string GetFullUrl() const
returns window url with append options
bool IsStandalone() const
Return true if browser should runs in standalone mode.
int GetHeight() const
returns preferable web window height
RWebDisplayArgs & SetBrowserKind(const std::string &kind)
Set browser kind as string argument.
std::string GetCustomExec() const
returns custom executable to start web browser
void SetExtraArgs(const std::string &args)
set extra command line arguments for starting web browser command
bool IsBatchMode() const
returns batch mode
bool IsHeadless() const
returns headless mode
@ kOn
web display enable, first try use embed displays like Qt or CEF, then native browsers and at the end ...
@ kFirefox
Mozilla Firefox browser.
@ kNative
either Chrome or Firefox - both support major functionality
@ kLocal
either CEF or Qt5 - both runs on local display without real http server
@ kServer
indicates that ROOT runs as server and just printouts window URL, browser should be started by the us...
@ kOff
disable web display, do not start any browser
@ kCEF
Chromium Embedded Framework - local display with CEF libs.
@ kSafari
Safari browser.
@ kQt6
Qt6 QWebEngine libraries - Chromium code packed in qt6.
@ kCustom
custom web browser, execution string should be provided
@ kChrome
Google Chrome browser.
@ kEdge
Microsoft Edge browser (Windows only)
void SetRedirectOutput(const std::string &fname="")
specify file name to which web browser output should be redirected
void SetHeadless(bool on=true)
set headless mode
const std::string & GetExtraArgs() const
get extra command line arguments for starting web browser command
int GetX() const
set preferable web window x position
bool IsLocalDisplay() const
returns true if local display like CEF or Qt5 QWebEngine should be used
std::string fBatchExec
batch execute line
std::string fHeadlessExec
headless execute line
static FILE * TemporaryFile(TString &name, int use_home_dir=0, const char *suffix=nullptr)
Create temporary file for web display Normally gSystem->TempFileName() method used to create file in ...
std::unique_ptr< RWebDisplayHandle > Display(const RWebDisplayArgs &args) override
Display given URL in web browser.
std::string fExec
standard execute line
void TestProg(const std::string &nexttry, bool check_std_paths=false)
Check if browser executable exists and can be used.
BrowserCreator(bool custom=true, const std::string &exec="")
Class to handle starting of web-browsers like Chrome or Firefox.
ChromeCreator(bool is_edge=false)
Constructor.
void ProcessGeometry(std::string &, const RWebDisplayArgs &) override
Replace $geometry placeholder with geometry settings Also RWebDisplayArgs::GetExtraArgs() are appende...
std::string MakeProfile(std::string &exec, bool) override
Handle profile argument.
std::string MakeProfile(std::string &exec, bool batch) override
Create Firefox profile to run independent browser window.
void ProcessGeometry(std::string &, const RWebDisplayArgs &) override
Process window geometry for Firefox.
bool IsActive() const override
Returns true if it can be used.
Handle of created web-based display Depending from type of web display, holds handle of started brows...
static std::map< std::string, std::unique_ptr< Creator > > & GetMap()
Static holder of registered creators of web displays.
static bool CheckIfCanProduceImages(RWebDisplayArgs &args)
Checks if configured browser can be used for image production.
static bool ProduceImages(const std::string &fname, const std::vector< std::string > &jsons, const std::vector< int > &widths, const std::vector< int > &heights, const char *batch_file=nullptr)
Produce image file(s) using JSON data as source Invokes JSROOT drawing functionality in headless brow...
static std::vector< std::string > ProduceImagesNames(const std::string &fname, unsigned nfiles=1)
Produce vector of file names for specified file pattern Depending from supported file forma.
static std::string GetImageFormat(const std::string &fname)
Detect image format There is special handling of ".screenshot.pdf" and ".screenshot....
void SetContent(const std::string &cont)
set content
static bool ProduceImage(const std::string &fname, const std::string &json, int width=800, int height=600, const char *batch_file=nullptr)
Produce image file using JSON data as source Invokes JSROOT drawing functionality in headless browser...
static bool CanProduceImages(const std::string &browser="")
Returns true if image production for specified browser kind is supported If browser not specified - u...
static bool NeedHttpServer(const RWebDisplayArgs &args)
Check if http server required for display.
static bool DisplayUrl(const std::string &url)
Display provided url in configured web browser.
static std::unique_ptr< RWebDisplayHandle > Display(const RWebDisplayArgs &args)
Create web display.
static std::unique_ptr< Creator > & FindCreator(const std::string &name, const std::string &libname="")
Search for specific browser creator If not found, try to add one.
static int GetBoolEnv(const std::string &name, int dfl=-1)
Parse boolean gEnv variable which should be "yes" or "no".
static TString Decode(const char *data)
Decode a base64 string date into a generic TString.
Definition TBase64.cxx:131
static TString ToJSON(const T *obj, Int_t compact=0, const char *member_name=nullptr)
Definition TBufferJSON.h:75
@ kNoSpaces
no new lines plus remove all spaces around "," and ":" symbols
Definition TBufferJSON.h:39
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:491
static char * ReadFileContent(const char *filename, Int_t &len)
Reads content of file from the disk.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:544
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3108
static const TString & GetDataDir()
Get the data directory in the installation. Static utility function.
Definition TROOT.cxx:3118
Random number generator class based on M.
Definition TRandom3.h:27
Basic string class.
Definition TString.h:138
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2271
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:2385
virtual FILE * TempFileName(TString &base, const char *dir=nullptr, const char *suffix=nullptr)
Create a secure temporary file by appending a unique 6 letter string to base.
Definition TSystem.cxx:1512
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1287
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1678
virtual int mkdir(const char *name, Bool_t recursive=kFALSE)
Make a file system directory.
Definition TSystem.cxx:918
virtual Int_t Exec(const char *shellcmd)
Execute a command.
Definition TSystem.cxx:653
virtual int Load(const char *module, const char *entry="", Bool_t system=kFALSE)
Load a shared library.
Definition TSystem.cxx:1870
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1094
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:1309
virtual std::string GetHomeDirectory(const char *userName=nullptr) const
Return the user's home directory.
Definition TSystem.cxx:907
virtual const char * UnixPathName(const char *unixpathname)
Convert from a local pathname to a Unix pathname.
Definition TSystem.cxx:1075
virtual int Rename(const char *from, const char *to)
Rename a file.
Definition TSystem.cxx:1363
virtual TString GetFromPipe(const char *command, Int_t *ret=nullptr, Bool_t redirectStderr=kFALSE)
Execute command and return output in TString.
Definition TSystem.cxx:686
virtual Bool_t IsAbsoluteFileName(const char *dir)
Return true if dir is an absolute pathname.
Definition TSystem.cxx:963
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:883
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1394
virtual const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Definition TSystem.cxx:1495
const Int_t n
Definition legend1.C:16
TH1F * h1
Definition legend1.C:5
Namespace for new ROOT classes and functions.
ROOT::RLogChannel & WebGUILog()
Log channel for WebGUI diagnostics.
TCanvas * slash()
Definition slash.C:1
TMarker m
Definition textangle.C:8