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 "TRandom.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"
28
29#include <fstream>
30#include <iostream>
31#include <filesystem>
32#include <memory>
33#include <regex>
34
35#ifdef _MSC_VER
36#include <process.h>
37#else
38#include <unistd.h>
39#include <stdlib.h>
40#include <signal.h>
41#include <spawn.h>
42#endif
43
44using namespace ROOT;
45using namespace std::string_literals;
46
47/** \class ROOT::RWebDisplayHandle
48\ingroup webdisplay
49
50Handle of created web-based display
51Depending from type of web display, holds handle of started browser process or other display-specific information
52to correctly stop and cleanup display.
53*/
54
55
56//////////////////////////////////////////////////////////////////////////////////////////////////
57/// Static holder of registered creators of web displays
58
59std::map<std::string, std::unique_ptr<RWebDisplayHandle::Creator>> &RWebDisplayHandle::GetMap()
60{
61 static std::map<std::string, std::unique_ptr<RWebDisplayHandle::Creator>> sMap;
62 return sMap;
63}
64
65//////////////////////////////////////////////////////////////////////////////////////////////////
66/// Search for specific browser creator
67/// If not found, try to add one
68/// \param name - creator name like ChromeCreator
69/// \param libname - shared library name where creator could be provided
70
71std::unique_ptr<RWebDisplayHandle::Creator> &RWebDisplayHandle::FindCreator(const std::string &name, const std::string &libname)
72{
73 auto &m = GetMap();
74 auto search = m.find(name);
75 if (search == m.end()) {
76
77 if (libname == "ChromeCreator") {
78 m.emplace(name, std::make_unique<ChromeCreator>(name == "edge"));
79 } else if (libname == "FirefoxCreator") {
80 m.emplace(name, std::make_unique<FirefoxCreator>());
81 } else if (libname == "SafariCreator") {
82 m.emplace(name, std::make_unique<SafariCreator>());
83 } else if (libname == "BrowserCreator") {
84 m.emplace(name, std::make_unique<BrowserCreator>(false));
85 } else if (!libname.empty()) {
86 gSystem->Load(libname.c_str());
87 }
88
89 search = m.find(name); // try again
90 }
91
92 if (search != m.end())
93 return search->second;
94
95 static std::unique_ptr<RWebDisplayHandle::Creator> dummy;
96 return dummy;
97}
98
99namespace ROOT {
100
101//////////////////////////////////////////////////////////////////////////////////////////////////
102/// Specialized handle to hold information about running browser process
103/// Used to correctly cleanup all processes and temporary directories
104
106
107#ifdef _MSC_VER
108 typedef int browser_process_id;
109#else
110 typedef pid_t browser_process_id;
111#endif
112 std::string fTmpDir; ///< temporary directory to delete at the end
113 std::string fTmpFile; ///< temporary file to remove
114 bool fHasPid{false};
116
117public:
118 RWebBrowserHandle(const std::string &url, const std::string &tmpdir, const std::string &tmpfile, const std::string &dump) :
119 RWebDisplayHandle(url), fTmpDir(tmpdir), fTmpFile(tmpfile)
120 {
121 SetContent(dump);
122 }
123
124 RWebBrowserHandle(const std::string &url, const std::string &tmpdir, const std::string &tmpfile, browser_process_id pid)
125 : RWebDisplayHandle(url), fTmpDir(tmpdir), fTmpFile(tmpfile), fHasPid(true), fPid(pid)
126 {
127 }
128
130 {
131#ifdef _MSC_VER
132 if (fHasPid)
133 gSystem->Exec(("taskkill /F /PID "s + std::to_string(fPid) + " >NUL 2>NUL").c_str());
134 std::string rmdir = "rmdir /S /Q ", rmfile = "del /F ";
135#else
136 if (fHasPid)
137 kill(fPid, SIGKILL);
138 std::string rmdir = "rm -rf ", rmfile = "rm -f ";
139#endif
140 if (!fTmpDir.empty())
141 gSystem->Exec((rmdir + fTmpDir).c_str());
142 if (!fTmpFile.empty())
143 gSystem->Exec((rmfile + fTmpFile).c_str());
144 }
145
146};
147
148} // namespace ROOT
149
150//////////////////////////////////////////////////////////////////////////////////////////////////
151/// Class to handle starting of web-browsers like Chrome or Firefox
152
153RWebDisplayHandle::BrowserCreator::BrowserCreator(bool custom, const std::string &exec)
154{
155 if (custom) return;
156
157 if (!exec.empty()) {
158 if (exec.find("$url") == std::string::npos) {
159 fProg = exec;
160#ifdef _MSC_VER
161 fExec = exec + " $url";
162#else
163 fExec = exec + " $url &";
164#endif
165 } else {
166 fExec = exec;
167 auto pos = exec.find(" ");
168 if (pos != std::string::npos)
169 fProg = exec.substr(0, pos);
170 }
171 } else if (gSystem->InheritsFrom("TMacOSXSystem")) {
172 fExec = "open \'$url\'";
173 } else if (gSystem->InheritsFrom("TWinNTSystem")) {
174 fExec = "start $url";
175 } else {
176 fExec = "xdg-open \'$url\' &";
177 }
178}
179
180//////////////////////////////////////////////////////////////////////////////////////////////////
181/// Check if browser executable exists and can be used
182
183void RWebDisplayHandle::BrowserCreator::TestProg(const std::string &nexttry, bool check_std_paths)
184{
185 if (nexttry.empty() || !fProg.empty())
186 return;
187
188 if (!gSystem->AccessPathName(nexttry.c_str(), kExecutePermission)) {
189#ifdef R__MACOSX
190 fProg = std::regex_replace(nexttry, std::regex("%20"), " ");
191#else
192 fProg = nexttry;
193#endif
194 return;
195 }
196
197 if (!check_std_paths)
198 return;
199
200#ifdef _MSC_VER
201 std::string ProgramFiles = gSystem->Getenv("ProgramFiles");
202 auto pos = ProgramFiles.find(" (x86)");
203 if (pos != std::string::npos)
204 ProgramFiles.erase(pos, 6);
205 std::string ProgramFilesx86 = gSystem->Getenv("ProgramFiles(x86)");
206
207 if (!ProgramFiles.empty())
208 TestProg(ProgramFiles + nexttry, false);
209 if (!ProgramFilesx86.empty())
210 TestProg(ProgramFilesx86 + nexttry, false);
211#endif
212}
213
214//////////////////////////////////////////////////////////////////////////////////////////////////
215/// Display given URL in web browser
216
217std::unique_ptr<RWebDisplayHandle>
219{
220 std::string url = args.GetFullUrl();
221 if (url.empty())
222 return nullptr;
223
225 std::cout << "New web window: " << url << std::endl;
226 return std::make_unique<RWebBrowserHandle>(url, "", "", "");
227 }
228
229 std::string exec;
230 if (args.IsBatchMode())
231 exec = fBatchExec;
232 else if (args.IsHeadless())
233 exec = fHeadlessExec;
234 else if (args.IsStandalone())
235 exec = fExec;
236 else
237 exec = "$prog $url &";
238
239 if (exec.empty())
240 return nullptr;
241
242 std::string swidth = std::to_string(args.GetWidth() > 0 ? args.GetWidth() : 800),
243 sheight = std::to_string(args.GetHeight() > 0 ? args.GetHeight() : 600),
244 sposx = std::to_string(args.GetX() >= 0 ? args.GetX() : 0),
245 sposy = std::to_string(args.GetY() >= 0 ? args.GetY() : 0);
246
247 ProcessGeometry(exec, args);
248
249 std::string rmdir = MakeProfile(exec, args.IsBatchMode() || args.IsHeadless());
250
251 std::string tmpfile;
252
253 // these are secret parameters, hide them in temp file
254 if (((url.find("token=") != std::string::npos) || (url.find("key=") != std::string::npos)) && !args.IsBatchMode() && !args.IsHeadless()) {
255 TString filebase = "root_start_";
256
257 auto f = gSystem->TempFileName(filebase, nullptr, ".html");
258
259 bool ferr = false;
260
261 if (!f) {
262 ferr = true;
263 } else {
264 std::string content = std::regex_replace(
265 "<!DOCTYPE html>\n"
266 "<html lang=\"en\">\n"
267 "<head>\n"
268 " <meta charset=\"utf-8\">\n"
269 " <meta http-equiv=\"refresh\" content=\"0;url=$url\"/>\n"
270 " <title>Opening ROOT widget</title>\n"
271 "</head>\n"
272 "<body>\n"
273 "<p>\n"
274 " This page should redirect you to a ROOT widget. If it doesn't,\n"
275 " <a href=\"$url\">click here to go to ROOT</a>.\n"
276 "</p>\n"
277 "</body>\n"
278 "</html>\n", std::regex("\\$url"), url);
279
280 if (fwrite(content.c_str(), 1, content.length(), f) != content.length())
281 ferr = true;
282
283 if (fclose(f) != 0)
284 ferr = true;
285
286 tmpfile = filebase.Data();
287
288 url = "file://"s + tmpfile;
289 }
290
291 if (ferr) {
292 if (!tmpfile.empty())
293 gSystem->Unlink(tmpfile.c_str());
294 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary HTML file to startup widget";
295 return nullptr;
296 }
297 }
298
299 exec = std::regex_replace(exec, std::regex("\\$rootetcdir"), TROOT::GetEtcDir().Data());
300 exec = std::regex_replace(exec, std::regex("\\$url"), url);
301 exec = std::regex_replace(exec, std::regex("\\$width"), swidth);
302 exec = std::regex_replace(exec, std::regex("\\$height"), sheight);
303 exec = std::regex_replace(exec, std::regex("\\$posx"), sposx);
304 exec = std::regex_replace(exec, std::regex("\\$posy"), sposy);
305
306 if (exec.compare(0,5,"fork:") == 0) {
307 if (fProg.empty()) {
308 if (!tmpfile.empty())
309 gSystem->Unlink(tmpfile.c_str());
310 R__LOG_ERROR(WebGUILog()) << "Fork instruction without executable";
311 return nullptr;
312 }
313
314 exec.erase(0, 5);
315
316#ifndef _MSC_VER
317
318 std::unique_ptr<TObjArray> fargs(TString(exec.c_str()).Tokenize(" "));
319 if (!fargs || (fargs->GetLast()<=0)) {
320 if (!tmpfile.empty())
321 gSystem->Unlink(tmpfile.c_str());
322 R__LOG_ERROR(WebGUILog()) << "Fork instruction is empty";
323 return nullptr;
324 }
325
326 std::vector<char *> argv;
327 argv.push_back((char *) fProg.c_str());
328 for (Int_t n = 0; n <= fargs->GetLast(); ++n)
329 argv.push_back((char *)fargs->At(n)->GetName());
330 argv.push_back(nullptr);
331
332 R__LOG_DEBUG(0, WebGUILog()) << "Show web window in browser with posix_spawn:\n" << fProg << " " << exec;
333
334 posix_spawn_file_actions_t action;
335 posix_spawn_file_actions_init(&action);
336 posix_spawn_file_actions_addopen (&action, STDOUT_FILENO, "/dev/null", O_WRONLY|O_APPEND, 0);
337 posix_spawn_file_actions_addopen (&action, STDERR_FILENO, "/dev/null", O_WRONLY|O_APPEND, 0);
338
339 pid_t pid;
340 int status = posix_spawn(&pid, argv[0], &action, nullptr, argv.data(), nullptr);
341
342 posix_spawn_file_actions_destroy(&action);
343
344 if (status != 0) {
345 if (!tmpfile.empty())
346 gSystem->Unlink(tmpfile.c_str());
347 R__LOG_ERROR(WebGUILog()) << "Fail to launch " << argv[0];
348 return nullptr;
349 }
350
351 // add processid and rm dir
352
353 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, pid);
354
355#else
356
357 if (fProg.empty()) {
358 if (!tmpfile.empty())
359 gSystem->Unlink(tmpfile.c_str());
360 R__LOG_ERROR(WebGUILog()) << "No Web browser found";
361 return nullptr;
362 }
363
364 // use UnixPathName to simplify handling of backslashes
365 exec = "wmic process call create '"s + gSystem->UnixPathName(fProg.c_str()) + " " + exec + "' | find \"ProcessId\" "s;
366 std::string process_id = gSystem->GetFromPipe(exec.c_str()).Data();
367 std::stringstream ss(process_id);
368 std::string tmp;
369 char c;
370 int pid = 0;
371 ss >> tmp >> c >> pid;
372
373 if (pid <= 0) {
374 if (!tmpfile.empty())
375 gSystem->Unlink(tmpfile.c_str());
376 R__LOG_ERROR(WebGUILog()) << "Fail to launch " << fProg;
377 return nullptr;
378 }
379
380 // add processid and rm dir
381 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, pid);
382#endif
383 }
384
385#ifdef _MSC_VER
386
387 if (exec.rfind("&") == exec.length() - 1) {
388
389 // if last symbol is &, use _spawn to detach execution
390 exec.resize(exec.length() - 1);
391
392 std::vector<char *> argv;
393 std::string firstarg = fProg;
394 auto slashpos = firstarg.find_last_of("/\\");
395 if (slashpos != std::string::npos)
396 firstarg.erase(0, slashpos + 1);
397 argv.push_back((char *)firstarg.c_str());
398
399 std::unique_ptr<TObjArray> fargs(TString(exec.c_str()).Tokenize(" "));
400 for (Int_t n = 1; n <= fargs->GetLast(); ++n)
401 argv.push_back((char *)fargs->At(n)->GetName());
402 argv.push_back(nullptr);
403
404 R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in " << fProg << " with:\n" << exec;
405
406 _spawnv(_P_NOWAIT, gSystem->UnixPathName(fProg.c_str()), argv.data());
407
408 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, ""s);
409 }
410
411 std::string prog = "\""s + gSystem->UnixPathName(fProg.c_str()) + "\""s;
412
413#else
414
415#ifdef R__MACOSX
416 std::string prog = std::regex_replace(fProg, std::regex(" "), "\\ ");
417#else
418 std::string prog = fProg;
419#endif
420
421#endif
422
423 exec = std::regex_replace(exec, std::regex("\\$prog"), prog);
424
425 std::string redirect = args.GetRedirectOutput(), dump_content;
426
427 if (!redirect.empty()) {
428 if (exec.find("$dumpfile") != std::string::npos) {
429 exec = std::regex_replace(exec, std::regex("\\$dumpfile"), redirect);
430 } else {
431 auto p = exec.length();
432 if (exec.rfind("&") == p-1) --p;
433 exec.insert(p, " >"s + redirect + " "s);
434 }
435 }
436
437 R__LOG_DEBUG(0, WebGUILog()) << "Showing web window in browser with:\n" << exec;
438
439 gSystem->Exec(exec.c_str());
440
441 // read content of redirected output
442 if (!redirect.empty()) {
443 dump_content = THttpServer::ReadFileContent(redirect.c_str());
444
445 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
446 ::Info("RWebDisplayHandle::Display", "Preserve dump file %s", redirect.c_str());
447 else
448 gSystem->Unlink(redirect.c_str());
449 }
450
451 return std::make_unique<RWebBrowserHandle>(url, rmdir, tmpfile, dump_content);
452}
453
454//////////////////////////////////////////////////////////////////////////////////////////////////
455/// Constructor
456
458{
459 fExec = gEnv->GetValue("WebGui.SafariInteractive", "open -a Safari $url");
460}
461
462//////////////////////////////////////////////////////////////////////////////////////////////////
463/// Returns true if it can be used
464
466{
467#ifdef R__MACOSX
468 return true;
469#else
470 return false;
471#endif
472}
473
474//////////////////////////////////////////////////////////////////////////////////////////////////
475/// Constructor
476
478{
479 fEdge = _edge;
480
481 fEnvPrefix = fEdge ? "WebGui.Edge" : "WebGui.Chrome";
482
483 TestProg(gEnv->GetValue(fEnvPrefix.c_str(), ""));
484
485 if (!fProg.empty() && !fEdge)
486 fChromeVersion = gEnv->GetValue("WebGui.ChromeVersion", -1);
487
488#ifdef _MSC_VER
489 if (fEdge)
490 TestProg("\\Microsoft\\Edge\\Application\\msedge.exe", true);
491 else
492 TestProg("\\Google\\Chrome\\Application\\chrome.exe", true);
493#endif
494#ifdef R__MACOSX
495 TestProg("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
496#endif
497#ifdef R__LINUX
498 TestProg("/usr/bin/chromium");
499 TestProg("/usr/bin/chromium-browser");
500 TestProg("/usr/bin/chrome-browser");
501 TestProg("/usr/bin/google-chrome-stable");
502 TestProg("/usr/bin/google-chrome");
503#endif
504
505// --no-sandbox is required to run chrome with super-user, but only in headless mode
506
507#ifdef _MSC_VER
508 // here --headless=old required to let normally end of Edge process when --dump-dom is used
509 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless=old --no-sandbox $geometry --dump-dom $url");
510 // in interactive headless mode fork used to let stop browser via process id
511 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless=old --no-sandbox --disable-gpu $geometry \"$url\"");
512 fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=$url &"); // & in windows mean usage of spawn
513#else
514#ifdef R__MACOSX
515 bool use_normal = true; // mac does not like new flag
516#else
517 bool use_normal = fChromeVersion < 119;
518#endif
519 if (use_normal) {
520 // old browser with standard headless mode
521 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless --no-sandbox --disable-extensions --disable-audio-output $geometry --dump-dom $url 2>/dev/null");
522 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless --no-sandbox --disable-extensions --disable-audio-output $geometry $url");
523 } else {
524 // newer version with headless=new mode
525 fBatchExec = gEnv->GetValue((fEnvPrefix + "Batch").c_str(), "$prog --headless=new --no-sandbox --disable-extensions --disable-audio-output $geometry --dump-dom $url 2>/dev/null");
526 fHeadlessExec = gEnv->GetValue((fEnvPrefix + "Headless").c_str(), "fork:--headless=new --no-sandbox --disable-extensions --disable-audio-output $geometry $url");
527 }
528 fExec = gEnv->GetValue((fEnvPrefix + "Interactive").c_str(), "$prog $geometry --new-window --app=\'$url\' >/dev/null 2>/dev/null &");
529#endif
530}
531
532
533//////////////////////////////////////////////////////////////////////////////////////////////////
534/// Replace $geometry placeholder with geometry settings
535/// Also RWebDisplayArgs::GetExtraArgs() are appended
536
538{
539 std::string geometry;
540 if ((args.GetWidth() > 0) && (args.GetHeight() > 0))
541 geometry = "--window-size="s + std::to_string(args.GetWidth())
542 + (args.IsHeadless() ? "x"s : ","s)
543 + std::to_string(args.GetHeight());
544
545 if (((args.GetX() >= 0) || (args.GetY() >= 0)) && !args.IsHeadless()) {
546 if (!geometry.empty()) geometry.append(" ");
547 geometry.append("--window-position="s + std::to_string(args.GetX() >= 0 ? args.GetX() : 0) + ","s +
548 std::to_string(args.GetY() >= 0 ? args.GetY() : 0));
549 }
550
551 if (!args.GetExtraArgs().empty()) {
552 if (!geometry.empty()) geometry.append(" ");
553 geometry.append(args.GetExtraArgs());
554 }
555
556 exec = std::regex_replace(exec, std::regex("\\$geometry"), geometry);
557}
558
559
560//////////////////////////////////////////////////////////////////////////////////////////////////
561/// Handle profile argument
562
563std::string RWebDisplayHandle::ChromeCreator::MakeProfile(std::string &exec, bool)
564{
565 std::string rmdir, profile_arg;
566
567 if (exec.find("$profile") == std::string::npos)
568 return rmdir;
569
570 const char *chrome_profile = gEnv->GetValue((fEnvPrefix + "Profile").c_str(), "");
571 if (chrome_profile && *chrome_profile) {
572 profile_arg = chrome_profile;
573 } else {
574 gRandom->SetSeed(0);
575 profile_arg = gSystem->TempDirectory();
576#ifdef _MSC_VER
577 char slash = '\\';
578#else
579 char slash = '/';
580#endif
581 if (!profile_arg.empty() && (profile_arg[profile_arg.length()-1] != slash))
582 profile_arg += slash;
583 profile_arg += "root_chrome_profile_"s + std::to_string(gRandom->Integer(0x100000));
584
585 rmdir = profile_arg;
586 }
587
588 exec = std::regex_replace(exec, std::regex("\\$profile"), profile_arg);
589
590 return rmdir;
591}
592
593
594//////////////////////////////////////////////////////////////////////////////////////////////////
595/// Constructor
596
598{
599 TestProg(gEnv->GetValue("WebGui.Firefox", ""));
600
601#ifdef _MSC_VER
602 TestProg("\\Mozilla Firefox\\firefox.exe", true);
603#endif
604#ifdef R__MACOSX
605 TestProg("/Applications/Firefox.app/Contents/MacOS/firefox");
606#endif
607#ifdef R__LINUX
608 TestProg("/usr/bin/firefox");
609 TestProg("/usr/bin/firefox-bin");
610#endif
611
612#ifdef _MSC_VER
613 // there is a problem when specifying the window size with wmic on windows:
614 // It gives: Invalid format. Hint: <paramlist> = <param> [, <paramlist>].
615 fBatchExec = gEnv->GetValue("WebGui.FirefoxBatch", "$prog -headless -no-remote $profile $url");
616 fHeadlessExec = gEnv->GetValue("WebGui.FirefoxHeadless", "fork:-headless -no-remote $profile \"$url\"");
617 fExec = gEnv->GetValue("WebGui.FirefoxInteractive", "$prog -no-remote $profile $geometry $url &");
618#else
619 fBatchExec = gEnv->GetValue("WebGui.FirefoxBatch", "$rootetcdir/runfirefox.sh $dumpfile $cleanup_profile $prog --headless -no-remote -new-instance $profile $url 2>/dev/null");
620 fHeadlessExec = gEnv->GetValue("WebGui.FirefoxHeadless", "fork:--headless -no-remote $profile --private-window $url");
621 fExec = gEnv->GetValue("WebGui.FirefoxInteractive", "$rootetcdir/runfirefox.sh __nodump__ $cleanup_profile $prog -no-remote $profile $geometry -url \'$url\' &");
622#endif
623}
624
625//////////////////////////////////////////////////////////////////////////////////////////////////
626/// Process window geometry for Firefox
627
629{
630 std::string geometry;
631 if ((args.GetWidth() > 0) && (args.GetHeight() > 0) && !args.IsHeadless())
632 geometry = "-width="s + std::to_string(args.GetWidth()) + " -height=" + std::to_string(args.GetHeight());
633
634 exec = std::regex_replace(exec, std::regex("\\$geometry"), geometry);
635}
636
637//////////////////////////////////////////////////////////////////////////////////////////////////
638/// Create Firefox profile to run independent browser window
639
640std::string RWebDisplayHandle::FirefoxCreator::MakeProfile(std::string &exec, bool batch_mode)
641{
642 std::string rmdir, profile_arg;
643
644 if (exec.find("$profile") == std::string::npos)
645 return rmdir;
646
647 const char *ff_profile = gEnv->GetValue("WebGui.FirefoxProfile", "");
648 const char *ff_profilepath = gEnv->GetValue("WebGui.FirefoxProfilePath", "");
649 Int_t ff_randomprofile = gEnv->GetValue("WebGui.FirefoxRandomProfile", (Int_t) 1);
650 if (ff_profile && *ff_profile) {
651 profile_arg = "-P "s + ff_profile;
652 } else if (ff_profilepath && *ff_profilepath) {
653 profile_arg = "-profile "s + ff_profilepath;
654 } else if (ff_randomprofile > 0) {
655
656 gRandom->SetSeed(0);
657 std::string profile_dir = gSystem->TempDirectory();
658
659#ifdef _MSC_VER
660 char slash = '\\';
661#else
662 char slash = '/';
663#endif
664 if (!profile_dir.empty() && (profile_dir[profile_dir.length()-1] != slash))
665 profile_dir += slash;
666 profile_dir += "root_ff_profile_"s + std::to_string(gRandom->Integer(0x100000));
667
668 profile_arg = "-profile "s + profile_dir;
669
670 if (gSystem->mkdir(profile_dir.c_str()) == 0) {
671 rmdir = profile_dir;
672
673 std::ofstream user_js(profile_dir + "/user.js", std::ios::trunc);
674 // workaround for current Firefox, without such settings it fail to close window and terminate it from batch
675 // also disable question about upload of data
676 user_js << "user_pref(\"datareporting.policy.dataSubmissionPolicyAcceptedVersion\", 2);" << std::endl;
677 user_js << "user_pref(\"datareporting.policy.dataSubmissionPolicyNotifiedTime\", \"1635760572813\");" << std::endl;
678
679 // try to ensure that window closes with last tab
680 user_js << "user_pref(\"browser.tabs.closeWindowWithLastTab\", true);" << std::endl;
681 user_js << "user_pref(\"dom.allow_scripts_to_close_windows\", true);" << std::endl;
682 user_js << "user_pref(\"browser.sessionstore.resume_from_crash\", false);" << std::endl;
683
684 if (batch_mode) {
685 // allow to dump messages to std output
686 user_js << "user_pref(\"browser.dom.window.dump.enabled\", true);" << std::endl;
687 } else {
688 // to suppress annoying privacy tab
689 user_js << "user_pref(\"datareporting.policy.firstRunURL\", \"\");" << std::endl;
690 // to use custom userChrome.css files
691 user_js << "user_pref(\"toolkit.legacyUserProfileCustomizations.stylesheets\", true);" << std::endl;
692 // do not put tabs in title
693 user_js << "user_pref(\"browser.tabs.inTitlebar\", 0);" << std::endl;
694
695 std::ofstream times_json(profile_dir + "/times.json", std::ios::trunc);
696 times_json << "{" << std::endl;
697 times_json << " \"created\": 1699968480952," << std::endl;
698 times_json << " \"firstUse\": null" << std::endl;
699 times_json << "}" << std::endl;
700 if (gSystem->mkdir((profile_dir + "/chrome").c_str()) == 0) {
701 std::ofstream style(profile_dir + "/chrome/userChrome.css", std::ios::trunc);
702 // do not show tabs
703 style << "#TabsToolbar { visibility: collapse; }" << std::endl;
704 // do not show URL
705 style << "#nav-bar, #urlbar-container, #searchbar { visibility: collapse !important; }" << std::endl;
706 }
707 }
708
709 } else {
710 R__LOG_ERROR(WebGUILog()) << "Cannot create Firefox profile directory " << profile_dir;
711 }
712 }
713
714 exec = std::regex_replace(exec, std::regex("\\$profile"), profile_arg);
715
716 if (exec.find("$cleanup_profile") != std::string::npos) {
717 if (rmdir.empty()) rmdir = "__dummy__";
718 exec = std::regex_replace(exec, std::regex("\\$cleanup_profile"), rmdir);
719 rmdir.clear(); // no need to delete directory - it will be removed by script
720 }
721
722 return rmdir;
723}
724
725///////////////////////////////////////////////////////////////////////////////////////////////////
726/// Check if http server required for display
727/// \param args - defines where and how to display web window
728
730{
734 return false;
735
736 if (!args.IsHeadless() && (args.GetBrowserKind() == RWebDisplayArgs::kOn)) {
737
738#ifdef WITH_QT6WEB
739 auto &qt6 = FindCreator("qt6", "libROOTQt6WebDisplay");
740 if (qt6 && qt6->IsActive())
741 return false;
742#endif
743#ifdef WITH_QT5WEB
744 auto &qt5 = FindCreator("qt5", "libROOTQt5WebDisplay");
745 if (qt5 && qt5->IsActive())
746 return false;
747#endif
748#ifdef WITH_CEFWEB
749 auto &cef = FindCreator("cef", "libROOTCefDisplay");
750 if (cef && cef->IsActive())
751 return false;
752#endif
753 }
754
755 return true;
756}
757
758
759///////////////////////////////////////////////////////////////////////////////////////////////////
760/// Create web display
761/// \param args - defines where and how to display web window
762/// Returns RWebDisplayHandle, which holds information of running browser application
763/// Can be used fully independent from RWebWindow classes just to show any web page
764
765std::unique_ptr<RWebDisplayHandle> RWebDisplayHandle::Display(const RWebDisplayArgs &args)
766{
767 std::unique_ptr<RWebDisplayHandle> handle;
768
770 return handle;
771
772 auto try_creator = [&](std::unique_ptr<Creator> &creator) {
773 if (!creator || !creator->IsActive())
774 return false;
775 handle = creator->Display(args);
776 return handle ? true : false;
777 };
778
779 bool handleAsLocal = (args.GetBrowserKind() == RWebDisplayArgs::kLocal) ||
780 (!args.IsHeadless() && (args.GetBrowserKind() == RWebDisplayArgs::kOn)),
781 has_qt5web = false, has_qt6web = false, has_cefweb = false;
782
783#ifdef WITH_QT5WEB
784 has_qt5web = true;
785#endif
786
787#ifdef WITH_QT6WEB
788 has_qt6web = true;
789#endif
790
791#ifdef WITH_CEFWEB
792 has_cefweb = true;
793#endif
794
795 if ((handleAsLocal && has_qt6web) || (args.GetBrowserKind() == RWebDisplayArgs::kQt6)) {
796 if (try_creator(FindCreator("qt6", "libROOTQt6WebDisplay")))
797 return handle;
798 }
799
800 // qt5 uses older chromium therefore do not invoke by default
801 if (has_qt5web && (args.GetBrowserKind() == RWebDisplayArgs::kQt5)) {
802 if (try_creator(FindCreator("qt5", "libROOTQt5WebDisplay")))
803 return handle;
804 }
805
806 if ((handleAsLocal && has_cefweb) || (args.GetBrowserKind() == RWebDisplayArgs::kCEF)) {
807 if (try_creator(FindCreator("cef", "libROOTCefDisplay")))
808 return handle;
809 }
810
811 if (args.IsLocalDisplay()) {
812 R__LOG_ERROR(WebGUILog()) << "Neither Qt5/6 nor CEF libraries were found to provide local display";
813 return handle;
814 }
815
816 bool handleAsNative =
818
819 if (handleAsNative || (args.GetBrowserKind() == RWebDisplayArgs::kChrome)) {
820 if (try_creator(FindCreator("chrome", "ChromeCreator")))
821 return handle;
822 }
823
824 if (handleAsNative || (args.GetBrowserKind() == RWebDisplayArgs::kFirefox)) {
825 if (try_creator(FindCreator("firefox", "FirefoxCreator")))
826 return handle;
827 }
828
829#ifdef _MSC_VER
830 // Edge browser cannot be run headless without registry change, therefore do not try it by default
831 if ((handleAsNative && !args.IsHeadless() && !args.IsBatchMode()) || (args.GetBrowserKind() == RWebDisplayArgs::kEdge)) {
832 if (try_creator(FindCreator("edge", "ChromeCreator")))
833 return handle;
834 }
835#endif
836
839 // R__LOG_ERROR(WebGUILog()) << "Neither Chrome nor Firefox browser cannot be started to provide display";
840 return handle;
841 }
842
844 if (try_creator(FindCreator("safari", "SafariCreator")))
845 return handle;
846 }
847
849 std::unique_ptr<Creator> creator = std::make_unique<BrowserCreator>(false, args.GetCustomExec());
850 try_creator(creator);
851 } else {
852 try_creator(FindCreator("browser", "BrowserCreator"));
853 }
854
855 return handle;
856}
857
858///////////////////////////////////////////////////////////////////////////////////////////////////
859/// Display provided url in configured web browser
860/// \param url - specified URL address like https://root.cern
861/// Browser can specified when starting `root --web=firefox`
862/// Returns true when browser started
863/// It is convenience method, equivalent to:
864/// ~~~
865/// RWebDisplayArgs args;
866/// args.SetUrl(url);
867/// args.SetStandalone(false);
868/// auto handle = RWebDisplayHandle::Display(args);
869/// ~~~
870
871bool RWebDisplayHandle::DisplayUrl(const std::string &url)
872{
873 RWebDisplayArgs args;
874 args.SetUrl(url);
875 args.SetStandalone(false);
876
877 auto handle = Display(args);
878
879 return !!handle;
880}
881
882///////////////////////////////////////////////////////////////////////////////////////////////////
883/// Checks if configured browser can be used for image production
884
886{
890 bool detected = false;
891
892 auto &h1 = FindCreator("chrome", "ChromeCreator");
893 if (h1 && h1->IsActive()) {
895 detected = true;
896 }
897
898 if (!detected) {
899 auto &h2 = FindCreator("firefox", "FirefoxCreator");
900 if (h2 && h2->IsActive()) {
902 detected = true;
903 }
904 }
905
906 return detected;
907 }
908
910 auto &h1 = FindCreator("chrome", "ChromeCreator");
911 return h1 && h1->IsActive();
912 }
913
915 auto &h2 = FindCreator("firefox", "FirefoxCreator");
916 return h2 && h2->IsActive();
917 }
918
919#ifdef _MSC_VER
921 auto &h3 = FindCreator("edge", "ChromeCreator");
922 return h3 && h3->IsActive();
923 }
924#endif
925
926 return true;
927}
928
929///////////////////////////////////////////////////////////////////////////////////////////////////
930/// Returns true if image production for specified browser kind is supported
931/// If browser not specified - use currently configured browser or try to test existing web browsers
932
933bool RWebDisplayHandle::CanProduceImages(const std::string &browser)
934{
935 RWebDisplayArgs args(browser);
936
937 return CheckIfCanProduceImages(args);
938}
939
940///////////////////////////////////////////////////////////////////////////////////////////////////
941/// Detect image format
942/// There is special handling of ".screenshot.pdf" and ".screenshot.png" extensions
943/// Creation of such files relies on headless browser functionality and fully supported only by Chrome browser
944
945std::string RWebDisplayHandle::GetImageFormat(const std::string &fname)
946{
947 std::string _fname = fname;
948 std::transform(_fname.begin(), _fname.end(), _fname.begin(), ::tolower);
949 auto EndsWith = [&_fname](const std::string &suffix) {
950 return (_fname.length() > suffix.length()) ? (0 == _fname.compare(_fname.length() - suffix.length(), suffix.length(), suffix)) : false;
951 };
952
953 if (EndsWith(".screenshot.pdf"))
954 return "s.pdf"s;
955 if (EndsWith(".pdf"))
956 return "pdf"s;
957 if (EndsWith(".json"))
958 return "json"s;
959 if (EndsWith(".svg"))
960 return "svg"s;
961 if (EndsWith(".screenshot.png"))
962 return "s.png"s;
963 if (EndsWith(".png"))
964 return "png"s;
965 if (EndsWith(".jpg") || EndsWith(".jpeg"))
966 return "jpeg"s;
967 if (EndsWith(".webp"))
968 return "webp"s;
969
970 return ""s;
971}
972
973
974///////////////////////////////////////////////////////////////////////////////////////////////////
975/// Produce image file using JSON data as source
976/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
977
978bool RWebDisplayHandle::ProduceImage(const std::string &fname, const std::string &json, int width, int height, const char *batch_file)
979{
980 return ProduceImages(fname, {json}, {width}, {height}, batch_file);
981}
982
983
984///////////////////////////////////////////////////////////////////////////////////////////////////
985/// Produce vector of file names for specified file pattern
986/// Depending from supported file forma
987
988std::vector<std::string> RWebDisplayHandle::ProduceImagesNames(const std::string &fname, unsigned nfiles)
989{
990 auto fmt = GetImageFormat(fname);
991
992 std::vector<std::string> fnames;
993
994 if ((fmt == "s.pdf") || (fmt == "s.png")) {
995 fnames.emplace_back(fname);
996 } else {
997 std::string farg = fname;
998
999 bool has_quialifier = farg.find("%") != std::string::npos;
1000
1001 if (!has_quialifier && (nfiles > 1) && (fmt != "pdf")) {
1002 farg.insert(farg.rfind("."), "%d");
1003 has_quialifier = true;
1004 }
1005
1006 for (unsigned n = 0; n < nfiles; n++) {
1007 if(has_quialifier) {
1008 auto expand_name = TString::Format(farg.c_str(), (int) n);
1009 fnames.emplace_back(expand_name.Data());
1010 } else if (n > 0)
1011 fnames.emplace_back(""); // empty name is multiPdf
1012 else
1013 fnames.emplace_back(fname);
1014 }
1015 }
1016
1017 return fnames;
1018}
1019
1020
1021///////////////////////////////////////////////////////////////////////////////////////////////////
1022/// Produce image file(s) using JSON data as source
1023/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1024
1025bool 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)
1026{
1027 return ProduceImages(ProduceImagesNames(fname, jsons.size()), jsons, widths, heights, batch_file);
1028}
1029
1030///////////////////////////////////////////////////////////////////////////////////////////////////
1031/// Produce image file(s) using JSON data as source
1032/// Invokes JSROOT drawing functionality in headless browser - Google Chrome or Mozilla Firefox
1033
1034bool 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)
1035{
1036 if (fnames.empty() || jsons.empty())
1037 return false;
1038
1039 std::vector<std::string> fmts;
1040 for (auto& fname : fnames)
1041 fmts.emplace_back(GetImageFormat(fname));
1042
1043 bool is_any_image = false;
1044
1045 for (unsigned n = 0; (n < fmts.size()) && (n < jsons.size()); n++) {
1046 if (fmts[n] == "json") {
1047 std::ofstream ofs(fnames[n]);
1048 ofs << jsons[n];
1049 fmts[n].clear();
1050 } else if (!fmts[n].empty())
1051 is_any_image = true;
1052 }
1053
1054 if (!is_any_image)
1055 return true;
1056
1057 std::string fdebug;
1058 if (fnames.size() == 1)
1059 fdebug = fnames[0];
1060 else
1062
1063 const char *jsrootsys = gSystem->Getenv("JSROOTSYS");
1064 TString jsrootsysdflt;
1065 if (!jsrootsys) {
1066 jsrootsysdflt = TROOT::GetDataDir() + "/js";
1067 if (gSystem->ExpandPathName(jsrootsysdflt)) {
1068 R__LOG_ERROR(WebGUILog()) << "Fail to locate JSROOT " << jsrootsysdflt;
1069 return false;
1070 }
1071 jsrootsys = jsrootsysdflt.Data();
1072 }
1073
1074 RWebDisplayArgs args; // set default browser kind, only Chrome/Firefox/Edge or CEF/Qt5/Qt6 can be used here
1075 if (!CheckIfCanProduceImages(args)) {
1076 R__LOG_ERROR(WebGUILog()) << "Fail to detect supported browsers for image production";
1077 return false;
1078 }
1079
1080 auto isChromeBased = (args.GetBrowserKind() == RWebDisplayArgs::kChrome) || (args.GetBrowserKind() == RWebDisplayArgs::kEdge),
1081 isFirefox = args.GetBrowserKind() == RWebDisplayArgs::kFirefox;
1082
1083 std::vector<std::string> draw_kinds;
1084 bool use_browser_draw = false;
1085 TString jsonkind;
1086
1087 if (fmts[0] == "s.png") {
1088 if (!isChromeBased && !isFirefox) {
1089 R__LOG_ERROR(WebGUILog()) << "Direct png image creation supported only by Chrome and Firefox browsers";
1090 return false;
1091 }
1092 use_browser_draw = true;
1093 jsonkind = "1111"; // special mark in canv_batch.htm
1094 } else if (fmts[0] == "s.pdf") {
1095 if (!isChromeBased) {
1096 R__LOG_ERROR(WebGUILog()) << "Direct creation of PDF files supported only by Chrome-based browser";
1097 return false;
1098 }
1099 use_browser_draw = true;
1100 jsonkind = "2222"; // special mark in canv_batch.htm
1101 } else {
1102 draw_kinds = fmts;
1103 jsonkind = TBufferJSON::ToJSON(&draw_kinds, TBufferJSON::kNoSpaces);
1104 }
1105
1106 if (!batch_file || !*batch_file)
1107 batch_file = "/js/files/canv_batch.htm";
1108
1109 TString origin = TROOT::GetDataDir() + batch_file;
1110 if (gSystem->ExpandPathName(origin)) {
1111 R__LOG_ERROR(WebGUILog()) << "Fail to find " << origin;
1112 return false;
1113 }
1114
1115 auto filecont = THttpServer::ReadFileContent(origin.Data());
1116 if (filecont.empty()) {
1117 R__LOG_ERROR(WebGUILog()) << "Fail to read content of " << origin;
1118 return false;
1119 }
1120
1121 int max_width = 0, max_height = 0, page_margin = 10;
1122 for (auto &w : widths)
1123 if (w > max_width)
1124 max_width = w;
1125 for (auto &h : heights)
1126 if (h > max_height)
1127 max_height = h;
1128
1129 auto jsonw = TBufferJSON::ToJSON(&widths, TBufferJSON::kNoSpaces);
1130 auto jsonh = TBufferJSON::ToJSON(&heights, TBufferJSON::kNoSpaces);
1131
1132 std::string mains;
1133 for (auto &json : jsons) {
1134 mains.append(mains.empty() ? "[" : ", ");
1135 mains.append(json);
1136 }
1137 mains.append("]");
1138
1139 if (strstr(jsrootsys, "http://") || strstr(jsrootsys, "https://") || strstr(jsrootsys, "file://"))
1140 filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), jsrootsys);
1141 else {
1142 static std::string jsroot_include = "<script id=\"jsroot\" src=\"$jsrootsys/build/jsroot.js\"></script>";
1143 auto p = filecont.find(jsroot_include);
1144 if (p != std::string::npos) {
1145 auto jsroot_build = THttpServer::ReadFileContent(std::string(jsrootsys) + "/build/jsroot.js");
1146 if (!jsroot_build.empty()) {
1147 // insert actual jsroot file location
1148 jsroot_build = std::regex_replace(jsroot_build, std::regex("'\\$jsrootsys'"), std::string("'file://") + jsrootsys + "/'");
1149 filecont.erase(p, jsroot_include.length());
1150 filecont.insert(p, "<script id=\"jsroot\">" + jsroot_build + "</script>");
1151 }
1152 }
1153
1154 filecont = std::regex_replace(filecont, std::regex("\\$jsrootsys"), "file://"s + jsrootsys);
1155 }
1156
1157 filecont = std::regex_replace(filecont, std::regex("\\$page_margin"), std::to_string(page_margin) + "px");
1158 filecont = std::regex_replace(filecont, std::regex("\\$page_width"), std::to_string(max_width + 2*page_margin) + "px");
1159 filecont = std::regex_replace(filecont, std::regex("\\$page_height"), std::to_string(max_height + 2*page_margin) + "px");
1160
1161 filecont = std::regex_replace(filecont, std::regex("\\$draw_kind"), jsonkind.Data());
1162 filecont = std::regex_replace(filecont, std::regex("\\$draw_widths"), jsonw.Data());
1163 filecont = std::regex_replace(filecont, std::regex("\\$draw_heights"), jsonh.Data());
1164 filecont = std::regex_replace(filecont, std::regex("\\$draw_objects"), mains);
1165
1166 TString dump_name;
1167 if (!use_browser_draw && (isChromeBased || isFirefox)) {
1168 dump_name = "canvasdump";
1169 FILE *df = gSystem->TempFileName(dump_name);
1170 if (!df) {
1171 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary file for dump-dom";
1172 return false;
1173 }
1174 fputs("placeholder", df);
1175 fclose(df);
1176 }
1177
1178 // When true, place HTML file into home directory
1179 // Some Chrome installation do not allow run html code from files, created in /tmp directory
1180 static bool chrome_tmp_workaround = false;
1181
1182 TString tmp_name, html_name;
1183
1184try_again:
1185
1187 args.SetUrl(""s);
1188 args.SetPageContent(filecont);
1189
1190 tmp_name.Clear();
1191 html_name.Clear();
1192
1193 R__LOG_DEBUG(0, WebGUILog()) << "Using file content_len " << filecont.length() << " to produce batch images ";
1194
1195 } else {
1196 tmp_name = "canvasbody";
1197 FILE *hf = gSystem->TempFileName(tmp_name);
1198 if (!hf) {
1199 R__LOG_ERROR(WebGUILog()) << "Fail to create temporary file for batch job";
1200 return false;
1201 }
1202 fputs(filecont.c_str(), hf);
1203 fclose(hf);
1204
1205 html_name = tmp_name + ".html";
1206
1207 if (chrome_tmp_workaround) {
1208 std::string homedir = gSystem->GetHomeDirectory();
1209 auto pos = html_name.Last('/');
1210 if (pos == kNPOS)
1211 html_name = TString::Format("/random%d.html", gRandom->Integer(1000000));
1212 else
1213 html_name.Remove(0, pos);
1214 html_name = homedir + html_name.Data();
1215 gSystem->Unlink(html_name.Data());
1216 gSystem->Unlink(tmp_name.Data());
1217
1218 std::ofstream ofs(html_name.Data(), std::ofstream::out);
1219 ofs << filecont;
1220 } else {
1221 if (gSystem->Rename(tmp_name.Data(), html_name.Data()) != 0) {
1222 R__LOG_ERROR(WebGUILog()) << "Fail to rename temp file " << tmp_name << " into " << html_name;
1223 gSystem->Unlink(tmp_name.Data());
1224 return false;
1225 }
1226 }
1227
1228 args.SetUrl("file://"s + gSystem->UnixPathName(html_name.Data()));
1229 args.SetPageContent(""s);
1230
1231 R__LOG_DEBUG(0, WebGUILog()) << "Using " << html_name << " content_len " << filecont.length() << " to produce batch images " << fdebug;
1232 }
1233
1234 TString wait_file_name, tgtfilename;
1235
1236 args.SetStandalone(true);
1237 args.SetHeadless(true);
1238 args.SetBatchMode(true);
1239 args.SetSize(widths[0], heights[0]);
1240
1241 if (use_browser_draw) {
1242
1243 tgtfilename = fnames[0].c_str();
1244 if (!gSystem->IsAbsoluteFileName(tgtfilename.Data()))
1246
1247 wait_file_name = tgtfilename;
1248
1249 if (fmts[0] == "s.pdf")
1250 args.SetExtraArgs("--print-to-pdf-no-header --print-to-pdf="s + gSystem->UnixPathName(tgtfilename.Data()));
1251 else if (isFirefox) {
1252 args.SetExtraArgs("--screenshot"); // firefox does not let specify output image file
1253 wait_file_name = "screenshot.png";
1254 } else
1255 args.SetExtraArgs("--screenshot="s + gSystem->UnixPathName(tgtfilename.Data()));
1256
1257 // remove target image file - we use it as detection when chrome is ready
1258 gSystem->Unlink(tgtfilename.Data());
1259
1260 } else if (isFirefox) {
1261 // firefox will use window.dump to output produced result
1262 args.SetRedirectOutput(dump_name.Data());
1263 gSystem->Unlink(dump_name.Data());
1264 } else if (isChromeBased) {
1265 // chrome should have --dump-dom args configures
1266 args.SetRedirectOutput(dump_name.Data());
1267 gSystem->Unlink(dump_name.Data());
1268 }
1269
1270 auto handle = RWebDisplayHandle::Display(args);
1271
1272 if (!handle) {
1273 R__LOG_DEBUG(0, WebGUILog()) << "Cannot start " << args.GetBrowserName() << " to produce image " << fdebug;
1274 return false;
1275 }
1276
1277 // delete temporary HTML file
1278 if (html_name.Length() > 0) {
1279 if (gEnv->GetValue("WebGui.PreserveBatchFiles", -1) > 0)
1280 ::Info("ProduceImages", "Preserve batch file %s", html_name.Data());
1281 else
1282 gSystem->Unlink(html_name.Data());
1283 }
1284
1285 if (!wait_file_name.IsNull() && gSystem->AccessPathName(wait_file_name.Data())) {
1286 R__LOG_ERROR(WebGUILog()) << "Fail to produce image " << fdebug;
1287 return false;
1288 }
1289
1290 if (use_browser_draw) {
1291 if (fmts[0] == "s.pdf")
1292 ::Info("ProduceImages", "PDF file %s with %d pages has been created", fnames[0].c_str(), (int) jsons.size());
1293 else {
1294 if (isFirefox)
1295 gSystem->Rename("screenshot.png", fnames[0].c_str());
1296 ::Info("ProduceImages", "PNG file %s with %d pages has been created", fnames[0].c_str(), (int) jsons.size());
1297 }
1298 } else {
1299 auto dumpcont = handle->GetContent();
1300
1301 if ((dumpcont.length() > 20) && (dumpcont.length() < 60) && !chrome_tmp_workaround && isChromeBased) {
1302 // chrome creates dummy html file with mostly no content
1303 // problem running chrome from /tmp directory, lets try work from home directory
1304
1305 printf("Handle chrome workaround\n");
1306 chrome_tmp_workaround = true;
1307 goto try_again;
1308 }
1309
1310 if (dumpcont.length() < 100) {
1311 R__LOG_ERROR(WebGUILog()) << "Fail to dump HTML code into " << (dump_name.IsNull() ? "CEF" : dump_name.Data());
1312 return false;
1313 }
1314
1315 std::string::size_type p = 0;
1316
1317 for (unsigned n = 0; n < fmts.size(); n++) {
1318 if (fmts[n].empty())
1319 continue;
1320 if (fmts[n] == "svg") {
1321 auto p1 = dumpcont.find("<svg", p);
1322 auto p2 = dumpcont.find("</svg></div>", p1 + 4);
1323 p = p2 + 6;
1324 std::ofstream ofs(fnames[n]);
1325 if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) {
1326 ofs << dumpcont.substr(p1, p2-p1+6);
1327 ::Info("ProduceImages", "SVG file %s size %d bytes has been created", fnames[n].c_str(), (int) (p2-p1+6));
1328 } else {
1329 R__LOG_ERROR(WebGUILog()) << "Fail to extract SVG from HTML dump " << dump_name;
1330 ofs << "Failure!!!\n" << dumpcont;
1331 return false;
1332 }
1333 } else {
1334 auto p1 = dumpcont.find(";base64,", p);
1335 auto p2 = dumpcont.find("></div>", p1 + 4);
1336 p = p2 + 5;
1337
1338 if ((p1 != std::string::npos) && (p2 != std::string::npos) && (p1 < p2)) {
1339 auto base64 = dumpcont.substr(p1+8, p2-p1-9);
1340 auto binary = TBase64::Decode(base64.c_str());
1341
1342 std::ofstream ofs(fnames[n], std::ios::binary);
1343 ofs.write(binary.Data(), binary.Length());
1344
1345 ::Info("ProduceImages", "Image file %s size %d bytes has been created", fnames[n].c_str(), (int) binary.Length());
1346 } else {
1347 R__LOG_ERROR(WebGUILog()) << "Fail to extract image from dump HTML code " << dump_name;
1348
1349 return false;
1350 }
1351 }
1352 }
1353 }
1354
1355 R__LOG_DEBUG(0, WebGUILog()) << "Create " << (fnames.size() > 1 ? "files " : "file ") << fdebug;
1356
1357 return true;
1358}
1359
nlohmann::json json
#define R__LOG_ERROR(...)
Definition RLogger.hxx:362
#define R__LOG_DEBUG(DEBUGLEVEL,...)
Definition RLogger.hxx:365
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define h(i)
Definition RSha256.hxx:106
constexpr Ssiz_t kNPOS
Definition RtypesCore.h:117
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:218
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
R__EXTERN TRandom * gRandom
Definition TRandom.h:62
@ kExecutePermission
Definition TSystem.h:43
R__EXTERN TSystem * gSystem
Definition TSystem.h:561
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
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.
@ kQt5
Qt5 QWebEngine libraries - Chromium code packed in qt5.
@ 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
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 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:530
static const TString & GetEtcDir()
Get the sysconfig directory in the installation. Static utility function.
Definition TROOT.cxx:3055
static const TString & GetDataDir()
Get the data directory in the installation. Static utility function.
Definition TROOT.cxx:3065
virtual void SetSeed(ULong_t seed=0)
Set the random generator seed.
Definition TRandom.cxx:615
virtual UInt_t Integer(UInt_t imax)
Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
Definition TRandom.cxx:361
Basic string class.
Definition TString.h:139
Ssiz_t Length() const
Definition TString.h:417
void Clear()
Clear string without changing its capacity.
Definition TString.cxx:1235
const char * Data() const
Definition TString.h:376
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition TString.cxx:931
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2264
Bool_t IsNull() const
Definition TString.h:414
TString & Remove(Ssiz_t pos)
Definition TString.h:685
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:1499
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1274
virtual const char * Getenv(const char *env)
Get environment variable.
Definition TSystem.cxx:1665
virtual int mkdir(const char *name, Bool_t recursive=kFALSE)
Make a file system directory.
Definition TSystem.cxx:906
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:1857
virtual const char * PrependPathName(const char *dir, TString &name)
Concatenate a directory and a file name.
Definition TSystem.cxx:1081
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1296
virtual std::string GetHomeDirectory(const char *userName=nullptr) const
Return the user's home directory.
Definition TSystem.cxx:895
virtual const char * UnixPathName(const char *unixpathname)
Convert from a local pathname to a Unix pathname.
Definition TSystem.cxx:1063
virtual int Rename(const char *from, const char *to)
Rename a file.
Definition TSystem.cxx:1350
virtual TString GetFromPipe(const char *command)
Execute command and return output in TString.
Definition TSystem.cxx:680
virtual Bool_t IsAbsoluteFileName(const char *dir)
Return true if dir is an absolute pathname.
Definition TSystem.cxx:951
virtual const char * WorkingDirectory()
Return working directory.
Definition TSystem.cxx:871
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1381
virtual const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Definition TSystem.cxx:1482
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::Experimental::RLogChannel & WebGUILog()
Log channel for WebGUI diagnostics.
TCanvas * slash()
Definition slash.C:1
TMarker m
Definition textangle.C:8