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 "TVirtualPad.h"
26#include "TString.h"
27#include "TSystem.h"
28#include "TError.h"
29#include "TTimer.h"
30#include "TROOT.h"
31#include "TBufferJSON.h"
32#include "TApplication.h"
33#include "TRint.h"
34#include "Getline.h"
35
36#include <sstream>
37#include <iostream>
38#include <algorithm>
39#include <memory>
40#include <mutex>
41#include <thread>
42#include <fstream>
43
44using namespace std::string_literals;
45
46namespace ROOT {
47
48class RBrowserTimer : public TTimer {
49public:
50 RBrowser &fBrowser; ///!< browser processing postponed requests
51
52 /// constructor
54
55 /// timeout handler
56 /// used to process postponed requests in main ROOT thread
58};
59
60
62public:
63
64 bool fIsEditor{true}; ///<! either editor or image viewer
65 std::string fTitle;
66 std::string fFileName;
67 std::string fContent;
68 bool fFirstSend{false}; ///<! if editor content was send at least once
69 std::string fItemPath; ///<! item path in the browser
70
71 RBrowserEditorWidget(const std::string &name, bool is_editor = true) : RBrowserWidget(name), fIsEditor(is_editor) {}
72 virtual ~RBrowserEditorWidget() = default;
73
74 void ResetConn() override { fFirstSend = false; }
75
76 std::string GetKind() const override { return fIsEditor ? "editor"s : "image"s; }
77 std::string GetTitle() override { return fTitle; }
78
79 bool DrawElement(std::shared_ptr<Browsable::RElement> &elem, const std::string & = "") override
80 {
81 if (fIsEditor && elem->IsCapable(Browsable::RElement::kActEdit)) {
82 auto code = elem->GetContent("text");
83 if (!code.empty()) {
84 fFirstSend = false;
85 fContent = code;
86 fTitle = elem->GetName();
87 fFileName = elem->GetContent("filename");
88 } else {
89 auto json = elem->GetContent("json");
90 if (!json.empty()) {
91 fFirstSend = false;
92 fContent = json;
93 fTitle = elem->GetName() + ".json";
94 fFileName = "";
95 }
96 }
97 if (!fContent.empty()) {
98 // page->fItemPath = item_path;
99 return true;
100 }
101 }
102
103 if (!fIsEditor && elem->IsCapable(Browsable::RElement::kActImage)) {
104 auto img = elem->GetContent("image64");
105 if (!img.empty()) {
106 fFirstSend = false;
107 fContent = img;
108 fTitle = elem->GetName();
109 fFileName = elem->GetContent("filename");
110 // fItemPath = item_path;
111
112 return true;
113 }
114 }
115
116 return false;
117 }
118
119 std::string SendWidgetContent() override
120 {
121 if (fFirstSend) return ""s;
122
123 fFirstSend = true;
124 std::vector<std::string> args = { GetName(), fTitle, fFileName, fContent };
125
126 std::string msg = fIsEditor ? "EDITOR:"s : "IMAGE:"s;
127 msg += TBufferJSON::ToJSON(&args).Data();
128 return msg;
129 }
130
131};
132
133
135public:
136
137 enum { kMaxContentLen = 10000000 };
138
139 std::string fTitle;
140 std::string fContent;
141 bool fFirstSend{false}; ///<! if editor content was send at least once
142
144 {
145 fTitle = "Cling info"s;
146 Refresh();
147 }
148
149 virtual ~RBrowserInfoWidget() = default;
150
151 void ResetConn() override { fFirstSend = false; }
152
153 std::string GetKind() const override { return "info"s; }
154 std::string GetTitle() override { return fTitle; }
155
156 bool DrawElement(std::shared_ptr<Browsable::RElement> &, const std::string & = "") override { return false; }
157
158 void Refresh()
159 {
160 fFirstSend = false;
161 fContent = "";
162
163 std::ostringstream pathtmp;
164 pathtmp << gSystem->TempDirectory() << "/info." << gSystem->GetPid() << ".log";
165
166 std::ofstream ofs(pathtmp.str(), std::ofstream::out | std::ofstream::app);
167 ofs << "";
168 ofs.close();
169
170 gSystem->RedirectOutput(pathtmp.str().c_str(), "a");
171 gROOT->ProcessLine(".g");
172 gSystem->RedirectOutput(nullptr);
173
174 std::ifstream infile(pathtmp.str());
175 if (infile) {
176 std::string line;
177 while (std::getline(infile, line) && (fContent.length() < kMaxContentLen)) {
178 fContent.append(line);
179 fContent.append("\n");
180 }
181 }
182
183 gSystem->Unlink(pathtmp.str().c_str());
184 }
185
186 void RefreshFromLogs(const std::string &promt, const std::vector<std::string> &logs)
187 {
188 int indx = 0, last_prompt = -1;
189 for (auto &line : logs) {
190 if (line == promt)
192 indx++;
193 }
194
195 if (last_prompt < 0) {
196 Refresh();
197 return;
198 }
199
200 fFirstSend = false;
201 fContent = "";
202
203 indx = 0;
204 for (auto &line : logs) {
205 if ((indx++ > last_prompt) && (fContent.length() < kMaxContentLen)) {
206 fContent.append(line);
207 fContent.append("\n");
208 }
209 }
210 }
211
212
213 std::string SendWidgetContent() override
214 {
215 if (fFirstSend)
216 return ""s;
217
218 if (fContent.empty())
219 Refresh();
220
221 fFirstSend = true;
222 std::vector<std::string> args = { GetName(), fTitle, fContent };
223
224 return "INFO:"s + TBufferJSON::ToJSON(&args).Data();
225 }
226
227};
228
229
231public:
232
233 RWebWindow *fWindow{nullptr}; // catched widget, TODO: to be changed to shared_ptr
234 std::string fCatchedKind; // kind of catched widget
235
236 std::string GetKind() const override { return "catched"s; }
237
238 std::string GetUrl() override { return fWindow ? ".."s + fWindow->GetUrl(false) : ""s; }
239
240 std::string GetTitle() override { return fCatchedKind; }
241
242 bool IsValid() override { return fWindow != nullptr; }
243
244 RBrowserCatchedWidget(const std::string &name, RWebWindow *win, const std::string &kind) :
246 fWindow(win),
247 fCatchedKind(kind)
248 {
249 }
250};
251
252} // namespace ROOT
253
254using namespace ROOT;
255
256
257/** \class ROOT::RBrowser
258\ingroup rbrowser
259\ingroup webwidgets
260
261\brief Web-based %ROOT files and objects browser
262
263\image html v7_rbrowser.png
264
265*/
266
267//////////////////////////////////////////////////////////////////////////////////////////////
268/// constructor
269
271{
272 if (gROOT->IsWebDisplayBatch()) {
273 ::Warning("RBrowser::RBrowser", "The RBrowser cannot run in web batch mode");
274 return;
275 }
276
277 std::ostringstream pathtmp;
278 pathtmp << gSystem->TempDirectory() << "/command." << gSystem->GetPid() << ".log";
280
282
284
285 fTimer = std::make_unique<RBrowserTimer>(10, kTRUE, *this);
286
288 fWebWindow->SetDefaultPage("file:rootui5sys/browser/browser.html");
289
290 // this is call-back, invoked when message received via websocket
291 fWebWindow->SetCallBacks([this](unsigned connid) { fConnId = connid; SendInitMsg(connid); },
292 [this](unsigned connid, const std::string &arg) { ProcessMsg(connid, arg); });
293 fWebWindow->SetGeometry(1200, 700); // configure predefined window geometry
294 fWebWindow->SetConnLimit(1); // the only connection is allowed
295 fWebWindow->SetMaxQueueLength(30); // number of allowed entries in the window queue
296
297 fWebWindow->GetManager()->SetShowCallback([this](RWebWindow &win, const RWebDisplayArgs &args) -> bool {
298
299 std::string kind;
300
301 if (args.GetWidgetKind() == "RCanvas")
302 kind = "rcanvas";
303 else if (args.GetWidgetKind() == "TCanvas")
304 kind = "tcanvas";
305 else if (args.GetWidgetKind() == "RGeomViewer")
306 kind = "geom";
307 else if (args.GetWidgetKind() == "RTreeViewer")
308 kind = "tree";
309
310 if (!fWebWindow || !fCatchWindowShow || kind.empty())
311 return false;
312
314 if (widget) {
315 widget->fBrowser = this;
316 fWidgets.emplace_back(widget);
317 fActiveWidgetName = widget->GetName();
318 } else {
319 widget = AddCatchedWidget(&win, kind);
320 }
321
322 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
323 fWebWindow->Send(0, NewWidgetMsg(widget));
324
325 return widget ? true : false;
326 });
327
328 fWebWindow->GetManager()->SetDeleteCallback([this](RWebWindow &win) -> void {
329 for (auto &widget : fWidgets) {
330 auto catched = dynamic_cast<RBrowserCatchedWidget *>(widget.get());
331 if (catched && (catched->fWindow == &win))
332 catched->fWindow = nullptr;
333 }
334 });
335
336 Show();
337}
338
339//////////////////////////////////////////////////////////////////////////////////////////////
340/// destructor
341
343{
344 if (fWebWindow) {
345 fWebWindow->GetManager()->SetShowCallback(nullptr);
346 fWebWindow->GetManager()->SetDeleteCallback(nullptr);
347 }
348}
349
350//////////////////////////////////////////////////////////////////////////////////////////////
351/// Process browser request
352
353std::string RBrowser::ProcessBrowserRequest(const std::string &msg)
354{
355 std::unique_ptr<RBrowserRequest> request;
356
357 if (msg.empty()) {
358 request = std::make_unique<RBrowserRequest>();
359 request->first = 0;
360 request->number = 100;
361 } else {
362 request = TBufferJSON::FromJSON<RBrowserRequest>(msg);
363 }
364
365 if (!request)
366 return ""s;
367
368 if (request->path.empty() && fWidgets.empty() && fBrowsable.GetWorkingPath().empty())
370
371 return "BREPL:"s + fBrowsable.ProcessRequest(*request.get());
372}
373
374/////////////////////////////////////////////////////////////////////////////////
375/// Process file save command in the editor
376
377void RBrowser::ProcessSaveFile(const std::string &fname, const std::string &content)
378{
379 if (fname.empty()) return;
380 R__LOG_DEBUG(0, BrowserLog()) << "SaveFile " << fname << " content length " << content.length();
381 std::ofstream f(fname);
382 f << content;
383}
384
385/////////////////////////////////////////////////////////////////////////////////
386/// Process run macro command in the editor
387
388void RBrowser::ProcessRunMacro(const std::string &file_path)
389{
390 if (file_path.rfind(".py") == file_path.length() - 3) {
391 TString exec;
392 exec.Form("TPython::ExecScript(\"%s\");", file_path.c_str());
393 gROOT->ProcessLine(exec.Data());
394 } else {
395 gInterpreter->ExecuteMacro(file_path.c_str());
396 }
397}
398
399/////////////////////////////////////////////////////////////////////////////////
400/// Process dbl click on browser item
401
402std::string RBrowser::ProcessDblClick(unsigned connid, std::vector<std::string> &args)
403{
404 args.pop_back(); // remove exec string, not used now
405
406 std::string opt = args.back();
407 args.pop_back(); // remove option
408
409 auto path = fBrowsable.GetWorkingPath();
410 path.insert(path.end(), args.begin(), args.end());
411
412 R__LOG_DEBUG(0, BrowserLog()) << "DoubleClick " << Browsable::RElement::GetPathAsString(path);
413
414 auto elem = fBrowsable.GetSubElement(path);
415 if (!elem) return ""s;
416
417 auto dflt_action = elem->GetDefaultAction();
418
419 // special case when canvas is clicked - always start new widget
421 std::string widget_kind;
422
423 if (elem->IsCapable(Browsable::RElement::kActDraw7))
424 widget_kind = "rcanvas";
425 else
426 widget_kind = "tcanvas";
427
428 std::string name = widget_kind + std::to_string(++fWidgetCnt);
429
431
432 if (!new_widget)
433 return ""s;
434
435 // assign back pointer
436 new_widget->fBrowser = this;
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
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
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()) {
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
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/// Return URL parameter for the window showing ROOT Browser
529/// See \ref ROOT::RWebWindow::GetUrl docu for more details
530
532{
533 if (fWebWindow)
534 return fWebWindow->GetUrl(remote);
535
536 return ""s;
537}
538
539
540//////////////////////////////////////////////////////////////////////////////////////////////
541/// Creates new widget
542
543std::shared_ptr<RBrowserWidget> RBrowser::AddWidget(const std::string &kind)
544{
545 std::string name = kind + std::to_string(++fWidgetCnt);
546
547 std::shared_ptr<RBrowserWidget> widget;
548
549 if (kind == "editor"s)
550 widget = std::make_shared<RBrowserEditorWidget>(name, true);
551 else if (kind == "image"s)
552 widget = std::make_shared<RBrowserEditorWidget>(name, false);
553 else if (kind == "info"s)
554 widget = std::make_shared<RBrowserInfoWidget>(name);
555 else
557
558 if (!widget) {
559 R__LOG_ERROR(BrowserLog()) << "Fail to create widget of kind " << kind;
560 return nullptr;
561 }
562
563 widget->fBrowser = this;
564 fWidgets.emplace_back(widget);
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())
576 return nullptr;
577
578 std::string name = "catched"s + std::to_string(++fWidgetCnt);
579
580 auto widget = std::make_shared<RBrowserCatchedWidget>(name, win, kind);
581
582 fWidgets.emplace_back(widget);
583
585
586 return widget;
587}
588
589
590//////////////////////////////////////////////////////////////////////////////////////////////
591/// Create new widget and send init message to the client
592
593void RBrowser::AddInitWidget(const std::string &kind)
594{
595 auto widget = AddWidget(kind);
596 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
597 fWebWindow->Send(0, NewWidgetMsg(widget));
598}
599
600//////////////////////////////////////////////////////////////////////////////////////////////
601/// Find widget by name or kind
602
603std::shared_ptr<RBrowserWidget> RBrowser::FindWidget(const std::string &name, const std::string &kind) const
604{
605 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
606 [name, kind](const std::shared_ptr<RBrowserWidget> &widget) {
607 return kind.empty() ? name == widget->GetName() : kind == widget->GetKind();
608 });
609
610 if (iter != fWidgets.end())
611 return *iter;
612
613 return nullptr;
614}
615
616//////////////////////////////////////////////////////////////////////////////////////////////
617/// Close and delete specified widget
618
619void RBrowser::CloseTab(const std::string &name)
620{
621 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(), [name](std::shared_ptr<RBrowserWidget> &widget) { return name == widget->GetName(); });
622 if (iter != fWidgets.end())
623 fWidgets.erase(iter);
624
625 if (fActiveWidgetName == name)
626 fActiveWidgetName.clear();
627}
628
629//////////////////////////////////////////////////////////////////////////////////////////////
630/// Get content of history file
631
632std::vector<std::string> RBrowser::GetRootHistory()
633{
634 std::vector<std::string> arr;
635
636 std::string path = gSystem->UnixPathName(gSystem->HomeDirectory());
637 path += "/.root_hist" ;
638 std::ifstream infile(path);
639
640 if (infile) {
641 std::string line;
642 while (std::getline(infile, line) && (arr.size() < 1000)) {
643 if(!(std::find(arr.begin(), arr.end(), line) != arr.end())) {
644 arr.emplace_back(line);
645 }
646 }
647 }
648
649 return arr;
650}
651
652//////////////////////////////////////////////////////////////////////////////////////////////
653/// Get content of log file
654
655std::vector<std::string> RBrowser::GetRootLogs()
656{
657 std::vector<std::string> arr;
658
659 std::ifstream infile(fPromptFileOutput);
660 if (infile) {
661 std::string line;
662 while (std::getline(infile, line) && (arr.size() < 10000)) {
663 arr.emplace_back(line);
664 }
665 }
666
667 return arr;
668}
669
670//////////////////////////////////////////////////////////////////////////////////////////////
671/// Process client connect
672
673void RBrowser::SendInitMsg(unsigned connid)
674{
675 std::vector<std::vector<std::string>> reply;
676
677 reply.emplace_back(fBrowsable.GetWorkingPath()); // first element is current path
678
679 for (auto &widget : fWidgets) {
680 widget->ResetConn();
681 reply.emplace_back(std::vector<std::string>({ widget->GetKind(), widget->GetUrl(), widget->GetName(), widget->GetTitle() }));
682 }
683
684 if (!fActiveWidgetName.empty())
685 reply.emplace_back(std::vector<std::string>({ "active"s, fActiveWidgetName }));
686
687 auto history = GetRootHistory();
688 if (history.size() > 0) {
689 history.insert(history.begin(), "history"s);
690 reply.emplace_back(history);
691 }
692
693 auto logs = GetRootLogs();
694 if (logs.size() > 0) {
695 logs.insert(logs.begin(), "logs"s);
696 reply.emplace_back(logs);
697 }
698
699 reply.emplace_back(std::vector<std::string>({
700 "drawoptions"s,
704 }));
705
706 std::string msg = "INMSG:";
708
709 fWebWindow->Send(connid, msg);
710}
711
712//////////////////////////////////////////////////////////////////////////////////////////////
713/// Send generic progress message to the web window
714/// Should show progress bar on client side
715
716void RBrowser::SendProgress(unsigned connid, float progr)
717{
718 long long millisec = gSystem->Now();
719
720 // let process window events
721 fWebWindow->Sync();
722
723 if ((!fLastProgressSendTm || millisec > fLastProgressSendTm - 200) && (progr > fLastProgressSend + 0.04) && fWebWindow->CanSend(connid)) {
724 fWebWindow->Send(connid, "PROGRESS:"s + std::to_string(progr));
725
728 }
729}
730
731
732//////////////////////////////////////////////////////////////////////////////////////////////
733/// Return the current directory of ROOT
734
736{
737 return "WORKPATH:"s + TBufferJSON::ToJSON(&fBrowsable.GetWorkingPath()).Data();
738}
739
740//////////////////////////////////////////////////////////////////////////////////////////////
741/// Create message which send to client to create new widget
742
743std::string RBrowser::NewWidgetMsg(std::shared_ptr<RBrowserWidget> &widget)
744{
745 std::vector<std::string> arr = { widget->GetKind(), widget->GetUrl(), widget->GetName(), widget->GetTitle(),
747 return "NEWWIDGET:"s + TBufferJSON::ToJSON(&arr, TBufferJSON::kNoSpaces).Data();
748}
749
750//////////////////////////////////////////////////////////////////////////////////////////////
751/// Check if any widget was modified and update if necessary
752
754{
755 std::vector<std::string> del_names;
756
757 for (auto &widget : fWidgets)
758 if (!widget->IsValid())
759 del_names.push_back(widget->GetName());
760
761 if (!del_names.empty())
762 fWebWindow->Send(connid, "CLOSE_WIDGETS:"s + TBufferJSON::ToJSON(&del_names, TBufferJSON::kNoSpaces).Data());
763
764 for (auto name : del_names)
765 CloseTab(name);
766
767 for (auto &widget : fWidgets)
768 widget->CheckModified();
769}
770
771//////////////////////////////////////////////////////////////////////////////////////////////
772/// Process postponed requests - decouple from websocket handling
773/// Only requests which can take longer time should be postponed
774
776{
777 if (fPostponed.empty())
778 return;
779
780 auto arr = fPostponed[0];
781 fPostponed.erase(fPostponed.begin(), fPostponed.begin()+1);
782 if (fPostponed.empty())
783 fTimer->TurnOff();
784
785 std::string reply;
786 unsigned connid = std::stoul(arr.back()); arr.pop_back();
787 std::string kind = arr.back(); arr.pop_back();
788
789 if (kind == "DBLCLK") {
790 reply = ProcessDblClick(connid, arr);
791 if (reply.empty()) reply = "NOPE";
792 }
793
794 if (!reply.empty())
795 fWebWindow->Send(connid, reply);
796}
797
798
799//////////////////////////////////////////////////////////////////////////////////////////////
800/// Process received message from the client
801
802void RBrowser::ProcessMsg(unsigned connid, const std::string &arg0)
803{
804 R__LOG_DEBUG(0, BrowserLog()) << "ProcessMsg len " << arg0.length() << " substr(30) " << arg0.substr(0, 30);
805
806 std::string kind, msg;
807 auto pos = arg0.find(":");
808 if (pos == std::string::npos) {
809 kind = arg0;
810 } else {
811 kind = arg0.substr(0, pos);
812 msg = arg0.substr(pos+1);
813 }
814
815 if (kind == "QUIT_ROOT") {
816
817 fWebWindow->TerminateROOT();
818
819 } else if (kind == "BRREQ") {
820 // central place for processing browser requests
822 if (!json.empty()) fWebWindow->Send(connid, json);
823
824 } else if (kind == "DBLCLK") {
825
826 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
827 if (arr && (arr->size() > 2)) {
828 arr->push_back(kind);
829 arr->push_back(std::to_string(connid));
830 fPostponed.push_back(*arr);
831 if (fPostponed.size() == 1)
832 fTimer->TurnOn();
833 } else {
834 fWebWindow->Send(connid, "NOPE");
835 }
836
837 } else if (kind == "WIDGET_SELECTED") {
839 auto widget = GetActiveWidget();
840 if (widget) {
841 auto reply = widget->SendWidgetContent();
842 if (!reply.empty()) fWebWindow->Send(connid, reply);
843 }
844 } else if (kind == "CLOSE_TAB") {
845 CloseTab(msg);
846 } else if (kind == "GETWORKPATH") {
847 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
848 } else if (kind == "CHPATH") {
849 auto path = TBufferJSON::FromJSON<Browsable::RElementPath_t>(msg);
850 if (path) fBrowsable.SetWorkingPath(*path);
851 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
852 } else if (kind == "CMD") {
853 std::string sPrompt = "root []";
854 TApplication *app = gROOT->GetApplication();
855 if (app->InheritsFrom("TRint")) {
856 sPrompt = ((TRint*)gROOT->GetApplication())->GetPrompt();
857 Gl_histadd((char *)msg.c_str());
858 }
859
860 std::ofstream ofs(fPromptFileOutput, std::ofstream::out | std::ofstream::app);
861 ofs << sPrompt << msg << std::endl;
862 ofs.close();
863
865 gROOT->ProcessLine(msg.c_str());
866 gSystem->RedirectOutput(nullptr);
867
868 if (msg == ".g"s) {
869 auto widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(""s, "info"s));
870 if (!widget) {
871 auto new_widget = AddWidget("info"s);
872 fWebWindow->Send(connid, NewWidgetMsg(new_widget));
873 widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(new_widget);
874 } else if (fActiveWidgetName != widget->GetName()) {
875 fWebWindow->Send(connid, "SELECT_WIDGET:"s + widget->GetName());
876 fActiveWidgetName = widget->GetName();
877 }
878
879 if (widget)
880 widget->RefreshFromLogs(sPrompt + msg, GetRootLogs());
881 }
882
883 CheckWidgtesModified(connid);
884 } else if (kind == "GETHISTORY") {
885
886 auto history = GetRootHistory();
887
888 fWebWindow->Send(connid, "HISTORY:"s + TBufferJSON::ToJSON(&history, TBufferJSON::kNoSpaces).Data());
889 } else if (kind == "GETLOGS") {
890
891 auto logs = GetRootLogs();
892 fWebWindow->Send(connid, "LOGS:"s + TBufferJSON::ToJSON(&logs, TBufferJSON::kNoSpaces).Data());
893
895
897
898 } else if (kind == "SYNCEDITOR") {
899 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
900 if (arr && (arr->size() > 4)) {
901 auto editor = std::dynamic_pointer_cast<RBrowserEditorWidget>(FindWidget(arr->at(0)));
902 if (editor) {
903 editor->fFirstSend = true;
904 editor->fTitle = arr->at(1);
905 editor->fFileName = arr->at(2);
906 if (!arr->at(3).empty()) editor->fContent = arr->at(4);
907 if ((arr->size() == 6) && (arr->at(5) == "SAVE"))
908 ProcessSaveFile(editor->fFileName, editor->fContent);
909 if ((arr->size() == 6) && (arr->at(5) == "RUN")) {
910 ProcessSaveFile(editor->fFileName, editor->fContent);
911 ProcessRunMacro(editor->fFileName);
912 CheckWidgtesModified(connid);
913 }
914 }
915 }
916 } else if (kind == "GETINFO") {
917 auto info = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(msg));
918 if (info) {
919 info->Refresh();
920 fWebWindow->Send(connid, info->SendWidgetContent());
921 }
922 } else if (kind == "NEWWIDGET") {
923 auto widget = AddWidget(msg);
924 if (widget)
925 fWebWindow->Send(connid, NewWidgetMsg(widget));
926 } else if (kind == "NEWCHANNEL") {
927 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
928 if (arr && (arr->size() == 2)) {
929 auto widget = FindWidget((*arr)[0]);
930 if (widget)
931 RWebWindow::ShowWindow(widget->GetWindow(), { fWebWindow, connid, std::stoi((*arr)[1]) });
932 }
933 } else if (kind == "CDWORKDIR") {
937 } else {
939 }
940 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
941 } else if (kind == "OPTIONS") {
942 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
943 if (arr && (arr->size() == 3)) {
947 }
948 }
949}
950
951//////////////////////////////////////////////////////////////////////////////////////////////
952/// Set working path in the browser
953
954void RBrowser::SetWorkingPath(const std::string &path)
955{
958 if (elem) {
960 if (fWebWindow && (fWebWindow->NumConnections() > 0))
962 }
963}
964
965//////////////////////////////////////////////////////////////////////////////////////////////
966/// Activate widget in RBrowser
967/// One should specify title and (optionally) kind of widget like "tcanvas" or "geom"
968
969bool RBrowser::ActivateWidget(const std::string &title, const std::string &kind)
970{
971 if (title.empty())
972 return false;
973
974 for (auto &widget : fWidgets) {
975
976 if (widget->GetTitle() != title)
977 continue;
978
979 if (!kind.empty() && (widget->GetKind() != kind))
980 continue;
981
982 if (fWebWindow)
983 fWebWindow->Send(0, "SELECT_WIDGET:"s + widget->GetName());
984 else
985 fActiveWidgetName = widget->GetName();
986 return true;
987 }
988
989 return false;
990}
991
992//////////////////////////////////////////////////////////////////////////////////////////////
993/// Set handle which will be cleared when connection is closed
994
995void RBrowser::ClearOnClose(const std::shared_ptr<void> &handle)
996{
997 fWebWindow->SetClearOnClose(handle);
998}
nlohmann::json json
#define R__LOG_ERROR(...)
Definition RLogger.hxx:357
#define R__LOG_DEBUG(DEBUGLEVEL,...)
Definition RLogger.hxx:360
#define f(i)
Definition RSha256.hxx:104
long Long_t
Definition RtypesCore.h:54
constexpr Bool_t kTRUE
Definition RtypesCore.h:93
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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:561
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:244
std::string GetUrl() override
Definition RBrowser.cxx:238
std::string GetKind() const override
Definition RBrowser.cxx:236
std::string GetTitle() override
Definition RBrowser.cxx:240
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:77
std::string fItemPath
! item path in the browser
Definition RBrowser.cxx:69
void ResetConn() override
Definition RBrowser.cxx:74
std::string GetKind() const override
Definition RBrowser.cxx:76
bool fFirstSend
! if editor content was send at least once
Definition RBrowser.cxx:68
RBrowserEditorWidget(const std::string &name, bool is_editor=true)
Definition RBrowser.cxx:71
bool fIsEditor
! either editor or image viewer
Definition RBrowser.cxx:64
virtual ~RBrowserEditorWidget()=default
bool DrawElement(std::shared_ptr< Browsable::RElement > &elem, const std::string &="") override
Definition RBrowser.cxx:79
std::string SendWidgetContent() override
Definition RBrowser.cxx:119
void RefreshFromLogs(const std::string &promt, const std::vector< std::string > &logs)
Definition RBrowser.cxx:186
void ResetConn() override
Definition RBrowser.cxx:151
RBrowserInfoWidget(const std::string &name)
Definition RBrowser.cxx:143
std::string GetTitle() override
Definition RBrowser.cxx:154
std::string GetKind() const override
Definition RBrowser.cxx:153
bool fFirstSend
! if editor content was send at least once
Definition RBrowser.cxx:141
std::string SendWidgetContent() override
Definition RBrowser.cxx:213
virtual ~RBrowserInfoWidget()=default
bool DrawElement(std::shared_ptr< Browsable::RElement > &, const std::string &="") override
Definition RBrowser.cxx:156
RBrowser & fBrowser
Definition RBrowser.cxx:50
RBrowserTimer(Long_t milliSec, Bool_t mode, RBrowser &br)
!< browser processing postponed requests
Definition RBrowser.cxx:53
void Timeout() override
timeout handler used to process postponed requests in main ROOT thread
Definition RBrowser.cxx:57
static std::shared_ptr< RBrowserWidget > DetectCatchedWindow(const std::string &kind, RWebWindow &win)
Check if catch window can be identified and normal widget can be created Used for TCanvas created in ...
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:543
std::vector< std::string > GetRootHistory()
Get content of history file.
Definition RBrowser.cxx:632
void AddInitWidget(const std::string &kind)
Create new widget and send init message to the client.
Definition RBrowser.cxx:593
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:402
void ClearOnClose(const std::shared_ptr< void > &handle)
Set handle which will be cleared when connection is closed.
Definition RBrowser.cxx:995
std::string fActiveWidgetName
! name of active widget
Definition RBrowser.hxx:38
RBrowser(bool use_rcanvas=false)
constructor
Definition RBrowser.cxx:270
void SetWorkingPath(const std::string &path)
Set working path in the browser.
Definition RBrowser.cxx:954
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:743
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:735
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:603
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:342
void ProcessSaveFile(const std::string &fname, const std::string &content)
Process file save command in the editor.
Definition RBrowser.cxx:377
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:531
std::string ProcessBrowserRequest(const std::string &msg)
Process browser request.
Definition RBrowser.cxx:353
std::vector< std::string > GetRootLogs()
Get content of log file.
Definition RBrowser.cxx:655
void ProcessMsg(unsigned connid, const std::string &arg)
Process received message from the client.
Definition RBrowser.cxx:802
void CheckWidgtesModified(unsigned connid)
Check if any widget was modified and update if necessary.
Definition RBrowser.cxx:753
void CloseTab(const std::string &name)
Close and delete specified widget.
Definition RBrowser.cxx:619
void ProcessPostponedRequests()
Process postponed requests - decouple from websocket handling Only requests which can take longer tim...
Definition RBrowser.cxx:775
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:969
void SendInitMsg(unsigned connid)
Process client connect.
Definition RBrowser.cxx:673
void SendProgress(unsigned connid, float progr)
Send generic progress message to the web window Should show progress bar on client side.
Definition RBrowser.cxx:716
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:388
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...
const_iterator begin() const
const_iterator end() const
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.
static unsigned ShowWindow(std::shared_ptr< RWebWindow > window, const RWebDisplayArgs &args="")
Static method to show web window Has to be used instead of RWebWindow::Show() when window potentially...
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
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::RLogChannel & BrowserLog()
Log channel for Browser diagnostics.