Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
gui_handler.cxx
Go to the documentation of this file.
1/// \file gui_handler.cxx
2// Author: Sergey Linev <S.Linev@gsi.de>
3// Date: 2017-06-29
4
5/*************************************************************************
6 * Copyright (C) 1995-2019, 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
13#if !defined(_MSC_VER)
14#pragma GCC diagnostic ignored "-Wunused-parameter"
15#pragma GCC diagnostic ignored "-Wshadow"
16#endif
17
18#include "gui_handler.h"
19#include "simple_app.h"
20
21#include <sstream>
22#include <fstream>
23#include <iostream>
24#include <string>
25
26#include "include/base/cef_bind.h"
27#include "include/cef_app.h"
28#include "include/cef_version.h"
29#include "include/views/cef_browser_view.h"
30#include "include/views/cef_window.h"
31#include "include/wrapper/cef_closure_task.h"
32#include "include/wrapper/cef_helpers.h"
33#include "include/cef_parser.h"
34#include "include/wrapper/cef_stream_resource_handler.h"
35
36#include "TEnv.h"
37#include "TUrl.h"
38#include "THttpServer.h"
39#include "THttpCallArg.h"
40#include "TSystem.h"
41#include "TBase64.h"
42#include <ROOT/RLogger.hxx>
43
45{
46 static ROOT::RLogChannel sChannel("ROOT.CefWebDisplay");
47 return sChannel;
48}
49
50
51GuiHandler::GuiHandler(bool use_views) : fUseViews(use_views), is_closing_(false)
52{
53 fConsole = gEnv->GetValue("WebGui.Console", (int)0);
54
55 // see https://bitbucket.org/chromiumembedded/cef-project/src/master/examples/resource_manager/?at=master for demo
56 // one probably can avoid to use scheme handler and just redirect requests
58}
59
61{
63
64 if (fUseViews) {
65 // Set the title of the window using the Views framework.
66 CefRefPtr<CefBrowserView> browser_view = CefBrowserView::GetForBrowser(browser);
67 if (browser_view) {
68 CefRefPtr<CefWindow> window = browser_view->GetWindow();
69 if (window) window->SetTitle(title);
70 }
71 } else {
72 // Set the title of the window using platform APIs.
74 }
75}
76
78{
80
81 // Add to the list of existing browsers.
82 fBrowserList.emplace_back(browser);
83}
84
86{
88
89 // Closing the main window requires special handling. See the DoClose()
90 // documentation in the CEF header for a detailed description of this
91 // process.
92 if (fBrowserList.size() == 1) {
93 // Set a flag to indicate that the window close should be allowed.
94 is_closing_ = true;
95 }
96
97 // Allow the close. For windowed browsers this will result in the OS close
98 // event being sent.
99 return false;
100}
101
103{
105
106 // Remove from the list of existing browsers.
107 auto bit = fBrowserList.begin();
108 for (; bit != fBrowserList.end(); ++bit) {
109 if ((*bit)->IsSame(browser)) {
110 fBrowserList.erase(bit);
111 break;
112 }
113 }
114
115 if (fBrowserList.empty()) {
116
117 // All browser windows have closed. Quit the application message loop.
118
120 }
121}
122
123// Returns a data: URI with the specified contents.
124std::string GuiHandler::GetDataURI(const std::string& data, const std::string& mime_type)
125{
126 return std::string("data:") + mime_type + ";base64," +
127 CefURIEncode(CefBase64Encode(data.data(), data.size()), false).ToString();
128}
129
130
132 const CefString &errorText, const CefString &failedUrl)
133{
135
136 // Don't display an error for downloaded files.
137 if (errorCode == ERR_ABORTED)
138 return;
139
140 // Display a load error message.
141 /*
142 std::stringstream ss;
143 ss << "<html><body bgcolor=\"white\">"
144 "<h2>Failed to load URL "
145 << failedUrl.ToString().substr(0,100) << " with error " << errorText.ToString() << " (" << errorCode
146 << ").</h2></body></html>";
147 frame->LoadURL(GetDataURI(ss.str(), "text/html"));
148 */
149
150 printf("Fail to load URL %s\n", failedUrl.ToString().substr(0,100).c_str());
151}
152
154{
155 if (!CefCurrentlyOn(TID_UI)) {
156 // Execute on the UI thread.
158 return;
159 }
160
161 if (fBrowserList.empty())
162 return;
163
164 for (auto &br : fBrowserList)
165 br->GetHost()->CloseBrowser(force_close);
166}
167
169 cef_log_severity_t level,
170 const CefString &message, const CefString &source,
171 int line)
172{
173 std::string src = source.ToString().substr(0,100);
174
175 switch (level) {
177 if (fConsole > -1)
178 std::cout << TString::Format("CEF: %s:%d: %s", src.c_str(), line, message.ToString().c_str()) << std::endl;
179 break;
181 if (fConsole > -2)
182 std::cerr << TString::Format("CEF: %s:%d: %s", src.c_str(), line, message.ToString().c_str()) << std::endl;
183 break;
184 default:
185 if (fConsole > 0)
186 std::cout << TString::Format("CEF: %s:%d: %s", src.c_str(), line, message.ToString().c_str()) << std::endl;
187 break;
188 }
189
190 return true;
191}
192
193
197 CefRefPtr<CefRequest> request,
198 CefRefPtr<CefCallback> callback) {
200
201 return fResourceManager->OnBeforeResourceLoad(browser, frame, request,
202 callback);
203}
204
205
207protected:
208
210
211public:
212 explicit TCefHttpCallArg() = default;
213
214 /** provide WS kind */
215 const char *GetWSKind() const override { return "longpoll"; }
216
217 /** provide WS platform */
218 const char *GetWSPlatform() const override { return "cef3"; }
219
221
222 // this is callback from HTTP server
223 void HttpReplied() override
224 {
225 if (IsFile()) {
226 // send file
227 std::string file_content = THttpServer::ReadFileContent((const char *)GetContent());
228 SetContent(std::move(file_content));
229 }
230
231 fCallBack->Continue(); // we have result and can continue with processing
232 }
233};
234
235
237public:
238 // QWebEngineUrlRequestJob *fRequest;
239
241 std::shared_ptr<TCefHttpCallArg> fArg;
242
244
245 explicit TGuiResourceHandler(THttpServer *serv, bool dummy = false)
246 {
247 fServer = serv;
248
249 if (!dummy)
250 fArg = std::make_shared<TCefHttpCallArg>();
251 }
252
254
255 void Cancel() override { CEF_REQUIRE_IO_THREAD(); }
256
258 {
260
261 if (fArg) {
262 fArg->AssignCallback(callback);
264 } else {
265 callback->Continue();
266 }
267
268 return true;
269 }
270#if CEF_VERSION_MAJOR > 114
272#else
274#endif
275 {
277
278 if (!fArg || fArg->Is404()) {
279 response->SetMimeType("text/html");
280 response->SetStatus(404);
281 response_length = 0;
282 } else {
283 response->SetMimeType(fArg->GetContentType());
284 response->SetStatus(200);
285 response_length = fArg->GetContentLength();
286
287 if (fArg->NumHeader() > 0) {
288 CefResponse::HeaderMap headers;
289 for (Int_t n = 0; n < fArg->NumHeader(); ++n) {
290 TString name = fArg->GetHeaderName(n);
291 TString value = fArg->GetHeader(name.Data());
292 headers.emplace(CefString(name.Data()), CefString(value.Data()));
293 }
294 response->SetHeaderMap(headers);
295 }
296 }
297 // DCHECK(!fArg->Is404());
298 }
299
300 bool ReadResponse(void *data_out, int bytes_to_read, int &bytes_read, CefRefPtr<CefCallback> callback) override
301 {
303
304 if (!fArg) return false;
305
306 bytes_read = 0;
307
308 if (fTransferOffset < fArg->GetContentLength()) {
309 char *data_ = (char *)fArg->GetContent();
310 // Copy the next block of data into the buffer.
311 int transfer_size = fArg->GetContentLength() - fTransferOffset;
316
318 }
319
320 // if content fully copied - can release reference, object will be cleaned up
321 if (fTransferOffset >= fArg->GetContentLength())
322 fArg.reset();
323
324 return bytes_read > 0;
325 }
326
329};
330
331
335 CefRefPtr<CefRequest> request) {
337
338 std::string addr = request->GetURL().ToString();
339 std::string prefix = "http://rootserver.local";
340
341 if (addr.compare(0, prefix.length(), prefix) != 0)
342 return fResourceManager->GetResourceHandler(browser, frame, request);
343
344 int indx = std::stoi(addr.substr(prefix.length(), addr.find("/", prefix.length()) - prefix.length()));
345
346 if ((indx < 0) || (indx >= (int) fServers.size()) || !fServers[indx]) {
347 R__LOG_ERROR(CefWebDisplayLog()) << "No THttpServer with index " << indx;
348 return nullptr;
349 }
350
352 if (serv->IsZombie()) {
353 fServers[indx] = nullptr;
354 R__LOG_ERROR(CefWebDisplayLog()) << "THttpServer with index " << indx << " is zombie now";
355 return nullptr;
356 }
357
358 TUrl url(addr.c_str());
359
360 const char *inp_path = url.GetFile();
361
362 TString inp_query = url.GetOptions();
363
365
366 if (serv->IsFileRequested(inp_path, fname)) {
367 // process file - no need for special requests handling
368
369 std::ifstream ifs(fname.Data());
370 // when file not exists - return default handler otherwise CEF terminates
371 if (!ifs)
372 return new TGuiResourceHandler(serv, true);
373
374 const char *mime = THttpServer::GetMimeType(fname.Data());
375
376 CefRefPtr<CefStreamReader> stream = CefStreamReader::CreateForFile(fname.Data());
377
378 // Constructor for HTTP status code 200 and no custom response headers.
379 // There’s also a version of the constructor for custom status code and response headers.
380 return new CefStreamResourceHandler(mime, stream);
381 }
382
383 std::string inp_method = request->GetMethod().ToString();
384
386 handler->fArg->SetMethod(inp_method.c_str());
387 handler->fArg->SetPathAndFileName(inp_path);
388 handler->fArg->SetTopName("webgui");
389
390 if (inp_method == "POST") {
391
392 CefRefPtr< CefPostData > post_data = request->GetPostData();
393
394 if (!post_data) {
395 R__LOG_ERROR(CefWebDisplayLog()) << "FATAL - NO POST DATA in CEF HANDLER!!!";
396 exit(1);
397 } else {
398 CefPostData::ElementVector elements;
399 post_data->GetElements(elements);
400 size_t sz = 0, off = 0;
401 for (unsigned n = 0; n < elements.size(); ++n)
402 sz += elements[n]->GetBytesCount();
403 std::string data;
404 data.resize(sz);
405
406 for (unsigned n = 0; n < elements.size(); ++n) {
407 sz = elements[n]->GetBytes(elements[n]->GetBytesCount(), (char *)data.data() + off);
408 off += sz;
409 }
410 handler->fArg->SetPostData(std::move(data));
411 }
412 } else if (inp_query.Index("&post=") != kNPOS) {
413 Int_t pos = inp_query.Index("&post=");
414 TString buf = TBase64::Decode(inp_query.Data() + pos + 6);
415 handler->fArg->SetPostData(std::string(buf.Data()));
416 inp_query.Resize(pos);
417 }
418
419 handler->fArg->SetQuery(inp_query.Data());
420
421 // just return handler
422 return handler;
423}
424
425///////////////////////////////////////////////////////////////////////////////////////////////////
426/// Generate URL for batch page
427/// Uses file:/// prefix to let access JSROOT scripts placed on file system
428/// Register provider for that page in resource manager
429
430std::string GuiHandler::AddBatchPage(const std::string &cont)
431{
432 std::string url = "file:///batch_page";
433 url.append(std::to_string(fBatchPageCount++));
434 url.append(".html");
435
436 fResourceManager->AddContentProvider(url, cont, "text/html", 0, std::string());
437 return url;
438}
439
440///////////////////////////////////////////////////////////////////////////////////////////////////
441/// Generate URL for RWebWindow page
442/// Register server instance and assign it with the index
443/// Produced URL only works inside CEF and does not represent real HTTP address
444
445std::string GuiHandler::MakePageUrl(THttpServer *serv, const std::string &addr)
446{
447 unsigned indx = 0;
448 while ((indx < fServers.size()) && (fServers[indx] != serv)) indx++;
449 if (indx >= fServers.size()) {
450 fServers.emplace_back(serv);
451 indx = fServers.size() - 1;
452 }
453
454 return std::string("http://rootserver.local") + std::to_string(indx) + addr;
455}
456
#define R__LOG_ERROR(...)
Definition RLogger.hxx:356
constexpr Ssiz_t kNPOS
The equivalent of std::string::npos for the ROOT class TString.
Definition RtypesCore.h:132
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:126
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 value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t src
char name[80]
Definition TGX11.cxx:148
const char * mime_type
Definition civetweb.c:8517
CefRefPtr< CefResourceManager > fResourceManager
bool is_closing_
Definition gui_handler.h:49
int fConsole
! console parameter, assigned via WebGui.Console rootrc parameter
Definition gui_handler.h:43
GuiHandler(bool use_views=false)
std::vector< THttpServer * > fServers
Definition gui_handler.h:47
void OnBeforeClose(CefRefPtr< CefBrowser > browser) override
CefRefPtr< CefResourceHandler > GetResourceHandler(CefRefPtr< CefBrowser > browser, CefRefPtr< CefFrame > frame, CefRefPtr< CefRequest > request) override
bool DoClose(CefRefPtr< CefBrowser > browser) override
BrowserList fBrowserList
Definition gui_handler.h:45
void CloseAllBrowsers(bool force_close)
int fBatchPageCount
void PlatformTitleChange(CefRefPtr< CefBrowser > browser, const CefString &title)
cef_return_value_t OnBeforeResourceLoad(CefRefPtr< CefBrowser > browser, CefRefPtr< CefFrame > frame, CefRefPtr< CefRequest > request, CefRefPtr< CefCallback > callback) override
void OnLoadError(CefRefPtr< CefBrowser > browser, CefRefPtr< CefFrame > frame, ErrorCode errorCode, const CefString &errorText, const CefString &failedUrl) override
static std::string GetDataURI(const std::string &data, const std::string &mime_type)
bool fUseViews
! if view framework is used, required for true headless mode
Definition gui_handler.h:42
std::string AddBatchPage(const std::string &cont)
Generate URL for batch page Uses file:/// prefix to let access JSROOT scripts placed on file system R...
std::string MakePageUrl(THttpServer *serv, const std::string &addr)
Generate URL for RWebWindow page Register server instance and assign it with the index Produced URL o...
bool OnConsoleMessage(CefRefPtr< CefBrowser > browser, cef_log_severity_t level, const CefString &message, const CefString &source, int line) override
void OnTitleChange(CefRefPtr< CefBrowser > browser, const CefString &title) override
void OnAfterCreated(CefRefPtr< CefBrowser > browser) override
A log configuration for a channel, e.g.
Definition RLogger.hxx:97
static TString Decode(const char *data)
Decode a base64 string date into a generic TString.
Definition TBase64.cxx:130
void AssignCallback(CefRefPtr< CefCallback > cb)
void HttpReplied() override
virtual method to inform object that http request is processed
const char * GetWSPlatform() const override
provide WS platform
CefRefPtr< CefCallback > fCallBack
const char * GetWSKind() const override
provide WS kind
TCefHttpCallArg()=default
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:511
~TGuiResourceHandler() override
bool ProcessRequest(CefRefPtr< CefRequest > request, CefRefPtr< CefCallback > callback) override
DISALLOW_COPY_AND_ASSIGN(TGuiResourceHandler)
std::shared_ptr< TCefHttpCallArg > fArg
IMPLEMENT_REFCOUNTING(TGuiResourceHandler)
bool ReadResponse(void *data_out, int bytes_to_read, int &bytes_read, CefRefPtr< CefCallback > callback) override
TGuiResourceHandler(THttpServer *serv, bool dummy=false)
THttpServer * fServer
void GetResponseHeaders(CefRefPtr< CefResponse > response, int64 &response_length, CefString &redirectUrl) override
void Cancel() override
Contains arguments for single HTTP call.
const void * GetContent() const
void SetContent(const char *cont)
Set content as text.
Bool_t IsFile() const
Online http server for arbitrary ROOT application.
Definition THttpServer.h:31
Bool_t SubmitHttp(std::shared_ptr< THttpCallArg > arg, Bool_t can_run_immediately=kFALSE)
Submit HTTP request.
static char * ReadFileContent(const char *filename, Int_t &len)
Reads content of file from the disk.
static const char * GetMimeType(const char *path)
Guess mime type base on file extension.
Basic string class.
Definition TString.h:138
const char * Data() const
Definition TString.h:386
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:2459
This class represents a WWW compatible URL.
Definition TUrl.h:33
TLine * line
ROOT::RLogChannel & CefWebDisplayLog()
ROOT::RLogChannel & CefWebDisplayLog()
const Int_t n
Definition legend1.C:16