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 RWebWindow *fWindow{nullptr}; // catched widget, TODO: to be changed to shared_ptr
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 fWindow->GetUrl(false); }
246
247 std::string GetTitle() override { return fCatchedKind; }
248
249 RBrowserCatchedWidget(const std::string &name, RWebWindow *win, const std::string &kind) :
251 fWindow(win),
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) { fConnId = connid; SendInitMsg(connid); },
295 [this](unsigned connid, const std::string &arg) { 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 auto widget = AddCatchedWidget(&win, kind);
316
317 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
318 fWebWindow->Send(0, NewWidgetMsg(widget));
319
320 return widget ? true : false;
321 });
322
323 Show();
324
325 // add first canvas by default
326
327 //if (GetUseRCanvas())
328 // AddWidget("rcanvas");
329 //else
330 // AddWidget("tcanvas");
331
332 // AddWidget("geom"); // add geometry viewer at the beginning
333
334 // AddWidget("editor"); // one can add empty editor if necessary
335}
336
337//////////////////////////////////////////////////////////////////////////////////////////////
338/// destructor
339
341{
342 if (fWebWindow)
343 fWebWindow->GetManager()->SetShowCallback(nullptr);
344}
345
346//////////////////////////////////////////////////////////////////////////////////////////////
347/// Process browser request
348
349std::string RBrowser::ProcessBrowserRequest(const std::string &msg)
350{
351 std::unique_ptr<RBrowserRequest> request;
352
353 if (msg.empty()) {
354 request = std::make_unique<RBrowserRequest>();
355 request->first = 0;
356 request->number = 100;
357 } else {
358 request = TBufferJSON::FromJSON<RBrowserRequest>(msg);
359 }
360
361 if (!request)
362 return ""s;
363
364 if (request->path.empty() && fWidgets.empty() && fBrowsable.GetWorkingPath().empty())
366
367 return "BREPL:"s + fBrowsable.ProcessRequest(*request.get());
368}
369
370/////////////////////////////////////////////////////////////////////////////////
371/// Process file save command in the editor
372
373void RBrowser::ProcessSaveFile(const std::string &fname, const std::string &content)
374{
375 if (fname.empty()) return;
376 R__LOG_DEBUG(0, BrowserLog()) << "SaveFile " << fname << " content length " << content.length();
377 std::ofstream f(fname);
378 f << content;
379}
380
381/////////////////////////////////////////////////////////////////////////////////
382/// Process run macro command in the editor
383
384void RBrowser::ProcessRunMacro(const std::string &file_path)
385{
386 if (file_path.rfind(".py") == file_path.length() - 3) {
387 TString exec;
388 exec.Form("TPython::ExecScript(\"%s\");", file_path.c_str());
389 gROOT->ProcessLine(exec.Data());
390 } else {
391 gInterpreter->ExecuteMacro(file_path.c_str());
392 }
393}
394
395/////////////////////////////////////////////////////////////////////////////////
396/// Process dbl click on browser item
397
398std::string RBrowser::ProcessDblClick(unsigned connid, std::vector<std::string> &args)
399{
400 args.pop_back(); // remove exec string, not used now
401
402 std::string opt = args.back();
403 args.pop_back(); // remove option
404
405 auto path = fBrowsable.GetWorkingPath();
406 path.insert(path.end(), args.begin(), args.end());
407
408 R__LOG_DEBUG(0, BrowserLog()) << "DoubleClick " << Browsable::RElement::GetPathAsString(path);
409
410 auto elem = fBrowsable.GetSubElement(path);
411 if (!elem) return ""s;
412
413 auto dflt_action = elem->GetDefaultAction();
414
415 // special case when canvas is clicked - always start new widget
416 if (dflt_action == Browsable::RElement::kActCanvas) {
417 std::string widget_kind;
418
419 if (elem->IsCapable(Browsable::RElement::kActDraw7))
420 widget_kind = "rcanvas";
421 else
422 widget_kind = "tcanvas";
423
424 std::string name = widget_kind + std::to_string(++fWidgetCnt);
425
426 auto new_widget = RBrowserWidgetProvider::CreateWidgetFor(widget_kind, name, elem);
427
428 if (!new_widget)
429 return ""s;
430
431 // assign back pointer
432 new_widget->fBrowser = this;
433
434 new_widget->Show("embed");
435 fWidgets.emplace_back(new_widget);
436 fActiveWidgetName = new_widget->GetName();
437
438 return NewWidgetMsg(new_widget);
439 }
440
441 // before display tree or geometry ensure that they read and cached inside element
442 if (elem->IsCapable(Browsable::RElement::kActGeom) || elem->IsCapable(Browsable::RElement::kActTree)) {
443 elem->GetChildsIter();
444 }
445
447 Browsable::RProvider::ProgressHandle handle(elem.get(), [this, connid](float progress, void *) {
448 SendProgress(connid, progress);
449 });
450
451 auto widget = GetActiveWidget();
452 if (widget && widget->DrawElement(elem, opt)) {
453 widget->SetPath(path);
454 return widget->SendWidgetContent();
455 }
456
457 // check if element was drawn in other widget and just activate that widget
458 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
459 [path](const std::shared_ptr<RBrowserWidget> &wg) { return path == wg->GetPath(); });
460
461 if (iter != fWidgets.end())
462 return "SELECT_WIDGET:"s + (*iter)->GetName();
463
464 // check if object can be drawn in RCanvas even when default action is drawing in TCanvas
465 if ((dflt_action == Browsable::RElement::kActDraw6) && GetUseRCanvas() && elem->IsCapable(Browsable::RElement::kActDraw7))
466 dflt_action = Browsable::RElement::kActDraw7;
467
468 std::string widget_kind;
469 switch(dflt_action) {
470 case Browsable::RElement::kActDraw6: widget_kind = "tcanvas"; break;
471 case Browsable::RElement::kActDraw7: widget_kind = "rcanvas"; break;
472 case Browsable::RElement::kActEdit: widget_kind = "editor"; break;
473 case Browsable::RElement::kActImage: widget_kind = "image"; break;
474 case Browsable::RElement::kActTree: widget_kind = "tree"; break;
475 case Browsable::RElement::kActGeom: widget_kind = "geom"; break;
476 default: widget_kind.clear();
477 }
478
479 if (!widget_kind.empty()) {
480 auto new_widget = AddWidget(widget_kind);
481 if (new_widget) {
482 // draw object before client side is created - should not be a problem
483 // after widget add in browser, connection will be established and data provided
484 if (new_widget->DrawElement(elem, opt))
485 new_widget->SetPath(path);
486 return NewWidgetMsg(new_widget);
487 }
488 }
489
490 if (elem->IsCapable(Browsable::RElement::kActBrowse) && (elem->GetNumChilds() > 0)) {
491 // remove extra index in subitems name
492 for (auto &pathelem : path)
496 }
497
498 return ""s;
499}
500
501/////////////////////////////////////////////////////////////////////////////////
502/// Show or update RBrowser in web window
503/// If web window already started - just refresh it like "reload" button does
504/// If no web window exists or \param always_start_new_browser configured, starts new window
505/// \param args display arguments
506
507void RBrowser::Show(const RWebDisplayArgs &args, bool always_start_new_browser)
508{
509 if (!fWebWindow->NumConnections() || always_start_new_browser) {
510 fWebWindow->Show(args);
511 } else {
512 SendInitMsg(0);
513 }
514}
515
516///////////////////////////////////////////////////////////////////////////////////////////////////////
517/// Hide ROOT Browser
518
520{
521 if (fWebWindow)
522 fWebWindow->CloseConnections();
523}
524
525///////////////////////////////////////////////////////////////////////////////////////////////////////
526/// Return URL parameter for the window showing ROOT Browser
527/// See \ref ROOT::RWebWindow::GetUrl docu for more details
528
529std::string RBrowser::GetWindowUrl(bool remote)
530{
531 if (fWebWindow)
532 return fWebWindow->GetUrl(remote);
533
534 return ""s;
535}
536
537
538//////////////////////////////////////////////////////////////////////////////////////////////
539/// Creates new widget
540
541std::shared_ptr<RBrowserWidget> RBrowser::AddWidget(const std::string &kind)
542{
543 std::string name = kind + std::to_string(++fWidgetCnt);
544
545 std::shared_ptr<RBrowserWidget> widget;
546
547 if (kind == "editor"s)
548 widget = std::make_shared<RBrowserEditorWidget>(name, true);
549 else if (kind == "image"s)
550 widget = std::make_shared<RBrowserEditorWidget>(name, false);
551 else if (kind == "info"s)
552 widget = std::make_shared<RBrowserInfoWidget>(name);
553 else
555
556 if (!widget) {
557 R__LOG_ERROR(BrowserLog()) << "Fail to create widget of kind " << kind;
558 return nullptr;
559 }
560
561 widget->fBrowser = this;
562 widget->Show("embed");
563 fWidgets.emplace_back(widget);
564
566
567 return widget;
568}
569
570//////////////////////////////////////////////////////////////////////////////////////////////
571/// Add widget catched from external scripts
572
573std::shared_ptr<RBrowserWidget> RBrowser::AddCatchedWidget(RWebWindow *win, const std::string &kind)
574{
575 if (!win || kind.empty()) return nullptr;
576
577 std::string name = "catched"s + std::to_string(++fWidgetCnt);
578
579 auto widget = std::make_shared<RBrowserCatchedWidget>(name, win, kind);
580
581 fWidgets.emplace_back(widget);
582
584
585 return widget;
586}
587
588
589//////////////////////////////////////////////////////////////////////////////////////////////
590/// Create new widget and send init message to the client
591
592void RBrowser::AddInitWidget(const std::string &kind)
593{
594 auto widget = AddWidget(kind);
595 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
596 fWebWindow->Send(0, NewWidgetMsg(widget));
597}
598
599//////////////////////////////////////////////////////////////////////////////////////////////
600/// Find widget by name or kind
601
602std::shared_ptr<RBrowserWidget> RBrowser::FindWidget(const std::string &name, const std::string &kind) const
603{
604 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
605 [name, kind](const std::shared_ptr<RBrowserWidget> &widget) {
606 return kind.empty() ? name == widget->GetName() : kind == widget->GetKind();
607 });
608
609 if (iter != fWidgets.end())
610 return *iter;
611
612 return nullptr;
613}
614
615//////////////////////////////////////////////////////////////////////////////////////////////
616/// Close and delete specified widget
617
618void RBrowser::CloseTab(const std::string &name)
619{
620 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(), [name](std::shared_ptr<RBrowserWidget> &widget) { return name == widget->GetName(); });
621 if (iter != fWidgets.end())
622 fWidgets.erase(iter);
623
624 if (fActiveWidgetName == name)
625 fActiveWidgetName.clear();
626}
627
628//////////////////////////////////////////////////////////////////////////////////////////////
629/// Get content of history file
630
631std::vector<std::string> RBrowser::GetRootHistory()
632{
633 std::vector<std::string> arr;
634
635 std::string path = gSystem->UnixPathName(gSystem->HomeDirectory());
636 path += "/.root_hist" ;
637 std::ifstream infile(path);
638
639 if (infile) {
640 std::string line;
641 while (std::getline(infile, line) && (arr.size() < 1000)) {
642 if(!(std::find(arr.begin(), arr.end(), line) != arr.end())) {
643 arr.emplace_back(line);
644 }
645 }
646 }
647
648 return arr;
649}
650
651//////////////////////////////////////////////////////////////////////////////////////////////
652/// Get content of log file
653
654std::vector<std::string> RBrowser::GetRootLogs()
655{
656 std::vector<std::string> arr;
657
658 std::ifstream infile(fPromptFileOutput);
659 if (infile) {
660 std::string line;
661 while (std::getline(infile, line) && (arr.size() < 10000)) {
662 arr.emplace_back(line);
663 }
664 }
665
666 return arr;
667}
668
669//////////////////////////////////////////////////////////////////////////////////////////////
670/// Process client connect
671
672void RBrowser::SendInitMsg(unsigned connid)
673{
674 std::vector<std::vector<std::string>> reply;
675
676 reply.emplace_back(fBrowsable.GetWorkingPath()); // first element is current path
677
678 for (auto &widget : fWidgets) {
679 widget->ResetConn();
680 reply.emplace_back(std::vector<std::string>({ widget->GetKind(), ".."s + widget->GetUrl(), widget->GetName(), widget->GetTitle() }));
681 }
682
683 if (!fActiveWidgetName.empty())
684 reply.emplace_back(std::vector<std::string>({ "active"s, fActiveWidgetName }));
685
686 auto history = GetRootHistory();
687 if (history.size() > 0) {
688 history.insert(history.begin(), "history"s);
689 reply.emplace_back(history);
690 }
691
692 auto logs = GetRootLogs();
693 if (logs.size() > 0) {
694 logs.insert(logs.begin(), "logs"s);
695 reply.emplace_back(logs);
696 }
697
698 reply.emplace_back(std::vector<std::string>({
699 "drawoptions"s,
703 }));
704
705 std::string msg = "INMSG:";
706 msg.append(TBufferJSON::ToJSON(&reply, TBufferJSON::kNoSpaces).Data());
707
708 fWebWindow->Send(connid, msg);
709}
710
711//////////////////////////////////////////////////////////////////////////////////////////////
712/// Send generic progress message to the web window
713/// Should show progress bar on client side
714
715void RBrowser::SendProgress(unsigned connid, float progr)
716{
717 long long millisec = gSystem->Now();
718
719 // let process window events
720 fWebWindow->Sync();
721
722 if ((!fLastProgressSendTm || millisec > fLastProgressSendTm - 200) && (progr > fLastProgressSend + 0.04) && fWebWindow->CanSend(connid)) {
723 fWebWindow->Send(connid, "PROGRESS:"s + std::to_string(progr));
724
725 fLastProgressSendTm = millisec;
726 fLastProgressSend = progr;
727 }
728}
729
730
731//////////////////////////////////////////////////////////////////////////////////////////////
732/// Return the current directory of ROOT
733
735{
736 return "WORKPATH:"s + TBufferJSON::ToJSON(&fBrowsable.GetWorkingPath()).Data();
737}
738
739//////////////////////////////////////////////////////////////////////////////////////////////
740/// Create message which send to client to create new widget
741
742std::string RBrowser::NewWidgetMsg(std::shared_ptr<RBrowserWidget> &widget)
743{
744 std::vector<std::string> arr = { widget->GetKind(), ".."s + widget->GetUrl(), widget->GetName(), widget->GetTitle(),
745 Browsable::RElement::GetPathAsString(widget->GetPath()) };
746 return "NEWWIDGET:"s + TBufferJSON::ToJSON(&arr, TBufferJSON::kNoSpaces).Data();
747}
748
749//////////////////////////////////////////////////////////////////////////////////////////////
750/// Check if any widget was modified and update if necessary
751
753{
754 for (auto &widget : fWidgets)
755 widget->CheckModified();
756}
757
758//////////////////////////////////////////////////////////////////////////////////////////////
759/// Process postponed requests - decouple from websocket handling
760/// Only requests which can take longer time should be postponed
761
763{
764 if (fPostponed.empty())
765 return;
766
767 auto arr = fPostponed[0];
768 fPostponed.erase(fPostponed.begin(), fPostponed.begin()+1);
769 if (fPostponed.empty())
770 fTimer->TurnOff();
771
772 std::string reply;
773 unsigned connid = std::stoul(arr.back()); arr.pop_back();
774 std::string kind = arr.back(); arr.pop_back();
775
776 if (kind == "DBLCLK") {
777 reply = ProcessDblClick(connid, arr);
778 if (reply.empty()) reply = "NOPE";
779 }
780
781 if (!reply.empty())
782 fWebWindow->Send(connid, reply);
783}
784
785
786//////////////////////////////////////////////////////////////////////////////////////////////
787/// Process received message from the client
788
789void RBrowser::ProcessMsg(unsigned connid, const std::string &arg0)
790{
791 R__LOG_DEBUG(0, BrowserLog()) << "ProcessMsg len " << arg0.length() << " substr(30) " << arg0.substr(0, 30);
792
793 std::string kind, msg;
794 auto pos = arg0.find(":");
795 if (pos == std::string::npos) {
796 kind = arg0;
797 } else {
798 kind = arg0.substr(0, pos);
799 msg = arg0.substr(pos+1);
800 }
801
802 if (kind == "QUIT_ROOT") {
803
804 fWebWindow->TerminateROOT();
805
806 } else if (kind == "BRREQ") {
807 // central place for processing browser requests
808 auto json = ProcessBrowserRequest(msg);
809 if (!json.empty()) fWebWindow->Send(connid, json);
810
811 } else if (kind == "DBLCLK") {
812
813 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
814 if (arr && (arr->size() > 2)) {
815 arr->push_back(kind);
816 arr->push_back(std::to_string(connid));
817 fPostponed.push_back(*arr);
818 if (fPostponed.size() == 1)
819 fTimer->TurnOn();
820 } else {
821 fWebWindow->Send(connid, "NOPE");
822 }
823
824 } else if (kind == "WIDGET_SELECTED") {
825 fActiveWidgetName = msg;
826 auto widget = GetActiveWidget();
827 if (widget) {
828 auto reply = widget->SendWidgetContent();
829 if (!reply.empty()) fWebWindow->Send(connid, reply);
830 }
831 } else if (kind == "CLOSE_TAB") {
832 CloseTab(msg);
833 } else if (kind == "GETWORKPATH") {
834 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
835 } else if (kind == "CHPATH") {
836 auto path = TBufferJSON::FromJSON<Browsable::RElementPath_t>(msg);
837 if (path) fBrowsable.SetWorkingPath(*path);
838 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
839 } else if (kind == "CMD") {
840 std::string sPrompt = "root []";
841 TApplication *app = gROOT->GetApplication();
842 if (app->InheritsFrom("TRint")) {
843 sPrompt = ((TRint*)gROOT->GetApplication())->GetPrompt();
844 Gl_histadd((char *)msg.c_str());
845 }
846
847 std::ofstream ofs(fPromptFileOutput, std::ofstream::out | std::ofstream::app);
848 ofs << sPrompt << msg << std::endl;
849 ofs.close();
850
852 gROOT->ProcessLine(msg.c_str());
853 gSystem->RedirectOutput(nullptr);
854
855 if (msg == ".g"s) {
856 auto widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(""s, "info"s));
857 if (!widget) {
858 auto new_widget = AddWidget("info"s);
859 fWebWindow->Send(connid, NewWidgetMsg(new_widget));
860 widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(new_widget);
861 } else if (fActiveWidgetName != widget->GetName()) {
862 fWebWindow->Send(connid, "SELECT_WIDGET:"s + widget->GetName());
863 fActiveWidgetName = widget->GetName();
864 }
865
866 if (widget)
867 widget->RefreshFromLogs(sPrompt + msg, GetRootLogs());
868 }
869
871 } else if (kind == "GETHISTORY") {
872
873 auto history = GetRootHistory();
874
875 fWebWindow->Send(connid, "HISTORY:"s + TBufferJSON::ToJSON(&history, TBufferJSON::kNoSpaces).Data());
876 } else if (kind == "GETLOGS") {
877
878 auto logs = GetRootLogs();
879 fWebWindow->Send(connid, "LOGS:"s + TBufferJSON::ToJSON(&logs, TBufferJSON::kNoSpaces).Data());
880
881 } else if (RFileDialog::IsMessageToStartDialog(arg0)) {
882
883 RFileDialog::Embed(fWebWindow, connid, arg0);
884
885 } else if (kind == "SYNCEDITOR") {
886 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
887 if (arr && (arr->size() > 4)) {
888 auto editor = std::dynamic_pointer_cast<RBrowserEditorWidget>(FindWidget(arr->at(0)));
889 if (editor) {
890 editor->fFirstSend = true;
891 editor->fTitle = arr->at(1);
892 editor->fFileName = arr->at(2);
893 if (!arr->at(3).empty()) editor->fContent = arr->at(4);
894 if ((arr->size() == 6) && (arr->at(5) == "SAVE"))
895 ProcessSaveFile(editor->fFileName, editor->fContent);
896 if ((arr->size() == 6) && (arr->at(5) == "RUN")) {
897 ProcessSaveFile(editor->fFileName, editor->fContent);
898 ProcessRunMacro(editor->fFileName);
900 }
901 }
902 }
903 } else if (kind == "GETINFO") {
904 auto info = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(msg));
905 if (info) {
906 info->Refresh();
907 fWebWindow->Send(connid, info->SendWidgetContent());
908 }
909 } else if (kind == "NEWWIDGET") {
910 auto widget = AddWidget(msg);
911 if (widget)
912 fWebWindow->Send(connid, NewWidgetMsg(widget));
913 } else if (kind == "CDWORKDIR") {
915 if (fBrowsable.GetWorkingPath() != wrkdir) {
917 } else {
919 }
920 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
921 } else if (kind == "OPTIONS") {
922 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
923 if (arr && (arr->size() == 3)) {
926 Browsable::RProvider::SetClassDrawOption("TProfile", (*arr)[2]);
927 }
928 }
929}
930
931//////////////////////////////////////////////////////////////////////////////////////////////
932/// Set working path in the browser
933
934void RBrowser::SetWorkingPath(const std::string &path)
935{
937 auto elem = fBrowsable.GetSubElement(p);
938 if (elem) {
940 if (fWebWindow && (fWebWindow->NumConnections() > 0))
942 }
943}
944
945//////////////////////////////////////////////////////////////////////////////////////////////
946/// Activate widget in RBrowser
947/// One should specify title and (optionally) kind of widget like "tcanvas" or "geom"
948
949bool RBrowser::ActivateWidget(const std::string &title, const std::string &kind)
950{
951 if (title.empty())
952 return false;
953
954 for (auto &widget : fWidgets) {
955
956 if (widget->GetTitle() != title)
957 continue;
958
959 if (!kind.empty() && (widget->GetKind() != kind))
960 continue;
961
962 if (fWebWindow)
963 fWebWindow->Send(0, "SELECT_WIDGET:"s + widget->GetName());
964 else
965 fActiveWidgetName = widget->GetName();
966 return true;
967 }
968
969 return false;
970}
971
972//////////////////////////////////////////////////////////////////////////////////////////////
973/// Set handle which will be cleared when connection is closed
974
975void RBrowser::ClearOnClose(const std::shared_ptr<void> &handle)
976{
977 fWebWindow->SetClearOnClose(handle);
978}
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:406
R__EXTERN TSystem * gSystem
Definition TSystem.h:555
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
RBrowserCatchedWidget(const std::string &name, RWebWindow *win, const std::string &kind)
Definition RBrowser.cxx:249
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
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:541
std::vector< std::string > GetRootHistory()
Get content of history file.
Definition RBrowser.cxx:631
void AddInitWidget(const std::string &kind)
Create new widget and send init message to the client.
Definition RBrowser.cxx:592
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:398
void ClearOnClose(const std::shared_ptr< void > &handle)
Set handle which will be cleared when connection is closed.
Definition RBrowser.cxx:975
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:934
void Hide()
hide Browser
Definition RBrowser.cxx:519
std::string NewWidgetMsg(std::shared_ptr< RBrowserWidget > &widget)
Create message which send to client to create new widget.
Definition RBrowser.cxx:742
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:507
std::string GetCurrentWorkingDirectory()
Return the current directory of ROOT.
Definition RBrowser.cxx:734
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:602
std::shared_ptr< RBrowserWidget > AddCatchedWidget(RWebWindow *win, const std::string &kind)
Add widget catched from external scripts.
Definition RBrowser.cxx:573
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:340
void ProcessSaveFile(const std::string &fname, const std::string &content)
Process file save command in the editor.
Definition RBrowser.cxx:373
void CheckWidgtesModified()
Check if any widget was modified and update if necessary.
Definition RBrowser.cxx:752
float fLastProgressSend
! last value of send progress
Definition RBrowser.hxx:42
std::string GetWindowUrl(bool remote)
Return URL parameter for the window showing ROOT Browser See ROOT::RWebWindow::GetUrl docu for more d...
Definition RBrowser.cxx:529
std::string ProcessBrowserRequest(const std::string &msg)
Process browser request.
Definition RBrowser.cxx:349
std::vector< std::string > GetRootLogs()
Get content of log file.
Definition RBrowser.cxx:654
void ProcessMsg(unsigned connid, const std::string &arg)
Process received message from the client.
Definition RBrowser.cxx:789
void CloseTab(const std::string &name)
Close and delete specified widget.
Definition RBrowser.cxx:618
void ProcessPostponedRequests()
Process postponed requests - decouple from websocket handling Only requests which can take longer tim...
Definition RBrowser.cxx:762
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:949
void SendInitMsg(unsigned connid)
Process client connect.
Definition RBrowser.cxx:672
void SendProgress(unsigned connid, float progr)
Send generic progress message to the web window Should show progress bar on client side.
Definition RBrowser.cxx:715
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:384
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.
std::string GetUrl(bool remote=true)
Return URL string to connect web window URL typically includes extra parameters required for connecti...
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:376
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition TString.cxx:2356
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:1715
virtual int GetPid()
Get process id.
Definition TSystem.cxx:707
virtual TTime Now()
Get current time in milliseconds since 0:00 Jan 1 1995.
Definition TSystem.cxx:463
virtual const char * UnixPathName(const char *unixpathname)
Convert from a local pathname to a Unix pathname.
Definition TSystem.cxx:1063
virtual const char * HomeDirectory(const char *userName=nullptr)
Return the user's home directory.
Definition TSystem.cxx:887
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
Handles synchronous and a-synchronous timer events.
Definition TTimer.h:51
TLine * line
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
ROOT::Experimental::RLogChannel & BrowserLog()
Log channel for Browser diagnostics.