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