Logo ROOT  
Reference Guide
RCanvasPainter.cxx
Go to the documentation of this file.
1// Author: Axel Naumann <axel@cern.ch>
2// Date: 2017-05-31
3// Warning: This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
4
5/*************************************************************************
6 * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
14#include "ROOT/RCanvas.hxx"
15#include <ROOT/RLogger.hxx>
16#include <ROOT/RDisplayItem.hxx>
18#include <ROOT/RMenuItems.hxx>
21#include <ROOT/RWebWindow.hxx>
22
23#include <memory>
24#include <string>
25#include <vector>
26#include <list>
27#include <thread>
28#include <chrono>
29#include <fstream>
30#include <algorithm>
31#include <cstdlib>
32#include <regex>
33
34#include "TList.h"
35#include "TEnv.h"
36#include "TROOT.h"
37#include "TFile.h"
38#include "TClass.h"
39#include "TBufferJSON.h"
40#include "TBase64.h"
41
42using namespace std::string_literals;
43using namespace ROOT::Experimental;
44
45namespace {
46RLogChannel &CanvasPainerLog() {
47 static RLogChannel sLog("ROOT.CanvasPainer");
48 return sLog;
49}
50}
51
52/** \class RCanvasPainter
53\ingroup webdisplay
54New implementation of canvas painter, using RWebWindow
55*/
56
57namespace ROOT {
58namespace Experimental {
59
61private:
62 struct WebConn {
63 unsigned fConnId{0}; ///<! connection id
64 std::list<std::string> fSendQueue; ///<! send queue for the connection
65 RDrawable::Version_t fSend{0}; ///<! indicates version send to connection
66 RDrawable::Version_t fDelivered{0}; ///<! indicates version confirmed from canvas
67 WebConn() = default;
68 WebConn(unsigned connid) : fConnId(connid) {}
69 };
70
71 struct WebCommand {
72 std::string fId; ///<! command identifier
73 std::string fName; ///<! command name
74 std::string fArg; ///<! command arguments
75 enum { sInit, sRunning, sReady } fState{sInit}; ///<! true when command submitted
76 bool fResult{false}; ///<! result of command execution
77 CanvasCallback_t fCallback{nullptr}; ///<! callback function associated with command
78 unsigned fConnId{0}; ///<! connection id for the command, when 0 specified command will be submitted to any available connection
79 WebCommand() = default;
80 WebCommand(const std::string &id, const std::string &name, const std::string &arg, CanvasCallback_t callback,
81 unsigned connid)
82 : fId(id), fName(name), fArg(arg), fCallback(callback), fConnId(connid)
83 {
84 }
85 void CallBack(bool res)
86 {
87 if (fCallback)
88 fCallback(res);
89 fCallback = nullptr;
90 }
91 };
92
93 struct WebUpdate {
94 uint64_t fVersion{0}; ///<! canvas version
95 CanvasCallback_t fCallback{nullptr}; ///<! callback function associated with the update
96 WebUpdate() = default;
97 WebUpdate(uint64_t ver, CanvasCallback_t callback) : fVersion(ver), fCallback(callback) {}
98 void CallBack(bool res)
99 {
100 if (fCallback)
101 fCallback(res);
102 fCallback = nullptr;
103 }
104 };
105
106 typedef std::vector<Detail::RMenuItem> MenuItemsVector;
107
108 RCanvas &fCanvas; ///<! Canvas we are painting, *this will be owned by canvas
109
110 std::shared_ptr<RWebWindow> fWindow; ///!< configured display
111
112 std::list<WebConn> fWebConn; ///<! connections list
113 std::list<std::shared_ptr<WebCommand>> fCmds; ///<! list of submitted commands
114 uint64_t fCmdsCnt{0}; ///<! commands counter
115
116 uint64_t fSnapshotDelivered{0}; ///<! minimal version delivered to all connections
117 std::list<WebUpdate> fUpdatesLst; ///<! list of callbacks for canvas update
118
119 int fJsonComp{23}; ///<! json compression for data send to client
120
121 /// Disable copy construction.
123
124 /// Disable assignment.
126
127 void CancelUpdates();
128
129 void CancelCommands(unsigned connid = 0);
130
131 void CheckDataToSend();
132
133 void ProcessData(unsigned connid, const std::string &arg);
134
136
137 std::shared_ptr<RDrawable> FindPrimitive(const RCanvas &can, const std::string &id, const RPadBase **subpad = nullptr);
138
139 void CreateWindow();
140
141 void SaveCreatedFile(std::string &reply);
142
143 void FrontCommandReplied(const std::string &reply);
144
145public:
146 RCanvasPainter(RCanvas &canv);
147
148 virtual ~RCanvasPainter();
149
150 void CanvasUpdated(uint64_t ver, bool async, CanvasCallback_t callback) final;
151
152 /// return true if canvas modified since last painting
153 bool IsCanvasModified(uint64_t id) const final { return fSnapshotDelivered != id; }
154
155 /// perform special action when drawing is ready
156 void DoWhenReady(const std::string &name, const std::string &arg, bool async, CanvasCallback_t callback) final;
157
158 bool ProduceBatchOutput(const std::string &fname, int width, int height) final;
159
160 std::string ProduceJSON() final;
161
162 void NewDisplay(const std::string &where) final;
163
164 int NumDisplays() const final;
165
166 std::string GetWindowAddr() const final;
167
168 void Run(double tm = 0.) final;
169
170 bool AddPanel(std::shared_ptr<RWebWindow>) final;
171
172 void SetClearOnClose(const std::shared_ptr<void> &) final;
173
174 /** \class CanvasPainterGenerator
175 Creates RCanvasPainter objects.
176 */
177
178 class GeneratorImpl : public Generator {
179 public:
180 /// Create a new RCanvasPainter to paint the given RCanvas.
181 std::unique_ptr<RVirtualCanvasPainter> Create(RCanvas &canv) const override
182 {
183 return std::make_unique<RCanvasPainter>(canv);
184 }
185 ~GeneratorImpl() = default;
186
187 /// Set RVirtualCanvasPainter::fgGenerator to a new GeneratorImpl object.
188 static void SetGlobalPainter()
189 {
190 if (GetGenerator()) {
191 R__LOG_ERROR(CanvasPainerLog()) << "Generator is already set! Skipping second initialization.";
192 return;
193 }
194 GetGenerator().reset(new GeneratorImpl());
195 }
196
197 /// Release the GeneratorImpl object.
198 static void ResetGlobalPainter() { GetGenerator().reset(); }
199 };
200};
201
202} // namespace Experimental
203} // namespace ROOT
204
206 TNewCanvasPainterReg() { RCanvasPainter::GeneratorImpl::SetGlobalPainter(); }
207 ~TNewCanvasPainterReg() { RCanvasPainter::GeneratorImpl::ResetGlobalPainter(); }
209
210
211////////////////////////////////////////////////////////////////////////////////
212/// Constructor
213
214RCanvasPainter::RCanvasPainter(RCanvas &canv) : fCanvas(canv)
215{
216 auto comp = gEnv->GetValue("WebGui.JsonComp", -1);
217 if (comp >= 0) fJsonComp = comp;
218}
219
220////////////////////////////////////////////////////////////////////////////////
221/// Destructor
222
224{
227 if (fWindow)
228 fWindow->CloseConnections();
229}
230
231////////////////////////////////////////////////////////////////////////////////
232/// Cancel all pending Canvas::Update()
233
235{
237 for (auto &item: fUpdatesLst)
238 item.fCallback(false);
239 fUpdatesLst.clear();
240}
241
242////////////////////////////////////////////////////////////////////////////////
243/// Cancel command execution on provided connection
244/// All commands are cancelled, when connid === 0
245
247{
248 std::list<std::shared_ptr<WebCommand>> remainingCmds;
249
250 for (auto &&cmd : fCmds) {
251 if (!connid || (cmd->fConnId == connid)) {
252 cmd->CallBack(false);
253 cmd->fState = WebCommand::sReady;
254 } else {
255 remainingCmds.emplace_back(std::move(cmd));
256 }
257 }
258
259 std::swap(fCmds, remainingCmds);
260}
261
262////////////////////////////////////////////////////////////////////////////////
263/// Check if canvas need to send data to the clients
264
266{
267 uint64_t min_delivered = 0;
268 bool is_any_send = true;
269 int loopcnt = 0;
270
271 while (is_any_send && (++loopcnt < 10)) {
272
273 is_any_send = false;
274
275 for (auto &conn : fWebConn) {
276
277 if (conn.fDelivered && (!min_delivered || (min_delivered < conn.fDelivered)))
278 min_delivered = conn.fDelivered;
279
280 // flag indicates that next version of canvas has to be send to that client
281 bool need_send_snapshot = (conn.fSend != fCanvas.GetModified()) && (conn.fDelivered == conn.fSend);
282
283 // ensure place in the queue for the send snapshot operation
284 if (need_send_snapshot && (loopcnt == 0))
285 if (std::find(conn.fSendQueue.begin(), conn.fSendQueue.end(), ""s) == conn.fSendQueue.end())
286 conn.fSendQueue.emplace_back(""s);
287
288 // check if direct data sending is possible
289 if (!fWindow->CanSend(conn.fConnId, true))
290 continue;
291
292 TString buf;
293
294 if (conn.fDelivered && !fCmds.empty() && (fCmds.front()->fState == WebCommand::sInit) &&
295 ((fCmds.front()->fConnId == 0) || (fCmds.front()->fConnId == conn.fConnId))) {
296
297 auto &cmd = fCmds.front();
298 cmd->fState = WebCommand::sRunning;
299 cmd->fConnId = conn.fConnId; // assign command to the connection
300 buf = "CMD:";
301 buf.Append(cmd->fId);
302 buf.Append(":");
303 buf.Append(cmd->fName);
304
305 } else if (!conn.fSendQueue.empty()) {
306
307 buf = conn.fSendQueue.front().c_str();
308 conn.fSendQueue.pop_front();
309
310 // empty string reserved for sending snapshot, if it no longer required process next entry
311 if (!need_send_snapshot && (buf.Length() == 0) && !conn.fSendQueue.empty()) {
312 buf = conn.fSendQueue.front().c_str();
313 conn.fSendQueue.pop_front();
314 }
315 }
316
317 if ((buf.Length() == 0) && need_send_snapshot) {
318 buf = "SNAP:";
319 buf += TString::ULLtoa(fCanvas.GetModified(), 10);
320 buf += ":";
321
322 RDrawable::RDisplayContext ctxt(&fCanvas, &fCanvas, conn.fSend);
323 ctxt.SetConnection(conn.fConnId, (conn.fConnId == fWebConn.begin()->fConnId));
324
325 buf += CreateSnapshot(ctxt);
326
327 conn.fSend = fCanvas.GetModified();
328 }
329
330 if (buf.Length() > 0) {
331 // sending of data can be moved into separate thread - not to block user code
332 fWindow->Send(conn.fConnId, buf.Data());
333 is_any_send = true;
334 }
335 }
336 }
337
338 // if there are updates submitted, but all connections disappeared - cancel all updates
339 if (fWebConn.empty() && fSnapshotDelivered)
340 return CancelUpdates();
341
342 if (fSnapshotDelivered != min_delivered) {
343 fSnapshotDelivered = min_delivered;
344
345 if (fUpdatesLst.size() > 0)
346 fUpdatesLst.erase(std::remove_if(fUpdatesLst.begin(), fUpdatesLst.end(), [this](WebUpdate &item) {
347 if (item.fVersion > fSnapshotDelivered)
348 return false;
349 item.CallBack(true);
350 return true;
351 }));
352 }
353}
354
355////////////////////////////////////////////////////////////////////////////////
356/// Method invoked when canvas should be updated on the client side
357/// Depending from delivered status, each client will received new data
358
359void RCanvasPainter::CanvasUpdated(uint64_t ver, bool async, CanvasCallback_t callback)
360{
361 if (fWindow)
362 fWindow->Sync();
363
364 if (ver && fSnapshotDelivered && (ver <= fSnapshotDelivered)) {
365 // if given canvas version was already delivered to clients, can return immediately
366 if (callback)
367 callback(true);
368 return;
369 }
370
371 if (!fWindow || !fWindow->HasConnection(0, false)) {
372 if (callback)
373 callback(false);
374 return;
375 }
376
378
379 if (callback)
380 fUpdatesLst.emplace_back(ver, callback);
381
382 // wait that canvas is painted
383 if (!async) {
384 fWindow->WaitForTimed([this, ver](double) {
385
386 if (fSnapshotDelivered >= ver)
387 return 1;
388
389 // all connections are gone
390 if (fWebConn.empty() && !fWindow->HasConnection(0, false))
391 return -2;
392
393 // time is not important - timeout handle before
394 // if (tm > 100) return -3;
395
396 // continue waiting
397 return 0;
398 });
399 }
400}
401
402////////////////////////////////////////////////////////////////////////////////
403/// Perform special action when drawing is ready
404
405void RCanvasPainter::DoWhenReady(const std::string &name, const std::string &arg, bool async,
406 CanvasCallback_t callback)
407{
408 // ensure that window exists
409 CreateWindow();
410
411 unsigned connid = 0;
412
413 if (arg == "AddPanel") {
414 // take first connection to add panel
415 connid = fWindow->GetConnectionId();
416 } else {
417 // create batch job to execute action
418 // connid = fWindow->MakeBatch();
419 }
420
421 if (!connid) {
422 if (callback)
423 callback(false);
424 return;
425 }
426
427 auto cmd = std::make_shared<WebCommand>(std::to_string(++fCmdsCnt), name, arg, callback, connid);
428 fCmds.emplace_back(cmd);
429
431
432 if (async) return;
433
434 int res = fWindow->WaitForTimed([this, cmd](double) {
435 if (cmd->fState == WebCommand::sReady) {
436 R__LOG_DEBUG(0, CanvasPainerLog()) << "Command " << cmd->fName << " done";
437 return cmd->fResult ? 1 : -1;
438 }
439
440 // connection is gone
441 if (!fWindow->HasConnection(cmd->fConnId, false))
442 return -2;
443
444 // time is not important - timeout handle before
445 // if (tm > 100.) return -3;
446
447 return 0;
448 });
449
450 if (res <= 0)
451 R__LOG_ERROR(CanvasPainerLog()) << name << " fail with " << arg << " result = " << res;
452}
453
454
455////////////////////////////////////////////////////////////////////////////////
456/// Produce batch output, using chrome headless mode with DOM dump
457
458bool RCanvasPainter::ProduceBatchOutput(const std::string &fname, int width, int height)
459{
461 ctxt.SetConnection(1, true);
462
463 auto snapshot = CreateSnapshot(ctxt);
464
465 auto len = fname.length();
466 if ((len > 4) && ((fname.compare(len-4,4,".json") == 0) || (fname.compare(len-4,4,".JSON") == 0))) {
467 std::ofstream f(fname);
468 if (!f) {
469 R__LOG_ERROR(CanvasPainerLog()) << "Fail to open file " << fname << " to store canvas snapshot";
470 return false;
471 }
472 R__LOG_INFO(CanvasPainerLog()) << "Store canvas in " << fname;
473 f << snapshot;
474 return true;
475 }
476
477 return RWebDisplayHandle::ProduceImage(fname, snapshot, width, height);
478}
479
480////////////////////////////////////////////////////////////////////////////////
481/// Produce JSON for the canvas
482
484{
486 ctxt.SetConnection(1, true);
487
488 return CreateSnapshot(ctxt);
489}
490
491////////////////////////////////////////////////////////////////////////////////
492/// Process data from the client
493
494void RCanvasPainter::ProcessData(unsigned connid, const std::string &arg)
495{
496 auto conn =
497 std::find_if(fWebConn.begin(), fWebConn.end(), [connid](WebConn &item) { return item.fConnId == connid; });
498
499 if (conn == fWebConn.end())
500 return; // no connection found
501
502 std::string cdata;
503
504 auto check_header = [&arg, &cdata](const std::string &header) {
505 if (arg.compare(0, header.length(), header) != 0)
506 return false;
507 cdata = arg.substr(header.length());
508 return true;
509 };
510
511 // R__LOG_DEBUG(0, CanvasPainerLog()) << "from client " << connid << " got data len:" << arg.length() << " val:" <<
512 // arg.substr(0,30);
513
514 if (check_header("READY")) {
515
516 } else if (check_header("SNAPDONE:")) {
517 conn->fDelivered = (uint64_t)std::stoll(cdata); // delivered version of the snapshot
518 } else if (arg == "QUIT") {
519 // use window manager to correctly terminate http server and ROOT session
520 fWindow->TerminateROOT();
521 return;
522 } else if (arg == "RELOAD") {
523 conn->fSend = 0; // reset send version, causes new data sending
524 } else if (arg == "INTERRUPT") {
525 gROOT->SetInterrupt();
526 } else if (check_header("REPLY:")) {
527 const char *sid = cdata.c_str();
528 const char *separ = strchr(sid, ':');
529 std::string id;
530 if (separ)
531 id.append(sid, separ - sid);
532 if (fCmds.empty()) {
533 R__LOG_ERROR(CanvasPainerLog()) << "Get REPLY without command";
534 } else if (fCmds.front()->fState != WebCommand::sRunning) {
535 R__LOG_ERROR(CanvasPainerLog()) << "Front command is not running when get reply";
536 } else if (fCmds.front()->fId != id) {
537 R__LOG_ERROR(CanvasPainerLog()) << "Mismatch with front command and ID in REPLY";
538 } else {
539 FrontCommandReplied(separ + 1);
540 }
541 } else if (check_header("SAVE:")) {
542 SaveCreatedFile(cdata);
543 } else if (check_header("PRODUCE:")) {
544 R__LOG_DEBUG(0, CanvasPainerLog()) << "Create file " << cdata;
545
546 TFile *f = TFile::Open(cdata.c_str(), "RECREATE");
547 f->WriteObject(&fCanvas, "Canvas");
548 delete f;
549 } else if (check_header("REQ:")) {
550 auto req = TBufferJSON::FromJSON<RDrawableRequest>(cdata);
551 if (req) {
552 std::shared_ptr<RDrawable> drawable;
553 req->GetContext().SetCanvas(&fCanvas);
554 if (req->GetId().empty() || (req->GetId() == "canvas")) {
555 req->GetContext().SetPad(nullptr); // no subpad for the canvas
556 req->GetContext().SetDrawable(&fCanvas, 0); // drawable is canvas itself
557 } else {
558 const RPadBase *subpad = nullptr;
559 drawable = FindPrimitive(fCanvas, req->GetId(), &subpad);
560 req->GetContext().SetPad(const_cast<RPadBase *>(subpad));
561 req->GetContext().SetDrawable(drawable.get(), 0);
562 }
563
564 req->GetContext().SetConnection(connid, conn == fWebConn.begin());
565
566 auto reply = req->Process();
567
568 if (req->ShouldBeReplyed()) {
569 if (!reply)
570 reply = std::make_unique<RDrawableReply>();
571
572 reply->SetRequestId(req->GetRequestId());
573
575 conn->fSendQueue.emplace_back("REPL_REQ:"s + json.Data());
576 }
577
578 // real update will be performed by CheckDataToSend()
579 if (req->NeedCanvasUpdate())
581
582 } else {
583 R__LOG_ERROR(CanvasPainerLog()) << "Fail to parse RDrawableRequest";
584 }
585 } else if (check_header("RESIZED:")) {
586 auto sz = TBufferJSON::FromJSON<std::vector<int>>(cdata);
587 if (sz && sz->size() == 2) {
588 fCanvas.SetWidth(sz->at(0));
589 fCanvas.SetHeight(sz->at(1));
590 }
591 } else if (check_header("CLEAR")) {
592 fCanvas.Wipe();
594 } else {
595 R__LOG_ERROR(CanvasPainerLog()) << "Got not recognized message" << arg;
596 }
597
599}
600
601////////////////////////////////////////////////////////////////////////////////
602/// Create web window for canvas
603
605{
606 if (fWindow) return;
607
609 fWindow->SetConnLimit(0); // allow any number of connections
610 fWindow->SetDefaultPage("file:rootui5sys/canv/canvas.html");
611 fWindow->SetCallBacks(
612 // connect
613 [this](unsigned connid) {
614 fWebConn.emplace_back(connid);
616 },
617 // data
618 [this](unsigned connid, const std::string &arg) { ProcessData(connid, arg); },
619 // disconnect
620 [this](unsigned connid) {
621 auto conn =
622 std::find_if(fWebConn.begin(), fWebConn.end(), [connid](WebConn &item) { return item.fConnId == connid; });
623
624 if (conn != fWebConn.end()) {
625 fWebConn.erase(conn);
626 CancelCommands(connid);
627 }
628 });
629 // fWindow->SetGeometry(500,300);
630}
631
632////////////////////////////////////////////////////////////////////////////////
633/// Create new display for the canvas
634/// See RWebWindowsManager::Show() docu for more info
635
636void RCanvasPainter::NewDisplay(const std::string &where)
637{
638 CreateWindow();
639
640 int width = fCanvas.GetWidth();
641 int height = fCanvas.GetHeight();
642
643 RWebDisplayArgs args(where);
644
645 if ((width > 10) && (height > 10)) {
646 // extra size of browser window header + ui5 menu
647 args.SetWidth(width + 4);
648 args.SetHeight(height + 36);
649 }
650
651 args.SetWidgetKind("RCanvas");
652
653 fWindow->Show(args);
654}
655
656////////////////////////////////////////////////////////////////////////////////
657/// Returns number of connected displays
658
660{
661 if (!fWindow) return 0;
662
663 return fWindow->NumConnections();
664}
665
666////////////////////////////////////////////////////////////////////////////////
667/// Returns web window name
668
670{
671 if (!fWindow) return "";
672
673 return fWindow->GetAddr();
674}
675
676////////////////////////////////////////////////////////////////////////////////
677/// Add window as panel inside canvas window
678
679bool RCanvasPainter::AddPanel(std::shared_ptr<RWebWindow> win)
680{
681 if (gROOT->IsWebDisplayBatch())
682 return false;
683
684 if (!fWindow) {
685 R__LOG_ERROR(CanvasPainerLog()) << "Canvas not yet shown in AddPanel";
686 return false;
687 }
688
689 if (!fWindow->IsShown()) {
690 R__LOG_ERROR(CanvasPainerLog()) << "Canvas window was not shown to call AddPanel";
691 return false;
692 }
693
694 std::string addr = fWindow->GetRelativeAddr(win);
695
696 if (addr.length() == 0) {
697 R__LOG_ERROR(CanvasPainerLog()) << "Cannot attach panel to canvas";
698 return false;
699 }
700
701 // connection is assigned, but can be refused by the client later
702 // therefore handle may be removed later
703
704 std::string cmd("ADDPANEL:");
705 cmd.append(addr);
706
707 /// one could use async mode
708 DoWhenReady(cmd, "AddPanel", true, nullptr);
709
710 return true;
711}
712
713////////////////////////////////////////////////////////////////////////////////
714/// Set handle to window which will be cleared when connection is closed
715
716void RCanvasPainter::SetClearOnClose(const std::shared_ptr<void> &handle)
717{
718 if (fWindow)
719 fWindow->SetClearOnClose(handle);
720}
721
722////////////////////////////////////////////////////////////////////////////////
723/// Create JSON representation of data, which should be send to the clients
724/// Here server-side painting is performed - each drawable adds own elements in
725/// so-called display list, which transferred to the clients
726
728{
729 auto canvitem = std::make_unique<RCanvasDisplayItem>();
730
731 fCanvas.DisplayPrimitives(*canvitem, ctxt);
732
733 canvitem->SetTitle(fCanvas.GetTitle());
734 canvitem->SetWindowSize(fCanvas.GetWidth(), fCanvas.GetHeight());
735
736 canvitem->BuildFullId(""); // create object id which unique identify it via pointer and position in subpads
737 canvitem->SetObjectID("canvas"); // for canvas itself use special id
738
740 json.SetCompact(fJsonComp);
741
742 static std::vector<const TClass *> exclude_classes = {
743 TClass::GetClass<RAttrMap::NoValue_t>(),
744 TClass::GetClass<RAttrMap::BoolValue_t>(),
745 TClass::GetClass<RAttrMap::IntValue_t>(),
746 TClass::GetClass<RAttrMap::DoubleValue_t>(),
747 TClass::GetClass<RAttrMap::StringValue_t>(),
748 TClass::GetClass<RAttrMap>(),
749 TClass::GetClass<RStyle::Block_t>(),
750 TClass::GetClass<RPadPos>(),
751 TClass::GetClass<RPadLength>(),
752 TClass::GetClass<RPadExtent>(),
753 TClass::GetClass<std::unordered_map<std::string,RAttrMap::Value_t*>>()
754 };
755
756 for (auto cl : exclude_classes)
757 json.SetSkipClassInfo(cl);
758
759 auto res = json.StoreObject(canvitem.get(), TClass::GetClass<RCanvasDisplayItem>());
760
761 return std::string(res.Data());
762}
763
764////////////////////////////////////////////////////////////////////////////////
765/// Find drawable in the canvas with specified id
766/// Used to communicate with the clients, which does not have any pointer
767
768std::shared_ptr<RDrawable>
769RCanvasPainter::FindPrimitive(const RCanvas &can, const std::string &id, const RPadBase **subpad)
770{
771 std::string search = id;
772 size_t pos = search.find("#");
773 // exclude extra specifier, later can be used for menu and commands execution
774 if (pos != std::string::npos)
775 search.resize(pos);
776
777 if (subpad) *subpad = can.FindPadForPrimitiveWithDisplayId(search);
778
779 return can.FindPrimitiveByDisplayId(search);
780}
781
782////////////////////////////////////////////////////////////////////////////////
783/// Method called when GUI sends file to save on local disk
784/// File data coded with base64 coding beside SVG format
785
786void RCanvasPainter::SaveCreatedFile(std::string &reply)
787{
788 size_t pos = reply.find(":");
789 if ((pos == std::string::npos) || (pos == 0)) {
790 R__LOG_ERROR(CanvasPainerLog()) << "SaveCreatedFile does not found ':' separator";
791 return;
792 }
793
794 std::string fname(reply, 0, pos);
795 reply.erase(0, pos + 1);
796
797 Bool_t isSvg = (fname.length() > 4) && ((fname.rfind(".svg") == fname.length()-4) || (fname.rfind(".SVG") == fname.length()-4));
798
799 int file_len = 0;
800
801 std::ofstream ofs(fname, std::ios::binary);
802 if (isSvg) {
803 ofs << reply;
804 file_len = reply.length();
805 } else {
806 TString binary = TBase64::Decode(reply.c_str());
807 ofs.write(binary.Data(), binary.Length());
808 file_len = binary.Length();
809 }
810 ofs.close();
811
812 R__LOG_INFO(CanvasPainerLog()) << " Save file from GUI " << fname << " len " << file_len;
813}
814
815////////////////////////////////////////////////////////////////////////////////
816/// Process reply on the currently active command
817
818void RCanvasPainter::FrontCommandReplied(const std::string &reply)
819{
820 auto cmd = fCmds.front();
821 fCmds.pop_front();
822
823 cmd->fState = WebCommand::sReady;
824
825 bool result = false;
826
827 if ((cmd->fName == "SVG") || (cmd->fName == "PNG") || (cmd->fName == "JPEG")) {
828 if (reply.length() == 0) {
829 R__LOG_ERROR(CanvasPainerLog()) << "Fail to produce image" << cmd->fArg;
830 } else {
831 TString content = TBase64::Decode(reply.c_str());
832 std::ofstream ofs(cmd->fArg, std::ios::binary);
833 ofs.write(content.Data(), content.Length());
834 ofs.close();
835 R__LOG_INFO(CanvasPainerLog()) << cmd->fName << " create file " << cmd->fArg << " length " << content.Length();
836 result = true;
837 }
838 } else if (cmd->fName.find("ADDPANEL:") == 0) {
839 R__LOG_DEBUG(0, CanvasPainerLog()) << "get reply for ADDPANEL " << reply;
840 result = (reply == "true");
841 } else {
842 R__LOG_ERROR(CanvasPainerLog()) << "Unknown command " << cmd->fName;
843 }
844
845 cmd->fResult = result;
846 cmd->CallBack(result);
847}
848
849////////////////////////////////////////////////////////////////////////////////
850/// Run canvas functionality for specified period of time
851/// Required when canvas used not from the main thread
852
853void RCanvasPainter::Run(double tm)
854{
855 if (fWindow) {
856 fWindow->Run(tm);
857 } else if (tm>0) {
858 std::this_thread::sleep_for(std::chrono::milliseconds(int(tm*1000)));
859 }
860}
nlohmann::json json
struct TNewCanvasPainterReg newCanvasPainterReg
#define R__LOG_ERROR(...)
Definition: RLogger.hxx:362
#define R__LOG_DEBUG(DEBUGLEVEL,...)
Definition: RLogger.hxx:365
#define R__LOG_INFO(...)
Definition: RLogger.hxx:364
#define f(i)
Definition: RSha256.hxx:104
R__EXTERN TEnv * gEnv
Definition: TEnv.h:170
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 result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize id
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 Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t win
Option_t Option_t width
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
char name[80]
Definition: TGX11.cxx:110
#define gROOT
Definition: TROOT.h:406
Abstract interface for painting a canvas.
static std::unique_ptr< Generator > & GetGenerator()
generator getter
static void ResetGlobalPainter()
Release the GeneratorImpl object.
std::unique_ptr< RVirtualCanvasPainter > Create(RCanvas &canv) const override
Create a new RCanvasPainter to paint the given RCanvas.
static void SetGlobalPainter()
Set RVirtualCanvasPainter::fgGenerator to a new GeneratorImpl object.
std::list< WebConn > fWebConn
!< configured display
std::list< std::shared_ptr< WebCommand > > fCmds
! list of submitted commands
uint64_t fCmdsCnt
! commands counter
uint64_t fSnapshotDelivered
! minimal version delivered to all connections
bool AddPanel(std::shared_ptr< RWebWindow >) final
Add window as panel inside canvas window.
std::list< WebUpdate > fUpdatesLst
! list of callbacks for canvas update
void CancelCommands(unsigned connid=0)
Cancel command execution on provided connection All commands are cancelled, when connid === 0.
void SaveCreatedFile(std::string &reply)
Method called when GUI sends file to save on local disk File data coded with base64 coding beside SVG...
std::shared_ptr< RWebWindow > fWindow
void CancelUpdates()
Cancel all pending Canvas::Update()
bool ProduceBatchOutput(const std::string &fname, int width, int height) final
Produce batch output, using chrome headless mode with DOM dump.
std::shared_ptr< RDrawable > FindPrimitive(const RCanvas &can, const std::string &id, const RPadBase **subpad=nullptr)
Find drawable in the canvas with specified id Used to communicate with the clients,...
void DoWhenReady(const std::string &name, const std::string &arg, bool async, CanvasCallback_t callback) final
perform special action when drawing is ready
std::vector< Detail::RMenuItem > MenuItemsVector
std::string GetWindowAddr() const final
Returns web window name.
void Run(double tm=0.) final
Run canvas functionality for specified period of time Required when canvas used not from the main thr...
int NumDisplays() const final
Returns number of connected displays.
void FrontCommandReplied(const std::string &reply)
Process reply on the currently active command.
void ProcessData(unsigned connid, const std::string &arg)
Process data from the client.
int fJsonComp
! json compression for data send to client
void CanvasUpdated(uint64_t ver, bool async, CanvasCallback_t callback) final
Method invoked when canvas should be updated on the client side Depending from delivered status,...
void CheckDataToSend()
Check if canvas need to send data to the clients.
void CreateWindow()
Create web window for canvas.
std::string ProduceJSON() final
Produce JSON for the canvas.
bool IsCanvasModified(uint64_t id) const final
return true if canvas modified since last painting
RCanvasPainter & operator=(const RCanvasPainter &)=delete
Disable assignment.
std::string CreateSnapshot(RDrawable::RDisplayContext &ctxt)
Create JSON representation of data, which should be send to the clients Here server-side painting is ...
RCanvasPainter(const RCanvasPainter &)=delete
Disable copy construction.
void SetClearOnClose(const std::shared_ptr< void > &) final
Set handle to window which will be cleared when connection is closed.
void NewDisplay(const std::string &where) final
Create new display for the canvas See RWebWindowsManager::Show() docu for more info.
RCanvas & fCanvas
! Canvas we are painting, *this will be owned by canvas
A window's topmost RPad.
Definition: RCanvas.hxx:47
const std::string & GetTitle() const
Get the canvas's title.
Definition: RCanvas.hxx:166
int GetHeight() const
Get canvas height.
Definition: RCanvas.hxx:111
uint64_t GetModified() const
Get modify counter.
Definition: RCanvas.hxx:137
void SetHeight(int height)
Set canvas height.
Definition: RCanvas.hxx:105
void SetWidth(int width)
Set canvas width.
Definition: RCanvas.hxx:102
int GetWidth() const
Get canvas width.
Definition: RCanvas.hxx:108
void SetConnection(unsigned connid, bool ismain)
Set connection id and ismain flag for connection.
Definition: RDrawable.hxx:154
const std::string & GetId() const
Definition: RDrawable.hxx:221
A log configuration for a channel, e.g.
Definition: RLogger.hxx:101
Base class for graphic containers for RDrawable-s.
Definition: RPadBase.hxx:37
void DisplayPrimitives(RPadBaseDisplayItem &paditem, RDisplayContext &ctxt)
Create display items for all primitives in the pad Each display item gets its special id,...
Definition: RPadBase.cxx:112
std::shared_ptr< RDrawable > FindPrimitiveByDisplayId(const std::string &display_id) const
Find primitive with unique id, produce for RDisplayItem Such id used for client-server identification...
Definition: RPadBase.cxx:64
const RPadBase * FindPadForPrimitiveWithDisplayId(const std::string &display_id) const
Find subpad which contains primitive with given display id.
Definition: RPadBase.cxx:87
void Wipe()
Wipe the pad by clearing the list of primitives.
Definition: RPadBase.hxx:190
Holds different arguments for starting browser with RWebDisplayHandle::Display() method.
RWebDisplayArgs & SetHeight(int h=0)
set preferable web window height
RWebDisplayArgs & SetWidgetKind(const std::string &kind)
set widget kind
RWebDisplayArgs & SetWidth(int w=0)
set preferable web window width
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...
Represents web window, which can be shown in web browser or any other supported environment.
Definition: RWebWindow.hxx:53
static std::shared_ptr< RWebWindow > Create()
Create new RWebWindow Using default RWebWindowsManager.
static TString Decode(const char *data)
Decode a base64 string date into a generic TString.
Definition: TBase64.cxx:131
Class for serializing object to and from JavaScript Object Notation (JSON) format.
Definition: TBufferJSON.h:30
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
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition: TEnv.cxx:491
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format.
Definition: TFile.h:54
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition: TFile.cxx:4053
Basic string class.
Definition: TString.h:136
Ssiz_t Length() const
Definition: TString.h:410
const char * Data() const
Definition: TString.h:369
static TString ULLtoa(ULong64_t value, Int_t base)
Converts a ULong64_t (twice the range of an Long64_t) to a TString with respect to the base specified...
Definition: TString.cxx:2150
TString & Append(const char *cs)
Definition: TString.h:565
void swap(RDirectoryEntry &e1, RDirectoryEntry &e2) noexcept
std::function< void(bool)> CanvasCallback_t
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
static constexpr double s
basic_json<> json
Definition: REveElement.hxx:62
unsigned fConnId
! connection id for the command, when 0 specified command will be submitted to any available connecti...
bool fResult
! result of command execution
CanvasCallback_t fCallback
! callback function associated with command
WebCommand(const std::string &id, const std::string &name, const std::string &arg, CanvasCallback_t callback, unsigned connid)
enum ROOT::Experimental::RCanvasPainter::WebCommand::@64 sInit
! true when command submitted
std::list< std::string > fSendQueue
! send queue for the connection
RDrawable::Version_t fDelivered
! indicates version confirmed from canvas
RDrawable::Version_t fSend
! indicates version send to connection
CanvasCallback_t fCallback
! callback function associated with the update
WebUpdate(uint64_t ver, CanvasCallback_t callback)