Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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
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)
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 ? fWindow->GetUrl(false) : ""s; }
246
247 std::string GetTitle() override { return fCatchedKind; }
248
249 bool IsValid() override { return fWindow != nullptr; }
250
251 RBrowserCatchedWidget(const std::string &name, RWebWindow *win, const std::string &kind) :
253 fWindow(win),
254 fCatchedKind(kind)
255 {
256 }
257};
258
259} // namespace ROOT
260
261using namespace ROOT;
262
263
264/** \class ROOT::RBrowser
265\ingroup rbrowser
266\ingroup webwidgets
267
268\brief Web-based %ROOT files and objects browser
269
270\image html v7_rbrowser.png
271
272*/
273
274//////////////////////////////////////////////////////////////////////////////////////////////
275/// constructor
276
278{
279 if (gROOT->IsWebDisplayBatch()) {
280 ::Warning("RBrowser::RBrowser", "The RBrowser cannot run in web batch mode");
281 return;
282 }
283
284 std::ostringstream pathtmp;
285 pathtmp << gSystem->TempDirectory() << "/command." << gSystem->GetPid() << ".log";
287
289
291
292 fTimer = std::make_unique<RBrowserTimer>(10, kTRUE, *this);
293
295 fWebWindow->SetDefaultPage("file:rootui5sys/browser/browser.html");
296
297 // this is call-back, invoked when message received via websocket
298 fWebWindow->SetCallBacks([this](unsigned connid) { fConnId = connid; SendInitMsg(connid); },
299 [this](unsigned connid, const std::string &arg) { ProcessMsg(connid, arg); });
300 fWebWindow->SetGeometry(1200, 700); // configure predefined window geometry
301 fWebWindow->SetConnLimit(1); // the only connection is allowed
302 fWebWindow->SetMaxQueueLength(30); // number of allowed entries in the window queue
303
304 fWebWindow->GetManager()->SetShowCallback([this](RWebWindow &win, const RWebDisplayArgs &args) -> bool {
305
306 std::string kind;
307
308 if (args.GetWidgetKind() == "RCanvas")
309 kind = "rcanvas";
310 else if (args.GetWidgetKind() == "TCanvas")
311 kind = "tcanvas";
312 else if (args.GetWidgetKind() == "RGeomViewer")
313 kind = "geom";
314 else if (args.GetWidgetKind() == "RTreeViewer")
315 kind = "tree";
316
317 if (!fWebWindow || !fCatchWindowShow || kind.empty())
318 return false;
319
321
322 auto widget = AddCatchedWidget(&win, kind);
323
324 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
325 fWebWindow->Send(0, NewWidgetMsg(widget));
326
327 return widget ? true : false;
328 });
329
330 fWebWindow->GetManager()->SetDeleteCallback([this](RWebWindow &win) -> void {
331 for (auto &widget : fWidgets) {
332 auto catched = dynamic_cast<RBrowserCatchedWidget *>(widget.get());
333 if (catched && (catched->fWindow == &win))
334 catched->fWindow = nullptr;
335 }
336
337 if (fWebWindow)
339 });
340
341 Show();
342
343 // add first canvas by default
344
345 //if (GetUseRCanvas())
346 // AddWidget("rcanvas");
347 //else
348 // AddWidget("tcanvas");
349
350 // AddWidget("geom"); // add geometry viewer at the beginning
351
352 // AddWidget("editor"); // one can add empty editor if necessary
353}
354
355//////////////////////////////////////////////////////////////////////////////////////////////
356/// destructor
357
359{
360 if (fWebWindow) {
361 fWebWindow->GetManager()->SetShowCallback(nullptr);
362 fWebWindow->GetManager()->SetDeleteCallback(nullptr);
363 }
364}
365
366//////////////////////////////////////////////////////////////////////////////////////////////
367/// Process browser request
368
369std::string RBrowser::ProcessBrowserRequest(const std::string &msg)
370{
371 std::unique_ptr<RBrowserRequest> request;
372
373 if (msg.empty()) {
374 request = std::make_unique<RBrowserRequest>();
375 request->first = 0;
376 request->number = 100;
377 } else {
378 request = TBufferJSON::FromJSON<RBrowserRequest>(msg);
379 }
380
381 if (!request)
382 return ""s;
383
384 if (request->path.empty() && fWidgets.empty() && fBrowsable.GetWorkingPath().empty())
386
387 return "BREPL:"s + fBrowsable.ProcessRequest(*request.get());
388}
389
390/////////////////////////////////////////////////////////////////////////////////
391/// Process file save command in the editor
392
393void RBrowser::ProcessSaveFile(const std::string &fname, const std::string &content)
394{
395 if (fname.empty()) return;
396 R__LOG_DEBUG(0, BrowserLog()) << "SaveFile " << fname << " content length " << content.length();
397 std::ofstream f(fname);
398 f << content;
399}
400
401/////////////////////////////////////////////////////////////////////////////////
402/// Process run macro command in the editor
403
404void RBrowser::ProcessRunMacro(const std::string &file_path)
405{
406 if (file_path.rfind(".py") == file_path.length() - 3) {
407 TString exec;
408 exec.Form("TPython::ExecScript(\"%s\");", file_path.c_str());
409 gROOT->ProcessLine(exec.Data());
410 } else {
411 gInterpreter->ExecuteMacro(file_path.c_str());
412 }
413}
414
415/////////////////////////////////////////////////////////////////////////////////
416/// Process dbl click on browser item
417
418std::string RBrowser::ProcessDblClick(unsigned connid, std::vector<std::string> &args)
419{
420 args.pop_back(); // remove exec string, not used now
421
422 std::string opt = args.back();
423 args.pop_back(); // remove option
424
425 auto path = fBrowsable.GetWorkingPath();
426 path.insert(path.end(), args.begin(), args.end());
427
428 R__LOG_DEBUG(0, BrowserLog()) << "DoubleClick " << Browsable::RElement::GetPathAsString(path);
429
430 auto elem = fBrowsable.GetSubElement(path);
431 if (!elem) return ""s;
432
433 auto dflt_action = elem->GetDefaultAction();
434
435 // special case when canvas is clicked - always start new widget
437 std::string widget_kind;
438
439 if (elem->IsCapable(Browsable::RElement::kActDraw7))
440 widget_kind = "rcanvas";
441 else
442 widget_kind = "tcanvas";
443
444 std::string name = widget_kind + std::to_string(++fWidgetCnt);
445
447
448 if (!new_widget)
449 return ""s;
450
451 // assign back pointer
452 new_widget->fBrowser = this;
453
454 new_widget->Show("embed");
455 fWidgets.emplace_back(new_widget);
456 fActiveWidgetName = new_widget->GetName();
457
458 return NewWidgetMsg(new_widget);
459 }
460
461 // before display tree or geometry ensure that they read and cached inside element
463 elem->GetChildsIter();
464 }
465
467 Browsable::RProvider::ProgressHandle handle(elem.get(), [this, connid](float progress, void *) {
468 SendProgress(connid, progress);
469 });
470
471 auto widget = GetActiveWidget();
472 if (widget && widget->DrawElement(elem, opt)) {
473 widget->SetPath(path);
474 return widget->SendWidgetContent();
475 }
476
477 // check if element was drawn in other widget and just activate that widget
478 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
479 [path](const std::shared_ptr<RBrowserWidget> &wg) { return path == wg->GetPath(); });
480
481 if (iter != fWidgets.end())
482 return "SELECT_WIDGET:"s + (*iter)->GetName();
483
484 // check if object can be drawn in RCanvas even when default action is drawing in TCanvas
487
488 std::string widget_kind;
489 switch(dflt_action) {
490 case Browsable::RElement::kActDraw6: widget_kind = "tcanvas"; break;
491 case Browsable::RElement::kActDraw7: widget_kind = "rcanvas"; break;
492 case Browsable::RElement::kActEdit: widget_kind = "editor"; break;
493 case Browsable::RElement::kActImage: widget_kind = "image"; break;
494 case Browsable::RElement::kActTree: widget_kind = "tree"; break;
495 case Browsable::RElement::kActGeom: widget_kind = "geom"; break;
496 default: widget_kind.clear();
497 }
498
499 if (!widget_kind.empty()) {
501 if (new_widget) {
502 // draw object before client side is created - should not be a problem
503 // after widget add in browser, connection will be established and data provided
504 if (new_widget->DrawElement(elem, opt))
505 new_widget->SetPath(path);
506 return NewWidgetMsg(new_widget);
507 }
508 }
509
510 if (elem->IsCapable(Browsable::RElement::kActBrowse) && (elem->GetNumChilds() > 0)) {
511 // remove extra index in subitems name
512 for (auto &pathelem : path)
516 }
517
518 return ""s;
519}
520
521/////////////////////////////////////////////////////////////////////////////////
522/// Show or update RBrowser in web window
523/// If web window already started - just refresh it like "reload" button does
524/// If no web window exists or \param always_start_new_browser configured, starts new window
525/// \param args display arguments
526
528{
529 if (!fWebWindow->NumConnections() || always_start_new_browser) {
530 fWebWindow->Show(args);
531 } else {
532 SendInitMsg(0);
533 }
534}
535
536///////////////////////////////////////////////////////////////////////////////////////////////////////
537/// Hide ROOT Browser
538
540{
541 if (fWebWindow)
542 fWebWindow->CloseConnections();
543}
544
545///////////////////////////////////////////////////////////////////////////////////////////////////////
546/// Return URL parameter for the window showing ROOT Browser
547/// See \ref ROOT::RWebWindow::GetUrl docu for more details
548
550{
551 if (fWebWindow)
552 return fWebWindow->GetUrl(remote);
553
554 return ""s;
555}
556
557
558//////////////////////////////////////////////////////////////////////////////////////////////
559/// Creates new widget
560
561std::shared_ptr<RBrowserWidget> RBrowser::AddWidget(const std::string &kind)
562{
563 std::string name = kind + std::to_string(++fWidgetCnt);
564
565 std::shared_ptr<RBrowserWidget> widget;
566
567 if (kind == "editor"s)
568 widget = std::make_shared<RBrowserEditorWidget>(name, true);
569 else if (kind == "image"s)
570 widget = std::make_shared<RBrowserEditorWidget>(name, false);
571 else if (kind == "info"s)
572 widget = std::make_shared<RBrowserInfoWidget>(name);
573 else
575
576 if (!widget) {
577 R__LOG_ERROR(BrowserLog()) << "Fail to create widget of kind " << kind;
578 return nullptr;
579 }
580
581 widget->fBrowser = this;
582 widget->Show("embed");
583 fWidgets.emplace_back(widget);
584
586
587 return widget;
588}
589
590//////////////////////////////////////////////////////////////////////////////////////////////
591/// Add widget catched from external scripts
592
593std::shared_ptr<RBrowserWidget> RBrowser::AddCatchedWidget(RWebWindow *win, const std::string &kind)
594{
595 if (!win || kind.empty()) return nullptr;
596
597 std::string name = "catched"s + std::to_string(++fWidgetCnt);
598
599 auto widget = std::make_shared<RBrowserCatchedWidget>(name, win, kind);
600
601 fWidgets.emplace_back(widget);
602
604
605 return widget;
606}
607
608
609//////////////////////////////////////////////////////////////////////////////////////////////
610/// Create new widget and send init message to the client
611
612void RBrowser::AddInitWidget(const std::string &kind)
613{
614 auto widget = AddWidget(kind);
615 if (widget && fWebWindow && (fWebWindow->NumConnections() > 0))
616 fWebWindow->Send(0, NewWidgetMsg(widget));
617}
618
619//////////////////////////////////////////////////////////////////////////////////////////////
620/// Find widget by name or kind
621
622std::shared_ptr<RBrowserWidget> RBrowser::FindWidget(const std::string &name, const std::string &kind) const
623{
624 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(),
625 [name, kind](const std::shared_ptr<RBrowserWidget> &widget) {
626 return kind.empty() ? name == widget->GetName() : kind == widget->GetKind();
627 });
628
629 if (iter != fWidgets.end())
630 return *iter;
631
632 return nullptr;
633}
634
635//////////////////////////////////////////////////////////////////////////////////////////////
636/// Close and delete specified widget
637
638void RBrowser::CloseTab(const std::string &name)
639{
640 auto iter = std::find_if(fWidgets.begin(), fWidgets.end(), [name](std::shared_ptr<RBrowserWidget> &widget) { return name == widget->GetName(); });
641 if (iter != fWidgets.end())
642 fWidgets.erase(iter);
643
644 if (fActiveWidgetName == name)
645 fActiveWidgetName.clear();
646}
647
648//////////////////////////////////////////////////////////////////////////////////////////////
649/// Get content of history file
650
651std::vector<std::string> RBrowser::GetRootHistory()
652{
653 std::vector<std::string> arr;
654
655 std::string path = gSystem->UnixPathName(gSystem->HomeDirectory());
656 path += "/.root_hist" ;
657 std::ifstream infile(path);
658
659 if (infile) {
660 std::string line;
661 while (std::getline(infile, line) && (arr.size() < 1000)) {
662 if(!(std::find(arr.begin(), arr.end(), line) != arr.end())) {
663 arr.emplace_back(line);
664 }
665 }
666 }
667
668 return arr;
669}
670
671//////////////////////////////////////////////////////////////////////////////////////////////
672/// Get content of log file
673
674std::vector<std::string> RBrowser::GetRootLogs()
675{
676 std::vector<std::string> arr;
677
678 std::ifstream infile(fPromptFileOutput);
679 if (infile) {
680 std::string line;
681 while (std::getline(infile, line) && (arr.size() < 10000)) {
682 arr.emplace_back(line);
683 }
684 }
685
686 return arr;
687}
688
689//////////////////////////////////////////////////////////////////////////////////////////////
690/// Process client connect
691
692void RBrowser::SendInitMsg(unsigned connid)
693{
694 std::vector<std::vector<std::string>> reply;
695
696 reply.emplace_back(fBrowsable.GetWorkingPath()); // first element is current path
697
698 for (auto &widget : fWidgets) {
699 widget->ResetConn();
700 reply.emplace_back(std::vector<std::string>({ widget->GetKind(), ".."s + widget->GetUrl(), widget->GetName(), widget->GetTitle() }));
701 }
702
703 if (!fActiveWidgetName.empty())
704 reply.emplace_back(std::vector<std::string>({ "active"s, fActiveWidgetName }));
705
706 auto history = GetRootHistory();
707 if (history.size() > 0) {
708 history.insert(history.begin(), "history"s);
709 reply.emplace_back(history);
710 }
711
712 auto logs = GetRootLogs();
713 if (logs.size() > 0) {
714 logs.insert(logs.begin(), "logs"s);
715 reply.emplace_back(logs);
716 }
717
718 reply.emplace_back(std::vector<std::string>({
719 "drawoptions"s,
723 }));
724
725 std::string msg = "INMSG:";
727
728 fWebWindow->Send(connid, msg);
729}
730
731//////////////////////////////////////////////////////////////////////////////////////////////
732/// Send generic progress message to the web window
733/// Should show progress bar on client side
734
735void RBrowser::SendProgress(unsigned connid, float progr)
736{
737 long long millisec = gSystem->Now();
738
739 // let process window events
740 fWebWindow->Sync();
741
742 if ((!fLastProgressSendTm || millisec > fLastProgressSendTm - 200) && (progr > fLastProgressSend + 0.04) && fWebWindow->CanSend(connid)) {
743 fWebWindow->Send(connid, "PROGRESS:"s + std::to_string(progr));
744
747 }
748}
749
750
751//////////////////////////////////////////////////////////////////////////////////////////////
752/// Return the current directory of ROOT
753
755{
756 return "WORKPATH:"s + TBufferJSON::ToJSON(&fBrowsable.GetWorkingPath()).Data();
757}
758
759//////////////////////////////////////////////////////////////////////////////////////////////
760/// Create message which send to client to create new widget
761
762std::string RBrowser::NewWidgetMsg(std::shared_ptr<RBrowserWidget> &widget)
763{
764 std::vector<std::string> arr = { widget->GetKind(), ".."s + widget->GetUrl(), widget->GetName(), widget->GetTitle(),
766 return "NEWWIDGET:"s + TBufferJSON::ToJSON(&arr, TBufferJSON::kNoSpaces).Data();
767}
768
769//////////////////////////////////////////////////////////////////////////////////////////////
770/// Check if any widget was modified and update if necessary
771
773{
774 std::vector<std::string> del_names;
775
776 for (auto &widget : fWidgets)
777 if (!widget->IsValid())
778 del_names.push_back(widget->GetName());
779
780 if (!del_names.empty())
781 fWebWindow->Send(connid, "CLOSE_WIDGETS:"s + TBufferJSON::ToJSON(&del_names, TBufferJSON::kNoSpaces).Data());
782
783 for (auto name : del_names)
784 CloseTab(name);
785
786 for (auto &widget : fWidgets)
787 widget->CheckModified();
788}
789
790//////////////////////////////////////////////////////////////////////////////////////////////
791/// Process postponed requests - decouple from websocket handling
792/// Only requests which can take longer time should be postponed
793
795{
796 if (fPostponed.empty())
797 return;
798
799 auto arr = fPostponed[0];
800 fPostponed.erase(fPostponed.begin(), fPostponed.begin()+1);
801 if (fPostponed.empty())
802 fTimer->TurnOff();
803
804 std::string reply;
805 unsigned connid = std::stoul(arr.back()); arr.pop_back();
806 std::string kind = arr.back(); arr.pop_back();
807
808 if (kind == "DBLCLK") {
809 reply = ProcessDblClick(connid, arr);
810 if (reply.empty()) reply = "NOPE";
811 }
812
813 if (!reply.empty())
814 fWebWindow->Send(connid, reply);
815}
816
817
818//////////////////////////////////////////////////////////////////////////////////////////////
819/// Process received message from the client
820
821void RBrowser::ProcessMsg(unsigned connid, const std::string &arg0)
822{
823 R__LOG_DEBUG(0, BrowserLog()) << "ProcessMsg len " << arg0.length() << " substr(30) " << arg0.substr(0, 30);
824
825 std::string kind, msg;
826 auto pos = arg0.find(":");
827 if (pos == std::string::npos) {
828 kind = arg0;
829 } else {
830 kind = arg0.substr(0, pos);
831 msg = arg0.substr(pos+1);
832 }
833
834 if (kind == "QUIT_ROOT") {
835
836 fWebWindow->TerminateROOT();
837
838 } else if (kind == "BRREQ") {
839 // central place for processing browser requests
841 if (!json.empty()) fWebWindow->Send(connid, json);
842
843 } else if (kind == "DBLCLK") {
844
845 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
846 if (arr && (arr->size() > 2)) {
847 arr->push_back(kind);
848 arr->push_back(std::to_string(connid));
849 fPostponed.push_back(*arr);
850 if (fPostponed.size() == 1)
851 fTimer->TurnOn();
852 } else {
853 fWebWindow->Send(connid, "NOPE");
854 }
855
856 } else if (kind == "WIDGET_SELECTED") {
858 auto widget = GetActiveWidget();
859 if (widget) {
860 auto reply = widget->SendWidgetContent();
861 if (!reply.empty()) fWebWindow->Send(connid, reply);
862 }
863 } else if (kind == "CLOSE_TAB") {
864 CloseTab(msg);
865 } else if (kind == "GETWORKPATH") {
866 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
867 } else if (kind == "CHPATH") {
868 auto path = TBufferJSON::FromJSON<Browsable::RElementPath_t>(msg);
869 if (path) fBrowsable.SetWorkingPath(*path);
870 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
871 } else if (kind == "CMD") {
872 std::string sPrompt = "root []";
873 TApplication *app = gROOT->GetApplication();
874 if (app->InheritsFrom("TRint")) {
875 sPrompt = ((TRint*)gROOT->GetApplication())->GetPrompt();
876 Gl_histadd((char *)msg.c_str());
877 }
878
879 std::ofstream ofs(fPromptFileOutput, std::ofstream::out | std::ofstream::app);
880 ofs << sPrompt << msg << std::endl;
881 ofs.close();
882
884 gROOT->ProcessLine(msg.c_str());
885 gSystem->RedirectOutput(nullptr);
886
887 if (msg == ".g"s) {
888 auto widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(""s, "info"s));
889 if (!widget) {
890 auto new_widget = AddWidget("info"s);
891 fWebWindow->Send(connid, NewWidgetMsg(new_widget));
892 widget = std::dynamic_pointer_cast<RBrowserInfoWidget>(new_widget);
893 } else if (fActiveWidgetName != widget->GetName()) {
894 fWebWindow->Send(connid, "SELECT_WIDGET:"s + widget->GetName());
895 fActiveWidgetName = widget->GetName();
896 }
897
898 if (widget)
899 widget->RefreshFromLogs(sPrompt + msg, GetRootLogs());
900 }
901
902 CheckWidgtesModified(connid);
903 } else if (kind == "GETHISTORY") {
904
905 auto history = GetRootHistory();
906
907 fWebWindow->Send(connid, "HISTORY:"s + TBufferJSON::ToJSON(&history, TBufferJSON::kNoSpaces).Data());
908 } else if (kind == "GETLOGS") {
909
910 auto logs = GetRootLogs();
911 fWebWindow->Send(connid, "LOGS:"s + TBufferJSON::ToJSON(&logs, TBufferJSON::kNoSpaces).Data());
912
914
916
917 } else if (kind == "SYNCEDITOR") {
918 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
919 if (arr && (arr->size() > 4)) {
920 auto editor = std::dynamic_pointer_cast<RBrowserEditorWidget>(FindWidget(arr->at(0)));
921 if (editor) {
922 editor->fFirstSend = true;
923 editor->fTitle = arr->at(1);
924 editor->fFileName = arr->at(2);
925 if (!arr->at(3).empty()) editor->fContent = arr->at(4);
926 if ((arr->size() == 6) && (arr->at(5) == "SAVE"))
927 ProcessSaveFile(editor->fFileName, editor->fContent);
928 if ((arr->size() == 6) && (arr->at(5) == "RUN")) {
929 ProcessSaveFile(editor->fFileName, editor->fContent);
930 ProcessRunMacro(editor->fFileName);
931 CheckWidgtesModified(connid);
932 }
933 }
934 }
935 } else if (kind == "GETINFO") {
936 auto info = std::dynamic_pointer_cast<RBrowserInfoWidget>(FindWidget(msg));
937 if (info) {
938 info->Refresh();
939 fWebWindow->Send(connid, info->SendWidgetContent());
940 }
941 } else if (kind == "NEWWIDGET") {
942 auto widget = AddWidget(msg);
943 if (widget)
944 fWebWindow->Send(connid, NewWidgetMsg(widget));
945 } else if (kind == "CDWORKDIR") {
949 } else {
951 }
952 fWebWindow->Send(connid, GetCurrentWorkingDirectory());
953 } else if (kind == "OPTIONS") {
954 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(msg);
955 if (arr && (arr->size() == 3)) {
959 }
960 }
961}
962
963//////////////////////////////////////////////////////////////////////////////////////////////
964/// Set working path in the browser
965
966void RBrowser::SetWorkingPath(const std::string &path)
967{
970 if (elem) {
972 if (fWebWindow && (fWebWindow->NumConnections() > 0))
974 }
975}
976
977//////////////////////////////////////////////////////////////////////////////////////////////
978/// Activate widget in RBrowser
979/// One should specify title and (optionally) kind of widget like "tcanvas" or "geom"
980
981bool RBrowser::ActivateWidget(const std::string &title, const std::string &kind)
982{
983 if (title.empty())
984 return false;
985
986 for (auto &widget : fWidgets) {
987
988 if (widget->GetTitle() != title)
989 continue;
990
991 if (!kind.empty() && (widget->GetKind() != kind))
992 continue;
993
994 if (fWebWindow)
995 fWebWindow->Send(0, "SELECT_WIDGET:"s + widget->GetName());
996 else
997 fActiveWidgetName = widget->GetName();
998 return true;
999 }
1000
1001 return false;
1002}
1003
1004//////////////////////////////////////////////////////////////////////////////////////////////
1005/// Set handle which will be cleared when connection is closed
1006
1007void RBrowser::ClearOnClose(const std::shared_ptr<void> &handle)
1008{
1009 fWebWindow->SetClearOnClose(handle);
1010}
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: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:572
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:251
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:561
std::vector< std::string > GetRootHistory()
Get content of history file.
Definition RBrowser.cxx:651
void AddInitWidget(const std::string &kind)
Create new widget and send init message to the client.
Definition RBrowser.cxx:612
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:418
void ClearOnClose(const std::shared_ptr< void > &handle)
Set handle which will be cleared when connection is closed.
std::string fActiveWidgetName
! name of active widget
Definition RBrowser.hxx:38
RBrowser(bool use_rcanvas=false)
constructor
Definition RBrowser.cxx:277
void SetWorkingPath(const std::string &path)
Set working path in the browser.
Definition RBrowser.cxx:966
void Hide()
hide Browser
Definition RBrowser.cxx:539
std::string NewWidgetMsg(std::shared_ptr< RBrowserWidget > &widget)
Create message which send to client to create new widget.
Definition RBrowser.cxx:762
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:527
std::string GetCurrentWorkingDirectory()
Return the current directory of ROOT.
Definition RBrowser.cxx:754
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:622
std::shared_ptr< RBrowserWidget > AddCatchedWidget(RWebWindow *win, const std::string &kind)
Add widget catched from external scripts.
Definition RBrowser.cxx:593
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:358
void ProcessSaveFile(const std::string &fname, const std::string &content)
Process file save command in the editor.
Definition RBrowser.cxx:393
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:549
std::string ProcessBrowserRequest(const std::string &msg)
Process browser request.
Definition RBrowser.cxx:369
std::vector< std::string > GetRootLogs()
Get content of log file.
Definition RBrowser.cxx:674
void ProcessMsg(unsigned connid, const std::string &arg)
Process received message from the client.
Definition RBrowser.cxx:821
void CheckWidgtesModified(unsigned connid)
Check if any widget was modified and update if necessary.
Definition RBrowser.cxx:772
void CloseTab(const std::string &name)
Close and delete specified widget.
Definition RBrowser.cxx:638
void ProcessPostponedRequests()
Process postponed requests - decouple from websocket handling Only requests which can take longer tim...
Definition RBrowser.cxx:794
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:981
void SendInitMsg(unsigned connid)
Process client connect.
Definition RBrowser.cxx:692
void SendProgress(unsigned connid, float progr)
Send generic progress message to the web window Should show progress bar on client side.
Definition RBrowser.cxx:735
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:404
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.
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::Experimental::RLogChannel & BrowserLog()
Log channel for Browser diagnostics.