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