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