Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RBrowser.cxx
Go to the documentation of this file.
1// Authors: Bertrand Bellenot <bertrand.bellenot@cern.ch> Sergey Linev <S.Linev@gsi.de>
2// Date: 2019-02-28
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-2021, 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
13#include <ROOT/RBrowser.hxx>
14
18
19#include <ROOT/RLogger.hxx>
20#include <ROOT/RFileDialog.hxx>
22
23#include "RBrowserWidget.hxx"
24
25#include "TString.h"
26#include "TSystem.h"
27#include "TError.h"
28#include "TTimer.h"
29#include "TROOT.h"
30#include "TBufferJSON.h"
31#include "TApplication.h"
32#include "TRint.h"
33#include "Getline.h"
34
35#include <sstream>
36#include <iostream>
37#include <algorithm>
38#include <memory>
39#include <mutex>
40#include <thread>
41#include <fstream>
42
43using namespace std::string_literals;
44
45namespace ROOT {
46
47class RBrowserTimer : public TTimer {
48public:
49 RBrowser &fBrowser; ///!< browser processing postponed requests
50
51 /// constructor
52 RBrowserTimer(Long_t milliSec, Bool_t mode, RBrowser &br) : TTimer(milliSec, mode), fBrowser(br) {}
53
54 /// timeout handler
55 /// used to process postponed requests in main ROOT thread
57};
58
59
61public:
62
63 bool fIsEditor{true}; ///<! either editor or image viewer
64 std::string fTitle;
65 std::string fFileName;
66 std::string fContent;
67 bool fFirstSend{false}; ///<! if editor content was send at least once
68 std::string fItemPath; ///<! item path in the browser
69
70 RBrowserEditorWidget(const std::string &name, bool is_editor = true) : RBrowserWidget(name), fIsEditor(is_editor) {}
71 virtual ~RBrowserEditorWidget() = default;
72
73 void ResetConn() override { fFirstSend = false; }
74
75 std::string GetKind() const override { return fIsEditor ? "editor"s : "image"s; }
76 std::string GetTitle() override { return fTitle; }
77 std::string GetUrl() override { return ""s; }
78
79 void Show(const std::string &) override {}
80
81 bool DrawElement(std::shared_ptr<Browsable::RElement> &elem, const std::string & = "") override
82 {
83 if (fIsEditor && elem->IsCapable(Browsable::RElement::kActEdit)) {
84 auto code = elem->GetContent("text");
85 if (!code.empty()) {
86 fFirstSend = false;
87 fContent = code;
88 fTitle = elem->GetName();
89 fFileName = elem->GetContent("filename");
90 } else {
91 auto json = elem->GetContent("json");
92 if (!json.empty()) {
93 fFirstSend = false;
94 fContent = json;
95 fTitle = elem->GetName() + ".json";
96 fFileName = "";
97 }
98 }
99 if (!fContent.empty()) {
100 // page->fItemPath = item_path;
101 return true;
102 }
103 }
104
105 if (!fIsEditor && elem->IsCapable(Browsable::RElement::kActImage)) {
106 auto img = elem->GetContent("image64");
107 if (!img.empty()) {
108 fFirstSend = false;
109 fContent = img;
110 fTitle = elem->GetName();
111 fFileName = elem->GetContent("filename");
112 // fItemPath = item_path;
113
114 return true;
115 }
116 }
117
118 return false;
119 }
120
121 std::string SendWidgetContent() override
122 {
123 if (fFirstSend) return ""s;
124
125 fFirstSend = true;
126 std::vector<std::string> args = { GetName(), fTitle, fFileName, fContent };
127
128 std::string msg = fIsEditor ? "EDITOR:"s : "IMAGE:"s;
129 msg += TBufferJSON::ToJSON(&args).Data();
130 return msg;
131 }
132
133};
134
135
137public:
138
139 enum { kMaxContentLen = 10000000 };
140
141 std::string fTitle;
142 std::string fContent;
143 bool fFirstSend{false}; ///<! if editor content was send at least once
144
146 {
147 fTitle = "Cling info"s;
148 Refresh();
149 }
150
151 virtual ~RBrowserInfoWidget() = default;
152
153 void ResetConn() override { fFirstSend = false; }
154
155 std::string GetKind() const override { return "info"s; }
156 std::string GetTitle() override { return fTitle; }
157 std::string GetUrl() override { return ""s; }
158
159 void Show(const std::string &) override {}
160
161 bool DrawElement(std::shared_ptr<Browsable::RElement> &, const std::string & = "") override { return false; }
162
163 void Refresh()
164 {
165 fFirstSend = false;
166 fContent = "";
167
168 std::ostringstream pathtmp;
169 pathtmp << gSystem->TempDirectory() << "/info." << gSystem->GetPid() << ".log";
170
171 std::ofstream ofs(pathtmp.str(), std::ofstream::out | std::ofstream::app);
172 ofs << "";
173 ofs.close();
174
175 gSystem->RedirectOutput(pathtmp.str().c_str(), "a");
176 gROOT->ProcessLine(".g");
177 gSystem->RedirectOutput(nullptr);
178
179 std::ifstream infile(pathtmp.str());
180 if (infile) {
181 std::string line;
182 while (std::getline(infile, line) && (fContent.length() < kMaxContentLen)) {
183 fContent.append(line);
184 fContent.append("\n");
185 }
186 }
187
188 gSystem->Unlink(pathtmp.str().c_str());
189 }
190
191 void RefreshFromLogs(const std::string &promt, const std::vector<std::string> &logs)
192 {
193 int indx = 0, last_prompt = -1;
194 for (auto &line : logs) {
195 if (line == promt)
196 last_prompt = indx;
197 indx++;
198 }
199
200 if (last_prompt < 0) {
201 Refresh();
202 return;
203 }
204
205 fFirstSend = false;
206 fContent = "";
207
208 indx = 0;
209 for (auto &line : logs) {
210 if ((indx++ > last_prompt) && (fContent.length() < kMaxContentLen)) {
211 fContent.append(line);
212 fContent.append("\n");
213 }
214 }
215 }
216
217
218 std::string SendWidgetContent() override
219 {
220 if (fFirstSend)
221 return ""s;
222
223 if (fContent.empty())
224 Refresh();
225
226 fFirstSend = true;
227 std::vector<std::string> args = { GetName(), fTitle, fContent };
228
229 return "INFO:"s + TBufferJSON::ToJSON(&args).Data();
230 }
231
232};
233
234
236public:
237
238 std::string fUrl; // url of catched widget
239 std::string fCatchedKind; // kind of catched widget
240
241 void Show(const std::string &) override {}
242
243 std::string GetKind() const override { return "catched"s; }
244
245 std::string GetUrl() override { return fUrl; }
246
247 std::string GetTitle() override { return fCatchedKind; }
248
249 RBrowserCatchedWidget(const std::string &name, const std::string &url, const std::string &kind) :
251 fUrl(url),
252 fCatchedKind(kind)
253 {
254 }
255};
256
257} // namespace ROOT
258
259using namespace ROOT;
260
261
262/** \class ROOT::RBrowser
263\ingroup rbrowser
264\brief Web-based %ROOT files and objects browser
265
266\image html v7_rbrowser.png
267
268*/
269
270//////////////////////////////////////////////////////////////////////////////////////////////
271/// constructor
272
273RBrowser::RBrowser(bool use_rcanvas)
274{
275 if (gROOT->IsWebDisplayBatch()) {
276 ::Warning("RBrowser::RBrowser", "The RBrowser cannot run in web batch mode");
277 return;
278 }
279
280 std::ostringstream pathtmp;
281 pathtmp << gSystem->TempDirectory() << "/command." << gSystem->GetPid() << ".log";
282 fPromptFileOutput = pathtmp.str();
283
284 SetUseRCanvas(use_rcanvas);
285
287
288 fTimer = std::make_unique<RBrowserTimer>(10, kTRUE, *this);
289
291 fWebWindow->SetDefaultPage("file:rootui5sys/browser/browser.html");
292
293 // this is call-back, invoked when message received via websocket
294 fWebWindow->SetCallBacks([this](unsigned connid) { if (!fConnId) { fConnId = connid; SendInitMsg(connid); } else fConnId = 0xffffff; },
295 [this](unsigned connid, const std::string &arg) { if ((connid == fConnId) && (fConnId != 0xffffff)) ProcessMsg(connid, arg); });
296 fWebWindow->SetGeometry(1200, 700); // configure predefined window geometry
297 fWebWindow->SetConnLimit(1); // the only connection is allowed
298 fWebWindow->SetMaxQueueLength(30); // number of allowed entries in the window queue
299
300 fWebWindow->GetManager()->SetShowCallback([this](RWebWindow &win, const RWebDisplayArgs &args) -> bool {
301
302 std::string kind;
303
304 if (args.GetWidgetKind() == "RCanvas")
305 kind = "rcanvas";
306 else if (args.GetWidgetKind() == "TCanvas")
307 kind = "tcanvas";
308 else if (args.GetWidgetKind() == "RGeomViewer")
309 kind = "geom";
310 else if (args.GetWidgetKind() == "RTreeViewer")
311 kind = "tree";
312
313 if (!fWebWindow || !fCatchWindowShow || kind.empty()) return false;
314
315 std::string url = fWebWindow->GetRelativeAddr(win);
316
317 auto widget = AddCatchedWidget(url, kind);
318
319 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
320 fWebWindow->Send(0, NewWidgetMsg(widget));
321
322 return widget ? true : false;
323 });
324
325 Show();
326
327 // add first canvas by default
328
329 //if (GetUseRCanvas())
330 // AddWidget("rcanvas");
331 //else
332 // AddWidget("tcanvas");
333
334 // AddWidget("geom"); // add geometry viewer at the beginning
335
336 // AddWidget("editor"); // one can add empty editor if necessary
337}
338
339//////////////////////////////////////////////////////////////////////////////////////////////
340/// destructor
341
343{
344 if (fWebWindow)
345 fWebWindow->GetManager()->SetShowCallback(nullptr);
346}
347
348//////////////////////////////////////////////////////////////////////////////////////////////
349/// Process browser request
350
351std::string RBrowser::ProcessBrowserRequest(const std::string &msg)
352{
353 std::unique_ptr<RBrowserRequest> request;
354
355 if (msg.empty()) {
356 request = std::make_unique<RBrowserRequest>();
357 request->first = 0;
358 request->number = 100;
359 } else {
360 request = TBufferJSON::FromJSON<RBrowserRequest>(msg);
361 }
362
363 if (!request)
364 return ""s;
365
366 if (request->path.empty() && fWidgets.empty() && fBrowsable.GetWorkingPath().empty())
368
369 return "BREPL:"s + fBrowsable.ProcessRequest(*request.get());
370}
371
372/////////////////////////////////////////////////////////////////////////////////
373/// Process file save command in the editor
374
375void RBrowser::ProcessSaveFile(const std::string &fname, const std::string &content)
376{
377 if (fname.empty()) return;
378 R__LOG_DEBUG(0, BrowserLog()) << "SaveFile " << fname << " content length " << content.length();
379 std::ofstream f(fname);
380 f << content;
381}
382
383/////////////////////////////////////////////////////////////////////////////////
384/// Process run macro command in the editor
385
386void RBrowser::ProcessRunMacro(const std::string &file_path)
387{
388 if (file_path.rfind(".py") == file_path.length() - 3) {
389 TString exec;
390 exec.Form("TPython::ExecScript(\"%s\");", file_path.c_str());
391 gROOT->ProcessLine(exec.Data());
392 } else {
393 gInterpreter->ExecuteMacro(file_path.c_str());
394 }
395}
396
397/////////////////////////////////////////////////////////////////////////////////
398/// Process dbl click on browser item
399
400std::string RBrowser::ProcessDblClick(unsigned connid, std::vector<std::string> &args)
401{
402 args.pop_back(); // remove exec string, not used now
403
404 std::string opt = args.back();
405 args.pop_back(); // remove option
406
407 auto path = fBrowsable.GetWorkingPath();
408 path.insert(path.end(), args.begin(), args.end());
409
410 R__LOG_DEBUG(0, BrowserLog()) << "DoubleClick " << Browsable::RElement::GetPathAsString(path);
411
412 auto elem = fBrowsable.GetSubElement(path);
413 if (!elem) return ""s;
414
415 auto dflt_action = elem->GetDefaultAction();
416
417 // special case when canvas is clicked - always start new widget
418 if (dflt_action == Browsable::RElement::kActCanvas) {
419 std::string widget_kind;
420
421 if (elem->IsCapable(Browsable::RElement::kActDraw7))
422 widget_kind = "rcanvas";
423 else
424 widget_kind = "tcanvas";
425
426 std::string name = widget_kind + std::to_string(++fWidgetCnt);
427
428 auto new_widget = RBrowserWidgetProvider::CreateWidgetFor(widget_kind, name, elem);
429
430 if (!new_widget)
431 return ""s;
432
433 // assign back pointer
434 new_widget->fBrowser = this;
435
436 new_widget->Show("embed");
437 fWidgets.emplace_back(new_widget);
438 fActiveWidgetName = new_widget->GetName();
439
440 return NewWidgetMsg(new_widget);
441 }
442
443 // before display tree or geometry ensure that they read and cached inside element
444 if (elem->IsCapable(Browsable::RElement::kActGeom) || elem->IsCapable(Browsable::RElement::kActTree)) {
445 elem->GetChildsIter();
446 }
447
449 Browsable::RProvider::ProgressHandle handle(elem.get(), [this, connid](float progress, void *) {
450 SendProgress(connid, progress);
451 });
452
453 auto widget = GetActiveWidget();
454 if (widget && widget->DrawElement(elem, opt)) {
455 widget->SetPath(path);
456 return widget->SendWidgetContent();
457 }
458
459 // check if element was drawn in other widget and just activate that widget
460 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
461 [path](const std::shared_ptr<RBrowserWidget> &wg) { return path == wg->GetPath(); });
462
463 if (iter != fWidgets.end())
464 return "SELECT_WIDGET:"s + (*iter)->GetName();
465
466 // check if object can be drawn in RCanvas even when default action is drawing in TCanvas
467 if ((dflt_action == Browsable::RElement::kActDraw6) && GetUseRCanvas() && elem->IsCapable(Browsable::RElement::kActDraw7))
468 dflt_action = Browsable::RElement::kActDraw7;
469
470 std::string widget_kind;
471 switch(dflt_action) {
472 case Browsable::RElement::kActDraw6: widget_kind = "tcanvas"; break;
473 case Browsable::RElement::kActDraw7: widget_kind = "rcanvas"; break;
474 case Browsable::RElement::kActEdit: widget_kind = "editor"; break;
475 case Browsable::RElement::kActImage: widget_kind = "image"; break;
476 case Browsable::RElement::kActTree: widget_kind = "tree"; break;
477 case Browsable::RElement::kActGeom: widget_kind = "geom"; break;
478 default: widget_kind.clear();
479 }
480
481 if (!widget_kind.empty()) {
482 auto new_widget = AddWidget(widget_kind);
483 if (new_widget) {
484 // draw object before client side is created - should not be a problem
485 // after widget add in browser, connection will be established and data provided
486 if (new_widget->DrawElement(elem, opt))
487 new_widget->SetPath(path);
488 return NewWidgetMsg(new_widget);
489 }
490 }
491
492 if (elem->IsCapable(Browsable::RElement::kActBrowse) && (elem->GetNumChilds() > 0)) {
493 // remove extra index in subitems name
494 for (auto &pathelem : path)
498 }
499
500 return ""s;
501}
502
503/////////////////////////////////////////////////////////////////////////////////
504/// Show or update RBrowser in web window
505/// If web window already started - just refresh it like "reload" button does
506/// If no web window exists or \param always_start_new_browser configured, starts new window
507/// \param args display arguments
508
509void RBrowser::Show(const RWebDisplayArgs &args, bool always_start_new_browser)
510{
511 if (!fWebWindow->NumConnections() || always_start_new_browser) {
512 fWebWindow->Show(args);
513 } else {
514 SendInitMsg(0);
515 }
516}
517
518///////////////////////////////////////////////////////////////////////////////////////////////////////
519/// Hide ROOT Browser
520
522{
523 if (fWebWindow)
524 fWebWindow->CloseConnections();
525}
526
527
528//////////////////////////////////////////////////////////////////////////////////////////////
529/// Creates new widget
530
531std::shared_ptr<RBrowserWidget> RBrowser::AddWidget(const std::string &kind)
532{
533 std::string name = kind + std::to_string(++fWidgetCnt);
534
535 std::shared_ptr<RBrowserWidget> widget;
536
537 if (kind == "editor"s)
538 widget = std::make_shared<RBrowserEditorWidget>(name, true);
539 else if (kind == "image"s)
540 widget = std::make_shared<RBrowserEditorWidget>(name, false);
541 else if (kind == "info"s)
542 widget = std::make_shared<RBrowserInfoWidget>(name);
543 else
545
546 if (!widget) {
547 R__LOG_ERROR(BrowserLog()) << "Fail to create widget of kind " << kind;
548 return nullptr;
549 }
550
551 widget->fBrowser = this;
552 widget->Show("embed");
553 fWidgets.emplace_back(widget);
554
556
557 return widget;
558}
559
560//////////////////////////////////////////////////////////////////////////////////////////////
561/// Add widget catched from external scripts
562
563std::shared_ptr<RBrowserWidget> RBrowser::AddCatchedWidget(const std::string &url, const std::string &kind)
564{
565 if (url.empty()) return nullptr;
566
567 std::string name = "catched"s + std::to_string(++fWidgetCnt);
568
569 auto widget = std::make_shared<RBrowserCatchedWidget>(name, url, kind);
570
571 fWidgets.emplace_back(widget);
572
574
575 return widget;
576}
577
578
579//////////////////////////////////////////////////////////////////////////////////////////////
580/// Create new widget and send init message to the client
581
582void RBrowser::AddInitWidget(const std::string &kind)
583{
584 auto widget = AddWidget(kind);
585 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
586 fWebWindow->Send(0, NewWidgetMsg(widget));
587}
588
589//////////////////////////////////////////////////////////////////////////////////////////////
590/// Find widget by name or kind
591
592std::shared_ptr<RBrowserWidget> RBrowser::FindWidget(const std::string &name, const std::string &kind) const
593{
594 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
595 [name, kind](const std::shared_ptr<RBrowserWidget> &widget) {
596 return kind.empty() ? name == widget->GetName() : kind == widget->GetKind();
597 });
598
599 if (iter != fWidgets.end())
600 return *iter;
601
602 return nullptr;
603}
604
605//////////////////////////////////////////////////////////////////////////////////////////////
606/// Close and delete specified widget
607
608void RBrowser::CloseTab(const std::string &name)
609{
610 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(), [name](std::shared_ptr<RBrowserWidget> &widget) { return name == widget->GetName(); });
611 if (iter != fWidgets.end())
612 fWidgets.erase(iter);
613
614 if (fActiveWidgetName == name)
615 fActiveWidgetName.clear();
616}
617
618//////////////////////////////////////////////////////////////////////////////////////////////
619/// Get content of history file
620
621std::vector<std::string> RBrowser::GetRootHistory()
622{
623 std::vector<std::string> arr;
624
625 std::string path = gSystem->UnixPathName(gSystem->HomeDirectory());
626 path += "/.root_hist" ;
627 std::ifstream infile(path);
628
629 if (infile) {
630 std::string line;
631 while (std::getline(infile, line) && (arr.size() < 1000)) {
632 if(!(std::find(arr.begin(), arr.end(), line) != arr.end())) {
633 arr.emplace_back(line);
634 }
635 }
636 }
637
638 return arr;
639}
640
641//////////////////////////////////////////////////////////////////////////////////////////////
642/// Get content of log file
643
644std::vector<std::string> RBrowser::GetRootLogs()
645{
646 std::vector<std::string> arr;
647
648 std::ifstream infile(fPromptFileOutput);
649 if (infile) {
650 std::string line;
651 while (std::getline(infile, line) && (arr.size() < 10000)) {
652 arr.emplace_back(line);
653 }
654 }
655
656 return arr;
657}
658
659//////////////////////////////////////////////////////////////////////////////////////////////
660/// Process client connect
661
662void RBrowser::SendInitMsg(unsigned connid)
663{
664 std::vector<std::vector<std::string>> reply;
665
666 reply.emplace_back(fBrowsable.GetWorkingPath()); // first element is current path
667
668 for (auto &widget : fWidgets) {
669 widget->ResetConn();
670 reply.emplace_back(std::vector<std::string>({ widget->GetKind(), widget->GetUrl(), widget->GetName(), widget->GetTitle() }));
671 }
672
673 if (!fActiveWidgetName.empty())
674 reply.emplace_back(std::vector<std::string>({ "active"s, fActiveWidgetName }));
675
676 auto history = GetRootHistory();
677 if (history.size() > 0) {
678 history.insert(history.begin(), "history"s);
679 reply.emplace_back(history);
680 }
681
682 auto logs = GetRootLogs();
683 if (logs.size() > 0) {
684 logs.insert(logs.begin(), "logs"s);
685 reply.emplace_back(logs);
686 }
687
688 reply.emplace_back(std::vector<std::string>({
689 "drawoptions"s,
693 }));
694
695 std::string msg = "INMSG:";
696 msg.append(TBufferJSON::ToJSON(&reply, TBufferJSON::kNoSpaces).Data());
697
698 fWebWindow->Send(connid, msg);
699}
700
701//////////////////////////////////////////////////////////////////////////////////////////////
702/// Send generic progress message to the web window
703/// Should show progress bar on client side
704
705void RBrowser::SendProgress(unsigned connid, float progr)
706{
707 long long millisec = gSystem->Now();
708
709 // let process window events
710 fWebWindow->Sync();
711
712 if ((!fLastProgressSendTm || millisec > fLastProgressSendTm - 200) && (progr > fLastProgressSend + 0.04) && fWebWindow->CanSend(connid)) {
713 fWebWindow->Send(connid, "PROGRESS:"s + std::to_string(progr));
714
715 fLastProgressSendTm = millisec;
716 fLastProgressSend = progr;
717 }
718}
719
720
721//////////////////////////////////////////////////////////////////////////////////////////////
722/// Return the current directory of ROOT
723
725{
726 return "WORKPATH:"s + TBufferJSON::ToJSON(&fBrowsable.GetWorkingPath()).Data();
727}
728
729//////////////////////////////////////////////////////////////////////////////////////////////
730/// Create message which send to client to create new widget
731
732std::string RBrowser::NewWidgetMsg(std::shared_ptr<RBrowserWidget> &widget)
733{
734 std::vector<std::string> arr = { widget->GetKind(), widget->GetUrl(), widget->GetName(), widget->GetTitle(),
735 Browsable::RElement::GetPathAsString(widget->GetPath()) };
736 return "NEWWIDGET:"s + TBufferJSON::ToJSON(&arr, TBufferJSON::kNoSpaces).Data();
737}
738
739//////////////////////////////////////////////////////////////////////////////////////////////
740/// Check if any widget was modified and update if necessary
741
743{
744 for (auto &widget : fWidgets)
745 widget->CheckModified();
746}
747
748//////////////////////////////////////////////////////////////////////////////////////////////
749/// Process postponed requests - decouple from websocket handling
750/// Only requests which can take longer time should be postponed
751
753{
754 if (fPostponed.empty())
755 return;
756
757 auto arr = fPostponed[0];
758 fPostponed.erase(fPostponed.begin(), fPostponed.begin()+1);
759 if (fPostponed.empty())
760 fTimer->TurnOff();
761
762 std::string reply;
763 unsigned connid = std::stoul(arr.back()); arr.pop_back();
764 std::string kind = arr.back(); arr.pop_back();
765
766 if (kind == "DBLCLK") {
767 reply = ProcessDblClick(connid, arr);
768 if (reply.empty()) reply = "NOPE";
769 }
770
771 if (!reply.empty())
772 fWebWindow->Send(connid, reply);
773}
774
775
776//////////////////////////////////////////////////////////////////////////////////////////////
777/// Process received message from the client
778
779void RBrowser::ProcessMsg(unsigned connid, const std::string &arg0)
780{
781 R__LOG_DEBUG(0, BrowserLog()) << "ProcessMsg len " << arg0.length() << " substr(30) " << arg0.substr(0, 30);
782
783 std::string kind, msg;
784 auto pos = arg0.find(":");
785 if (pos == std::string::npos) {
786 kind = arg0;
787 } else {
788 kind = arg0.substr(0, pos);
789 msg = arg0.substr(pos+1);
790 }
791
792 if (kind == "QUIT_ROOT") {
793
794 fWebWindow->TerminateROOT();
795
796 } else if (kind == "BRREQ") {
797 // central place for processing browser requests
798 auto json = ProcessBrowserRequest(msg);
799 if (!json.empty()) fWebWindow->Send(connid, json);
800
801 } else if (kind == "DBLCLK") {
802
803 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
804 if (arr && (arr->size() > 2)) {
805 arr->push_back(kind);
806 arr->push_back(std::to_string(connid));
807 fPostponed.push_back(*arr);
808 if (fPostponed.size() == 1)
809 fTimer->TurnOn();
810 } else {
811 fWebWindow->Send(connid, "NOPE");
812 }
813
814 } else if (kind == "WIDGET_SELECTED") {
815 fActiveWidgetName = msg;
816 auto widget = GetActiveWidget();
817 if (widget) {
818 auto reply = widget->SendWidgetContent();
819 if (!reply.empty()) fWebWindow->Send(connid, reply);
820 }
821 } else if (kind == "CLOSE_TAB") {
822 CloseTab(msg);
823 } else if (kind == "GETWORKPATH") {
824 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
825 } else if (kind == "CHPATH") {
826 auto path = TBufferJSON::FromJSON<Browsable::RElementPath_t>(msg);
827 if (path) fBrowsable.SetWorkingPath(*path);
828 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
829 } else if (kind == "CMD") {
830 std::string sPrompt = "root []";
831 TApplication *app = gROOT->GetApplication();
832 if (app->InheritsFrom("TRint")) {
833 sPrompt = ((TRint*)gROOT->GetApplication())->GetPrompt();
834 Gl_histadd((char *)msg.c_str());
835 }
836
837 std::ofstream ofs(fPromptFileOutput, std::ofstream::out | std::ofstream::app);
838 ofs << sPrompt << msg << std::endl;
839 ofs.close();
840
842 gROOT->ProcessLine(msg.c_str());
843 gSystem->RedirectOutput(nullptr);
844
845 if (msg == ".g"s) {
846 auto widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(""s, "info"s));
847 if (!widget) {
848 auto new_widget = AddWidget("info"s);
849 fWebWindow->Send(connid, NewWidgetMsg(new_widget));
850 widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(new_widget);
851 } else if (fActiveWidgetName != widget->GetName()) {
852 fWebWindow->Send(connid, "SELECT_WIDGET:"s + widget->GetName());
853 fActiveWidgetName = widget->GetName();
854 }
855
856 if (widget)
857 widget->RefreshFromLogs(sPrompt + msg, GetRootLogs());
858 }
859
861 } else if (kind == "GETHISTORY") {
862
863 auto history = GetRootHistory();
864
865 fWebWindow->Send(connid, "HISTORY:"s + TBufferJSON::ToJSON(&history, TBufferJSON::kNoSpaces).Data());
866 } else if (kind == "GETLOGS") {
867
868 auto logs = GetRootLogs();
869 fWebWindow->Send(connid, "LOGS:"s + TBufferJSON::ToJSON(&logs, TBufferJSON::kNoSpaces).Data());
870
871 } else if (RFileDialog::IsMessageToStartDialog(arg0)) {
872
873 RFileDialog::Embed(fWebWindow, connid, arg0);
874
875 } else if (kind == "SYNCEDITOR") {
876 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
877 if (arr && (arr->size() > 4)) {
878 auto editor = std::dynamic_pointer_cast<RBrowserEditorWidget>(FindWidget(arr->at(0)));
879 if (editor) {
880 editor->fFirstSend = true;
881 editor->fTitle = arr->at(1);
882 editor->fFileName = arr->at(2);
883 if (!arr->at(3).empty()) editor->fContent = arr->at(4);
884 if ((arr->size() == 6) && (arr->at(5) == "SAVE"))
885 ProcessSaveFile(editor->fFileName, editor->fContent);
886 if ((arr->size() == 6) && (arr->at(5) == "RUN")) {
887 ProcessSaveFile(editor->fFileName, editor->fContent);
888 ProcessRunMacro(editor->fFileName);
889 }
890 }
891 }
892 } else if (kind == "GETINFO") {
893 auto info = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(msg));
894 if (info) {
895 info->Refresh();
896 fWebWindow->Send(connid, info->SendWidgetContent());
897 }
898 } else if (kind == "NEWWIDGET") {
899 auto widget = AddWidget(msg);
900 if (widget)
901 fWebWindow->Send(connid, NewWidgetMsg(widget));
902 } else if (kind == "CDWORKDIR") {
904 if (fBrowsable.GetWorkingPath() != wrkdir) {
906 } else {
908 }
909 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
910 } else if (kind == "OPTIONS") {
911 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
912 if (arr && (arr->size() == 3)) {
915 Browsable::RProvider::SetClassDrawOption("TProfile", (*arr)[2]);
916 }
917 }
918}
919
920//////////////////////////////////////////////////////////////////////////////////////////////
921/// Set working path in the browser
922
923void RBrowser::SetWorkingPath(const std::string &path)
924{
926 auto elem = fBrowsable.GetSubElement(p);
927 if (elem) {
929 if (fWebWindow && (fWebWindow->NumConnections() > 0))
931 }
932}
933
934//////////////////////////////////////////////////////////////////////////////////////////////
935/// Activate widget in RBrowser
936/// One should specify title and (optionally) kind of widget like "tcanvas" or "geom"
937
938bool RBrowser::ActivateWidget(const std::string &title, const std::string &kind)
939{
940 if (title.empty())
941 return false;
942
943 for (auto &widget : fWidgets) {
944
945 if (widget->GetTitle() != title)
946 continue;
947
948 if (!kind.empty() && (widget->GetKind() != kind))
949 continue;
950
951 if (fWebWindow)
952 fWebWindow->Send(0, "SELECT_WIDGET:"s + widget->GetName());
953 else
954 fActiveWidgetName = widget->GetName();
955 return true;
956 }
957
958 return false;
959}
960
961//////////////////////////////////////////////////////////////////////////////////////////////
962/// Set handle which will be cleared when connection is closed
963
964void RBrowser::ClearOnClose(const std::shared_ptr<void> &handle)
965{
966 fWebWindow->SetClearOnClose(handle);
967}
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
long Long_t
Definition RtypesCore.h:54
constexpr Bool_t kTRUE
Definition RtypesCore.h:100
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:229
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t win
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:110
#define gInterpreter
#define gROOT
Definition TROOT.h:407
R__EXTERN TSystem * gSystem
Definition TSystem.h:560
static int ExtractItemIndex(std::string &name)
Extract index from name Index coded by client with ###<indx>$$$ suffix Such coding used by browser to...
Definition RElement.cxx:178
@ kActImage
can be shown in image viewer, can provide image
Definition RElement.hxx:54
@ kActDraw6
can be drawn inside ROOT6 canvas
Definition RElement.hxx:55
@ kActCanvas
indicate that it is canvas and should be drawn directly
Definition RElement.hxx:57
@ kActTree
can be shown in tree viewer
Definition RElement.hxx:58
@ kActGeom
can be shown in geometry viewer
Definition RElement.hxx:59
@ kActBrowse
just browse (expand) item
Definition RElement.hxx:52
@ kActEdit
can provide data for text editor
Definition RElement.hxx:53
@ kActDraw7
can be drawn inside ROOT7 canvas
Definition RElement.hxx:56
static std::string GetPathAsString(const RElementPath_t &path)
Converts element path back to string.
Definition RElement.cxx:160
static RElementPath_t ParsePath(const std::string &str)
Parse string path to produce RElementPath_t One should avoid to use string pathes as much as possible...
Definition RElement.cxx:116
static bool SetClassDrawOption(const ClassArg &, const std::string &)
Set draw option for the class Return true if entry for the class exists.
static std::string GetClassDrawOption(const ClassArg &)
Return configured draw option for the class.
static RElementPath_t GetWorkingPath(const std::string &workdir="")
Return working path in browser hierarchy.
Definition RSysFile.cxx:571
void Show(const std::string &) override
Definition RBrowser.cxx:241
std::string GetUrl() override
Definition RBrowser.cxx:245
std::string GetKind() const override
Definition RBrowser.cxx:243
std::string GetTitle() override
Definition RBrowser.cxx:247
RBrowserCatchedWidget(const std::string &name, const std::string &url, const std::string &kind)
Definition RBrowser.cxx:249
std::shared_ptr< Browsable::RElement > GetSubElement(const Browsable::RElementPath_t &path)
Returns sub-element starting from top, using cached data.
void ClearCache()
Clear internal objects cache.
std::string ProcessRequest(const RBrowserRequest &request)
Process browser request, returns string with JSON of RBrowserReply data.
void SetWorkingPath(const Browsable::RElementPath_t &path)
set working directory relative to top element
const Browsable::RElementPath_t & GetWorkingPath() const
void CreateDefaultElements()
Create default elements shown in the RBrowser.
std::string GetTitle() override
Definition RBrowser.cxx:76
std::string fItemPath
! item path in the browser
Definition RBrowser.cxx:68
void ResetConn() override
Definition RBrowser.cxx:73
std::string GetKind() const override
Definition RBrowser.cxx:75
bool fFirstSend
! if editor content was send at least once
Definition RBrowser.cxx:67
RBrowserEditorWidget(const std::string &name, bool is_editor=true)
Definition RBrowser.cxx:70
bool fIsEditor
! either editor or image viewer
Definition RBrowser.cxx:63
std::string GetUrl() override
Definition RBrowser.cxx:77
virtual ~RBrowserEditorWidget()=default
void Show(const std::string &) override
Definition RBrowser.cxx:79
bool DrawElement(std::shared_ptr< Browsable::RElement > &elem, const std::string &="") override
Definition RBrowser.cxx:81
std::string SendWidgetContent() override
Definition RBrowser.cxx:121
void RefreshFromLogs(const std::string &promt, const std::vector< std::string > &logs)
Definition RBrowser.cxx:191
void ResetConn() override
Definition RBrowser.cxx:153
RBrowserInfoWidget(const std::string &name)
Definition RBrowser.cxx:145
std::string GetTitle() override
Definition RBrowser.cxx:156
std::string GetKind() const override
Definition RBrowser.cxx:155
bool fFirstSend
! if editor content was send at least once
Definition RBrowser.cxx:143
std::string SendWidgetContent() override
Definition RBrowser.cxx:218
virtual ~RBrowserInfoWidget()=default
std::string GetUrl() override
Definition RBrowser.cxx:157
void Show(const std::string &) override
Definition RBrowser.cxx:159
bool DrawElement(std::shared_ptr< Browsable::RElement > &, const std::string &="") override
Definition RBrowser.cxx:161
RBrowser & fBrowser
Definition RBrowser.cxx:49
RBrowserTimer(Long_t milliSec, Bool_t mode, RBrowser &br)
!< browser processing postponed requests
Definition RBrowser.cxx:52
void Timeout() override
timeout handler used to process postponed requests in main ROOT thread
Definition RBrowser.cxx:56
static std::shared_ptr< RBrowserWidget > CreateWidgetFor(const std::string &kind, const std::string &name, std::shared_ptr< Browsable::RElement > &element)
Create specified widget for existing object.
static std::shared_ptr< RBrowserWidget > CreateWidget(const std::string &kind, const std::string &name)
Create specified widget.
Abstract Web-based widget, which can be used in the RBrowser Used to embed canvas,...
const std::string & GetName() const
Web-based ROOT files and objects browser.
Definition RBrowser.hxx:27
std::unique_ptr< RBrowserTimer > fTimer
! timer to handle postponed requests
Definition RBrowser.hxx:48
RBrowserData fBrowsable
! central browsing element
Definition RBrowser.hxx:47
std::shared_ptr< RBrowserWidget > AddWidget(const std::string &kind)
Creates new widget.
Definition RBrowser.cxx:531
std::vector< std::string > GetRootHistory()
Get content of history file.
Definition RBrowser.cxx:621
void AddInitWidget(const std::string &kind)
Create new widget and send init message to the client.
Definition RBrowser.cxx:582
std::vector< std::vector< std::string > > fPostponed
! postponed messages, handled in timer
Definition RBrowser.hxx:49
std::shared_ptr< RWebWindow > fWebWindow
! web window to browser
Definition RBrowser.hxx:45
int fWidgetCnt
! counter for created widgets
Definition RBrowser.hxx:40
std::shared_ptr< RBrowserWidget > GetActiveWidget() const
Definition RBrowser.hxx:54
std::string ProcessDblClick(unsigned connid, std::vector< std::string > &args)
Process dbl click on browser item.
Definition RBrowser.cxx:400
void ClearOnClose(const std::shared_ptr< void > &handle)
Set handle which will be cleared when connection is closed.
Definition RBrowser.cxx:964
std::string fActiveWidgetName
! name of active widget
Definition RBrowser.hxx:38
RBrowser(bool use_rcanvas=false)
constructor
Definition RBrowser.cxx:273
void SetWorkingPath(const std::string &path)
Set working path in the browser.
Definition RBrowser.cxx:923
void Hide()
hide Browser
Definition RBrowser.cxx:521
std::string NewWidgetMsg(std::shared_ptr< RBrowserWidget > &widget)
Create message which send to client to create new widget.
Definition RBrowser.cxx:732
bool fCatchWindowShow
! if arbitrary RWebWindow::Show calls should be catched by browser
Definition RBrowser.hxx:37
std::string fPromptFileOutput
! file name for prompt output
Definition RBrowser.hxx:41
void Show(const RWebDisplayArgs &args="", bool always_start_new_browser=false)
show Browser in specified place
Definition RBrowser.cxx:509
std::string GetCurrentWorkingDirectory()
Return the current directory of ROOT.
Definition RBrowser.cxx:724
std::shared_ptr< RBrowserWidget > AddCatchedWidget(const std::string &url, const std::string &kind)
Add widget catched from external scripts.
Definition RBrowser.cxx:563
void SetUseRCanvas(bool on=true)
Definition RBrowser.hxx:83
std::shared_ptr< RBrowserWidget > FindWidget(const std::string &name, const std::string &kind="") const
Find widget by name or kind.
Definition RBrowser.cxx:592
bool GetUseRCanvas() const
Definition RBrowser.hxx:82
std::vector< std::shared_ptr< RBrowserWidget > > fWidgets
! all browser widgets
Definition RBrowser.hxx:39
virtual ~RBrowser()
destructor
Definition RBrowser.cxx:342
void ProcessSaveFile(const std::string &fname, const std::string &content)
Process file save command in the editor.
Definition RBrowser.cxx:375
void CheckWidgtesModified()
Check if any widget was modified and update if necessary.
Definition RBrowser.cxx:742
float fLastProgressSend
! last value of send progress
Definition RBrowser.hxx:42
std::string ProcessBrowserRequest(const std::string &msg)
Process browser request.
Definition RBrowser.cxx:351
std::vector< std::string > GetRootLogs()
Get content of log file.
Definition RBrowser.cxx:644
void ProcessMsg(unsigned connid, const std::string &arg)
Process received message from the client.
Definition RBrowser.cxx:779
void CloseTab(const std::string &name)
Close and delete specified widget.
Definition RBrowser.cxx:608
void ProcessPostponedRequests()
Process postponed requests - decouple from websocket handling Only requests which can take longer tim...
Definition RBrowser.cxx:752
unsigned fConnId
! default connection id
Definition RBrowser.hxx:34
bool ActivateWidget(const std::string &title, const std::string &kind="")
Activate widget in RBrowser One should specify title and (optionally) kind of widget like "tcanvas" o...
Definition RBrowser.cxx:938
void SendInitMsg(unsigned connid)
Process client connect.
Definition RBrowser.cxx:662
void SendProgress(unsigned connid, float progr)
Send generic progress message to the web window Should show progress bar on client side.
Definition RBrowser.cxx:705
long long fLastProgressSendTm
! time when last progress message was send
Definition RBrowser.hxx:43
void ProcessRunMacro(const std::string &file_path)
Process run macro command in the editor.
Definition RBrowser.cxx:386
static bool IsMessageToStartDialog(const std::string &msg)
Check if this could be the message send by client to start new file dialog If returns true,...
static std::shared_ptr< RFileDialog > Embed(const std::shared_ptr< RWebWindow > &window, unsigned connid, const std::string &args)
Create dialog instance to use as embedded dialog inside other widget Embedded dialog started on the c...
Holds different arguments for starting browser with RWebDisplayHandle::Display() method.
const std::string & GetWidgetKind() const
returns widget kind
Represents web window, which can be shown in web browser or any other supported environment.
static std::shared_ptr< RWebWindow > Create()
Create new RWebWindow Using default RWebWindowsManager.
This class creates the ROOT Application Environment that interfaces to the windowing system eventloop...
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 Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:525
Definition TRint.h:31
Basic string class.
Definition TString.h:139
const char * Data() const
Definition TString.h:380
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2334
virtual Int_t RedirectOutput(const char *name, const char *mode="a", RedirectHandle_t *h=nullptr)
Redirect standard output (stdout, stderr) to the specified file.
Definition TSystem.cxx:1700
virtual int GetPid()
Get process id.
Definition TSystem.cxx:694
virtual TTime Now()
Get current time in milliseconds since 0:00 Jan 1 1995.
Definition TSystem.cxx:450
virtual const char * UnixPathName(const char *unixpathname)
Convert from a local pathname to a Unix pathname.
Definition TSystem.cxx:1050
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:874
virtual int Unlink(const char *name)
Unlink, i.e.
Definition TSystem.cxx:1368
virtual const char * TempDirectory() const
Return a user configured or systemwide directory to create temporary files in.
Definition TSystem.cxx:1469
Handles synchronous and a-synchronous timer events.
Definition TTimer.h:51
TLine * line
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
ROOT::Experimental::RLogChannel & BrowserLog()
Log channel for Browser diagnostics.