Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TWebCanvas.cxx
Go to the documentation of this file.
1// Author: Sergey Linev, GSI 7/12/2016
2
3/*************************************************************************
4 * Copyright (C) 1995-2023, Rene Brun and Fons Rademakers. *
5 * All rights reserved. *
6 * *
7 * For the licensing terms see $ROOTSYS/LICENSE. *
8 * For the list of contributors see $ROOTSYS/README/CREDITS. *
9 *************************************************************************/
10
11#include "TWebCanvas.h"
12
13#include "TWebSnapshot.h"
14#include "TWebPadPainter.h"
15#include "TWebPS.h"
16#include "TWebMenuItem.h"
18#include "THttpServer.h"
19
20#include "TSystem.h"
21#include "TStyle.h"
22#include "TCanvas.h"
23#include "TButton.h"
24#include "TSlider.h"
25#include "TFrame.h"
26#include "TPaveText.h"
27#include "TPaveStats.h"
28#include "TText.h"
29#include "TROOT.h"
30#include "TClass.h"
31#include "TColor.h"
32#include "TObjArray.h"
33#include "TArrayI.h"
34#include "TList.h"
35#include "TF1.h"
36#include "TF2.h"
37#include "TF3.h"
38#include "TH1.h"
39#include "TH2.h"
40#include "THStack.h"
41#include "TMultiGraph.h"
42#include "TEnv.h"
43#include "TError.h"
44#include "TGraph.h"
45#include "TGraphPolar.h"
46#include "TGraphPolargram.h"
47#include "TGraph2D.h"
48#include "TGaxis.h"
49#include "TScatter.h"
50#include "TCutG.h"
51#include "TBufferJSON.h"
52#include "TBase64.h"
53#include "TAtt3D.h"
54#include "TView.h"
55#include "TExec.h"
56#include "TVirtualX.h"
57#include "TMath.h"
58#include "TTimer.h"
59#include "TThread.h"
60
61#include <cstdio>
62#include <cstring>
63#include <fstream>
64#include <iostream>
65#include <memory>
66#include <sstream>
67#include <vector>
68
69
70class TWebCanvasTimer : public TTimer {
75public:
77
78 Bool_t IsSlow() const { return fSlow; }
80 {
81 fSlow = slow;
82 fSlowCnt = 0;
83 SetTime(slow ? 50 : 10);
84 }
85
86 /// used to send control messages to clients
87 void Timeout() override
88 {
90 return;
94 if (res) {
95 fSlowCnt = 0;
96 } else if (++fSlowCnt > 100 && !IsSlow()) {
98 }
99 }
100};
101
102
103/** \class TWebCanvas
104\ingroup webgui6
105\ingroup webwidgets
106
107Basic TCanvasImp ABI implementation for Web-based Graphics
108Provides painting of main ROOT classes in web browsers using [JSROOT](https://root.cern/js/)
109
110Following settings parameters can be useful for TWebCanvas:
111
112 WebGui.FullCanvas: 1 read-only mode (0), full-functional canvas (1) (default - 1)
113 WebGui.StyleDelivery: 1 provide gStyle object to JSROOT client (default - 1)
114 WebGui.PaletteDelivery: 1 provide color palette to JSROOT client (default - 1)
115 WebGui.TF1UseSave: 1 used saved values for function drawing: 0 - off, 1 - if client fail to evaluate function, 2 - always (default - 1)
116
117TWebCanvas is used by default in interactive ROOT session. To use web-based canvas in batch mode for image
118generation, one should explicitly specify `--web` option when starting ROOT:
119
120 [shell] root -b --web tutorials/hsimple.root -e 'hpxpy->Draw("colz"); c1->SaveAs("image.png");'
121
122If for any reasons TWebCanvas does not provide required functionality, one always can disable it.
123Either by specifying `root --web=off` when starting ROOT or by setting `Canvas.Name: TRootCanvas` in rootrc file.
124
125*/
126
127using namespace std::string_literals;
128
129static const std::string sid_pad_histogram = "__pad_histogram__";
130
131
140
141static std::vector<WebFont_t> gWebFonts;
142
143std::string TWebCanvas::gCustomScripts = {};
144std::vector<std::string> TWebCanvas::gCustomClasses = {};
145
148std::vector<std::string> TWebCanvas::gBatchFiles;
149std::vector<std::string> TWebCanvas::gBatchJsons;
150std::vector<int> TWebCanvas::gBatchWidths;
151std::vector<int> TWebCanvas::gBatchHeights;
152
153//////////////////////////////////////////////////////////////////////////////////////////////////
154/// Configure batch image mode for web graphics.
155/// Allows to process many images with single headless browser invocation and increase performance of image production.
156/// When many canvases are stored as image in difference places, they first collected in batch and then processed when at least `n`
157/// images are prepared. Only then headless browser invoked and create all these images at once.
158/// This allows to significantly increase performance of image production in web mode
159
166
167//////////////////////////////////////////////////////////////////////////////////////////////////
168/// Flush batch images
169
171{
172 bool res = true;
173
174 if (gBatchJsons.size() > 0)
176
177 gBatchFiles.clear();
178 gBatchJsons.clear();
179 gBatchWidths.clear();
180 gBatchHeights.clear();
181
182 return res;
183}
184
185////////////////////////////////////////////////////////////////////////////////
186/// Constructor
187
189 : TCanvasImp(c, name, x, y, width, height)
190{
191 // Workaround for multi-threaded environment
192 // Ensure main thread id picked when canvas implementation is created -
193 // otherwise it may be assigned in other thread and screw-up gPad access.
194 // Workaround may not work if main thread id was wrongly initialized before
195 // This resolves issue https://github.com/root-project/root/issues/15498
197
198 fTimer = new TWebCanvasTimer(*this);
199
201 fStyleDelivery = gEnv->GetValue("WebGui.StyleDelivery", 1);
202 fPaletteDelivery = gEnv->GetValue("WebGui.PaletteDelivery", 1);
203 fPrimitivesMerge = gEnv->GetValue("WebGui.PrimitivesMerge", 100);
204 fTF1UseSave = gEnv->GetValue("WebGui.TF1UseSave", (Int_t) 1);
206
207 fWebConn.emplace_back(0); // add special connection which only used to perform updates
208
209 fTimer->TurnOn();
210
211 // fAsyncMode = kTRUE;
212}
213
214
215////////////////////////////////////////////////////////////////////////////////
216/// Destructor
217
219{
220 if(fWindow)
221 fWindow->Reset();
222
223 delete fTimer;
224}
225
226//////////////////////////////////////////////////////////////////////////////////////////////////
227/// Add font to static list of fonts supported by the canvas
228/// Name specifies name of the font, second is font file with .ttf or .woff2 extension
229/// Only True Type Fonts (ttf) are supported by PDF
230/// Returns font index which can be used in
231/// auto font_indx = TWebCanvas::AddFont("test", "test.ttf", 2);
232/// gStyle->SetStatFont(font_indx);
233
234Font_t TWebCanvas::AddFont(const char *name, const char *fontfile, Int_t precision)
235{
236 Font_t maxindx = 22;
237 for (auto &entry : gWebFonts) {
238 if (entry.fName == name)
239 return precision > 0 ? entry.fIndx*10 + precision : entry.fIndx;
240 if (entry.fIndx > maxindx)
241 maxindx = entry.fIndx;
242 }
243
244 TString fullname = fontfile, fmt = "ttf";
245 auto pos = fullname.Last('.');
246 if (pos != kNPOS) {
247 fmt = fullname(pos+1, fullname.Length() - pos);
248 fmt.ToLower();
249 if ((fmt != "ttf") && (fmt != "woff2")) {
250 ::Error("TWebCanvas::AddFont", "Unsupported font file extension %s", fmt.Data());
251 return (Font_t) -1;
252 }
253 }
254
255 gSystem->ExpandPathName(fullname);
256
257 if (gSystem->AccessPathName(fullname.Data(), kReadPermission)) {
258 ::Error("TWebCanvas::AddFont", "Not possible to read font file %s", fullname.Data());
259 return (Font_t) -1;
260 }
261
262 std::ifstream is(fullname.Data(), std::ios::in | std::ios::binary);
263 std::string res;
264 if (is) {
265 is.seekg(0, std::ios::end);
266 res.resize(is.tellg());
267 is.seekg(0, std::ios::beg);
268 is.read((char *)res.data(), res.length());
269 if (!is)
270 res.clear();
271 }
272
273 if (res.empty()) {
274 ::Error("TWebCanvas::AddFont", "Fail to read font file %s", fullname.Data());
275 return (Font_t) -1;
276 }
277
278 TString base64 = TBase64::Encode(res.c_str(), res.length());
279
280 maxindx++;
281
282 gWebFonts.emplace_back(maxindx, name, fmt, base64);
283
284 return precision > 0 ? maxindx*10 + precision : maxindx;
285}
286
287////////////////////////////////////////////////////////////////////////////////
288/// Initialize window for the web canvas
289/// At this place canvas is not yet register to the list of canvases - one cannot call RWebWindow::Show()
290
292{
293 return 111222333; // should not be used at all
294}
295
296////////////////////////////////////////////////////////////////////////////////
297/// Creates web-based pad painter
298
303
304////////////////////////////////////////////////////////////////////////////////
305/// Returns kTRUE when object is fully supported on JSROOT side
306/// In ROOT7 Paint function will just return appropriate flag that object can be displayed on JSROOT side
307
309{
310 if (!obj)
311 return kTRUE;
312
313 static const struct {
314 const char *name{nullptr};
315 bool with_derived{false};
316 bool reduse_by_many{false};
317 } supported_classes[] = {{"ROOT::Experimental::RTreeMapPainter"},
318 {"TH1", true},
319 {"TF1", true},
320 {"TGraph", true},
321 {"TScatter"},
322 {"TFrame"},
323 {"THStack"},
324 {"TMultiGraph"},
325 {"TGraphPolargram", true},
326 {"TPave", true},
327 {"TGaxis"},
328 {"TEfficiency"},
329 {"TPave", true},
330 {"TButton", true},
331 {"TSlider", true},
332 {"TArrow"},
333 {"TBox", false, true}, // can be handled via TWebPainter, disable for large number of primitives (like in greyscale.C)
334 {"TWbox"}, // some extra calls which cannot be handled via TWebPainter
335 {"TLine", false, true}, // can be handler via TWebPainter, disable for large number of primitives (like in greyscale.C)
336 {"TEllipse", true, true}, // can be handled via TWebPainter, disable for large number of primitives (like in greyscale.C)
337 {"TPie"},
338 {"TText"},
339 {"TLatex"},
340 {"TLink"},
341 {"TAnnotation"},
342 {"TMathText"},
343 {"TMarker"},
344 {"TPolyMarker"},
345 {"TPolyLine", true, true}, // can be handled via TWebPainter, simplify colors handling
346 {"TPolyMarker3D"},
347 {"TPolyLine3D"},
348 {"TGraphTime"},
349 {"TGraph2D"},
350 {"TGraph2DErrors"},
351 {"TGraphTime"},
352 {"TASImage"},
353 {"TRatioPlot"},
354 {"TSpline"},
355 {"TSpline3"},
356 {"TSpline5"},
357 {"TGeoManager"},
358 {"TGeoVolume"},
359 {}};
360
361 // fast check of class name
362 for (int i = 0; supported_classes[i].name != nullptr; ++i)
364 return kTRUE;
365
366 // now check inheritance only for configured classes
367 for (int i = 0; supported_classes[i].name != nullptr; ++i)
369 if (obj->InheritsFrom(supported_classes[i].name))
370 return kTRUE;
371
372 return IsCustomClass(obj->IsA());
373}
374
375//////////////////////////////////////////////////////////////////////////////////////////////////
376/// Configures custom script for canvas.
377/// If started with "modules:" prefix, module(s) will be imported with `loadModules` function of JSROOT.
378/// If custom path was configured in RWebWindowsManager::AddServerLocation, it can be used in module paths.
379/// If started with "load:" prefix, code will be loaded with `loadScript` function of JSROOT (old, deprecated way)
380/// Script also can be a plain JavaScript code which imports JSROOT and provides draw function for custom classes
381/// See tutorials/visualisation/webgui/custom/custom.mjs demonstrating such example
382
383void TWebCanvas::SetCustomScripts(const std::string &src)
384{
386}
387
388//////////////////////////////////////////////////////////////////////////////////////////////////
389/// Returns configured custom script
390
392{
393 return gCustomScripts;
394}
395
396//////////////////////////////////////////////////////////////////////////////////////////////////
397/// For batch mode special handling of scripts are required
398/// Headless browser not able to load modules from the file system
399/// Therefore custom web-canvas modules and scripts has to be loaded in advance and processed
400
402{
403 if (!batch || gCustomScripts.empty() || (gCustomScripts.find("modules:") != 0))
404 return gCustomScripts;
405
407
408 std::string content;
409
410 std::string modules_names = gCustomScripts.substr(8);
411
412 std::map<std::string, bool> mapped_funcs;
413
414 while (!modules_names.empty()) {
415 std::string modname;
416 auto p = modules_names.find(";");
417 if (p == std::string::npos) {
419 modules_names.clear();
420 } else {
421 modname = modules_names.substr(0, p);
422 modules_names = modules_names.substr(p+1);
423 }
424
425 p = modname.find("/");
426 if ((p == std::string::npos) || modname.empty())
427 continue;
428
429 std::string pathname = modname.substr(0, p+1);
430 std::string filename = modname.substr(p+1);
431
432 auto fpath = loc[pathname];
433
434 if (fpath.empty())
435 continue;
436
438 if (cont.empty())
439 continue;
440
441 // check that special mark is in the script
442 auto pmark = cont.find("$$jsroot_batch_conform$$");
443 if (pmark == std::string::npos)
444 continue;
445
446 // process line like this
447 // import { ObjectPainter, addMoveHandler, addDrawFunc, ensureTCanvas } from 'jsroot';
448
449 static const std::string str1 = "import {";
450 static const std::string str2 = "} from 'jsroot';";
451
452 auto p1 = cont.find(str1);
453 auto p2 = cont.find(str2, p1);
454 if ((p1 == std::string::npos) || (p2 == std::string::npos) || (p2 > pmark))
455 continue;
456
457 TString globs;
458
459 TString funcs = cont.substr(p1 + 8, p2 - p1 - 8).c_str();
460 auto arr = funcs.Tokenize(",");
461
462 TIter next(arr);
463 while (auto obj = next()) {
464 TString name = obj->GetName();
465 name = name.Strip(TString::kBoth);
466 if (!mapped_funcs[name.Data()]) {
467 globs.Append(TString::Format("globalThis.%s = JSROOT.%s;\n", name.Data(), name.Data()));
468 mapped_funcs[name.Data()] = true;
469 }
470 }
471 delete arr;
472
473 cont.erase(p1, p2 + str2.length() - p1);
474
475 cont.insert(p1, globs.Data());
476
477 content.append(cont);
478 }
479
480 return content;
481}
482
483
484//////////////////////////////////////////////////////////////////////////////////////////////////
485/// Assign custom class
486
487void TWebCanvas::AddCustomClass(const std::string &clname, bool with_derived)
488{
489 if (with_derived)
490 gCustomClasses.emplace_back("+"s + clname);
491 else
492 gCustomClasses.emplace_back(clname);
493}
494
495//////////////////////////////////////////////////////////////////////////////////////////////////
496/// Checks if class belongs to custom
497
499{
500 for (auto &name : gCustomClasses) {
501 if (name[0] == '+') {
502 if (cl->InheritsFrom(name.substr(1).c_str()))
503 return true;
504 } else if (name.compare(cl->GetName()) == 0) {
505 return true;
506 }
507 }
508 return false;
509}
510
511//////////////////////////////////////////////////////////////////////////////////////////////////
512/// Creates representation of the object for painting in web browser
513
515{
516 if (IsJSSupportedClass(obj, masterps != nullptr)) {
517 master.NewPrimitive(obj, opt).SetSnapshot(TWebSnapshot::kObject, obj);
518 return;
519 }
520
521 // painter is not necessary for batch canvas, but keep configuring it for a while
522 auto *painter = dynamic_cast<TWebPadPainter *>(Canvas()->GetCanvasPainter());
523
524 TView *view = nullptr;
525
527
528 gPad = pad;
529
530 if (obj->InheritsFrom(TAtt3D::Class()) && !pad->GetView()) {
531 pad->GetViewer3D("pad");
532 view = TView::CreateView(1, 0, 0); // Cartesian view by default
533 pad->SetView(view);
534
535 // Set view to perform first auto-range (scaling) pass
536 view->SetAutoRange(kTRUE);
537 }
538
540
542 if (!masterps) {
543 webps = new TWebPS;
544 webps->GetPainting()->SetClassName(obj->ClassName());
545 webps->GetPainting()->SetObjectName(obj->GetName());
546 }
548 if (painter)
549 painter->SetPainting(webps->GetPainting(), webps);
550
551 // calling Paint function for the object
552 obj->Paint(opt);
553
554 if (view) {
555 view->SetAutoRange(kFALSE);
556 // call 3D paint once again to make real drawing
557 obj->Paint(opt);
558 pad->SetView(nullptr);
559 }
560
561 if (painter)
562 painter->SetPainting(nullptr, nullptr);
563
565
566 fPadsStatus[pad]._has_specials = true;
567
568 // if there are master PS, do not create separate entries
569 if (!masterps) {
570 if (!webps->IsEmptyPainting())
571 master.NewPrimitive(obj, opt).SetSnapshot(TWebSnapshot::kSVG, webps->TakePainting(), kTRUE);
572 delete webps;
573 }
574}
575
576//////////////////////////////////////////////////////////////////////////////////////////////////
577/// Calculate hash function for all colors and palette
578
580{
581 UInt_t hash = 0;
582
583 TObjArray *colors = (TObjArray *)gROOT->GetListOfColors();
584
585 if (colors) {
586 for (Int_t n = 0; n <= colors->GetLast(); ++n)
587 if (colors->At(n))
588 hash += TString::Hash(colors->At(n), TColor::Class()->Size());
589 }
590
592
593 hash += TString::Hash(pal.GetArray(), pal.GetSize() * sizeof(Int_t));
594
595 return hash;
596}
597
598
599//////////////////////////////////////////////////////////////////////////////////////////////////
600/// Add special canvas objects with list of colors and color palette
601
603{
604 TObjArray *colors = (TObjArray *)gROOT->GetListOfColors();
605
606 if (!colors)
607 return;
608
609 //Int_t cnt = 0;
610 //for (Int_t n = 0; n <= colors->GetLast(); ++n)
611 // if (colors->At(n))
612 // cnt++;
613 //if (cnt <= 598)
614 // return; // normally there are 598 colors defined
615
617
618 auto listofcols = new TWebPainting;
619 for (Int_t n = 0; n <= colors->GetLast(); ++n)
620 listofcols->AddColor(n, (TColor *)colors->At(n));
621
622 // store palette in the buffer
623 auto *tgt = listofcols->Reserve(pal.GetSize());
624 for (Int_t i = 0; i < pal.GetSize(); i++)
625 tgt[i] = pal[i];
626 listofcols->FixSize();
627
628 master.NewSpecials().SetSnapshot(TWebSnapshot::kColors, listofcols, kTRUE);
629}
630
631//////////////////////////////////////////////////////////////////////////////////////////////////
632/// Add special canvas objects with custom fonts
633
635{
636 for (auto &entry : gWebFonts) {
637 TString code = TString::Format("%d:%s:%s:%s", entry.fIndx, entry.fName.Data(), entry.fFormat.Data(), entry.fData.Data());
638 auto custom_font = new TWebPainting;
639 custom_font->AddOper(code.Data());
640 master.NewSpecials().SetSnapshot(TWebSnapshot::kFont, custom_font, kTRUE);
641 }
642}
643
644//////////////////////////////////////////////////////////////////////////////////////////////////
645/// Create snapshot for pad and all primitives
646/// Callback function is used to create JSON in the middle of data processing -
647/// when all misc objects removed from canvas list of primitives or histogram list of functions
648/// After that objects are moved back to their places
649
651{
652 auto &pad_status = fPadsStatus[pad];
653
654 // send primitives if version 0 or actual pad version grater than already send version
655 bool process_primitives = (version == 0) || (pad_status.fVersion > version);
656
657 if (paddata.IsSetObjectIds()) {
658 paddata.SetActive(pad == gPad);
659 paddata.SetObjectIDAsPtr(pad);
660 }
661 paddata.SetSnapshot(TWebSnapshot::kSubPad, pad); // add ref to the pad
662 paddata.SetWithoutPrimitives(!process_primitives);
663 paddata.SetHasExecs(pad->GetListOfExecs()); // if pad execs are there provide more events from client
664
665 // check style changes every time when creating canvas snapshot
666 if (resfunc && (GetStyleDelivery() > 0)) {
667
669 auto hash = TString::Hash(gStyle, TStyle::Class()->Size());
670 if ((hash != fStyleHash) || (fStyleVersion == 0)) {
673 }
674 }
675
677 paddata.NewPrimitive().SetSnapshot(TWebSnapshot::kStyle, gStyle);
678 }
679
680 // for the first time add custom fonts to the canvas snapshot
681 if (resfunc && (version == 0))
683
684 fAllPads.emplace_back(pad);
685
686 TList *primitives = pad->GetListOfPrimitives();
687
689 bool usemaster = primitives ? (primitives->GetSize() > fPrimitivesMerge) : false;
690
691 TIter iter(primitives);
692 TObject *obj = nullptr;
693 TFrame *frame = nullptr;
694 TPaveText *title = nullptr;
695 TGraphPolar *first_polar = nullptr;
696 TGraphPolargram *polargram = nullptr;
698 bool need_frame = false, has_histo = false, need_palette = false;
699 std::string need_title;
700
701 auto checkNeedPalette = [](TH1* hist, const TString &opt) {
702 auto check = [&opt](const TString &arg) {
703 return opt.Contains(arg + "Z") || opt.Contains(arg + "HZ");
704 };
705
706 return ((hist->GetDimension() == 2) && (check("COL") || check("LEGO") || check("LEGO4") || check("SURF2"))) ||
707 ((hist->GetDimension() == 3) && (check("BOX2") || check("BOX3")));
708 };
709
710 while (process_primitives && ((obj = iter()) != nullptr)) {
711 TString opt = iter.GetOption();
712 opt.ToUpper();
713
714 if (obj->InheritsFrom(THStack::Class())) {
715 // workaround for THStack, create extra components before sending to client
716 if (!opt.Contains("PADS") && !opt.Contains("SAME")) {
718
719 auto hs = static_cast<THStack *>(obj);
720
721 if (!opt.Contains("NOSTACK") && !opt.Contains("CANDLE") && !opt.Contains("VIOLIN") && !IsReadOnly() && !fUsedObjs[hs]) {
723 fUsedObjs[hs] = true;
724 }
725
726 if (strlen(obj->GetTitle()) > 0)
727 need_title = obj->GetTitle();
729 hs->BuildPrimitives(iter.GetOption(), do_rebuild_stack);
730 has_histo = true;
731 need_frame = true;
732 }
733 } else if (obj->InheritsFrom(TMultiGraph::Class())) {
734 // workaround for TMultiGraph
735 if (opt.Contains("A")) {
736 auto mg = static_cast<TMultiGraph *>(obj);
738 mg->GetHistogram(); // force creation of histogram without any drawings
739 has_histo = true;
740 if (strlen(obj->GetTitle()) > 0)
741 need_title = obj->GetTitle();
742 need_frame = true;
743 }
744 } else if (obj->InheritsFrom(TFrame::Class())) {
745 if (!frame)
746 frame = static_cast<TFrame *>(obj);
747 } else if (obj->InheritsFrom(TH1::Class())) {
748 need_frame = true;
749 has_histo = true;
750 if (!obj->TestBit(TH1::kNoTitle) && !opt.Contains("SAME") && !opt.Contains("AXIS") && !opt.Contains("AXIG") && (strlen(obj->GetTitle()) > 0))
751 need_title = obj->GetTitle();
752 if (checkNeedPalette(static_cast<TH1*>(obj), opt))
753 need_palette = true;
754 } else if (obj->InheritsFrom(TGraphPolar::Class())) {
755 auto polar = static_cast<TGraphPolar *> (obj);
756 if (!first_polar) {
758 need_title = first_polar->GetTitle();
759 polargram = first_polar->GetPolargram();
760 if (!polargram) {
761 polargram = first_polar->CreatePolargram(opt);
762 polargram_drawopt = opt.Contains("N") ? "N" : "";
763 if (opt.Contains("O")) polargram_drawopt.Append("O");
764 }
765 }
766 polar->SetPolargram(polargram);
767 } else if (obj->InheritsFrom(TGraph::Class())) {
768 if (opt.Contains("A")) {
769 need_frame = true;
770 if (!has_histo && (strlen(obj->GetTitle()) > 0) && !obj->TestBit(TH1::kNoTitle))
771 need_title = obj->GetTitle();
772 }
773 } else if (obj->InheritsFrom(TGraph2D::Class())) {
774 if (!has_histo && (strlen(obj->GetTitle()) > 0))
775 need_title = obj->GetTitle();
776 } else if (obj->InheritsFrom(TScatter::Class())) {
777 need_frame = need_palette = true;
778 if (strlen(obj->GetTitle()) > 0)
779 need_title = obj->GetTitle();
780 } else if (obj->InheritsFrom(TF1::Class())) {
781 if (!opt.Contains("SAME")) {
783 if (!has_histo && (strlen(obj->GetTitle()) > 0))
784 need_title = obj->GetTitle();
785 }
786 } else if (obj->InheritsFrom(TPaveText::Class())) {
787 if (strcmp(obj->GetName(), "title") == 0)
788 title = static_cast<TPaveText *>(obj);
789 } else if (obj->InheritsFrom(TButton::Class())) {
790 auto btn = (TButton *) obj;
791 auto text = dynamic_cast<TText *> (btn->GetListOfPrimitives()->First());
792 if (text) {
793 text->SetTitle(btn->GetTitle());
794 text->SetTextSize(btn->GetTextSize());
795 text->SetTextFont(btn->GetTextFont());
796 text->SetTextAlign(btn->GetTextAlign());
797 text->SetTextColor(btn->GetTextColor());
798 text->SetTextAngle(btn->GetTextAngle());
799 }
800 }
801 }
802
803 if (need_frame && !frame && primitives && CanCreateObject("TFrame")) {
804 if (!IsReadOnly() && need_palette && (pad->GetRightMargin() < 0.12) && (pad->GetRightMargin() == gStyle->GetPadRightMargin()))
805 pad->SetRightMargin(0.12);
806
807 frame = pad->GetFrame();
808 if(frame)
809 primitives->AddFirst(frame, "");
810 }
811
812 if (!need_title.empty() && gStyle->GetOptTitle()) {
813 if (title) {
814 auto line0 = title->GetLine(0);
815 if (line0 && !IsReadOnly()) line0->SetTitle(need_title.c_str());
816 } else if (primitives && CanCreateObject("TPaveText")) {
817 title = new TPaveText(0, 0, 0, 0, "blNDC");
820 title->SetName("title");
823 title->SetTextFont(gStyle->GetTitleFont(""));
824 if (gStyle->GetTitleFont("") % 10 > 2)
826 title->AddText(need_title.c_str());
827 title->SetBit(kCanDelete);
828 primitives->Add(title, title->GetOption());
829 }
830 }
831
832 if (polargram && (polargram_drawopt != "-"))
833 primitives->Add(polargram, polargram_drawopt);
834
835 auto flush_master = [&]() {
836 if (!usemaster || masterps.IsEmptyPainting()) return;
837
838 paddata.NewPrimitive(pad).SetSnapshot(TWebSnapshot::kSVG, masterps.TakePainting(), kTRUE);
839 masterps.CreatePainting(); // create for next operations
840 };
841
842 auto check_cutg_in_options = [&](const TString &opt) {
843 auto p1 = opt.Index("["), p2 = opt.Index("]");
844 if ((p1 != kNPOS) && (p2 != kNPOS) && p2 > p1 + 1) {
845 TString cutname = opt(p1 + 1, p2 - p1 - 1);
846 TObject *cutg = primitives->FindObject(cutname.Data());
847 if (!cutg || (cutg->IsA() != TCutG::Class())) {
848 cutg = gROOT->GetListOfSpecials()->FindObject(cutname.Data());
849 if (cutg && cutg->IsA() == TCutG::Class())
850 paddata.NewPrimitive(cutg, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, cutg);
851 }
852 }
853 };
854
855 auto check_save_tf1 = [&](TObject *fobj, bool ignore_nodraw = false) {
856 if (!paddata.IsBatchMode() && (fTF1UseSave <= 0))
857 return;
858 if (!ignore_nodraw && fobj->TestBit(TF1::kNotDraw))
859 return;
860
861 auto f1 = static_cast<TF1 *>(fobj);
862 // check if TF1 can be used
863 if (!f1->IsValid())
864 return;
865
866 // in default case save buffer used as is
867 if ((fTF1UseSave == 1) && f1->HasSave())
868 return;
869
870 auto f3 = dynamic_cast<TF3 *>(f1);
871 auto f2 = dynamic_cast<TF2 *>(f1);
872 if (f3)
873 f3->Save(f3->GetXmin(), f3->GetXmax(), f3->GetYmin(), f3->GetYmax(), f3->GetZmin(), f3->GetZmax());
874 else if (f2)
875 f2->Save(f2->GetXmin(), f2->GetXmax(), f2->GetYmin(), f2->GetYmax(), 0, 0);
876 else
877 f1->Save(f1->GetXmin(), f1->GetXmax(), 0, 0, 0, 0);
878 };
879
880 auto create_stats = [&]() {
881 TPaveStats *stats = nullptr;
882 if (CanCreateObject("TPaveStats")) {
883 stats = new TPaveStats(
886 gStyle->GetStatX(),
887 gStyle->GetStatY(), "brNDC");
888
889 // do not set optfit and optstat, they calling pad->Update,
890 // values correctly set already in TPaveStats constructor
891 // stats->SetOptFit(gStyle->GetOptFit());
892 // stats->SetOptStat(gStyle->GetOptStat());
896 stats->SetTextFont(gStyle->GetStatFont());
897 if (gStyle->GetStatFont()%10 > 2)
901 stats->SetName("stats");
902
904 stats->SetTextAlign(12);
905 stats->SetBit(kCanDelete);
906 stats->SetBit(kMustCleanup);
907 }
908
909 return stats;
910 };
911
912 auto check_graph_funcs = [&](TGraph *gr, TList *funcs = nullptr) {
913 if (!funcs && gr)
915 if (!funcs)
916 return;
917
919 TPaveStats *stats = nullptr;
920 bool has_tf1 = false;
921
922 while (auto fobj = fiter()) {
923 if (fobj->InheritsFrom(TPaveStats::Class()))
924 stats = dynamic_cast<TPaveStats *> (fobj);
925 else if (fobj->InheritsFrom(TF1::Class())) {
927 has_tf1 = true;
928 }
929 }
930
931 if (!stats && has_tf1 && gr && !gr->TestBit(TGraph::kNoStats) && (gStyle->GetOptFit() > 0)) {
932 stats = create_stats();
933 if (stats) {
934 stats->SetOptStat(0);
935 stats->SetOptFit(gStyle->GetOptFit());
936 stats->SetParent(funcs);
937 funcs->Add(stats);
938 }
939 }
940 };
941
942 iter.Reset();
943
944 bool first_obj = true;
945
947 pad_status._has_specials = false;
948
949 while ((obj = iter()) != nullptr) {
950 if (obj->IsA() == TPad::Class()) {
951 flush_master();
952 CreatePadSnapshot(paddata.NewSubPad(), (TPad *)obj, version, nullptr);
953 } else if (!process_primitives) {
954 continue;
955 } else if (obj->InheritsFrom(TH1::Class())) {
956 flush_master();
957
958 TH1 *hist = static_cast<TH1 *>(obj);
959 hist->BufferEmpty();
960
961 TPaveStats *stats = nullptr;
962 TObject *palette = nullptr;
963
965 while (auto fobj = fiter()) {
966 if (fobj->InheritsFrom(TPaveStats::Class()))
967 stats = dynamic_cast<TPaveStats *> (fobj);
968 else if (fobj->InheritsFrom("TPaletteAxis"))
969 palette = fobj;
970 else if (fobj->InheritsFrom(TF1::Class()))
972 }
973
974 TString hopt = iter.GetOption();
975 TString o = hopt;
976 o.ToUpper();
977
978 if (!stats && (first_obj || o.Contains("SAMES")) && (gStyle->GetOptStat() > 0)) {
979 stats = create_stats();
980 if (stats) {
981 stats->SetParent(hist);
982 hist->GetListOfFunctions()->Add(stats);
983 }
984 }
985
986 if (!palette && CanCreateObject("TPaletteAxis") && checkNeedPalette(hist, o)) {
987 std::stringstream exec;
988 exec << "new TPaletteAxis(0,0,0,0, (TH1*)" << std::hex << std::showbase << (size_t)hist << ");";
989 palette = (TObject *)gROOT->ProcessLine(exec.str().c_str());
990 if (palette)
992 }
993
994 paddata.NewPrimitive(obj, hopt.Data()).SetSnapshot(TWebSnapshot::kObject, obj);
995
996 if (hist->GetDimension() == 2)
998
999 first_obj = false;
1000 } else if (obj->InheritsFrom(TGraphPolar::Class())) {
1001 flush_master();
1002
1003 auto polar = static_cast<TGraphPolar *>(obj);
1004
1006
1007 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1008
1009 first_obj = false;
1010 } else if (obj->InheritsFrom(TGraphPolargram::Class())) {
1011 // do nothing, object must be streamed with graphpolar
1012 } else if (obj->InheritsFrom(TGraph::Class())) {
1013 flush_master();
1014
1015 TGraph *gr = static_cast<TGraph *>(obj);
1016
1018
1019 TString gropt = iter.GetOption();
1020
1021 // ensure histogram exists on server to draw it properly on clients side
1022 if (!IsReadOnly() && (first_obj || gropt.Index("A", 0, TString::kIgnoreCase) != kNPOS ||
1023 (gropt.Index("X+", 0, TString::kIgnoreCase) != kNPOS) || (gropt.Index("Y+", 0, TString::kIgnoreCase) != kNPOS)))
1024 gr->GetHistogram();
1025
1026 paddata.NewPrimitive(obj, gropt.Data()).SetSnapshot(TWebSnapshot::kObject, obj);
1027
1028 first_obj = false;
1029 } else if (obj->InheritsFrom(TGraph2D::Class())) {
1030 flush_master();
1031
1032 TGraph2D *gr2d = static_cast<TGraph2D *>(obj);
1033
1034 check_graph_funcs(nullptr, gr2d->GetListOfFunctions());
1035
1036 // ensure correct range of histogram
1037 if (!IsReadOnly() && first_obj) {
1038 TString gropt = iter.GetOption();
1039 gropt.ToUpper();
1040 Bool_t zscale = gropt.Contains("TRI1") || gropt.Contains("TRI2") || gropt.Contains("COL");
1041 Bool_t cont5_draw = gropt.Contains("CONT5");
1042 Bool_t real_draw = gropt.Contains("TRI") || gropt.Contains("LINE") || gropt.Contains("ERR") || gropt.Contains("P") || cont5_draw;
1043
1044 TString hopt = !real_draw ? iter.GetOption() : (cont5_draw ? "" : (zscale ? "lego2z" : "lego2"));
1045 if (title) hopt.Append(";;use_pad_title");
1046
1047 // if gr2d not draw - let create histogram with correspondent content
1048 auto hist = gr2d->GetHistogram(real_draw ? "empty" : "");
1049
1050 paddata.NewPrimitive(gr2d, hopt.Data(), "#hist").SetSnapshot(TWebSnapshot::kObject, hist);
1051 }
1052
1053 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1054 first_obj = false;
1055 } else if (obj->InheritsFrom(TMultiGraph::Class())) {
1056 flush_master();
1057
1058 TMultiGraph *mgr = static_cast<TMultiGraph *>(obj);
1059 TIter fiter(mgr->GetListOfFunctions());
1060 while (auto fobj = fiter()) {
1061 if (fobj->InheritsFrom(TF1::Class()))
1063 }
1064
1065 TIter giter(mgr->GetListOfGraphs());
1066 while (auto gobj = giter())
1067 check_graph_funcs(static_cast<TGraph *>(gobj));
1068
1069 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1070
1071 first_obj = false;
1072 } else if (obj->InheritsFrom(THStack::Class())) {
1073 flush_master();
1074
1075 THStack *hs = static_cast<THStack *>(obj);
1076
1077 TString hopt = iter.GetOption();
1078 hopt.ToLower();
1079 if (!hopt.Contains("nostack") && !hopt.Contains("candle") && !hopt.Contains("violin") && !hopt.Contains("pads")) {
1080 auto arr = hs->GetStack();
1081 arr->SetName(hs->GetName()); // mark list for JS
1082 paddata.NewPrimitive(arr, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, arr);
1083 }
1084
1085 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1086
1087 first_obj = hs->GetNhists() > 0; // real drawing only if there are histograms
1088 } else if (obj->InheritsFrom(TScatter::Class())) {
1089 flush_master();
1090
1091 TScatter *scatter = static_cast<TScatter *>(obj);
1092
1093 TObject *palette = nullptr;
1094
1095 TIter fiter(scatter->GetGraph()->GetListOfFunctions());
1096 while (auto fobj = fiter()) {
1097 if (fobj->InheritsFrom("TPaletteAxis"))
1098 palette = fobj;
1099 }
1100
1101 // ensure histogram exists on server to draw it properly on clients side
1102 if (!IsReadOnly() && first_obj)
1103 scatter->GetHistogram();
1104
1105 if (!palette && CanCreateObject("TPaletteAxis")) {
1106 std::stringstream exec;
1107 exec << "new TPaletteAxis(0,0,0,0,0,0);";
1108 palette = (TObject *)gROOT->ProcessLine(exec.str().c_str());
1109 if (palette)
1110 scatter->GetGraph()->GetListOfFunctions()->AddFirst(palette);
1111 }
1112
1113 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1114
1115 first_obj = false;
1116 } else if (obj->InheritsFrom(TF1::Class())) {
1117 flush_master();
1118 auto f1 = static_cast<TF1 *> (obj);
1119
1120 TString f1opt = iter.GetOption();
1121
1122 check_save_tf1(obj, true);
1123 if (fTF1UseSave > 1)
1124 f1opt.Append(";force_saved");
1125 else if (fTF1UseSave == 1)
1126 f1opt.Append(";prefer_saved");
1127
1128 if (first_obj) {
1129 auto hist = f1->GetHistogram();
1130 paddata.NewPrimitive(hist, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, hist);
1131 f1opt.Append(";webcanv_hist");
1132 }
1133
1134 if (f1->IsA() == TF2::Class())
1136
1137 paddata.NewPrimitive(f1, f1opt.Data()).SetSnapshot(TWebSnapshot::kObject, f1);
1138
1139 first_obj = false;
1140
1141 } else if (obj->InheritsFrom(TGaxis::Class())) {
1142 flush_master();
1143 auto gaxis = static_cast<TGaxis *> (obj);
1144 auto func = gaxis->GetFunction();
1145 if (func)
1146 paddata.NewPrimitive(func, "__ignore_drawing__").SetSnapshot(TWebSnapshot::kObject, func);
1147
1148 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1149 } else if (obj->InheritsFrom(TFrame::Class())) {
1150 flush_master();
1151 if (frame && (obj == frame)) {
1152 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1153 frame = nullptr; // add frame only once
1154 }
1155 } else if (IsJSSupportedClass(obj, usemaster)) {
1156 flush_master();
1157 paddata.NewPrimitive(obj, iter.GetOption()).SetSnapshot(TWebSnapshot::kObject, obj);
1158 } else {
1159 CreateObjectSnapshot(paddata, pad, obj, iter.GetOption(), usemaster ? &masterps : nullptr);
1160 }
1161 }
1162
1163 flush_master();
1164
1165 bool provide_colors = false;
1166
1167 if ((GetPaletteDelivery() > 2) || ((GetPaletteDelivery() == 2) && resfunc)) {
1168 // provide colors: either for each subpad (> 2) or only for canvas (== 2)
1170 } else if ((GetPaletteDelivery() == 1) && resfunc) {
1171 // check that colors really changing, using hash
1172
1174 auto hash = CalculateColorsHash();
1175 if ((hash != fColorsHash) || (fColorsVersion == 0)) {
1176 fColorsHash = hash;
1178 }
1179 }
1180
1182 }
1183
1184 // add colors after painting is performed - new colors may be generated only during painting
1185 if (provide_colors)
1187
1188 if (!resfunc)
1189 return;
1190
1191 // now hide all primitives to perform I/O
1192 std::vector<TList *> all_primitives(fAllPads.size());
1193 for (unsigned n = 0; n < fAllPads.size(); ++n) {
1194 all_primitives[n] = fAllPads[n]->fPrimitives;
1195 fAllPads[n]->fPrimitives = nullptr;
1196 }
1197
1198 // execute function to prevent storing of colors with custom TCanvas streamer
1200
1201 // invoke callback for streaming
1202 resfunc(&paddata);
1203
1204 // and restore back primitives - delete any temporary if necessary
1205 for (unsigned n = 0; n < fAllPads.size(); ++n) {
1206 if (fAllPads[n]->fPrimitives)
1207 delete fAllPads[n]->fPrimitives;
1208 fAllPads[n]->fPrimitives = all_primitives[n];
1209 }
1210 fAllPads.clear();
1211 fUsedObjs.clear();
1212}
1213
1214//////////////////////////////////////////////////////////////////////////////////////////////////
1215/// Add control message for specified connection
1216/// Same control message can be overwritten many time before it really sends to the client
1217/// If connid == 0, message will be add to all connections
1218/// After ctrl message is add to the output, short timer is activated and message send afterwards
1219
1220void TWebCanvas::AddCtrlMsg(unsigned connid, const std::string &key, const std::string &value)
1221{
1223
1224 for (auto &conn : fWebConn) {
1225 if (conn.match(connid)) {
1226 conn.fCtrl[key] = value;
1227 new_ctrl = kTRUE;
1228 }
1229 }
1230
1231 if (new_ctrl && fTimer->IsSlow())
1233}
1234
1235
1236//////////////////////////////////////////////////////////////////////////////////////////////////
1237/// Add message to send queue for specified connection
1238/// If connid == 0, message will be add to all connections
1239
1240void TWebCanvas::AddSendQueue(unsigned connid, const std::string &msg)
1241{
1242 for (auto &conn : fWebConn) {
1243 if (conn.match(connid))
1244 conn.fSend.emplace(msg);
1245 }
1246}
1247
1248
1249//////////////////////////////////////////////////////////////////////////////////////////////////
1250/// Check if any data should be send to client
1251/// If connid != 0, only selected connection will be checked
1252
1254{
1255 if (!Canvas())
1256 return kFALSE;
1257
1258 bool isMoreData = false, isAnySend = false;
1259
1260 for (auto &conn : fWebConn) {
1261
1262 bool isConnData = !conn.fCtrl.empty() || !conn.fSend.empty() ||
1263 ((conn.fCheckedVersion < fCanvVersion) && (conn.fSendVersion == conn.fDrawVersion));
1264
1265 while ((conn.is_batch() && !connid) || (conn.match(connid) && fWindow && fWindow->CanSend(conn.fConnId, true))) {
1266 // check if any control messages still there to keep timer running
1267
1268 std::string buf;
1269
1270 if (!conn.fCtrl.empty()) {
1272 conn.fCtrl.clear();
1273 } else if (!conn.fSend.empty()) {
1274 std::swap(buf, conn.fSend.front());
1275 conn.fSend.pop();
1276 } else if ((conn.fCheckedVersion < fCanvVersion) && (conn.fSendVersion == conn.fDrawVersion)) {
1277
1278 buf = "SNAP6:"s + std::to_string(fCanvVersion) + ":"s;
1279
1280 TCanvasWebSnapshot holder(IsReadOnly(), true, false); // readonly, set ids, batchmode
1281
1282 holder.SetFixedSize(fFixedSize); // set fixed size flag
1283
1284 // scripts send only when canvas drawn for the first time
1285 if (!conn.fSendVersion)
1286 holder.SetScripts(ProcessCustomScripts(false));
1287
1288 holder.SetHighlightConnect(Canvas()->HasConnection("Highlighted(TVirtualPad*,TObject*,Int_t,Int_t)"));
1289
1290 CreatePadSnapshot(holder, Canvas(), conn.fSendVersion, [&buf, &conn, this](TPadWebSnapshot *snap) {
1291 if (conn.is_batch()) {
1292 // for batch connection only calling of CreatePadSnapshot is important
1293 buf.clear();
1294 return;
1295 }
1296
1298 auto hash = json.Hash();
1299 if (conn.fLastSendHash && (conn.fLastSendHash == hash) && conn.fSendVersion) {
1300 // prevent looping when same data send many times
1301 buf.clear();
1302 } else {
1303 buf.append(json.Data());
1304 conn.fLastSendHash = hash;
1305 }
1306 });
1307
1308 conn.fCheckedVersion = fCanvVersion;
1309
1310 conn.fSendVersion = fCanvVersion;
1311
1312 if (buf.empty())
1313 conn.fDrawVersion = fCanvVersion;
1314 } else {
1315 isConnData = false;
1316 break;
1317 }
1318
1319 if (!buf.empty() && !conn.is_batch()) {
1320 fWindow->Send(conn.fConnId, buf);
1321 isAnySend = true;
1322 }
1323 }
1324
1325 if (isConnData)
1326 isMoreData = true;
1327 }
1328
1329 if (fTimer->IsSlow() && isMoreData)
1330 fTimer->SetSlow(kFALSE);
1331
1332 return isAnySend;
1333}
1334
1335//////////////////////////////////////////////////////////////////////////////////////////
1336/// Close web canvas - not implemented
1337
1339{
1340}
1341
1342//////////////////////////////////////////////////////////////////////////////////////////
1343/// Create web window for the canvas
1344
1346{
1347 if (fWindow)
1348 return;
1349
1351
1352 fWindow->SetConnLimit(0); // configure connections limit
1353
1354 fWindow->SetDefaultPage("file:rootui5sys/canv/canvas6.html");
1355
1356 fWindow->SetCallBacks(
1357 // connection
1358 [this](unsigned connid) {
1359 if (fWindow->GetConnectionId(0) == connid)
1360 fWebConn.emplace(fWebConn.begin() + 1, connid);
1361 else
1362 fWebConn.emplace_back(connid);
1363 CheckDataToSend(connid);
1364 },
1365 // data
1366 [this](unsigned connid, const std::string &arg) {
1367 ProcessData(connid, arg);
1369 },
1370 // disconnect
1371 [this](unsigned connid) {
1372 unsigned indx = 0;
1373 for (auto &c : fWebConn) {
1374 if (c.fConnId == connid) {
1375 fWebConn.erase(fWebConn.begin() + indx);
1376 break;
1377 }
1378 indx++;
1379 }
1380 });
1381}
1382
1383//////////////////////////////////////////////////////////////////////////////////////////
1384/// Show canvas in specified place.
1385/// If parameter args not specified, default ROOT web display will be used
1386
1388{
1390
1393
1394 auto w = Canvas()->GetWindowWidth(), h = Canvas()->GetWindowHeight();
1395 if ((w > 0) && (w < 50000) && (h > 0) && (h < 30000))
1396 fWindow->SetGeometry(w, h);
1397
1399}
1400
1401//////////////////////////////////////////////////////////////////////////////////////////
1402/// Show canvas in browser window
1403
1405{
1406 if (gROOT->IsWebDisplayBatch())
1407 return;
1408
1409 if (fWindow && !fWindow->HasConnection(0))
1410 fLastDrawVersion = 0;
1411
1413 args.SetWidgetKind("TCanvas");
1414 args.SetSize(Canvas()->GetWindowWidth(), Canvas()->GetWindowHeight());
1415 args.SetPos(Canvas()->GetWindowTopX(), Canvas()->GetWindowTopY());
1416
1417 ShowWebWindow(args);
1418}
1419
1420//////////////////////////////////////////////////////////////////////////////////////////
1421/// Function used to send command to browser to toggle menu, toolbar, editors, ...
1422
1423void TWebCanvas::ShowCmd(const std::string &arg, Bool_t show)
1424{
1425 AddCtrlMsg(0, arg, show ? "1"s : "0"s);
1426}
1427
1428//////////////////////////////////////////////////////////////////////////////////////////
1429/// Activate object in editor in web browser
1430
1432{
1433 if (!pad || !obj) return;
1434
1435 UInt_t hash = TString::Hash(&obj, sizeof(obj));
1436
1437 AddCtrlMsg(0, "edit"s, std::to_string(hash));
1438}
1439
1440//////////////////////////////////////////////////////////////////////////////////////////
1441/// Returns kTRUE if web canvas has graphical editor
1442
1444{
1445 return (fClientBits & TCanvas::kShowEditor) != 0;
1446}
1447
1448//////////////////////////////////////////////////////////////////////////////////////////
1449/// Returns kTRUE if web canvas has menu bar
1450
1452{
1453 return (fClientBits & TCanvas::kMenuBar) != 0;
1454}
1455
1456//////////////////////////////////////////////////////////////////////////////////////////
1457/// Returns kTRUE if web canvas has status bar
1458
1463
1464//////////////////////////////////////////////////////////////////////////////////////////
1465/// Returns kTRUE if tooltips are activated in web canvas
1466
1468{
1469 return (fClientBits & TCanvas::kShowToolTips) != 0;
1470}
1471
1472//////////////////////////////////////////////////////////////////////////////////////////
1473/// Set window position of web canvas
1474
1476{
1477 AddCtrlMsg(0, "x"s, std::to_string(x));
1478 AddCtrlMsg(0, "y"s, std::to_string(y));
1479}
1480
1481//////////////////////////////////////////////////////////////////////////////////////////
1482/// Set window size of web canvas
1483
1485{
1486 AddCtrlMsg(0, "w"s, std::to_string(w));
1487 AddCtrlMsg(0, "h"s, std::to_string(h));
1488}
1489
1490//////////////////////////////////////////////////////////////////////////////////////////
1491/// Set window title of web canvas
1492
1494{
1495 AddCtrlMsg(0, "title"s, newTitle);
1496}
1497
1498//////////////////////////////////////////////////////////////////////////////////////////
1499/// Set canvas size of web canvas
1500
1502{
1503 fFixedSize = kTRUE;
1504 AddCtrlMsg(0, "cw"s, std::to_string(cw));
1505 AddCtrlMsg(0, "ch"s, std::to_string(ch));
1506 if ((cw > 0) && (ch > 0)) {
1507 Canvas()->fCw = cw;
1508 Canvas()->fCh = ch;
1509 } else {
1510 // temporary value, will be reported back from client
1511 Canvas()->fCw = Canvas()->fWindowWidth;
1513 }
1514}
1515
1516//////////////////////////////////////////////////////////////////////////////////////////
1517/// Iconify browser window
1518
1520{
1521 AddCtrlMsg(0, "winstate"s, "iconify"s);
1522}
1523
1524//////////////////////////////////////////////////////////////////////////////////////////
1525/// Raise browser window
1526
1528{
1529 AddCtrlMsg(0, "winstate"s, "raise"s);
1530}
1531
1532//////////////////////////////////////////////////////////////////////////////////////////
1533/// Assign clients bits
1534
1543
1544//////////////////////////////////////////////////////////////////////////////////////////////////
1545/// Decode all pad options, which includes ranges plus objects options
1546
1548{
1549 if (IsReadOnly() || msg.empty())
1550 return kFALSE;
1551
1552 auto arr = TBufferJSON::FromJSON<std::vector<TWebPadOptions>>(msg);
1553
1554 if (!arr)
1555 return kFALSE;
1556
1558
1559 TPad *pad_with_execs = nullptr;
1560 TExec *hist_exec = nullptr;
1561
1562 for (unsigned n = 0; n < arr->size(); ++n) {
1563 auto &r = arr->at(n);
1564
1565 TPad *pad = dynamic_cast<TPad *>(FindPrimitive(r.snapid));
1566
1567 if (!pad)
1568 continue;
1569
1570 if (pad == Canvas()) {
1571 AssignStatusBits(r.bits);
1572 Canvas()->fCw = r.cw;
1573 Canvas()->fCh = r.ch;
1574 if (r.w.size() == 4)
1576 }
1577
1578 // only if get OPTIONS message from client allow to change gPad
1579 if (r.active && (pad != gPad) && process_execs)
1580 gPad = pad;
1581
1582 if ((pad->GetTickx() != r.tickx) || (pad->GetTicky() != r.ticky))
1583 pad->SetTicks(r.tickx, r.ticky);
1584 if ((pad->GetGridx() != (r.gridx > 0)) || (pad->GetGridy() != (r.gridy > 0)))
1585 pad->SetGrid(r.gridx, r.gridy);
1586 pad->fLogx = r.logx;
1587 pad->fLogy = r.logy;
1588 pad->fLogz = r.logz;
1589
1590 pad->SetLeftMargin(r.mleft);
1591 pad->SetRightMargin(r.mright);
1592 pad->SetTopMargin(r.mtop);
1593 pad->SetBottomMargin(r.mbottom);
1594
1595 if (r.ranges) {
1596 // avoid call of original methods, set members directly
1597 // pad->Range(r.px1, r.py1, r.px2, r.py2);
1598 // pad->RangeAxis(r.ux1, r.uy1, r.ux2, r.uy2);
1599
1600 pad->fX1 = r.px1;
1601 pad->fX2 = r.px2;
1602 pad->fY1 = r.py1;
1603 pad->fY2 = r.py2;
1604
1605 pad->fUxmin = r.ux1;
1606 pad->fUxmax = r.ux2;
1607 pad->fUymin = r.uy1;
1608 pad->fUymax = r.uy2;
1609 }
1610
1611 // pad->SetPad(r.mleft, r.mbottom, 1-r.mright, 1-r.mtop);
1612
1613 pad->fAbsXlowNDC = r.xlow;
1614 pad->fAbsYlowNDC = r.ylow;
1615 pad->fAbsWNDC = r.xup - r.xlow;
1616 pad->fAbsHNDC = r.yup - r.ylow;
1617
1618 if (pad == Canvas()) {
1619 pad->fXlowNDC = r.xlow;
1620 pad->fYlowNDC = r.ylow;
1621 pad->fXUpNDC = r.xup;
1622 pad->fYUpNDC = r.yup;
1623 pad->fWNDC = r.xup - r.xlow;
1624 pad->fHNDC = r.yup - r.ylow;
1625 } else {
1626 auto mother = pad->GetMother();
1627 if (mother->GetAbsWNDC() > 0. && mother->GetAbsHNDC() > 0.) {
1628 pad->fXlowNDC = (r.xlow - mother->GetAbsXlowNDC()) / mother->GetAbsWNDC();
1629 pad->fYlowNDC = (r.ylow - mother->GetAbsYlowNDC()) / mother->GetAbsHNDC();
1630 pad->fXUpNDC = (r.xup - mother->GetAbsXlowNDC()) / mother->GetAbsWNDC();
1631 pad->fYUpNDC = (r.yup - mother->GetAbsYlowNDC()) / mother->GetAbsHNDC();
1632 pad->fWNDC = (r.xup - r.xlow) / mother->GetAbsWNDC();
1633 pad->fHNDC = (r.yup - r.ylow) / mother->GetAbsHNDC();
1634 }
1635 }
1636
1637 if (r.phi || r.theta) {
1638 pad->fPhi = r.phi;
1639 pad->fTheta = r.theta;
1640 }
1641
1642 // copy of code from TPad::ResizePad()
1643
1644 Double_t pxlow = r.xlow * r.cw;
1645 Double_t pylow = (1-r.ylow) * r.ch;
1646 Double_t pxrange = (r.xup - r.xlow) * r.cw;
1647 Double_t pyrange = -1*(r.yup - r.ylow) * r.ch;
1648
1649 Double_t rounding = 0.00005;
1650 Double_t xrange = r.px2 - r.px1;
1651 Double_t yrange = r.py2 - r.py1;
1652
1653 if ((xrange != 0.) && (pxrange != 0)) {
1654 // Linear X axis
1655 pad->fXtoAbsPixelk = rounding + pxlow - pxrange*r.px1/xrange; //origin at left
1656 pad->fXtoPixelk = rounding + -pxrange*r.px1/xrange;
1657 pad->fXtoPixel = pxrange/xrange;
1658 pad->fAbsPixeltoXk = r.px1 - pxlow*xrange/pxrange;
1659 pad->fPixeltoXk = r.px1;
1660 pad->fPixeltoX = xrange/pxrange;
1661 }
1662
1663 if ((yrange != 0.) && (pyrange != 0.)) {
1664 // Linear Y axis
1665 pad->fYtoAbsPixelk = rounding + pylow - pyrange*r.py1/yrange; //origin at top
1666 pad->fYtoPixelk = rounding + -pyrange - pyrange*r.py1/yrange;
1667 pad->fYtoPixel = pyrange/yrange;
1668 pad->fAbsPixeltoYk = r.py1 - pylow*yrange/pyrange;
1669 pad->fPixeltoYk = r.py1;
1670 pad->fPixeltoY = yrange/pyrange;
1671 }
1672
1673 pad->SetFixedAspectRatio(kFALSE);
1674
1675 TObjLink *objlnk = nullptr;
1676
1677 TH1 *hist = static_cast<TH1 *>(FindPrimitive(sid_pad_histogram, 1, pad, &objlnk));
1678
1679 if (hist) {
1680
1681 TObject *hist_holder = objlnk ? objlnk->GetObject() : nullptr;
1682 if (hist_holder == hist)
1683 hist_holder = nullptr;
1684
1685 Bool_t no_entries = hist->GetEntries();
1687
1688 Double_t hmin = 0., hmax = 0.;
1689
1690 auto setAxisRange = [](TAxis *ax, Double_t r1, Double_t r2) {
1691 if (r1 != r2)
1692 ax->SetRangeUser(r1, r2);
1693 else if ((ax->GetFirst() == ax->GetLast()) || ((ax->GetFirst() > 0) && (ax->GetLast() <= ax->GetNbins())))
1694 // only if no underflow/overflow bins selected - let reset
1695 ax->SetRange(0, 0);
1696 };
1697
1698 setAxisRange(hist->GetXaxis(), r.zx1, r.zx2);
1699
1700 if (hist->GetDimension() == 1) {
1701 hmin = r.zy1;
1702 hmax = r.zy2;
1703 if ((hmin == hmax) && !no_entries && !is_stack) {
1704 // if there are no zooming on Y and histogram has no entries, hmin/hmax should be set to full range
1705 hmin = pad->fLogy ? TMath::Power(pad->fLogy < 2 ? 10 : pad->fLogy, r.uy1) : r.uy1;
1706 hmax = pad->fLogy ? TMath::Power(pad->fLogy < 2 ? 10 : pad->fLogy, r.uy2) : r.uy2;
1707 }
1708 } else {
1709 setAxisRange(hist->GetYaxis(), r.zy1, r.zy2);
1710 }
1711
1712 if (hist->GetDimension() == 2) {
1713 hmin = r.zz1;
1714 hmax = r.zz2;
1715 if ((hmin == hmax) && !no_entries) {
1716 // z scale is not transformed
1717 hmin = r.uz1;
1718 hmax = r.uz2;
1719 }
1720 } else if (hist->GetDimension() == 3) {
1721 setAxisRange(hist->GetZaxis(), r.zz1, r.zz2);
1722 }
1723
1724 if (hmin == hmax)
1725 hmin = hmax = -1111;
1726
1727 if (is_stack) {
1728 hist->SetMinimum(hmin);
1729 hist->SetMaximum(hmax);
1730 hist->SetBit(TH1::kIsZoomed, hmin != hmax);
1731 } else if (!hist_holder || (hist_holder->IsA() == TScatter::Class())) {
1732 hist->SetMinimum(hmin);
1733 hist->SetMaximum(hmax);
1734 } else {
1735 auto SetMember = [hist_holder](const char *name, Double_t value) {
1736 auto offset = hist_holder->IsA()->GetDataMemberOffset(name);
1737 if (offset > 0)
1738 *((Double_t *)((char*) hist_holder + offset)) = value;
1739 else
1740 ::Error("SetMember", "Cannot find %s data member in %s", name, hist_holder->ClassName());
1741 };
1742
1743 // directly set min/max in classes like THStack, TGraph, TMultiGraph
1744 SetMember("fMinimum", hmin);
1745 SetMember("fMaximum", hmax);
1746 }
1747
1748 TIter next(hist->GetListOfFunctions());
1749 while (auto fobj = next())
1750 if (!hist_exec && fobj->InheritsFrom(TExec::Class())) {
1751 hist_exec = (TExec *) fobj;
1753 }
1754 }
1755
1756 std::map<std::string, int> idmap;
1757
1758 for (auto &item : r.primitives) {
1759 auto iter = idmap.find(item.snapid);
1760 int idcnt = 1;
1761 if (iter == idmap.end())
1762 idmap[item.snapid] = 1;
1763 else
1764 idcnt = ++iter->second;
1765
1767 }
1768
1769 // without special objects no need for explicit update of the pad
1770 if (fPadsStatus[pad]._has_specials) {
1771 pad->Modified(kTRUE);
1773 }
1774
1775 if (process_execs && (gPad == pad))
1777 }
1778
1780
1781 if (fUpdatedSignal) fUpdatedSignal(); // invoke signal
1782
1783 return need_update;
1784}
1785
1786//////////////////////////////////////////////////////////////////////////////////////////////////
1787/// Process TExec objects in the pad
1788
1790{
1791 auto execs = pad ? pad->GetListOfExecs() : nullptr;
1792
1793 if ((!execs || !execs->GetSize()) && !extra)
1794 return;
1795
1796 auto saveps = gVirtualPS;
1797 TWebPS ps;
1798 gVirtualPS = &ps;
1799
1800 auto savex = gVirtualX;
1801 TVirtualX x;
1802 gVirtualX = &x;
1803
1804 TIter next(execs);
1805 while (auto obj = next()) {
1806 auto exec = dynamic_cast<TExec *>(obj);
1807 if (exec)
1808 exec->Exec();
1809 }
1810
1811 if (extra)
1812 extra->Exec();
1813
1815 gVirtualX = savex;
1816}
1817
1818//////////////////////////////////////////////////////////////////////////////////////////
1819/// Execute one or several methods for selected object
1820/// String can be separated by ";;" to let execute several methods at once
1822{
1823 std::string buf = lines;
1824
1825 Int_t indx = 0;
1826
1827 while (obj && !buf.empty()) {
1828 std::string sub = buf;
1829 auto pos = buf.find(";;");
1830 if (pos == std::string::npos) {
1831 sub = buf;
1832 buf.clear();
1833 } else {
1834 sub = buf.substr(0,pos);
1835 buf = buf.substr(pos+2);
1836 }
1837 if (sub.empty()) continue;
1838
1839 std::stringstream exec;
1840 exec << "((" << obj->ClassName() << " *) " << std::hex << std::showbase << (size_t)obj << ")->" << sub << ";";
1842 Info("ProcessLinesForObject", "Obj %s Execute %s", obj->GetName(), exec.str().c_str());
1843 gROOT->ProcessLine(exec.str().c_str());
1844 indx++;
1845 }
1846}
1847
1848//////////////////////////////////////////////////////////////////////////////////////////
1849/// Handle data from web browser
1850/// Returns kFALSE if message was not processed
1851
1852Bool_t TWebCanvas::ProcessData(unsigned connid, const std::string &arg)
1853{
1854 if (arg.empty())
1855 return kTRUE;
1856
1857 // try to identify connection for given WS request
1858 unsigned indx = 0; // first connection is batch and excluded
1859 while(++indx < fWebConn.size()) {
1860 if (fWebConn[indx].fConnId == connid)
1861 break;
1862 }
1863 if (indx >= fWebConn.size())
1864 return kTRUE;
1865
1866 Bool_t is_main_connection = indx == 1; // first connection allow to make changes
1867
1868 struct FlagGuard {
1869 Bool_t &flag;
1870 FlagGuard(Bool_t &_flag) : flag(_flag) { flag = true; }
1871 ~FlagGuard() { flag = false; }
1872 };
1873
1875
1876 const char *cdata = arg.c_str();
1877
1878 if (arg == "KEEPALIVE") {
1879 // do nothing
1880
1881 } else if (arg == "QUIT") {
1882
1883 // use window manager to correctly terminate http server
1884 fWindow->TerminateROOT();
1885
1886 } else if (arg.compare(0, 7, "READY6:") == 0) {
1887
1888 // this is reply on drawing of ROOT6 snapshot
1889 // it confirms when drawing of specific canvas version is completed
1890
1891 cdata += 7;
1892
1893 const char *separ = strchr(cdata, ':');
1894 if (!separ) {
1895 fWebConn[indx].fDrawVersion = std::stoll(cdata);
1896 } else {
1897 fWebConn[indx].fDrawVersion = std::stoll(std::string(cdata, separ - cdata));
1899 if (DecodePadOptions(separ+1, false))
1901 }
1902
1903 if (indx == 1)
1904 fLastDrawVersion = fWebConn[indx].fDrawVersion;
1905
1906 } else if (arg == "RELOAD") {
1907
1908 // trigger reload of canvas data
1909 fWebConn[indx].reset();
1910
1911 } else if (arg.compare(0, 5, "SAVE:") == 0) {
1912
1913 // save image produced by the client side - like png or svg
1914 const char *img = cdata + 5;
1915
1916 const char *separ = strchr(img, ':');
1917 if (separ) {
1919 img = separ + 1;
1920
1921 std::ofstream ofs(filename.Data());
1922
1923 int filelen = -1;
1924
1925 if (filename.Index(".svg") != kNPOS) {
1926 // ofs << "<?xml version=\"1.0\" standalone=\"no\"?>";
1927 ofs << img;
1928 filelen = strlen(img);
1929 } else {
1931 ofs.write(binary.Data(), binary.Length());
1932 filelen = binary.Length();
1933 }
1934 ofs.close();
1935
1936 Info("ProcessData", "File %s size %d has been created", filename.Data(), filelen);
1937 }
1938
1939 } else if (arg.compare(0, 8, "PRODUCE:") == 0) {
1940
1941 // create ROOT, PDF, ... files using native ROOT functionality
1942 Canvas()->Print(arg.c_str() + 8);
1943
1944 } else if (arg.compare(0, 8, "GETMENU:") == 0) {
1945
1946 TObject *obj = FindPrimitive(arg.substr(8));
1947 if (!obj)
1948 obj = Canvas();
1949
1950 TWebMenuItems items(arg.c_str() + 8);
1951 items.PopulateObjectMenu(obj, obj->IsA());
1952 std::string buf = "MENU:";
1953 buf.append(TBufferJSON::ToJSON(&items, 103).Data());
1954
1955 AddSendQueue(connid, buf);
1956
1957 } else if (arg.compare(0, 11, "STATUSBITS:") == 0) {
1958
1959 if (is_main_connection) {
1960 AssignStatusBits(std::stoul(arg.substr(11)));
1961 if (fUpdatedSignal) fUpdatedSignal(); // invoke signal
1962 }
1963
1964 } else if (arg.compare(0, 10, "HIGHLIGHT:") == 0) {
1965
1966 if (is_main_connection) {
1967 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(arg.substr(10));
1968 if (!arr || (arr->size() != 4)) {
1969 Error("ProcessData", "Wrong arguments count %d in highlight message", (int)(arr ? arr->size() : -1));
1970 } else {
1971 auto pad = dynamic_cast<TVirtualPad *>(FindPrimitive(arr->at(0)));
1972 auto obj = FindPrimitive(arr->at(1));
1973 int argx = std::stoi(arr->at(2));
1974 int argy = std::stoi(arr->at(3));
1975 if (pad && obj) {
1976 Canvas()->Highlighted(pad, obj, argx, argy);
1978 }
1979 }
1980 }
1981
1982 } else if (ROOT::RWebWindow::IsFileDialogMessage(arg)) {
1983
1985
1986 } else if (IsReadOnly() || !is_main_connection) {
1987
1988 ///////////////////////////////////////////////////////////////////////////////////////
1989 // all following messages are not allowed in readonly mode or for secondary connections
1990
1991 return kFALSE;
1992
1993 } else if (arg.compare(0, 9, "OPTIONS6:") == 0) {
1994
1995 if (DecodePadOptions(arg.substr(9), true))
1997
1998 } else if (arg.compare(0, 9, "FITPANEL:") == 0) {
1999
2000 std::string chid = arg.substr(9);
2001
2002 TH1 *hist = nullptr;
2003 TIter iter(Canvas()->GetListOfPrimitives());
2004 while (auto obj = iter()) {
2005 hist = dynamic_cast<TH1 *>(obj);
2006 if (hist) break;
2007 }
2008
2010 if (chid == "standalone")
2011 showcmd = "panel->Show()";
2012 else
2013 showcmd = TString::Format("auto wptr = (std::shared_ptr<ROOT::RWebWindow>*)0x%zx;"
2014 "panel->Show({*wptr, %u, %s})",
2015 (size_t) &fWindow, connid, chid.c_str());
2016
2017 auto cmd = TString::Format("auto panel = std::make_shared<ROOT::Experimental::RFitPanel>(\"FitPanel\");"
2018 "panel->AssignCanvas(\"%s\");"
2019 "panel->AssignHistogram((TH1 *)0x%zx);"
2020 "%s;panel->ClearOnClose(panel);",
2021 Canvas()->GetName(), (size_t) hist, showcmd.Data());
2022 gROOT->ProcessLine(cmd.Data());
2023 } else if (arg == "START_BROWSER"s) {
2024
2025 gROOT->ProcessLine("new TBrowser;");
2026
2027 } else if (arg.compare(0, 6, "EVENT:") == 0) {
2028 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(arg.substr(6));
2029 if (!arr || (arr->size() != 5)) {
2030 Error("ProcessData", "Wrong arguments count %d in event message", (int)(arr ? arr->size() : -1));
2031 } else {
2032 auto pad = dynamic_cast<TPad *>(FindPrimitive(arr->at(0)));
2033 std::string kind = arr->at(1);
2034 int event = -1;
2035 if (kind == "move"s) event = kMouseMotion;
2036 int argx = std::stoi(arr->at(2));
2037 int argy = std::stoi(arr->at(3));
2038 auto selobj = FindPrimitive(arr->at(4));
2039
2040 if ((event >= 0) && pad && (pad == gPad)) {
2041 Canvas()->fEvent = event;
2042 Canvas()->fEventX = argx;
2043 Canvas()->fEventY = argy;
2044
2045 Canvas()->fSelected = selobj;
2046
2048 }
2049 }
2050
2051 } else if (arg.compare(0, 8, "PRIMIT6:") == 0) {
2052
2053 auto opt = TBufferJSON::FromJSON<TWebObjectOptions>(arg.c_str() + 8);
2054
2055 if (opt) {
2056 TPad *modpad = ProcessObjectOptions(*opt, nullptr);
2057
2058 // indicate that pad was modified
2059 if (modpad)
2060 modpad->Modified();
2061 }
2062
2063 } else if (arg.compare(0, 11, "PADCLICKED:") == 0) {
2064
2065 auto click = TBufferJSON::FromJSON<TWebPadClick>(arg.c_str() + 11);
2066
2067 if (click) {
2068
2069 TPad *pad = dynamic_cast<TPad *>(FindPrimitive(click->padid));
2070
2071 if (pad && pad->InheritsFrom(TButton::Class())) {
2072 auto btn = (TButton *) pad;
2073 const char *mthd = btn->GetMethod();
2074 if (mthd && *mthd) {
2075 auto cpad = gROOT->GetSelectedPad();
2076 if (cpad)
2077 cpad->cd();
2078 gROOT->ProcessLine(mthd);
2079 }
2080 return kTRUE;
2081 }
2082
2083 if (pad && (pad != gPad)) {
2084 gPad = pad;
2088 }
2089
2090 if (!click->objid.empty()) {
2091 auto selobj = FindPrimitive(click->objid);
2093 Canvas()->fSelected = selobj;
2094 if (pad && selobj && fObjSelectSignal)
2096 }
2097
2098 if ((click->x >= 0) && (click->y >= 0)) {
2100 Canvas()->fEventX = click->x;
2101 Canvas()->fEventY = click->y;
2102 if (click->dbl && fPadDblClickedSignal)
2104 else if (!click->dbl && fPadClickedSignal)
2106 }
2107
2109 }
2110
2111 } else if (arg.compare(0, 8, "OBJEXEC:") == 0) {
2112
2113 auto buf = arg.substr(8);
2114 auto pos = buf.find(":");
2115
2116 if ((pos > 0) && (pos != std::string::npos)) {
2117 auto sid = buf.substr(0, pos);
2118 buf.erase(0, pos + 1);
2119
2120 TObjLink *lnk = nullptr;
2121 TPad *objpad = nullptr;
2122
2123 TObject *obj = FindPrimitive(sid, 1, nullptr, &lnk, &objpad);
2124
2125 if (obj && !buf.empty()) {
2126
2127 ProcessLinesForObject(obj, buf);
2128
2129 if (objpad)
2130 objpad->Modified();
2131 else
2132 Canvas()->Modified();
2133
2135 }
2136 }
2137
2138 } else if (arg.compare(0, 12, "EXECANDSEND:") == 0) {
2139
2140 // execute method and send data, used by drawing projections
2141
2142 std::string buf = arg.substr(12);
2143 std::string reply;
2144 TObject *obj = nullptr;
2145
2146 auto pos = buf.find(":");
2147
2148 if (pos > 0) {
2149 // only first client can execute commands
2150 reply = buf.substr(0, pos);
2151 buf.erase(0, pos + 1);
2152 pos = buf.find(":");
2153 if (pos > 0) {
2154 auto sid = buf.substr(0, pos);
2155 buf.erase(0, pos + 1);
2156 obj = FindPrimitive(sid);
2157 }
2158 }
2159
2160 if (obj && !buf.empty() && !reply.empty()) {
2161 std::stringstream exec;
2162 exec << "((" << obj->ClassName() << " *) " << std::hex << std::showbase << (size_t)obj
2163 << ")->" << buf << ";";
2164 if (gDebug > 0)
2165 Info("ProcessData", "Obj %s Exec %s", obj->GetName(), exec.str().c_str());
2166
2167 auto res = gROOT->ProcessLine(exec.str().c_str());
2168 TObject *resobj = (TObject *)(res);
2169 if (resobj) {
2170 std::string send = reply;
2171 send.append(":");
2172 send.append(TBufferJSON::ToJSON(resobj, 23).Data());
2173 AddSendQueue(connid, send);
2174 if (reply[0] == 'D')
2175 delete resobj; // delete object if first symbol in reply is D
2176 }
2177 }
2178
2179 } else if (arg.compare(0, 6, "CLEAR:") == 0) {
2180 std::string snapid = arg.substr(6);
2181
2182 TPad *pad = dynamic_cast<TPad *>(FindPrimitive(snapid));
2183
2184 if (pad) {
2185 pad->Clear();
2186 pad->Modified();
2188 } else {
2189 Error("ProcessData", "Not found pad with id %s to clear\n", snapid.c_str());
2190 }
2191 } else if (arg.compare(0, 7, "DIVIDE:") == 0) {
2192 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(arg.substr(7));
2193 if (arr && arr->size() == 2) {
2194 TPad *pad = dynamic_cast<TPad *>(FindPrimitive(arr->at(0)));
2195 int nn = 0, n1 = 0, n2 = 0;
2196
2197 std::string divide = arr->at(1);
2198 auto p = divide.find('x');
2199 if (p == std::string::npos)
2200 p = divide.find('X');
2201
2202 if (p != std::string::npos) {
2203 n1 = std::stoi(divide.substr(0,p));
2204 n2 = std::stoi(divide.substr(p+1));
2205 } else {
2206 nn = std::stoi(divide);
2207 }
2208
2209 if (pad && ((nn > 1) || (n1*n2 > 1))) {
2210 pad->Clear();
2211 pad->Modified();
2212 if (nn > 1)
2213 pad->DivideSquare(nn);
2214 else
2215 pad->Divide(n1, n2);
2216 pad->cd(1);
2218 }
2219 }
2220
2221 } else if (arg.compare(0, 8, "DRAWOPT:") == 0) {
2222
2223 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(arg.substr(8));
2224 if (arr && arr->size() == 2) {
2225 TObjLink *objlnk = nullptr;
2226 FindPrimitive(arr->at(0), 1, nullptr, &objlnk);
2227 if (objlnk)
2228 objlnk->SetOption(arr->at(1).c_str());
2229 }
2230
2231 } else if (arg.compare(0, 8, "RESIZED:") == 0) {
2232
2233 auto arr = TBufferJSON::FromJSON<std::vector<int>>(arg.substr(8));
2234 if (arr && arr->size() == 7) {
2235 // set members directly to avoid redrawing of the client again
2236 Canvas()->fCw = arr->at(4);
2237 Canvas()->fCh = arr->at(5);
2238 fFixedSize = arr->at(6) > 0;
2239 arr->resize(4);
2241 }
2242
2243 } else if (arg.compare(0, 7, "POPOBJ:") == 0) {
2244
2245 auto arr = TBufferJSON::FromJSON<std::vector<std::string>>(arg.substr(7));
2246 if (arr && arr->size() == 2) {
2247 TPad *pad = dynamic_cast<TPad *>(FindPrimitive(arr->at(0)));
2248 TObject *obj = FindPrimitive(arr->at(1), 0, pad);
2249 if (pad && obj && (obj != pad->GetListOfPrimitives()->Last())) {
2250 TIter next(pad->GetListOfPrimitives());
2251 while (auto o = next())
2252 if (obj == o) {
2253 TString opt = next.GetOption();
2254 pad->Remove(obj, kFALSE);
2255 pad->Add(obj, opt.Data());
2256 break;
2257 }
2258 }
2259 }
2260
2261 } else if (arg.compare(0, 8, "SHOWURL:") == 0) {
2262
2264 args.SetUrl(arg.substr(8));
2265 args.SetStandalone(false);
2266
2268
2269 } else if (arg == "INTERRUPT"s) {
2270
2271 gROOT->SetInterrupt();
2272
2273 } else {
2274
2275 // unknown message, probably should be processed by other implementation
2276 return kFALSE;
2277
2278 }
2279
2280 return kTRUE;
2281}
2282
2283//////////////////////////////////////////////////////////////////////////////////////////
2284/// Returns true if any pad in the canvas were modified
2285/// Reset modified flags, increment canvas version (if inc_version is true)
2286
2288{
2289 if (fPadsStatus.find(pad) == fPadsStatus.end())
2290 fPadsStatus[pad] = PadStatus{0, true, true};
2291
2292 auto &entry = fPadsStatus[pad];
2293 entry._detected = true;
2294 if (pad->IsModified()) {
2295 pad->Modified(kFALSE);
2296 entry._modified = true;
2297 }
2298
2299 TIter iter(pad->GetListOfPrimitives());
2300 while (auto obj = iter()) {
2301 if (obj->IsA() == TPad::Class())
2302 CheckPadModified(static_cast<TPad *>(obj));
2303 }
2304}
2305
2306//////////////////////////////////////////////////////////////////////////////////////////
2307/// Check if any pad on the canvas was modified
2308/// If yes, increment version of correspondent pad
2309/// Returns true when canvas really modified
2310
2312{
2313 // clear temporary flags
2314 for (auto &entry : fPadsStatus) {
2315 entry.second._detected = false;
2316 entry.second._modified = force_modified;
2317 }
2318
2319 // scan sub-pads
2321
2322 // remove no-longer existing pads
2323 bool is_any_modified = false;
2324 for(auto iter = fPadsStatus.begin(); iter != fPadsStatus.end(); ) {
2325 if (iter->second._modified)
2326 is_any_modified = true;
2327 if (!iter->second._detected)
2328 fPadsStatus.erase(iter++);
2329 else
2330 iter++;
2331 }
2332
2333 // if any pad modified, increment canvas version and set version of modified pads
2334 if (is_any_modified) {
2335 fCanvVersion++;
2336 for(auto &entry : fPadsStatus)
2337 if (entry.second._modified)
2338 entry.second.fVersion = fCanvVersion;
2339 }
2340
2341 return is_any_modified;
2342}
2343
2344//////////////////////////////////////////////////////////////////////////////////////////
2345/// Set window geometry as array with coordinates and dimensions
2346
2347void TWebCanvas::SetWindowGeometry(const std::vector<int> &arr)
2348{
2350 Canvas()->fWindowTopX = arr[0];
2351 Canvas()->fWindowTopY = arr[1];
2352 Canvas()->fWindowWidth = arr[2];
2353 Canvas()->fWindowHeight = arr[3];
2354 if (fWindow) {
2355 // position is unreliable and cannot be used
2356 // fWindow->SetPosition(arr[0], arr[1]);
2357 fWindow->SetGeometry(arr[2], arr[3]);
2358 }
2359}
2360
2361//////////////////////////////////////////////////////////////////////////////////////////
2362/// Returns window geometry including borders and menus
2363
2365{
2366 if (fWindowGeometry.size() == 4) {
2367 x = fWindowGeometry[0];
2368 y = fWindowGeometry[1];
2369 w = fWindowGeometry[2];
2370 h = fWindowGeometry[3];
2371 } else {
2372 x = Canvas()->fWindowTopX;
2373 y = Canvas()->fWindowTopY;
2374 w = Canvas()->fWindowWidth;
2375 h = Canvas()->fWindowHeight;
2376 }
2377 return 0;
2378}
2379
2380
2381//////////////////////////////////////////////////////////////////////////////////////////
2382/// if canvas or any subpad was modified,
2383/// scan all primitives in the TCanvas and subpads and convert them into
2384/// the structure which will be delivered to JSROOT client
2385
2387{
2389
2391
2392 if (!fProcessingData && !IsAsyncMode() && !async)
2394 else if (fWindow)
2395 fWindow->Sync();
2396
2397 return kTRUE;
2398}
2399
2400//////////////////////////////////////////////////////////////////////////////////////////
2401/// Increment canvas version and force sending data to client - do not wait for reply
2402
2404{
2405 CheckCanvasModified(true);
2406
2407 if (!fWindow) {
2408 TCanvasWebSnapshot holder(IsReadOnly(), false, true); // readonly, set ids, batchmode
2409
2410 holder.SetScripts(ProcessCustomScripts(true));
2411
2412 CreatePadSnapshot(holder, Canvas(), 0, nullptr);
2413 } else {
2415 }
2416}
2417
2418//////////////////////////////////////////////////////////////////////////////////////////
2419/// Wait when specified version of canvas was painted and confirmed by browser
2420
2422{
2423 if (!fWindow)
2424 return kTRUE;
2425
2426 // simple polling loop until specified version delivered to the clients
2427 // first 500 loops done without sleep, then with 1ms sleep and last 500 with 100 ms sleep
2428
2429 long cnt = 0, cnt_limit = GetLongerPolling() ? 5500 : 1500;
2430
2431 if (gDebug > 2)
2432 Info("WaitWhenCanvasPainted", "version %ld", (long)ver);
2433
2434 while (cnt++ < cnt_limit) {
2435
2436 // handle send operations, check connection timeouts
2437 fWindow->Sync();
2438
2439 if (!fWindow->HasConnection(0, false)) {
2440 if (gDebug > 2)
2441 Info("WaitWhenCanvasPainted", "no connections - abort");
2442 return kFALSE; // wait ~1 min if no new connection established
2443 }
2444
2445 if ((fWebConn.size() > 1) && (fWebConn[1].fDrawVersion >= ver)) {
2446 if (gDebug > 2)
2447 Info("WaitWhenCanvasPainted", "ver %ld got painted", (long)ver);
2448 return kTRUE;
2449 }
2450
2451 if (!fWindow->HasConnection(0) && (fLastDrawVersion > 0)) {
2452 if (gDebug > 2)
2453 Info("WaitWhenCanvasPainted", "ver %ld got painted before client disconnected", (long)fLastDrawVersion);
2454 return kTRUE;
2455 }
2456
2458 if (cnt > 500)
2459 gSystem->Sleep((cnt < cnt_limit - 500) ? 1 : 100); // increase sleep interval when do very often
2460 }
2461
2462 if (gDebug > 2)
2463 Info("WaitWhenCanvasPainted", "timeout");
2464
2465 return kFALSE;
2466}
2467
2468//////////////////////////////////////////////////////////////////////////////////////////
2469/// Create JSON painting output for given pad
2470/// Produce JSON can be used for offline drawing with JSROOT
2471
2473{
2474 TString res;
2475 if (!pad)
2476 return res;
2477
2478 TCanvas *c = dynamic_cast<TCanvas *>(pad);
2479 if (c) {
2481 } else {
2482 auto imp = std::make_unique<TWebCanvas>(pad->GetCanvas(), pad->GetName(), 0, 0, pad->GetWw(), pad->GetWh(), kTRUE);
2483
2484 TPadWebSnapshot holder(true, false, batchmode); // readonly, no ids, batchmode
2485
2486 imp->CreatePadSnapshot(holder, pad, 0, [&res, json_compression](TPadWebSnapshot *snap) {
2488 });
2489 }
2490
2491 return res;
2492}
2493
2494//////////////////////////////////////////////////////////////////////////////////////////
2495/// Create JSON painting output for given canvas
2496/// Produce JSON can be used for offline drawing with JSROOT
2497
2499{
2500 TString res;
2501
2502 if (!c)
2503 return res;
2504
2505 {
2506 auto imp = std::make_unique<TWebCanvas>(c, c->GetName(), 0, 0, c->GetWw(), c->GetWh(), kTRUE);
2507
2508 TCanvasWebSnapshot holder(true, false, batchmode); // readonly, no ids, batchmode
2509
2511
2512 imp->CreatePadSnapshot(holder, c, 0, [&res, json_compression](TPadWebSnapshot *snap) {
2514 });
2515 }
2516
2517 return res;
2518}
2519
2520//////////////////////////////////////////////////////////////////////////////////////////
2521/// Create JSON painting output for given canvas and store into the file
2522/// See TBufferJSON::ExportToFile() method for more details about option
2523/// If option string starts with symbol 'b', JSON for batch mode will be generated (default)
2524/// If option string starts with symbol 'i', JSON for interactive mode will be generated
2525
2527{
2528 Int_t res = 0;
2530 if (option) {
2531 if (*option == 'b') {
2532 batchmode = kTRUE;
2533 ++option;
2534 } else if (*option == 'i') {
2535 batchmode = kFALSE;
2536 ++option;
2537 }
2538 }
2539
2540 if (!c)
2541 return res;
2542
2543 {
2544 auto imp = std::make_unique<TWebCanvas>(c, c->GetName(), 0, 0, c->GetWw(), c->GetWh(), kTRUE);
2545
2546 TCanvasWebSnapshot holder(true, false, batchmode); // readonly, no ids, batchmode
2547
2549
2550 imp->CreatePadSnapshot(holder, c, 0, [&res, filename, option](TPadWebSnapshot *snap) {
2552 });
2553 }
2554
2555 return res;
2556}
2557
2558//////////////////////////////////////////////////////////////////////////////////////////
2559/// Create image using batch (headless) capability of Chrome or Firefox browsers
2560/// Supported png, jpeg, svg, pdf formats
2561
2563{
2564 if (!pad)
2565 return false;
2566
2568 if (!json.Length())
2569 return false;
2570
2571 TString fname = fileName;
2572 const char *endings[4] = {"(", "[", "]", ")"};
2573 const char *suffix = nullptr;
2574 for (int n = 0; (n < 4) && !suffix; ++n) {
2575 if (fname.EndsWith(endings[n])) {
2576 fname.Resize(fname.Length() - 1);
2577 suffix = endings[n];
2578 }
2579 }
2580
2582
2584 if (fmt.empty())
2585 return false;
2586
2587 if (suffix) {
2588 if (fmt != "pdf")
2589 return false;
2590 switch (*suffix) {
2591 case '(': gBatchMultiPdf = fname.Data(); flush_batch = kFALSE; break;
2592 case '[': gBatchMultiPdf = fname.Data(); append_batch = kFALSE; flush_batch = kFALSE; break;
2593 case ']': gBatchMultiPdf.clear(); append_batch = kFALSE; break;
2594 case ')': gBatchMultiPdf.clear(); fname.Append("+"); break;
2595 }
2596 } else if (fmt == "pdf") {
2597 if (!gBatchMultiPdf.empty()) {
2598 if (gBatchMultiPdf.compare(fileName) == 0) {
2601 suffix = "+"; // to let append to the batch
2602 if ((gBatchFiles.size() > 0) && (gBatchFiles.back().compare(0, fname.Length(), fname.Data()) == 0))
2603 fname.Append("+"); // .pdf+ means appending image to previous
2604 } else {
2605 ::Error("TWebCanvas::ProduceImage", "Cannot change PDF name when multi-page PDF active");
2606 return false;
2607 }
2608 }
2609 } else if (!gBatchMultiPdf.empty()) {
2610 ::Error("TWebCanvas::ProduceImage", "Cannot produce other images when multi-page PDF active");
2611 return false;
2612 }
2613
2614 if (!width && !height) {
2615 if ((pad->GetCanvas() == pad) || (pad->IsA() == TCanvas::Class())) {
2616 width = pad->GetWw();
2617 height = pad->GetWh();
2618 } else {
2619 width = (Int_t) (pad->GetAbsWNDC() * pad->GetCanvas()->GetWw());
2620 height = (Int_t) (pad->GetAbsHNDC() * pad->GetCanvas()->GetWh());
2621 }
2622 }
2623
2624 if (!suffix && (!gBatchImageMode || (fmt == "s.pdf") || (fmt == "json") || (fmt == "s.png")))
2626
2627 if (append_batch) {
2628 gBatchFiles.emplace_back(fname.Data());
2629 gBatchJsons.emplace_back(json);
2630 gBatchWidths.emplace_back(width);
2631 gBatchHeights.emplace_back(height);
2632 }
2633
2634 if (!flush_batch || (gBatchJsons.size() < gBatchImageMode))
2635 return true;
2636
2637 return FlushBatchImages();
2638}
2639
2640//////////////////////////////////////////////////////////////////////////////////////////
2641/// Create images for several pads using batch (headless) capability of Chrome or Firefox browsers
2642/// Supported png, jpeg, svg, pdf, webp formats
2643/// One can include %d qualifier which will be replaced by image index using printf functionality.
2644/// If for pdf format %d qualifier not specified, all images will be stored in single PDF file.
2645/// For all other formats %d qualifier will be add before extension automatically
2646
2647bool TWebCanvas::ProduceImages(std::vector<TPad *> pads, const char *filename, Int_t width, Int_t height)
2648{
2649 if (pads.empty())
2650 return false;
2651
2652 std::vector<std::string> jsons;
2653 std::vector<Int_t> widths, heights;
2654
2655 for (unsigned n = 0; n < pads.size(); ++n) {
2656 auto pad = pads[n];
2657
2659 if (!json.Length())
2660 continue;
2661
2662 Int_t w = width, h = height;
2663
2664 if (!w && !h) {
2665 if ((pad->GetCanvas() == pad) || (pad->IsA() == TCanvas::Class())) {
2666 w = pad->GetWw();
2667 h = pad->GetWh();
2668 } else {
2669 w = (Int_t) (pad->GetAbsWNDC() * pad->GetCanvas()->GetWw());
2670 h = (Int_t) (pad->GetAbsHNDC() * pad->GetCanvas()->GetWh());
2671 }
2672 }
2673
2674 jsons.emplace_back(json.Data());
2675 widths.emplace_back(w);
2676 heights.emplace_back(h);
2677 }
2678
2680
2681 if (!gBatchImageMode || (fmt == "json") || (fmt == "s.png") || (fmt == "s.pdf"))
2683
2685
2687 gBatchJsons.insert(gBatchJsons.end(), jsons.begin(), jsons.end());
2690 if (gBatchJsons.size() < gBatchImageMode)
2691 return true;
2692
2693 return FlushBatchImages();
2694}
2695
2696
2697//////////////////////////////////////////////////////////////////////////////////////////
2698/// Process data for single primitive
2699/// Returns object pad if object was modified
2700
2702{
2703 TObjLink *lnk = nullptr;
2704 TPad *objpad = nullptr;
2705 TObject *obj = FindPrimitive(item.snapid, idcnt, pad, &lnk, &objpad);
2706
2707 if (item.fcust.compare("exec") == 0) {
2708 auto pos = item.opt.find("(");
2709 if (obj && (pos != std::string::npos) && obj->IsA()->GetMethodAllAny(item.opt.substr(0,pos).c_str())) {
2710 std::stringstream exec;
2711 exec << "((" << obj->ClassName() << " *) " << std::hex << std::showbase
2712 << (size_t)obj << ")->" << item.opt << ";";
2713 if (gDebug > 0)
2714 Info("ProcessObjectOptions", "Obj %s Execute %s", obj->GetName(), exec.str().c_str());
2715 gROOT->ProcessLine(exec.str().c_str());
2716 } else {
2717 Error("ProcessObjectOptions", "Fail to execute %s for object %p %s", item.opt.c_str(), obj, obj ? obj->ClassName() : "---");
2718 objpad = nullptr;
2719 }
2720 return objpad;
2721 }
2722
2723 bool modified = false;
2724
2725 if (obj && lnk) {
2726 auto pos = item.opt.find(";;use_"); // special coding of extra options
2727 if (pos != std::string::npos) item.opt.resize(pos);
2728
2729 if (gDebug > 0)
2730 Info("ProcessObjectOptions", "Set draw option %s for object %s %s", item.opt.c_str(),
2731 obj->ClassName(), obj->GetName());
2732
2733 lnk->SetOption(item.opt.c_str());
2734
2735 modified = true;
2736 }
2737
2738 if (item.fcust.compare(0,10,"auto_exec:") == 0) {
2739 ProcessLinesForObject(obj, item.fcust.substr(10));
2740 } else if (item.fcust.compare("frame") == 0) {
2741 if (obj && obj->InheritsFrom(TFrame::Class())) {
2742 TFrame *frame = static_cast<TFrame *>(obj);
2743 if (item.fopt.size() >= 4) {
2744 frame->SetX1(item.fopt[0]);
2745 frame->SetY1(item.fopt[1]);
2746 frame->SetX2(item.fopt[2]);
2747 frame->SetY2(item.fopt[3]);
2748 modified = true;
2749 }
2750 }
2751 } else if (item.fcust.compare(0,4,"pave") == 0) {
2752 if (obj && obj->InheritsFrom(TPave::Class())) {
2753 TPave *pave = static_cast<TPave *>(obj);
2754 if ((item.fopt.size() >= 4) && objpad) {
2756
2757 // first time need to overcome init problem
2758 pave->ConvertNDCtoPad();
2759
2760 pave->SetX1NDC(item.fopt[0]);
2761 pave->SetY1NDC(item.fopt[1]);
2762 pave->SetX2NDC(item.fopt[2]);
2763 pave->SetY2NDC(item.fopt[3]);
2764 modified = true;
2765
2766 pave->ConvertNDCtoPad();
2767 }
2768 if ((item.fcust.length() > 4) && pave->InheritsFrom(TPaveStats::Class())) {
2769 // add text lines for statsbox
2770 auto stats = static_cast<TPaveStats *>(pave);
2771 stats->Clear();
2772 size_t pos_start = 6, pos_end;
2773 while ((pos_end = item.fcust.find(";;", pos_start)) != std::string::npos) {
2774 stats->AddText(item.fcust.substr(pos_start, pos_end - pos_start).c_str());
2775 pos_start = pos_end + 2;
2776 }
2777 stats->AddText(item.fcust.substr(pos_start).c_str());
2778 }
2779 }
2780 } else if (item.fcust.compare(0,9,"func_fail") == 0) {
2781 if (fTF1UseSave <= 0) {
2782 fTF1UseSave = 1;
2783 modified = true;
2784 }
2785 }
2786
2787 return modified ? objpad : nullptr;
2788}
2789
2790//////////////////////////////////////////////////////////////////////////////////////////////////
2791/// Search of object with given id in list of primitives
2792/// One could specify pad where search could be start
2793/// Also if object is in list of primitives, one could ask for entry link for such object,
2794/// This can allow to change draw option
2795
2797{
2798 if (sid.empty() || (sid == "0"s))
2799 return nullptr;
2800
2801 if (!pad)
2802 pad = Canvas();
2803
2804 std::string subelement;
2805 long unsigned id = 0;
2806 bool search_hist = (sid == sid_pad_histogram);
2807 if (!search_hist) {
2808 auto separ = sid.find("#");
2809
2810 if (separ == std::string::npos) {
2811 id = std::stoul(sid);
2812 } else {
2813 subelement = sid.substr(separ + 1);
2814 id = std::stoul(sid.substr(0, separ));
2815 }
2816 if (TString::Hash(&pad, sizeof(pad)) == id)
2817 return pad;
2818 }
2819
2820 for (auto lnk = pad->GetListOfPrimitives()->FirstLink(); lnk != nullptr; lnk = lnk->Next()) {
2821 TObject *obj = lnk->GetObject();
2822 if (!obj) continue;
2823
2824 if (!search_hist && (TString::Hash(&obj, sizeof(obj)) != id)) {
2825 if (obj->IsA() == TPad::Class()) {
2826 obj = FindPrimitive(sid, idcnt, (TPad *)obj, objlnk, objpad);
2827 if (objpad && !*objpad)
2828 *objpad = pad;
2829 if (obj)
2830 return obj;
2831 }
2832 continue;
2833 }
2834
2835 // one may require to access n-th object
2836 if (!search_hist && --idcnt > 0)
2837 continue;
2838
2839 if (objpad)
2840 *objpad = pad;
2841
2842 if (objlnk)
2843 *objlnk = lnk;
2844
2845 if (search_hist)
2846 subelement = "hist";
2847
2848 auto getHistogram = [](TObject *container) -> TH1* {
2849 auto offset = container->IsA()->GetDataMemberOffset("fHistogram");
2850 if (offset > 0)
2851 return *((TH1 **)((char *)container + offset));
2852 ::Error("getHistogram", "Cannot access fHistogram data member in %s", container->ClassName());
2853 return nullptr;
2854 };
2855
2856 while(!subelement.empty() && obj) {
2857 // do not return link if sub-selement is searched - except for histogram
2858 if (!search_hist && objlnk)
2859 *objlnk = nullptr;
2860
2861 std::string kind = subelement;
2862 auto separ = kind.find("#");
2863 if (separ == std::string::npos) {
2864 subelement.clear();
2865 } else {
2866 kind.resize(separ);
2867 subelement = subelement.substr(separ + 1);
2868 }
2869
2870 TH1 *h1 = obj->InheritsFrom(TH1::Class()) ? static_cast<TH1 *>(obj) : nullptr;
2871 TGraph *gr = obj->InheritsFrom(TGraph::Class()) ? static_cast<TGraph *>(obj) : nullptr;
2872 TGraph2D *gr2d = obj->InheritsFrom(TGraph2D::Class()) ? static_cast<TGraph2D *>(obj) : nullptr;
2873 TScatter *scatter = obj->InheritsFrom(TScatter::Class()) ? static_cast<TScatter *>(obj) : nullptr;
2874 TMultiGraph *mg = obj->InheritsFrom(TMultiGraph::Class()) ? static_cast<TMultiGraph *>(obj) : nullptr;
2875 THStack *hs = obj->InheritsFrom(THStack::Class()) ? static_cast<THStack *>(obj) : nullptr;
2876 TF1 *f1 = obj->InheritsFrom(TF1::Class()) ? static_cast<TF1 *>(obj) : nullptr;
2877
2878 if (kind.compare("hist") == 0) {
2879 if (h1)
2880 obj = h1;
2881 else if (gr)
2882 obj = getHistogram(gr);
2883 else if (mg)
2884 obj = getHistogram(mg);
2885 else if (hs && (hs->GetNhists() > 0))
2886 obj = getHistogram(hs);
2887 else if (scatter)
2888 obj = getHistogram(scatter);
2889 else if (f1)
2890 obj = getHistogram(f1);
2891 else if (gr2d)
2892 obj = getHistogram(gr2d);
2893 else
2894 obj = nullptr;
2895 } else if (kind.compare("x") == 0) {
2896 obj = h1 ? h1->GetXaxis() : nullptr;
2897 } else if (kind.compare("y") == 0) {
2898 obj = h1 ? h1->GetYaxis() : nullptr;
2899 } else if (kind.compare("z") == 0) {
2900 obj = h1 ? h1->GetZaxis() : nullptr;
2901 } else if ((kind.compare(0,5,"func_") == 0) || (kind.compare(0,5,"indx_") == 0)) {
2902 auto funcname = kind.substr(5);
2903 TList *col = nullptr;
2904 if (h1)
2905 col = h1->GetListOfFunctions();
2906 else if (gr)
2907 col = gr->GetListOfFunctions();
2908 else if (mg)
2909 col = mg->GetListOfFunctions();
2910 else if (scatter->GetGraph())
2911 col = scatter->GetGraph()->GetListOfFunctions();
2912 if (!col)
2913 obj = nullptr;
2914 else if (kind.compare(0,5,"func_") == 0)
2915 obj = col->FindObject(funcname.c_str());
2916 else
2917 obj = col->At(std::stoi(funcname));
2918 } else if (kind.compare("polargram") == 0) {
2919 auto polar = dynamic_cast<TGraphPolar *>(obj);
2920 obj = polar ? polar->GetPolargram() : nullptr;
2921 } else if (kind.compare(0,7,"graphs_") == 0) {
2922 TList *graphs = mg ? mg->GetListOfGraphs() : nullptr;
2923 obj = graphs ? graphs->At(std::stoi(kind.substr(7))) : nullptr;
2924 } else if (kind.compare(0,6,"hists_") == 0) {
2925 TList *hists = hs ? hs->GetHists() : nullptr;
2926 obj = hists ? hists->At(std::stoi(kind.substr(6))) : nullptr;
2927 } else if (kind.compare(0,6,"stack_") == 0) {
2928 auto stack = hs ? hs->GetStack() : nullptr;
2929 obj = stack ? stack->At(std::stoi(kind.substr(6))) : nullptr;
2930 } else if (kind.compare(0,7,"member_") == 0) {
2931 auto member = kind.substr(7);
2932 auto offset = obj->IsA() ? obj->IsA()->GetDataMemberOffset(member.c_str()) : 0;
2933 obj = (offset > 0) ? *((TObject **)((char *) obj + offset)) : nullptr;
2934 } else {
2935 obj = nullptr;
2936 }
2937 }
2938
2939 if (!search_hist || obj)
2940 return obj;
2941 }
2942
2943 return nullptr;
2944}
2945
2946//////////////////////////////////////////////////////////////////////////////////////////////////
2947/// Static method to create TWebCanvas instance
2948/// Used by plugin manager
2949
2951{
2952 Bool_t readonly = gEnv->GetValue("WebGui.FullCanvas", (Int_t) 1) == 0;
2953
2954 auto imp = new TWebCanvas(c, name, x, y, width, height, readonly);
2955
2956 c->fWindowTopX = x;
2957 c->fWindowTopY = y;
2958 c->fWindowWidth = width;
2959 c->fWindowHeight = height;
2960 if (!gROOT->IsBatch() && (height > 25))
2961 height -= 25;
2962 c->fCw = width;
2963 c->fCh = height;
2964
2965 return imp;
2966}
2967
2968//////////////////////////////////////////////////////////////////////////////////////////////////
2969/// Create TCanvas and assign TWebCanvas implementation to it
2970/// Canvas is not displayed automatically, therefore canv->Show() method must be called
2971/// Or canvas can be embed in other widgets.
2972
2974{
2975 auto canvas = new TCanvas(kFALSE);
2976 canvas->SetName(name);
2977 canvas->SetTitle(title);
2978 canvas->ResetBit(TCanvas::kShowEditor);
2979 canvas->ResetBit(TCanvas::kShowToolBar);
2980 canvas->SetBit(TCanvas::kMenuBar, kTRUE);
2981 canvas->SetCanvas(canvas);
2982 canvas->SetBatch(kTRUE); // mark canvas as batch
2983 canvas->SetEditable(kTRUE); // ensure fPrimitives are created
2984
2985 // copy gStyle attributes
2986 canvas->SetFillColor(gStyle->GetCanvasColor());
2987 canvas->SetFillStyle(1001);
2988 canvas->SetGrid(gStyle->GetPadGridX(),gStyle->GetPadGridY());
2989 canvas->SetTicks(gStyle->GetPadTickX(),gStyle->GetPadTickY());
2990 canvas->SetLogx(gStyle->GetOptLogx());
2991 canvas->SetLogy(gStyle->GetOptLogy());
2992 canvas->SetLogz(gStyle->GetOptLogz());
2993 canvas->SetBottomMargin(gStyle->GetPadBottomMargin());
2994 canvas->SetTopMargin(gStyle->GetPadTopMargin());
2995 canvas->SetLeftMargin(gStyle->GetPadLeftMargin());
2996 canvas->SetRightMargin(gStyle->GetPadRightMargin());
2997 canvas->SetBorderSize(gStyle->GetCanvasBorderSize());
2998 canvas->SetBorderMode(gStyle->GetCanvasBorderMode());
2999
3000 auto imp = static_cast<TWebCanvas *> (NewCanvas(canvas, name, 0, 0, width, height));
3001
3002 canvas->SetCanvasImp(imp);
3003
3004 canvas->cd();
3005
3006 {
3008 auto l1 = gROOT->GetListOfCleanups();
3009 if (!l1->FindObject(canvas))
3010 l1->Add(canvas);
3011 auto l2 = gROOT->GetListOfCanvases();
3012 if (!l2->FindObject(canvas))
3013 l2->Add(canvas);
3014 }
3015
3016 // ensure creation of web window
3017 imp->CreateWebWindow();
3018
3019 return canvas;
3020}
3021
@ kMouseMotion
Definition Buttons.h:23
@ kButton1Double
Definition Buttons.h:24
@ kButton1Up
Definition Buttons.h:19
nlohmann::json json
#define c(i)
Definition RSha256.hxx:101
#define h(i)
Definition RSha256.hxx:106
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:59
unsigned int UInt_t
Unsigned integer 4 bytes (unsigned int)
Definition RtypesCore.h:60
short Font_t
Font number (short)
Definition RtypesCore.h:95
constexpr Bool_t kFALSE
Definition RtypesCore.h:108
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:131
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:83
constexpr Bool_t kTRUE
Definition RtypesCore.h:107
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
R__EXTERN TEnv * gEnv
Definition TEnv.h:170
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
Definition TError.cxx:241
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t hmin
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 TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t hmax
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 TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
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 r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void funcs
Option_t Option_t width
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
Option_t Option_t TPoint TPoint const char text
char name[80]
Definition TGX11.cxx:110
@ kCanDelete
Definition TObject.h:372
@ kMustCleanup
Definition TObject.h:373
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:627
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:414
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
@ kReadPermission
Definition TSystem.h:55
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
#define R__LOCKGUARD(mutex)
R__EXTERN TVirtualPS * gVirtualPS
Definition TVirtualPS.h:84
#define gPad
#define gVirtualX
Definition TVirtualX.h:338
static std::vector< WebFont_t > gWebFonts
static const std::string sid_pad_histogram
Color * colors
Definition X3DBuffer.c:21
const_iterator begin() const
const_iterator end() const
Holds different arguments for starting browser with RWebDisplayHandle::Display() method.
EBrowserKind GetBrowserKind() const
returns configured browser kind, see EBrowserKind for supported values
void SetStandalone(bool on=true)
Set standalone mode for running browser, default on When disabled, normal browser window (or just tab...
RWebDisplayArgs & SetWidgetKind(const std::string &kind)
set widget kind
RWebDisplayArgs & SetSize(int w, int h)
set preferable web window width and height
RWebDisplayArgs & SetUrl(const std::string &url)
set window url
RWebDisplayArgs & SetPos(int x=-1, int y=-1)
set preferable web window x and y position, negative is default
@ kCEF
Chromium Embedded Framework - local display with CEF libs.
@ kQt6
Qt6 QWebEngine libraries - Chromium code packed in qt6.
static bool ProduceImages(const std::string &fname, const std::vector< std::string > &jsons, const std::vector< int > &widths, const std::vector< int > &heights, const char *batch_file=nullptr)
Produce image file(s) using JSON data as source Invokes JSROOT drawing functionality in headless brow...
static std::vector< std::string > ProduceImagesNames(const std::string &fname, unsigned nfiles=1)
Produce vector of file names for specified file pattern Depending from supported file forma.
static std::string GetImageFormat(const std::string &fname)
Detect image format There is special handling of ".screenshot.pdf" and ".screenshot....
static bool ProduceImage(const std::string &fname, const std::string &json, int width=800, int height=600, const char *batch_file=nullptr)
Produce image file using JSON data as source Invokes JSROOT drawing functionality in headless browser...
static std::unique_ptr< RWebDisplayHandle > Display(const RWebDisplayArgs &args)
Create web display.
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...
static bool EmbedFileDialog(const std::shared_ptr< RWebWindow > &window, unsigned connid, const std::string &args)
Create dialog instance to use as embedded dialog inside provided widget Loads libROOTBrowserv7 and tr...
static bool IsFileDialogMessage(const std::string &msg)
Check if this could be the message send by client to start new file dialog If returns true,...
static std::map< std::string, std::string > GetServerLocations()
Returns server locations as <std::string, std::string> Key is location name (with slash at the end) a...
Array of integers (32 bits per element).
Definition TArrayI.h:27
static TClass * Class()
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition TAttFill.h:38
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition TAttFill.h:40
virtual void SetTextAlign(Short_t align=11)
Set the text alignment.
Definition TAttText.h:44
virtual void SetTextColor(Color_t tcolor=1)
Set the text color.
Definition TAttText.h:46
virtual void SetTextFont(Font_t tfont=62)
Set the text font.
Definition TAttText.h:48
virtual void SetTextSize(Float_t tsize=1)
Set the text size.
Definition TAttText.h:49
Class to manage histogram axis.
Definition TAxis.h:32
static TString Decode(const char *data)
Decode a base64 string date into a generic TString.
Definition TBase64.cxx:130
static TString Encode(const char *data)
Transform data into a null terminated base64 string.
Definition TBase64.cxx:106
virtual void SetY2(Double_t y2)
Definition TBox.h:65
virtual void SetX1(Double_t x1)
Definition TBox.h:62
virtual void SetX2(Double_t x2)
Definition TBox.h:63
virtual void SetY1(Double_t y1)
Definition TBox.h:64
static Int_t ExportToFile(const char *filename, const TObject *obj, const char *option=nullptr)
Convert object into JSON and store in text file Returns size of the produce file Used in TObject::Sav...
static TString ToJSON(const T *obj, Int_t compact=0, const char *member_name=nullptr)
Definition TBufferJSON.h:77
@ kNoSpaces
no new lines plus remove all spaces around "," and ":" symbols
Definition TBufferJSON.h:39
@ kMapAsObject
store std::map, std::unordered_map as JSON object
Definition TBufferJSON.h:41
@ kSameSuppression
zero suppression plus compress many similar values together
Definition TBufferJSON.h:45
A TButton object is a user interface object.
Definition TButton.h:18
static TClass * Class()
ABC describing GUI independent main window (with menubar, scrollbars and a drawing area).
Definition TCanvasImp.h:30
TCanvas * Canvas() const
Definition TCanvasImp.h:58
friend class TCanvas
Definition TCanvasImp.h:31
The Canvas class.
Definition TCanvas.h:23
UInt_t fCw
Width of the canvas along X (pixels)
Definition TCanvas.h:43
UInt_t GetWindowHeight() const
Definition TCanvas.h:162
void SetClickSelectedPad(TPad *pad)
Definition TCanvas.h:211
Int_t fWindowTopX
Top X position of window (in pixels)
Definition TCanvas.h:39
Int_t fEventX
! Last X mouse position in canvas
Definition TCanvas.h:46
TVirtualPadPainter * GetCanvasPainter()
Access and (probably) creation of pad painter.
Definition TCanvas.cxx:2613
UInt_t fWindowWidth
Width of window (including borders, etc.)
Definition TCanvas.h:41
Int_t fEventY
! Last Y mouse position in canvas
Definition TCanvas.h:47
UInt_t fWindowHeight
Height of window (including menubar, borders, etc.)
Definition TCanvas.h:42
TObject * fSelected
! Currently selected object
Definition TCanvas.h:49
UInt_t fCh
Height of the canvas along Y (pixels)
Definition TCanvas.h:44
UInt_t GetWindowWidth() const
Definition TCanvas.h:161
Int_t fWindowTopY
Top Y position of window (in pixels)
Definition TCanvas.h:40
void SetClickSelected(TObject *obj)
Definition TCanvas.h:209
@ kShowToolTips
Definition TCanvas.h:97
@ kShowToolBar
Definition TCanvas.h:92
@ kShowEventStatus
Definition TCanvas.h:89
@ kMenuBar
Definition TCanvas.h:91
@ kShowEditor
Definition TCanvas.h:93
virtual void Highlighted(TVirtualPad *pad, TObject *obj, Int_t x, Int_t y)
Emit Highlighted() signal.
Definition TCanvas.cxx:1610
static TClass * Class()
Int_t fEvent
! Type of current or last handled event
Definition TCanvas.h:45
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
Bool_t InheritsFrom(const char *cl) const override
Return kTRUE if this class inherits from a class with name "classname".
Definition TClass.cxx:4901
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
The color creation and management class.
Definition TColor.h:22
static const TArrayI & GetPalette()
Static function returning the current active palette.
Definition TColor.cxx:1521
static TClass * Class()
static Bool_t DefinedColors(Int_t set_always_on=0)
Static method returning kTRUE if some new colors have been defined after initialisation or since the ...
Definition TColor.cxx:1542
static TClass * Class()
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:503
TExec is a utility class that can be used to execute a C++ command when some event happens in a pad.
Definition TExec.h:26
virtual void Exec(const char *command="")
Execute the command referenced by this object.
Definition TExec.cxx:142
static TClass * Class()
1-Dim function class
Definition TF1.h:182
virtual Double_t GetXmax() const
Definition TF1.h:525
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function Note that this histogram is managed ...
Definition TF1.cxx:1634
static TClass * Class()
@ kNotDraw
Definition TF1.h:297
virtual Bool_t IsValid() const
Return kTRUE if the function is valid.
Definition TF1.cxx:2931
virtual void Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax)
Save values of function in array fSave.
Definition TF1.cxx:3211
TClass * IsA() const override
Definition TF1.h:694
virtual Double_t GetXmin() const
Definition TF1.h:521
Bool_t HasSave() const
Return true if function has data in fSave buffer.
Definition TF1.h:403
A 2-Dim function with parameters.
Definition TF2.h:29
void Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax) override
Save values of function in array fSave.
Definition TF2.cxx:860
static TClass * Class()
TF3 defines a 3D Function with Parameters.
Definition TF3.h:28
Define a Frame.
Definition TFrame.h:19
static TClass * Class()
The axis painter class.
Definition TGaxis.h:26
static TClass * Class()
Graphics object made of three arrays X, Y and Z with the same number of points each.
Definition TGraph2D.h:41
static TClass * Class()
To draw a polar graph.
Definition TGraphPolar.h:23
static TClass * Class()
To draw polar axis.
static TClass * Class()
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
static TClass * Class()
@ kNoStats
Don't draw stats box.
Definition TGraph.h:74
TList * GetListOfFunctions() const
Definition TGraph.h:125
virtual TH1F * GetHistogram() const
Returns a pointer to the histogram used to draw the axis Takes into account the two following cases.
Definition TGraph.cxx:1458
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
TAxis * GetZaxis()
Definition TH1.h:573
static TClass * Class()
virtual Int_t GetDimension() const
Definition TH1.h:527
@ kNoTitle
Don't draw the histogram title.
Definition TH1.h:408
@ kIsZoomed
Bit set when zooming on Y axis.
Definition TH1.h:407
TAxis * GetXaxis()
Definition TH1.h:571
virtual void SetMaximum(Double_t maximum=-1111)
Definition TH1.h:652
TAxis * GetYaxis()
Definition TH1.h:572
virtual void SetMinimum(Double_t minimum=-1111)
Definition TH1.h:653
virtual Double_t GetEntries() const
Return the current number of entries.
Definition TH1.cxx:4457
TList * GetListOfFunctions() const
Definition TH1.h:488
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition TH1.cxx:1409
The Histogram stack class.
Definition THStack.h:40
static TClass * Class()
static char * ReadFileContent(const char *filename, Int_t &len)
Reads content of file from the disk.
Option_t * GetOption() const
void Reset()
A doubly linked list.
Definition TList.h:38
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void Add(TObject *obj) override
Definition TList.h:81
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:487
void AddFirst(TObject *obj) override
Add object at the beginning of the list.
Definition TList.cxx:97
A TMultiGraph is a collection of TGraph (or derived) objects.
Definition TMultiGraph.h:34
TList * GetListOfGraphs() const
Definition TMultiGraph.h:67
static TClass * Class()
TList * GetListOfFunctions()
Return pointer to list of functions.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
An array of TObjects.
Definition TObjArray.h:31
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:458
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:882
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:544
virtual const char * GetTitle() const
Returns title of object.
Definition TObject.cxx:502
virtual TClass * IsA() const
Definition TObject.h:248
virtual void Paint(Option_t *option="")
This method must be overridden if a class wants to paint itself.
Definition TObject.cxx:626
The most important graphics class in the ROOT system.
Definition TPad.h:28
static TClass * Class()
void Modified(Bool_t flag=true) override
Mark pad modified Will be repainted when TCanvas::Update() will be called next time.
Definition TPad.cxx:7586
void Print(const char *filename="") const override
This method is equivalent to SaveAs("filename"). See TPad::SaveAs for details.
Definition TPad.cxx:5043
The histogram statistics painter class.
Definition TPaveStats.h:18
virtual void SetStatFormat(const char *format="6.4g")
Change (i.e. set) the format for printing statistics.
void SetOptStat(Int_t stat=1)
Set the stat option.
virtual void SetFitFormat(const char *format="5.4g")
Change (i.e. set) the format for printing fit parameters in statistics box.
void SetParent(TObject *obj) override
Definition TPaveStats.h:53
void SetOptFit(Int_t fit=1)
Set the fit option.
static TClass * Class()
A Pave (see TPave) with text, lines or/and boxes inside.
Definition TPaveText.h:21
virtual TText * AddText(Double_t x1, Double_t y1, const char *label)
Add a new Text line to this pavetext at given coordinates.
static TClass * Class()
void Clear(Option_t *option="") override
Clear all lines in this pavetext.
virtual TText * GetLine(Int_t number) const
Get Pointer to line number in this pavetext.
A TBox with a bordersize and a shadow option.
Definition TPave.h:19
virtual void SetName(const char *name="")
Definition TPave.h:81
virtual void SetBorderSize(Int_t bordersize=4)
Sets the border size of the TPave box and shadow.
Definition TPave.h:79
static TClass * Class()
Option_t * GetOption() const override
Definition TPave.h:59
A TScatter is able to draw four variables scatter plot on a single plot.
Definition TScatter.h:32
static TClass * Class()
Basic string class.
Definition TString.h:138
Ssiz_t Length() const
Definition TString.h:425
const char * Data() const
Definition TString.h:384
@ kBoth
Definition TString.h:284
@ kIgnoreCase
Definition TString.h:285
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition TString.cxx:938
void ToUpper()
Change string to upper case.
Definition TString.cxx:1202
UInt_t Hash(ECaseCompare cmp=kExact) const
Return hash value.
Definition TString.cxx:684
TString & Append(const char *cs)
Definition TString.h:581
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2384
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:641
Int_t GetOptLogy() const
Definition TStyle.h:250
Int_t GetOptStat() const
Definition TStyle.h:247
Color_t GetStatTextColor() const
Definition TStyle.h:260
Int_t GetOptTitle() const
Definition TStyle.h:248
Int_t GetPadTickX() const
Definition TStyle.h:219
Float_t GetStatFontSize() const
Definition TStyle.h:263
Float_t GetStatX() const
Definition TStyle.h:266
Float_t GetPadRightMargin() const
Definition TStyle.h:216
Style_t GetTitleFont(Option_t *axis="X") const
Return title font.
Definition TStyle.cxx:1217
Float_t GetStatY() const
Definition TStyle.h:267
Color_t GetTitleFillColor() const
Definition TStyle.h:273
Style_t GetTitleStyle() const
Definition TStyle.h:275
Bool_t GetPadGridY() const
Definition TStyle.h:218
Color_t GetStatColor() const
Definition TStyle.h:259
Float_t GetPadLeftMargin() const
Definition TStyle.h:215
Bool_t GetPadGridX() const
Definition TStyle.h:217
Float_t GetStatH() const
Definition TStyle.h:269
static TClass * Class()
Int_t GetPadTickY() const
Definition TStyle.h:220
Width_t GetTitleBorderSize() const
Definition TStyle.h:277
Color_t GetCanvasColor() const
Definition TStyle.h:190
Float_t GetPadBottomMargin() const
Definition TStyle.h:213
Width_t GetStatBorderSize() const
Definition TStyle.h:261
Color_t GetTitleTextColor() const
Definition TStyle.h:274
Int_t GetOptLogx() const
Definition TStyle.h:249
Style_t GetStatStyle() const
Definition TStyle.h:264
Float_t GetStatW() const
Definition TStyle.h:268
const char * GetFitFormat() const
Definition TStyle.h:201
Int_t GetCanvasBorderMode() const
Definition TStyle.h:192
const char * GetStatFormat() const
Definition TStyle.h:265
Width_t GetCanvasBorderSize() const
Definition TStyle.h:191
Int_t GetOptFit() const
Definition TStyle.h:246
Style_t GetStatFont() const
Definition TStyle.h:262
Int_t GetOptLogz() const
Definition TStyle.h:251
Float_t GetTitleFontSize() const
Definition TStyle.h:276
Float_t GetPadTopMargin() const
Definition TStyle.h:214
virtual Bool_t ExpandPathName(TString &path)
Expand a pathname getting rid of special shell characters like ~.
Definition TSystem.cxx:1285
virtual Bool_t AccessPathName(const char *path, EAccessMode mode=kFileExists)
Returns FALSE if one can access a file using the specified access mode.
Definition TSystem.cxx:1307
virtual void Sleep(UInt_t milliSec)
Sleep milliSec milli seconds.
Definition TSystem.cxx:435
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
Definition TSystem.cxx:414
Base class for several text objects.
Definition TText.h:22
static Long_t SelfId()
Static method returning the id for the current thread.
Definition TThread.cxx:552
Handles synchronous and a-synchronous timer events.
Definition TTimer.h:51
virtual void TurnOn()
Add the timer to the system timer list.
Definition TTimer.cxx:246
void SetTime(Long_t milliSec)
Definition TTimer.h:91
See TView3D.
Definition TView.h:25
static TView * CreateView(Int_t system=1, const Double_t *rmin=nullptr, const Double_t *rmax=nullptr)
Create a concrete default 3-d view via the plug-in manager.
Definition TView.cxx:26
virtual void SetAutoRange(Bool_t autorange=kTRUE)=0
TVirtualPS is an abstract interface to Postscript, PDF, SVG.
Definition TVirtualPS.h:30
To make it possible to use GL for 2D graphic in a TPad/TCanvas.
small helper class to store/restore gPad context in TPad methods
Definition TVirtualPad.h:61
TVirtualPad is an abstract base class for the Pad and Canvas classes.
Definition TVirtualPad.h:51
Semi-Abstract base class defining a generic interface to the underlying, low level,...
Definition TVirtualX.h:46
void SetSlow(Bool_t slow=kTRUE)
TWebCanvasTimer(TWebCanvas &canv)
Bool_t IsSlow() const
void Timeout() override
used to send control messages to clients
TWebCanvas & fCanv
Basic TCanvasImp ABI implementation for Web-based Graphics Provides painting of main ROOT classes in ...
Definition TWebCanvas.h:35
TVirtualPadPainter * CreatePadPainter() override
Creates web-based pad painter.
void ForceUpdate() override
Increment canvas version and force sending data to client - do not wait for reply.
static TCanvas * CreateWebCanvas(const char *name, const char *title, UInt_t width=1200, UInt_t height=800)
Create TCanvas and assign TWebCanvas implementation to it Canvas is not displayed automatically,...
static void AddCustomClass(const std::string &clname, bool with_derived=false)
Assign custom class.
static TString CreatePadJSON(TPad *pad, Int_t json_compression=0, Bool_t batchmode=kFALSE)
Create JSON painting output for given pad Produce JSON can be used for offline drawing with JSROOT.
void SetCanvasSize(UInt_t w, UInt_t h) override
Set canvas size of web canvas.
UInt_t fColorsHash
! last hash of colors/palette
Definition TWebCanvas.h:107
Int_t fTF1UseSave
! use save buffer for TF1/TF2, 0:off, 1:prefer, 2:force
Definition TWebCanvas.h:108
void ShowCmd(const std::string &arg, Bool_t show)
Function used to send command to browser to toggle menu, toolbar, editors, ...
Long64_t fColorsVersion
! current colors/palette version, checked every time when new snapshot created
Definition TWebCanvas.h:106
virtual Bool_t IsReadOnly() const
Definition TWebCanvas.h:197
std::shared_ptr< ROOT::RWebWindow > fWindow
Definition TWebCanvas.h:88
virtual Bool_t IsJSSupportedClass(TObject *obj, Bool_t many_primitives=kFALSE)
Returns kTRUE when object is fully supported on JSROOT side In ROOT7 Paint function will just return ...
void AddCtrlMsg(unsigned connid, const std::string &key, const std::string &value)
Add control message for specified connection Same control message can be overwritten many time before...
static void SetCustomScripts(const std::string &src)
Configures custom script for canvas.
ObjectSelectSignal_t fObjSelectSignal
! signal emitted when new object selected in the pad
Definition TWebCanvas.h:116
PadClickedSignal_t fPadClickedSignal
! signal emitted when simple mouse click performed on the pad
Definition TWebCanvas.h:114
void SetLongerPolling(Bool_t on)
Definition TWebCanvas.h:253
UInt_t fStyleHash
! last hash of gStyle
Definition TWebCanvas.h:105
virtual Bool_t CanCreateObject(const std::string &)
Definition TWebCanvas.h:171
void ShowWebWindow(const ROOT::RWebDisplayArgs &user_args="")
Show canvas in specified place.
Int_t fPrimitivesMerge
! number of PS primitives, which will be merged together
Definition TWebCanvas.h:98
void Show() override
Show canvas in browser window.
Bool_t WaitWhenCanvasPainted(Long64_t ver)
Wait when specified version of canvas was painted and confirmed by browser.
static UInt_t gBatchImageMode
! configured batch size
Definition TWebCanvas.h:123
static std::string gCustomScripts
! custom JavaScript code or URL on JavaScript files to load before start drawing
Definition TWebCanvas.h:143
Bool_t IsAsyncMode() const
Definition TWebCanvas.h:257
Long64_t fLastDrawVersion
! last draw version
Definition TWebCanvas.h:92
UInt_t CalculateColorsHash()
Calculate hash function for all colors and palette.
void SetWindowGeometry(const std::vector< int > &arr)
Set window geometry as array with coordinates and dimensions.
Bool_t HasStatusBar() const override
Returns kTRUE if web canvas has status bar.
static std::vector< std::string > gCustomClasses
! list of custom classes, which can be delivered as is to client
Definition TWebCanvas.h:144
void CreateWebWindow()
Create web window for the canvas.
void Close() override
Close web canvas - not implemented.
static bool ProduceImages(std::vector< TPad * > pads, const char *filename, Int_t width=0, Int_t height=0)
Create images for several pads using batch (headless) capability of Chrome or Firefox browsers Suppor...
Bool_t HasMenuBar() const override
Returns kTRUE if web canvas has menu bar.
Int_t InitWindow() override
Initialize window for the web canvas At this place canvas is not yet register to the list of canvases...
void CheckPadModified(TPad *pad)
Returns true if any pad in the canvas were modified Reset modified flags, increment canvas version (i...
void RaiseWindow() override
Raise browser window.
static bool ProduceImage(TPad *pad, const char *filename, Int_t width=0, Int_t height=0)
Create image using batch (headless) capability of Chrome or Firefox browsers Supported png,...
void ActivateInEditor(TPad *pad, TObject *obj)
Activate object in editor in web browser.
std::vector< WebConn > fWebConn
! connections
Definition TWebCanvas.h:83
PadSignal_t fActivePadChangedSignal
! signal emitted when active pad changed in the canvas
Definition TWebCanvas.h:113
Bool_t GetLongerPolling() const
Definition TWebCanvas.h:254
UInt_t fClientBits
! latest status bits from client like editor visible or not
Definition TWebCanvas.h:93
std::function< void(TPadWebSnapshot *)> PadPaintingReady_t
Function called when pad painting produced.
Definition TWebCanvas.h:55
Int_t fPaletteDelivery
! colors palette delivery 0:never, 1:once, 2:always, 3:per subpad
Definition TWebCanvas.h:97
Bool_t fProcessingData
! flag used to prevent blocking methods when process data is invoked
Definition TWebCanvas.h:102
Bool_t HasToolTips() const override
Returns kTRUE if tooltips are activated in web canvas.
std::vector< TPad * > fAllPads
! list of all pads recognized during streaming
Definition TWebCanvas.h:94
friend class TWebCanvasTimer
Definition TWebCanvas.h:37
TWebCanvasTimer * fTimer
! timer to submit control messages
Definition TWebCanvas.h:84
static std::vector< std::string > gBatchJsons
! converted jsons batch job
Definition TWebCanvas.h:126
Long64_t fCanvVersion
! actual canvas version, changed with every new Modified() call
Definition TWebCanvas.h:91
std::vector< int > fWindowGeometry
! last received window geometry
Definition TWebCanvas.h:109
TPad * ProcessObjectOptions(TWebObjectOptions &item, TPad *pad, int idcnt=1)
Process data for single primitive Returns object pad if object was modified.
void CreateObjectSnapshot(TPadWebSnapshot &master, TPad *pad, TObject *obj, const char *opt, TWebPS *masterps=nullptr)
Creates representation of the object for painting in web browser.
std::map< TObject *, bool > fUsedObjs
! map of used objects during streaming
Definition TWebCanvas.h:95
void AddColorsPalette(TPadWebSnapshot &master)
Add special canvas objects with list of colors and color palette.
Long64_t fStyleVersion
! current gStyle object version, checked every time when new snapshot created
Definition TWebCanvas.h:104
static std::string gBatchMultiPdf
! name of current multi-page pdf file
Definition TWebCanvas.h:124
static void BatchImageMode(UInt_t n=100)
Configure batch image mode for web graphics.
std::vector< std::unique_ptr< ROOT::RWebDisplayHandle > > fHelpHandles
! array of handles for help widgets
Definition TWebCanvas.h:118
void AddSendQueue(unsigned connid, const std::string &msg)
Add message to send queue for specified connection If connid == 0, message will be add to all connect...
void SetWindowPosition(Int_t x, Int_t y) override
Set window position of web canvas.
UpdatedSignal_t fUpdatedSignal
! signal emitted when canvas updated or state is changed
Definition TWebCanvas.h:112
Int_t fJsonComp
! compression factor for messages send to the client
Definition TWebCanvas.h:99
static std::vector< int > gBatchWidths
! batch job widths
Definition TWebCanvas.h:127
~TWebCanvas() override
Destructor.
static std::string ProcessCustomScripts(bool batch)
For batch mode special handling of scripts are required Headless browser not able to load modules fro...
Bool_t fReadOnly
!< configured display
Definition TWebCanvas.h:90
std::map< TPad *, PadStatus > fPadsStatus
! map of pads in canvas and their status flags
Definition TWebCanvas.h:86
static Font_t AddFont(const char *name, const char *ttffile, Int_t precision=2)
Add font to static list of fonts supported by the canvas Name specifies name of the font,...
void AddCustomFonts(TPadWebSnapshot &master)
Add special canvas objects with custom fonts.
Bool_t CheckDataToSend(unsigned connid=0)
Check if any data should be send to client If connid != 0, only selected connection will be checked.
Bool_t PerformUpdate(Bool_t async) override
if canvas or any subpad was modified, scan all primitives in the TCanvas and subpads and convert them...
void AssignStatusBits(UInt_t bits)
Assign clients bits.
virtual Bool_t ProcessData(unsigned connid, const std::string &arg)
Handle data from web browser Returns kFALSE if message was not processed.
void ProcessLinesForObject(TObject *obj, const std::string &lines)
Execute one or several methods for selected object String can be separated by ";;" to let execute sev...
TWebCanvas(TCanvas *c, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height, Bool_t readonly=kTRUE)
Constructor.
static std::vector< int > gBatchHeights
! batch job heights
Definition TWebCanvas.h:128
static Int_t StoreCanvasJSON(TCanvas *c, const char *filename, const char *option="")
Create JSON painting output for given canvas and store into the file See TBufferJSON::ExportToFile() ...
static const std::string & GetCustomScripts()
Returns configured custom script.
void Iconify() override
Iconify browser window.
void SetWindowTitle(const char *newTitle) override
Set window title of web canvas.
UInt_t GetWindowGeometry(Int_t &x, Int_t &y, UInt_t &w, UInt_t &h) override
Returns window geometry including borders and menus.
static std::vector< std::string > gBatchFiles
! file names for batch job
Definition TWebCanvas.h:125
static TCanvasImp * NewCanvas(TCanvas *c, const char *name, Int_t x, Int_t y, UInt_t width, UInt_t height)
Static method to create TWebCanvas instance Used by plugin manager.
static TString CreateCanvasJSON(TCanvas *c, Int_t json_compression=0, Bool_t batchmode=kFALSE)
Create JSON painting output for given canvas Produce JSON can be used for offline drawing with JSROOT...
Bool_t HasEditor() const override
Returns kTRUE if web canvas has graphical editor.
Int_t fStyleDelivery
! gStyle delivery to clients: 0:never, 1:once, 2:always
Definition TWebCanvas.h:96
PadClickedSignal_t fPadDblClickedSignal
! signal emitted when simple mouse click performed on the pad
Definition TWebCanvas.h:115
void ProcessExecs(TPad *pad, TExec *extra=nullptr)
Process TExec objects in the pad.
static bool FlushBatchImages()
Flush batch images.
void CreatePadSnapshot(TPadWebSnapshot &paddata, TPad *pad, Long64_t version, PadPaintingReady_t func)
Create snapshot for pad and all primitives Callback function is used to create JSON in the middle of ...
Bool_t CheckCanvasModified(bool force_modified=false)
Check if any pad on the canvas was modified If yes, increment version of correspondent pad Returns tr...
virtual Bool_t DecodePadOptions(const std::string &, bool process_execs=false)
Decode all pad options, which includes ranges plus objects options.
Int_t GetPaletteDelivery() const
Definition TWebCanvas.h:248
void SetWindowSize(UInt_t w, UInt_t h) override
Set window size of web canvas.
static bool IsCustomClass(const TClass *cl)
Checks if class belongs to custom.
TObject * FindPrimitive(const std::string &id, int idcnt=1, TPad *pad=nullptr, TObjLink **objlnk=nullptr, TPad **objpad=nullptr)
Search of object with given id in list of primitives One could specify pad where search could be star...
Bool_t fFixedSize
! is canvas size fixed
Definition TWebCanvas.h:110
Int_t GetStyleDelivery() const
Definition TWebCanvas.h:245
Class used to transport drawing options from the client.
Implement TVirtualPadPainter which abstracts painting operations.
Object used to store paint operations and deliver them to JSROOT.
@ kStyle
gStyle object
@ kObject
object itself
@ kSVG
list of SVG primitives
@ kSubPad
subpad
@ kFont
custom web font
@ kColors
list of ROOT colors + palette
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
TGraphErrors * gr
Definition legend1.C:25
TH1F * h1
Definition legend1.C:5
TF1 * f1
Definition legend1.C:11
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Returns x raised to the power y.
Definition TMath.h:732
TString fName
TString fFormat
WebFont_t()=default
TString fData
WebFont_t(Int_t indx, const TString &name, const TString &fmt, const TString &data)