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