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
267std::unique_ptr<RWebDisplayHandle>
269{
270 std::string url = args.GetFullUrl();
271 if (url.empty())
272 return nullptr;
273
275 std::cout << "New web window: " << url << std::endl;
276 return std::make_unique<RWebBrowserHandle>(url, "", "", "");
277 }
278
279 std::string exec;
280 if (args.IsBatchMode())
281 exec = fBatchExec;
282 else if (args.IsHeadless())
283 exec = fHeadlessExec;
284 else if (args.IsStandalone())
285 exec = fExec;
286 else
287 exec = "$prog $url &";
288
289 if (exec.empty())
290 return nullptr;
291
292 std::string swidth = std::to_string(args.GetWidth() > 0 ? args.GetWidth() : 800),
293 sheight = std::to_string(args.GetHeight() > 0 ? args.GetHeight() : 600),
294 sposx = std::to_string(args.GetX() >= 0 ? args.GetX() : 0),
295 sposy = std::to_string(args.GetY() >= 0 ? args.GetY() : 0);
296
297 ProcessGeometry(exec, args);
298
299 std::string rmdir = MakeProfile(exec, args.IsBatchMode() || args.IsHeadless());
300
301 std::string tmpfile;
302
303 // these are secret parameters, hide them in temp file
304 if (((url.find("token=") != std::string::npos) || (url.find("key=") != std::string::npos)) && !args.IsBatchMode() && !args.IsHeadless()) {
305 TString filebase = "root_start_";
306
307 auto f = TemporaryFile(filebase, IsSnapBrowser() ? 1 : 0, ".html");
308
309 bool ferr = false;
310
311 if (!f) {
312 ferr = true;
313 } else {
314 std::string content = std::regex_replace(
315 "<!DOCTYPE html>\n"
316 "<html lang=\"en\">\n"
317 "<head>\n"
318 " <meta charset=\"utf-8\">\n"
319 " <meta http-equiv=\"refresh\" content=\"0;url=$url\"/>\n"
320 " <title>Opening ROOT widget</title>\n"
321 "</head>\n"
322 "<body>\n"
323 "<p>\n"
324 " This page should redirect you to a ROOT widget. If it doesn't,\n"
325 " <a href=\"$url\">click here to go to ROOT</a>.\n"
326 "</p>\n"
327 "</body>\n"
328 "</html>\n", std::regex("\\$url"), url);
329
330 if (fwrite(content.c_str(), 1, content.length(), f) != content.length())
331 ferr = true;
332
333 if (fclose(f) != 0)
334 ferr = true;
335
336 tmpfile = filebase.Data();
337
338 url = "file://"s + tmpfile;
339 }
340
341 if (ferr) {
342 if (!tmpfile.empty())
343 gSystem->Unlink(tmpfile.c_str());
344 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary HTML file to startup widget";
345 return nullptr;
346 }
347 }
348
349 exec = std::regex_replace(exec, std::regex("\\$rootetcdir"), TROOT::GetEtcDir().Data());
350 exec = std::regex_replace(exec, std::regex("\\$url"), url);
351 exec = std::regex_replace(exec, std::regex("\\$width"), swidth);
352 exec = std::regex_replace(exec, std::regex("\\$height"), sheight);
353 exec = std::regex_replace(exec, std::regex("\\$posx"), sposx);
354 exec = std::regex_replace(exec, std::regex("\\$posy"), sposy);
355
356 if (exec.compare(0,5,"fork:") == 0) {
357 if (fProg.empty()) {
358 if (!tmpfile.empty())
359 gSystem->Unlink(tmpfile.c_str());
360 R__LOG_ERROR(WebGUILog()) << "Fork instruction without executable";
361 return nullptr;
362 }
363
364 exec.erase(0, 5);
365
366 // in case of redirection process will wait until output is produced
367 std::string redirect = args.GetRedirectOutput();
368
369#ifndef _MSC_VER
370
371 std::unique_ptr<TObjArray> fargs(TString(exec.c_str()).Tokenize(" "));
372 if (!fargs || (fargs->GetLast()<=0)) {
373 if (!tmpfile.empty())
374 gSystem->Unlink(tmpfile.c_str());
375 R__LOG_ERROR(WebGUILog()) << "Fork instruction is empty";
376 return nullptr;
377 }
378
379 std::vector<char *> argv;
380 argv.push_back((char *) fProg.c_str());
381 for (Int_t n = 0; n <= fargs->GetLast(); ++n)
382 argv.push_back((char *)fargs->At(n)->GetName());
383 argv.push_back(nullptr);
384
385 R__LOG_DEBUG(0, WebGUILog()) << "Show web window in browser with posix_spawn:\n" << fProg << " " << exec;
386
389 if (redirect.empty())
391 else
394
395#ifdef R__MACOSX
396 char **envp = *_NSGetEnviron();
397#elif defined (__FreeBSD__)
398 //this is needed because the FreeBSD linker does not like to resolve these special symbols
399 //in shared libs with -Wl,--no-undefined
400 char** envp = (char**)dlsym(RTLD_DEFAULT, "environ");
401#else
402 char **envp = environ;
403#endif
404
405 pid_t pid;
406 int status = posix_spawn(&pid, argv[0], &action, nullptr, argv.data(), envp);
407
409
410 if (status != 0) {
411 if (!tmpfile.empty())
412 gSystem->Unlink(tmpfile.c_str());
413 R__LOG_ERROR(WebGUILog()) << "Fail to launch " << argv[0];
414 return nullptr;
415 }
416
417 if (!redirect.empty()) {
418 Int_t batch_timeout = gEnv->GetValue("WebGui.BatchTimeout", 30);
419 struct sigaction Act, Old;
420 int elapsed_time = 0;
421
422 if (batch_timeout) {
423 memset(&Act, 0, sizeof(Act));
424 Act.sa_handler = DummyTimeOutHandler;
425 sigemptyset(&Act.sa_mask);
430 }
431
432 int job_done = 0;
433 std::string dump_content;
434
435 while (!job_done) {
436
437 // wait until output is produced
438 int wait_status = 0;
439
441
442 // try read dump anyway
444
445 if (dump_content.find("<div>###batch###job###done###</div>") != std::string::npos)
446 job_done = 1;
447
448 if (wait_res == -1) {
449 // failure when finish process
451 if ((errno == EINTR) && (alarm_timeout > 0) && !job_done) {
452 if (alarm_timeout > 2) alarm_timeout = 2;
455 } else {
456 // end of timeout - do not try to wait any longer
457 job_done = 1;
458 }
459 } else if (!WIFEXITED(wait_status) && !WIFSIGNALED(wait_status)) {
460 // abnormal end of browser process
461 job_done = 1;
462 } else {
463 // this is normal finish, no need for process kill
464 job_done = 2;
465 }
466 }
467
468 if (job_done != 2) {
469 // kill browser process when no normal end was detected
470 kill(pid, SIGKILL);
471 }
472
473 if (batch_timeout) {
474 alarm(0); // disable alarm
475 sigaction(SIGALRM, &Old, nullptr);
476 }
477
478 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
479 ::Info("RWebDisplayHandle::Display", "Preserve dump file %s", redirect.c_str());
480 else
481 gSystem->Unlink(redirect.c_str());
482
483 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, dump_content);
484 }
485
486 // add processid and rm dir
487
488 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, pid);
489
490#else
491
492 if (fProg.empty()) {
493 if (!tmpfile.empty())
494 gSystem->Unlink(tmpfile.c_str());
495 R__LOG_ERROR(WebGUILog()) << "No Web browser found";
496 return nullptr;
497 }
498
499 // use UnixPathName to simplify handling of backslashes
500 exec = "wmic process call create '"s + gSystem->UnixPathName(fProg.c_str()) + " " + exec + "' | find \"ProcessId\" "s;
501 std::string process_id = gSystem->GetFromPipe(exec.c_str()).Data();
502 std::stringstream ss(process_id);
503 std::string tmp;
504 char c;
505 int pid = 0;
506 ss >> tmp >> c >> pid;
507
508 if (pid <= 0) {
509 if (!tmpfile.empty())
510 gSystem->Unlink(tmpfile.c_str());
511 R__LOG_ERROR(WebGUILog()) << "Fail to launch " << fProg;
512 return nullptr;
513 }
514
515 // add processid and rm dir
516 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, pid);
517#endif
518 }
519
520#ifdef _MSC_VER
521
522 if (exec.rfind("&") == exec.length() - 1) {
523
524 // if last symbol is &, use _spawn to detach execution
525 exec.resize(exec.length() - 1);
526
527 std::vector<char *> argv;
528 std::string firstarg = fProg;
529 auto slashpos = firstarg.find_last_of("/\\");
530 if (slashpos != std::string::npos)
531 firstarg.erase(0, slashpos + 1);
532 argv.push_back((char *)firstarg.c_str());
533
534 std::unique_ptr<TObjArray> fargs(TString(exec.c_str()).Tokenize(" "));
535 for (Int_t n = 1; n <= fargs->GetLast(); ++n)
536 argv.push_back((char *)fargs->At(n)->GetName());
537 argv.push_back(nullptr);
538
539 R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in " << fProg << " with:\n" << exec;
540
541 _spawnv(_P_NOWAIT, gSystem->UnixPathName(fProg.c_str()), argv.data());
542
543 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, ""s);
544 }
545
546 std::string prog = "\""s + gSystem->UnixPathName(fProg.c_str()) + "\""s;
547
548#else
549
550#ifdef R__MACOSX
551 std::string prog = std::regex_replace(fProg, std::regex(" "), "\\ ");
552#else
553 std::string prog = fProg;
554#endif
555
556#endif
557
558 exec = std::regex_replace(exec, std::regex("\\$prog"), prog);
559
560 std::string redirect = args.GetRedirectOutput(), dump_content;
561
562 if (!redirect.empty()) {
563 if (exec.find("$dumpfile") != std::string::npos) {
564 exec = std::regex_replace(exec, std::regex("\\$dumpfile"), redirect);
565 } else {
566 auto p = exec.length();
567 if (exec.rfind("&") == p-1) --p;
568 exec.insert(p, " >"s + redirect + " "s);
569 }
570 }
571
572 R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in browser with:\n" << exec;
573
574 gSystem->Exec(exec.c_str());
575
576 // read content of redirected output
577 if (!redirect.empty()) {
579
580 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
581 ::Info("RWebDisplayHandle::Display", "Preserve dump file %s", redirect.c_str());
582 else
583 gSystem->Unlink(redirect.c_str());
584 }
585
586 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, dump_content);
587}
588
589//////////////////////////////////////////////////////////////////////////////////////////////////
590/// Constructor
591
593{
594 fExec = gEnv->GetValue("WebGui.SafariInteractive", "open -a Safari $url");
595}
596
597//////////////////////////////////////////////////////////////////////////////////////////////////
598/// Returns true if it can be used
599
601{
602#ifdef R__MACOSX
603 return true;
604#else
605 return false;
606#endif
607}
608
609//////////////////////////////////////////////////////////////////////////////////////////////////
610/// Constructor
611
613{
614 fEdge = _edge;
615
616 fEnvPrefix = fEdge ? "WebGui.Edge" : "WebGui.Chrome";
617
618 TestProg(gEnv->GetValue(fEnvPrefix.c_str(), ""));
619
620 if (!fProg.empty() && !fEdge)
621 fChromeVersion = gEnv->GetValue("WebGui.ChromeVersion", -1);
622
623#ifdef _MSC_VER
624 if (fEdge)
625 TestProg("\\Microsoft\\Edge\\Application\\msedge.exe", true);
626 else
627 TestProg("\\Google\\Chrome\\Application\\chrome.exe", true);
628#endif
629#ifdef R__MACOSX
630 TestProg("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
631#endif
632#ifdef R__LINUX
633 TestProg("/snap/bin/chromium"); // test snap before to detect it properly
634 TestProg("/usr/bin/chromium");
635 TestProg("/usr/bin/chromium-browser");
636 TestProg("/usr/bin/chrome-browser");
637 TestProg("/usr/bin/google-chrome-stable");
638 TestProg("/usr/bin/google-chrome");
639#endif
640
641// --no-sandbox is required to run chrome with super-user, but only in headless mode
642// --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
643
644#ifdef _MSC_VER
645 // here --headless=old was used to let normally end of Edge process when --dump-dom is used
646 // while on Windows chrome and edge version not tested, just suppose that newest chrome is used
647 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless --no-sandbox $geometry --dump-dom $url");
648 // in interactive headless mode fork used to let stop browser via process id
649 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless --no-sandbox --disable-gpu $geometry \"$url\"");
650 fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=$url &"); // & in windows mean usage of spawn
651#else
652#ifdef R__MACOSX
653 bool use_normal = true; // mac does not like new flag
654#else
655 bool use_normal = (fChromeVersion < 119) || (fChromeVersion > 131);
656#endif
657 if (use_normal) {
658 // old or newest browser with standard headless mode
659 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "fork:--headless --no-sandbox --disable-extensions --disable-audio-output $geometry --dump-dom $url");
660 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless --no-sandbox --disable-extensions --disable-audio-output $geometry $url");
661 } else {
662 // newer version with headless=new mode
663 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "fork:--headless=new --no-sandbox --disable-extensions --disable-audio-output $geometry --dump-dom $url");
664 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless=new --no-sandbox --disable-extensions --disable-audio-output $geometry $url");
665 }
666 fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=\'$url\' >/dev/null 2>/dev/null &");
667#endif
668}
669
670
671//////////////////////////////////////////////////////////////////////////////////////////////////
672/// Replace $geometry placeholder with geometry settings
673/// Also RWebDisplayArgs::GetExtraArgs() are appended
674
676{
677 std::string geometry;
678 if ((args.GetWidth() > 0) && (args.GetHeight() > 0))
679 geometry = "--window-size="s + std::to_string(args.GetWidth())
680 + (args.IsHeadless() ? "x"s : ","s)
681 + std::to_string(args.GetHeight());
682
683 if (((args.GetX() >= 0) || (args.GetY() >= 0)) && !args.IsHeadless()) {
684 if (!geometry.empty()) geometry.append(" ");
685 geometry.append("--window-position="s + std::to_string(args.GetX() >= 0 ? args.GetX() : 0) + ","s +
686 std::to_string(args.GetY() >= 0 ? args.GetY() : 0));
687 }
688
689 if (!args.GetExtraArgs().empty()) {
690 if (!geometry.empty()) geometry.append(" ");
691 geometry.append(args.GetExtraArgs());
692 }
693
694 exec = std::regex_replace(exec, std::regex("\\$geometry"), geometry);
695}
696
697
698//////////////////////////////////////////////////////////////////////////////////////////////////
699/// Handle profile argument
700
701std::string RWebDisplayHandle::ChromeCreator::MakeProfile(std::string &exec, bool)
702{
703 std::string rmdir, profile_arg;
704
705 if (exec.find("$profile") == std::string::npos)
706 return rmdir;
707
708 const char *chrome_profile = gEnv->GetValue((fEnvPrefix + "Profile").c_str(), "");
711 } else {
713 rnd.SetSeed(0);
715 if ((profile_arg.compare(0, 4, "/tmp") == 0) && IsSnapBrowser())
717
718#ifdef _MSC_VER
719 char slash = '\\';
720#else
721 char slash = '/';
722#endif
723 if (!profile_arg.empty() && (profile_arg[profile_arg.length()-1] != slash))
725 profile_arg += "root_chrome_profile_"s + std::to_string(rnd.Integer(0x100000));
726
727 rmdir = profile_arg;
728 }
729
730 exec = std::regex_replace(exec, std::regex("\\$profile"), profile_arg);
731
732 return rmdir;
733}
734
735
736//////////////////////////////////////////////////////////////////////////////////////////////////
737/// Constructor
738
740{
741 TestProg(gEnv->GetValue("WebGui.Firefox", ""));
742
743#ifdef _MSC_VER
744 TestProg("\\Mozilla Firefox\\firefox.exe", true);
745#endif
746#ifdef R__MACOSX
747 TestProg("/Applications/Firefox.app/Contents/MacOS/firefox");
748#endif
749#ifdef R__LINUX
750 TestProg("/snap/bin/firefox");
751 TestProg("/usr/bin/firefox");
752 TestProg("/usr/bin/firefox-bin");
753#endif
754
755#ifdef _MSC_VER
756 // there is a problem when specifying the window size with wmic on windows:
757 // It gives: Invalid format. Hint: <paramlist> = <param> [, <paramlist>].
758 fBatchExec = gEnv->GetValue("WebGui.FirefoxBatch", "$prog -headless -no-remote $profile $url");
759 fHeadlessExec = gEnv->GetValue("WebGui.FirefoxHeadless", "fork:-headless -no-remote $profile \"$url\"");
760 fExec = gEnv->GetValue("WebGui.FirefoxInteractive", "$prog -no-remote $profile $geometry $url &");
761#else
762 fBatchExec = gEnv->GetValue("WebGui.FirefoxBatch", "fork:--headless -no-remote -new-instance $profile $url");
763 fHeadlessExec = gEnv->GetValue("WebGui.FirefoxHeadless", "fork:--headless -no-remote $profile --private-window $url");
764 fExec = gEnv->GetValue("WebGui.FirefoxInteractive", "$rootetcdir/runfirefox.sh __nodump__ $cleanup_profile $prog -no-remote $profile $geometry -url \'$url\' &");
765#endif
766}
767
768//////////////////////////////////////////////////////////////////////////////////////////////////
769/// Process window geometry for Firefox
770
772{
773 std::string geometry;
774 if ((args.GetWidth() > 0) && (args.GetHeight() > 0) && !args.IsHeadless())
775 geometry = "-width="s + std::to_string(args.GetWidth()) + " -height=" + std::to_string(args.GetHeight());
776
777 exec = std::regex_replace(exec, std::regex("\\$geometry"), geometry);
778}
779
780//////////////////////////////////////////////////////////////////////////////////////////////////
781/// Create Firefox profile to run independent browser window
782
784{
785 std::string rmdir, profile_arg;
786
787 if (exec.find("$profile") == std::string::npos)
788 return rmdir;
789
790 const char *ff_profile = gEnv->GetValue("WebGui.FirefoxProfile", "");
791 const char *ff_profilepath = gEnv->GetValue("WebGui.FirefoxProfilePath", "");
792 Int_t ff_randomprofile = RWebWindowWSHandler::GetBoolEnv("WebGui.FirefoxRandomProfile", 1);
793 if (ff_profile && *ff_profile) {
794 profile_arg = "-P "s + ff_profile;
795 } else if (ff_profilepath && *ff_profilepath) {
796 profile_arg = "-profile "s + ff_profilepath;
797 } else if (ff_randomprofile > 0) {
799 rnd.SetSeed(0);
800 std::string profile_dir = gSystem->TempDirectory();
801 if ((profile_dir.compare(0, 4, "/tmp") == 0) && IsSnapBrowser())
803
804#ifdef _MSC_VER
805 char slash = '\\';
806#else
807 char slash = '/';
808#endif
809 if (!profile_dir.empty() && (profile_dir[profile_dir.length()-1] != slash))
811 profile_dir += "root_ff_profile_"s + std::to_string(rnd.Integer(0x100000));
812
813 profile_arg = "-profile "s + profile_dir;
814
815 if (gSystem->mkdir(profile_dir.c_str()) == 0) {
816 rmdir = profile_dir;
817
818 std::ofstream user_js(profile_dir + "/user.js", std::ios::trunc);
819 // workaround for current Firefox, without such settings it fail to close window and terminate it from batch
820 // also disable question about upload of data
821 user_js << "user_pref(\"datareporting.policy.dataSubmissionPolicyAcceptedVersion\", 2);" << std::endl;
822 user_js << "user_pref(\"datareporting.policy.dataSubmissionPolicyNotifiedTime\", \"1635760572813\");" << std::endl;
823
824 // try to ensure that window closes with last tab
825 user_js << "user_pref(\"browser.tabs.closeWindowWithLastTab\", true);" << std::endl;
826 user_js << "user_pref(\"dom.allow_scripts_to_close_windows\", true);" << std::endl;
827 user_js << "user_pref(\"browser.sessionstore.resume_from_crash\", false);" << std::endl;
828
829 if (batch_mode) {
830 // allow to dump messages to std output
831 user_js << "user_pref(\"browser.dom.window.dump.enabled\", true);" << std::endl;
832 } else {
833 // to suppress annoying privacy tab
834 user_js << "user_pref(\"datareporting.policy.firstRunURL\", \"\");" << std::endl;
835 // to use custom userChrome.css files
836 user_js << "user_pref(\"toolkit.legacyUserProfileCustomizations.stylesheets\", true);" << std::endl;
837 // do not put tabs in title
838 user_js << "user_pref(\"browser.tabs.inTitlebar\", 0);" << std::endl;
839
840#ifdef R__LINUX
841 // fix WebGL creation problem on some Linux platforms
842 user_js << "user_pref(\"webgl.out-of-process\", false);" << std::endl;
843#endif
844
845 std::ofstream times_json(profile_dir + "/times.json", std::ios::trunc);
846 times_json << "{" << std::endl;
847 times_json << " \"created\": 1699968480952," << std::endl;
848 times_json << " \"firstUse\": null" << std::endl;
849 times_json << "}" << std::endl;
850 if (gSystem->mkdir((profile_dir + "/chrome").c_str()) == 0) {
851 std::ofstream style(profile_dir + "/chrome/userChrome.css", std::ios::trunc);
852 // do not show tabs
853 style << "#TabsToolbar { visibility: collapse; }" << std::endl;
854 // do not show URL
855 style << "#nav-bar, #urlbar-container, #searchbar { visibility: collapse !important; }" << std::endl;
856 }
857 }
858
859 } else {
860 R__LOG_ERROR(WebGUILog()) << "Cannot create Firefox profile directory " << profile_dir;
861 }
862 }
863
864 exec = std::regex_replace(exec, std::regex("\\$profile"), profile_arg);
865
866 if (exec.find("$cleanup_profile") != std::string::npos) {
867 if (rmdir.empty()) rmdir = "__dummy__";
868 exec = std::regex_replace(exec, std::regex("\\$cleanup_profile"), rmdir);
869 rmdir.clear(); // no need to delete directory - it will be removed by script
870 }
871
872 return rmdir;
873}
874
875///////////////////////////////////////////////////////////////////////////////////////////////////
876/// Check if http server required for display
877/// \param args - defines where and how to display web window
878
880{
883 return false;
884
885 if (!args.IsHeadless() && (args.GetBrowserKind() == RWebDisplayArgs::kOn)) {
886
887#ifdef WITH_QT6WEB
888 auto &qt6 = FindCreator("qt6", "libROOTQt6WebDisplay");
889 if (qt6 && qt6->IsActive())
890 return false;
891#endif
892#ifdef WITH_CEFWEB
893 auto &cef = FindCreator("cef", "libROOTCefDisplay");
894 if (cef && cef->IsActive())
895 return false;
896#endif
897 }
898
899 return true;
900}
901
902
903///////////////////////////////////////////////////////////////////////////////////////////////////
904/// Create web display
905/// \param args - defines where and how to display web window
906/// Returns RWebDisplayHandle, which holds information of running browser application
907/// Can be used fully independent from RWebWindow classes just to show any web page
908
909std::unique_ptr<RWebDisplayHandle> RWebDisplayHandle::Display(const RWebDisplayArgs &args)
910{
911 std::unique_ptr<RWebDisplayHandle> handle;
912
914 return handle;
915
916 auto try_creator = [&](std::unique_ptr<Creator> &creator) {
917 if (!creator || !creator->IsActive())
918 return false;
919 handle = creator->Display(args);
920 return handle ? true : false;
921 };
922
924 (!args.IsHeadless() && (args.GetBrowserKind() == RWebDisplayArgs::kOn)),
925 has_qt6web = false, has_cefweb = false;
926
927#ifdef WITH_QT6WEB
928 has_qt6web = true;
929#endif
930
931#ifdef WITH_CEFWEB
932 has_cefweb = true;
933#endif
934
936 if (try_creator(FindCreator("qt6", "libROOTQt6WebDisplay")))
937 return handle;
938 }
939
941 if (try_creator(FindCreator("cef", "libROOTCefDisplay")))
942 return handle;
943 }
944
945 if (args.IsLocalDisplay()) {
946 R__LOG_ERROR(WebGUILog()) << "Neither Qt5/6 nor CEF libraries were found to provide local display";
947 return handle;
948 }
949
950 bool handleAsNative =
952
954 if (try_creator(FindCreator("chrome", "ChromeCreator")))
955 return handle;
956 }
957
959 if (try_creator(FindCreator("firefox", "FirefoxCreator")))
960 return handle;
961 }
962
963#ifdef _MSC_VER
964 // Edge browser cannot be run headless without registry change, therefore do not try it by default
965 if ((handleAsNative && !args.IsHeadless() && !args.IsBatchMode()) || (args.GetBrowserKind() == RWebDisplayArgs::kEdge)) {
966 if (try_creator(FindCreator("edge", "ChromeCreator")))
967 return handle;
968 }
969#endif
970
973 // R__LOG_ERROR(WebGUILog()) << "Neither Chrome nor Firefox browser cannot be started to provide display";
974 return handle;
975 }
976
978 if (try_creator(FindCreator("safari", "SafariCreator")))
979 return handle;
980 }
981
983 std::unique_ptr<Creator> creator = std::make_unique<BrowserCreator>(false, args.GetCustomExec());
984 try_creator(creator);
985 } else {
986 try_creator(FindCreator("browser", "BrowserCreator"));
987 }
988
989 return handle;
990}
991
992///////////////////////////////////////////////////////////////////////////////////////////////////
993/// Display provided url in configured web browser
994/// \param url - specified URL address like https://root.cern
995/// Browser can specified when starting `root --web=firefox`
996/// Returns true when browser started
997/// It is convenience method, equivalent to:
998/// ~~~
999/// RWebDisplayArgs args;
1000/// args.SetUrl(url);
1001/// args.SetStandalone(false);
1002/// auto handle = RWebDisplayHandle::Display(args);
1003/// ~~~
1004
1005bool RWebDisplayHandle::DisplayUrl(const std::string &url)
1006{
1007 RWebDisplayArgs args;
1008 args.SetUrl(url);
1009 args.SetStandalone(false);
1010
1011 auto handle = Display(args);
1012
1013 return !!handle;
1014}
1015
1016///////////////////////////////////////////////////////////////////////////////////////////////////
1017/// Checks if configured browser can be used for image production
1018
1020{
1024 bool detected = false;
1025
1026 auto &h1 = FindCreator("chrome", "ChromeCreator");
1027 if (h1 && h1->IsActive()) {
1029 detected = true;
1030 }
1031
1032 if (!detected) {
1033 auto &h2 = FindCreator("firefox", "FirefoxCreator");
1034 if (h2 && h2->IsActive()) {
1036 detected = true;
1037 }
1038 }
1039
1040 return detected;
1041 }
1042
1044 auto &h1 = FindCreator("chrome", "ChromeCreator");
1045 return h1 && h1->IsActive();
1046 }
1047
1049 auto &h2 = FindCreator("firefox", "FirefoxCreator");
1050 return h2 && h2->IsActive();
1051 }
1052
1053#ifdef _MSC_VER
1054 if (args.GetBrowserKind() == RWebDisplayArgs::kEdge) {
1055 auto &h3 = FindCreator("edge", "ChromeCreator");
1056 return h3 && h3->IsActive();
1057 }
1058#endif
1059
1060 return true;
1061}
1062
1063///////////////////////////////////////////////////////////////////////////////////////////////////
1064/// Returns true if image production for specified browser kind is supported
1065/// If browser not specified - use currently configured browser or try to test existing web browsers
1066
1068{
1070
1071 return CheckIfCanProduceImages(args);
1072}
1073
1074///////////////////////////////////////////////////////////////////////////////////////////////////
1075/// Detect image format
1076/// There is special handling of ".screenshot.pdf" and ".screenshot.png" extensions
1077/// Creation of such files relies on headless browser functionality and fully supported only by Chrome browser
1078
1079std::string RWebDisplayHandle::GetImageFormat(const std::string &fname)
1080{
1081 std::string _fname = fname;
1082 std::transform(_fname.begin(), _fname.end(), _fname.begin(), ::tolower);
1083 auto EndsWith = [&_fname](const std::string &suffix) {
1084 return (_fname.length() > suffix.length()) ? (0 == _fname.compare(_fname.length() - suffix.length(), suffix.length(), suffix)) : false;
1085 };
1086
1087 if (EndsWith(".screenshot.pdf"))
1088 return "s.pdf"s;
1089 if (EndsWith(".pdf"))
1090 return "pdf"s;
1091 if (EndsWith(".json"))
1092 return "json"s;
1093 if (EndsWith(".svg"))
1094 return "svg"s;
1095 if (EndsWith(".screenshot.png"))
1096 return "s.png"s;
1097 if (EndsWith(".png"))
1098 return "png"s;
1099 if (EndsWith(".jpg") || EndsWith(".jpeg"))
1100 return "jpeg"s;
1101 if (EndsWith(".webp"))
1102 return "webp"s;
1103
1104 return ""s;
1105}
1106
1107
1108///////////////////////////////////////////////////////////////////////////////////////////////////
1109/// Produce image file using JSON data as source
1110/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1111
1112bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string &json, int width, int height, const char *batch_file)
1113{
1114 return ProduceImages(fname, {json}, {width}, {height}, batch_file);
1115}
1116
1117
1118///////////////////////////////////////////////////////////////////////////////////////////////////
1119/// Produce vector of file names for specified file pattern
1120/// Depending from supported file forma
1121
1122std::vector<std::string> RWebDisplayHandle::ProduceImagesNames(const std::string &fname, unsigned nfiles)
1123{
1124 auto fmt = GetImageFormat(fname);
1125
1126 std::vector<std::string> fnames;
1127
1128 if ((fmt == "s.pdf") || (fmt == "s.png")) {
1129 fnames.emplace_back(fname);
1130 } else {
1131 std::string farg = fname;
1132
1133 bool has_quialifier = farg.find("%") != std::string::npos;
1134
1135 if (!has_quialifier && (nfiles > 1) && (fmt != "pdf")) {
1136 farg.insert(farg.rfind("."), "%d");
1137 has_quialifier = true;
1138 }
1139
1140 for (unsigned n = 0; n < nfiles; n++) {
1141 if(has_quialifier) {
1142 auto expand_name = TString::Format(farg.c_str(), (int) n);
1143 fnames.emplace_back(expand_name.Data());
1144 } else if (n > 0)
1145 fnames.emplace_back(""); // empty name is multiPdf
1146 else
1147 fnames.emplace_back(fname);
1148 }
1149 }
1150
1151 return fnames;
1152}
1153
1154
1155///////////////////////////////////////////////////////////////////////////////////////////////////
1156/// Produce image file(s) using JSON data as source
1157/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1158
1159bool 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)
1160{
1162}
1163
1164///////////////////////////////////////////////////////////////////////////////////////////////////
1165/// Produce image file(s) using JSON data as source
1166/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1167
1168bool 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)
1169{
1170 if (fnames.empty() || jsons.empty())
1171 return false;
1172
1173 std::vector<std::string> fmts;
1174 for (auto& fname : fnames)
1175 fmts.emplace_back(GetImageFormat(fname));
1176
1177 bool is_any_image = false;
1178
1179 for (unsigned n = 0; (n < fmts.size()) && (n < jsons.size()); n++) {
1180 if (fmts[n] == "json") {
1181 std::ofstream ofs(fnames[n]);
1182 ofs << jsons[n];
1183 fmts[n].clear();
1184 } else if (!fmts[n].empty())
1185 is_any_image = true;
1186 }
1187
1188 if (!is_any_image)
1189 return true;
1190
1191 std::string fdebug;
1192 if (fnames.size() == 1)
1193 fdebug = fnames[0];
1194 else
1196
1197 const char *jsrootsys = gSystem->Getenv("JSROOTSYS");
1199 if (!jsrootsys) {
1200 jsrootsysdflt = TROOT::GetDataDir() + "/js";
1202 R__LOG_ERROR(WebGUILog()) << "Fail to locate JSROOT " << jsrootsysdflt;
1203 return false;
1204 }
1205 jsrootsys = jsrootsysdflt.Data();
1206 }
1207
1208 RWebDisplayArgs args; // set default browser kind, only Chrome/Firefox/Edge or CEF/Qt5/Qt6 can be used here
1209 if (!CheckIfCanProduceImages(args)) {
1210 R__LOG_ERROR(WebGUILog()) << "Fail to detect supported browsers for image production";
1211 return false;
1212 }
1213
1217
1218 std::vector<std::string> draw_kinds;
1219 bool use_browser_draw = false, can_optimize_json = false;
1220 int use_home_dir = 0;
1222
1223 // Some Chrome installation do not allow run html code from files, created in /tmp directory
1224 // When during session such failures happened, force usage of home directory from the beginning
1225 static int chrome_tmp_workaround = 0;
1226
1227 if (isChrome) {
1229 auto &h1 = FindCreator("chrome", "ChromeCreator");
1230 if (h1 && h1->IsActive() && h1->IsSnapBrowser() && (use_home_dir == 0))
1231 use_home_dir = 1;
1232 }
1233
1234 if (fmts[0] == "s.png") {
1235 if (!isChromeBased && !isFirefox) {
1236 R__LOG_ERROR(WebGUILog()) << "Direct png image creation supported only by Chrome and Firefox browsers";
1237 return false;
1238 }
1239 use_browser_draw = true;
1240 jsonkind = "1111"; // special mark in canv_batch.htm
1241 } else if (fmts[0] == "s.pdf") {
1242 if (!isChromeBased) {
1243 R__LOG_ERROR(WebGUILog()) << "Direct creation of PDF files supported only by Chrome-based browser";
1244 return false;
1245 }
1246 use_browser_draw = true;
1247 jsonkind = "2222"; // special mark in canv_batch.htm
1248 } else {
1249 draw_kinds = fmts;
1251 can_optimize_json = true;
1252 }
1253
1254 if (!batch_file || !*batch_file)
1255 batch_file = "/js/files/canv_batch.htm";
1256
1259 R__LOG_ERROR(WebGUILog()) << "Fail to find " << origin;
1260 return false;
1261 }
1262
1264 if (filecont.empty()) {
1265 R__LOG_ERROR(WebGUILog()) << "Fail to read content of " << origin;
1266 return false;
1267 }
1268
1269 int max_width = 0, max_height = 0, page_margin = 10;
1270 for (auto &w : widths)
1271 if (w > max_width)
1272 max_width = w;
1273 for (auto &h : heights)
1274 if (h > max_height)
1275 max_height = h;
1276
1279
1280 std::string mains, prev;
1281 for (auto &json : jsons) {
1282 mains.append(mains.empty() ? "[" : ", ");
1283 if (can_optimize_json && (json == prev)) {
1284 mains.append("'same'");
1285 } else {
1286 mains.append(json);
1287 prev = json;
1288 }
1289 }
1290 mains.append("]");
1291
1292 if (strstr(jsrootsys, "http://") || strstr(jsrootsys, "https://") || strstr(jsrootsys, "file://"))
1293 filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), jsrootsys);
1294 else {
1295 static std::string jsroot_include = "<script id=\"jsroot\" src=\"$jsrootsys/build/jsroot.js\"></script>";
1296 auto p = filecont.find(jsroot_include);
1297 if (p != std::string::npos) {
1298 auto jsroot_build = THttpServer::ReadFileContent(std::string(jsrootsys) + "/build/jsroot.js");
1299 if (!jsroot_build.empty()) {
1300 // insert actual jsroot file location
1301 jsroot_build = std::regex_replace(jsroot_build, std::regex("'\\$jsrootsys'"), std::string("'file://") + jsrootsys + "/'");
1302 filecont.erase(p, jsroot_include.length());
1303 filecont.insert(p, "<script id=\"jsroot\">" + jsroot_build + "</script>");
1304 }
1305 }
1306
1307 filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), "file://"s + jsrootsys);
1308 }
1309
1310 filecont = std::regex_replace(filecont, std::regex("\\$page_margin"), std::to_string(page_margin) + "px");
1311 filecont = std::regex_replace(filecont, std::regex("\\$page_width"), std::to_string(max_width + 2*page_margin) + "px");
1312 filecont = std::regex_replace(filecont, std::regex("\\$page_height"), std::to_string(max_height + 2*page_margin) + "px");
1313
1314 filecont = std::regex_replace(filecont, std::regex("\\$draw_kind"), jsonkind.Data());
1315 filecont = std::regex_replace(filecont, std::regex("\\$draw_widths"), jsonw.Data());
1316 filecont = std::regex_replace(filecont, std::regex("\\$draw_heights"), jsonh.Data());
1317 filecont = std::regex_replace(filecont, std::regex("\\$draw_objects"), mains);
1318
1320
1322 dump_name = "canvasdump";
1324 if (!df) {
1325 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary file for dump-dom";
1326 return false;
1327 }
1328 fputs("placeholder", df);
1329 fclose(df);
1330 }
1331
1332try_again:
1333
1335 args.SetUrl(""s);
1337
1338 html_name.Clear();
1339
1340 R__LOG_DEBUG(0, WebGUILog()) << "Using file content_len " << filecont.length() << " to produce batch images ";
1341
1342 } else {
1343 html_name = "canvasbody";
1345 if (!hf) {
1346 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary file for batch job";
1347 return false;
1348 }
1349 fputs(filecont.c_str(), hf);
1350 fclose(hf);
1351
1352 args.SetUrl("file://"s + gSystem->UnixPathName(html_name.Data()));
1353 args.SetPageContent(""s);
1354
1355 R__LOG_DEBUG(0, WebGUILog()) << "Using " << html_name << " content_len " << filecont.length() << " to produce batch images " << fdebug;
1356 }
1357
1359
1360 args.SetStandalone(true);
1361 args.SetHeadless(true);
1362 args.SetBatchMode(true);
1363 args.SetSize(widths[0], heights[0]);
1364
1365 if (use_browser_draw) {
1366
1367 tgtfilename = fnames[0].c_str();
1370
1372
1373 if (fmts[0] == "s.pdf")
1374 args.SetExtraArgs("--print-to-pdf-no-header --print-to-pdf="s + gSystem->UnixPathName(tgtfilename.Data()));
1375 else if (isFirefox) {
1376 args.SetExtraArgs("--screenshot"); // firefox does not let specify output image file
1377 wait_file_name = "screenshot.png";
1378 } else
1379 args.SetExtraArgs("--screenshot="s + gSystem->UnixPathName(tgtfilename.Data()));
1380
1381 // remove target image file - we use it as detection when chrome is ready
1382 gSystem->Unlink(tgtfilename.Data());
1383
1384 } else if (isFirefox) {
1385 // firefox will use window.dump to output produced result
1386 args.SetRedirectOutput(dump_name.Data());
1387 gSystem->Unlink(dump_name.Data());
1388 } else if (isChromeBased) {
1389 // chrome should have --dump-dom args configures
1390 args.SetRedirectOutput(dump_name.Data());
1391 gSystem->Unlink(dump_name.Data());
1392 }
1393
1394 auto handle = RWebDisplayHandle::Display(args);
1395
1396 if (!handle) {
1397 R__LOG_DEBUG(0, WebGUILog()) << "Cannot start " << args.GetBrowserName() << " to produce image " << fdebug;
1398 return false;
1399 }
1400
1401 // delete temporary HTML file
1402 if (html_name.Length() > 0) {
1403 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
1404 ::Info("ProduceImages", "Preserve batch file %s", html_name.Data());
1405 else
1406 gSystem->Unlink(html_name.Data());
1407 }
1408
1409 if (!wait_file_name.IsNull() && gSystem->AccessPathName(wait_file_name.Data())) {
1410 R__LOG_ERROR(WebGUILog()) << "Fail to produce image " << fdebug;
1411 return false;
1412 }
1413
1414 if (use_browser_draw) {
1415 if (fmts[0] == "s.pdf")
1416 ::Info("ProduceImages", "PDF file %s with %d pages has been created", fnames[0].c_str(), (int) jsons.size());
1417 else {
1418 if (isFirefox)
1419 gSystem->Rename("screenshot.png", fnames[0].c_str());
1420 ::Info("ProduceImages", "PNG file %s with %d pages has been created", fnames[0].c_str(), (int) jsons.size());
1421 }
1422 } else {
1423 auto dumpcont = handle->GetContent();
1424
1425 if ((dumpcont.length() > 20) && (dumpcont.length() < 60) && (use_home_dir < 2) && isChrome) {
1426 // chrome creates dummy html file with mostly no content
1427 // problem running chrome from /tmp directory, lets try work from home directory
1428 R__LOG_INFO(WebGUILog()) << "Use home directory for running chrome in batch, set TMPDIR for preferable temp directory";
1430 goto try_again;
1431 }
1432
1433 if (dumpcont.length() < 100) {
1434 R__LOG_ERROR(WebGUILog()) << "Fail to dump HTML code into " << (dump_name.IsNull() ? "CEF" : dump_name.Data());
1435 return false;
1436 }
1437
1438 std::string::size_type p = 0;
1439
1440 for (unsigned n = 0; n < fmts.size(); n++) {
1441 if (fmts[n].empty())
1442 continue;
1443 if (fmts[n] == "svg") {
1444 auto p1 = dumpcont.find("<div><svg", p);
1445 auto p2 = dumpcont.find("</svg></div>", p1 + 8);
1446 p = p2 + 12;
1447 std::ofstream ofs(fnames[n]);
1448 if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) {
1449 if (p2 - p1 > 10) {
1450 ofs << dumpcont.substr(p1 + 5, p2 - p1 + 1);
1451 ::Info("ProduceImages", "Image file %s size %d bytes has been created", fnames[n].c_str(), (int) (p2 - p1 + 1));
1452 } else {
1453 ::Error("ProduceImages", "Failure producing %s", fnames[n].c_str());
1454 }
1455 }
1456 } else {
1457 auto p0 = dumpcont.find("<img src=\"", p);
1458 auto p1 = dumpcont.find(";base64,", p0 + 8);
1459 auto p2 = dumpcont.find("\">", p1 + 8);
1460 p = p2 + 2;
1461
1462 if ((p0 != std::string::npos) && (p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) {
1463 auto base64 = dumpcont.substr(p1+8, p2-p1-8);
1464 if ((base64 == "failure") || (base64.length() < 10)) {
1465 ::Error("ProduceImages", "Failure producing %s", fnames[n].c_str());
1466 } else {
1467 auto binary = TBase64::Decode(base64.c_str());
1468 std::ofstream ofs(fnames[n], std::ios::binary);
1469 ofs.write(binary.Data(), binary.Length());
1470 ::Info("ProduceImages", "Image file %s size %d bytes has been created", fnames[n].c_str(), (int) binary.Length());
1471 }
1472 } else {
1473 ::Error("ProduceImages", "Failure producing %s", fnames[n].c_str());
1474 return false;
1475 }
1476 }
1477 }
1478 }
1479
1480 R__LOG_DEBUG(0, WebGUILog()) << "Create " << (fnames.size() > 1 ? "files " : "file ") << fdebug;
1481
1482 return true;
1483}
1484
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 Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:185
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:543
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3057
static const TString & GetDataDir()
Get the data directory in the installation. Static utility function.
Definition TROOT.cxx:3067
Random number generator class based on M.
Definition TRandom3.h:27
Basic string class.
Definition TString.h:139
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2264
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
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
std::ostream & Info()
Definition hadd.cxx:177
const Int_t n
Definition legend1.C:16
TH1F * h1
Definition legend1.C:5
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
ROOT::RLogChannel & WebGUILog()
Log channel for WebGUI diagnostics.
TCanvas * slash()
Definition slash.C:1
TMarker m
Definition textangle.C:8