Repository navigation
Expand file tree
/
Copy pathmainframe.cpp
More file actions
602 lines (481 loc) · 20.2 KB
/
Copy pathmainframe.cpp
File metadata and controls
602 lines (481 loc) · 20.2 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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
///////////////////////////////////////////////////////////////////////////////
// Project: wxECharts
// Home: https://github.com/PBfordev/wxecharts
// File Name: mainframe.cpp
// Purpose: Implementation of application's main frame
// Author: PB
// Created: 2024-08-22
// Copyright: (c) 2024 PB
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#include <wx/wx.h>
#include <wx/base64.h>
#include <wx/ffile.h>
#include <wx/filename.h>
#include <wx/grid.h>
#include <wx/mstream.h>
#include <wx/numdlg.h>
#include <wx/splitter.h>
#include <wx/statline.h>
#include <wx/stdpaths.h>
#include <wx/tokenzr.h>
#include <wx/webview.h>
#ifdef __WXMSW__
#include <wx/msw/private/comptr.h>
#endif // #ifdef __WXMSW__
#include "chartdlgs.h"
#include "mainframe.h"
#if USING_WEBVIEW_EDGE
#include <WebView2.h>
#endif // #if USING_WEBVIEW_EDGE
#ifdef __WXGTK__
#include <webkit2/webkit2.h>
#endif // #ifdef __WXGTK__
#include <json.hpp>
using namespace std;
using json = nlohmann::ordered_json;
wxEChartsMainFrame::wxEChartsMainFrame(wxWindow* parent, const wxString& chartAssetsFolder)
: wxFrame(parent, wxID_ANY, wxTheApp->GetAppDisplayName())
{
SetMinClientSize(FromDIP(wxSize(600, 400)));
wxMenu* menu = new wxMenu;
menu->Append(ID_CHART_COLORS, _("Change Chart &Colors...\tCtrl+C"));
menu->Append(ID_CHART_SIZING_OPTIONS, _("Change Chart Sizing &Options...\tCtrl+O"));
menu->AppendSeparator();
menu->Append(wxID_SAVE, _("&Save chart as PNG...\tCtrl+S"));
menu->AppendSeparator();
menu->Append(ID_SHOW_DEVTOOLS, _("Show &DevTools\tCtrl+D"));
SetMenuBar(new wxMenuBar());
GetMenuBar()->Append(menu, _("&Chart"));
Bind(wxEVT_MENU, &wxEChartsMainFrame::OnChartColors, this, ID_CHART_COLORS);
Bind(wxEVT_MENU, &wxEChartsMainFrame::OnChartSizingOptions, this, ID_CHART_SIZING_OPTIONS);
Bind(wxEVT_MENU, &wxEChartsMainFrame::OnChartSave, this, wxID_SAVE);
Bind(wxEVT_MENU, &wxEChartsMainFrame::OnShowDevTools, this, ID_SHOW_DEVTOOLS);
InitChartData();
wxSplitterWindow* mainSplitter = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxSP_BORDER | wxSP_LIVE_UPDATE);
wxSplitterWindow* topSplitter = new wxSplitterWindow(mainSplitter, wxID_ANY, wxDefaultPosition, wxDefaultSize,
wxSP_BORDER | wxSP_LIVE_UPDATE);
wxPanel* gridAndHelpPanel = new wxPanel(topSplitter);
wxBoxSizer* gridAndHelpPanelSizer = new wxBoxSizer(wxVERTICAL);
CreateGrid(gridAndHelpPanel);
gridAndHelpPanelSizer->Add(m_grid, wxSizerFlags().Expand().Border());
const auto helpText = "To interact with the chart:\n"
"* use the Chart menu,\n"
"* change a value in the grid,\n"
"* doubleclick a data point or the y axis,\n"
"* right click the chart window.\n";
wxTextCtrl* helpCtrl = new wxTextCtrl(gridAndHelpPanel, wxID_ANY, helpText, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY);
helpCtrl->SetBackgroundColour(gridAndHelpPanel->GetBackgroundColour());
gridAndHelpPanelSizer->Add(helpCtrl, wxSizerFlags().Expand().Border());
gridAndHelpPanel->SetSizer(gridAndHelpPanelSizer);
CreateWebView(topSplitter, chartAssetsFolder);
wxTextCtrl* logCtrl = new wxTextCtrl(mainSplitter, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxTE_RICH2);
wxLog::SetActiveTarget(new wxLogTextCtrl(logCtrl));
wxLog::DisableTimestamp();
topSplitter->SetSashGravity(0);
topSplitter->SetMinimumPaneSize(FromDIP(20));
topSplitter->SplitVertically(gridAndHelpPanel, m_webView, gridAndHelpPanel->GetBestWidth(-1));
topSplitter->Bind(wxEVT_SPLITTER_DOUBLECLICKED, [topSplitter, gridAndHelpPanel](wxSplitterEvent&)
{ topSplitter->SetSashPosition(gridAndHelpPanel->GetBestWidth(-1)); });
mainSplitter->SetSashGravity(1);
mainSplitter->SetMinimumPaneSize(FromDIP(100));
mainSplitter->SplitHorizontally(topSplitter, logCtrl, -FromDIP(60));
wxLogMessage("Using chart assets folder '%s'.", chartAssetsFolder);
wxLogMessage("Using wxWebView backend '%s'.", wxWebView::GetBackendVersionInfo(m_webViewBackend).ToString());
}
void wxEChartsMainFrame::InitChartData()
{
m_chartHelper.AddVariableNames({"Variable 1", "Variable 2", "Variable 3"});
ChartHelper::ValueSeries s;
s.name = "Group A";
s.type = ChartHelper::Bar;
s.data = {10, 20, 30};
m_chartHelper.AddSeries(s);
s.name = "Group B";
s.type = ChartHelper::Bar;
s.data = {15, 25, 35};
m_chartHelper.AddSeries(s);
}
void wxEChartsMainFrame::CreateGrid(wxWindow* parent)
{
const auto variableNames = m_chartHelper.GetVariableNames();
const auto seriesNames = m_chartHelper.GetSeriesNames();
m_grid = new wxGrid(parent, wxID_ANY);
m_grid->SetDefaultRenderer(new wxGridCellFloatRenderer(-1, 1));
m_grid->SetDefaultEditor(new wxGridCellFloatEditor(-1, 1));
m_grid->EnableDragRowSize(false);
m_grid->CreateGrid(variableNames.size(), seriesNames.size());
for ( size_t row = 0; row < variableNames.size(); ++row )
m_grid->SetRowLabelValue(row, variableNames[row]);
for ( size_t col = 0; col < seriesNames.size(); ++col )
{
vector<double> data;
m_grid->SetColLabelValue(col, seriesNames[col]);
if ( m_chartHelper.GetSeriesData(col, data) )
{
for ( size_t row = 0; row < variableNames.size(); ++row )
m_grid->SetCellValue(row, col, wxString::FromDouble(data[row]));
}
}
m_grid->Bind(wxEVT_GRID_CELL_CHANGING, &wxEChartsMainFrame::OnGridCellChanging, this);
m_grid->Bind(wxEVT_GRID_CELL_CHANGED, &wxEChartsMainFrame::OnGridCellChanged, this);
}
void wxEChartsMainFrame::CreateWebView(wxWindow* parent, const wxString& assetsFolder)
{
const wxString url = wxString::Format("file://%s", wxFileName(assetsFolder, "wxecharts.html").GetFullPath());
m_webViewBackend = wxWebViewBackendDefault;
#if USING_WEBVIEW_EDGE
m_webViewBackend = wxWebViewBackendEdge;
#endif
m_webView = wxWebView::New(parent, wxID_ANY, url, wxDefaultPosition, wxDefaultSize, m_webViewBackend);
m_webView->EnableContextMenu(false);
m_webView->EnableHistory(false);
m_webView->Bind(wxEVT_WEBVIEW_SCRIPT_RESULT, &wxEChartsMainFrame::OnWebViewScriptResult, this);
if ( m_webView->AddScriptMessageHandler("wxmsg") )
m_webView->Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, &wxEChartsMainFrame::OnWebViewMessageReceived, this);
else
wxLogError(_("Could not install the webview message handler, the application will be unusable."));
#if wxCHECK_VERSION(3, 3, 0)
m_webView->Bind(wxEVT_WEBVIEW_CREATED, [this](wxWebViewEvent&){ ConfigureWebView(); });
#endif // #if wxCHECK_VERSION(3, 3, 0)
m_webView->Bind(wxEVT_WEBVIEW_LOADED, &wxEChartsMainFrame::OnWebViewPageLoaded, this);
m_webView->Bind(wxEVT_WEBVIEW_ERROR, &wxEChartsMainFrame::OnWebViewError, this);
}
void wxEChartsMainFrame::ConfigureWebView()
{
if ( m_webViewConfigured )
return;
void* nativeBackend = m_webView->GetNativeBackend();
if ( !nativeBackend )
return;
m_webViewConfigured = true;
#if USING_WEBVIEW_EDGE
ICoreWebView2* webView2 = static_cast<ICoreWebView2*>(nativeBackend);
HRESULT hr;
wxCOMPtr<ICoreWebView2Settings> settings;
hr = webView2->get_Settings(&settings);
if ( FAILED(hr) )
{
wxLogError(_("Could not obtain WebView2Settings (error code 0x%08lx)."), (long)hr);
return;
}
settings->put_IsBuiltInErrorPageEnabled(FALSE);
settings->put_IsZoomControlEnabled(FALSE);
wxCOMPtr<ICoreWebView2Settings3> settings3;
hr = settings->QueryInterface(wxIID_PPV_ARGS(ICoreWebView2Settings3, &settings3));
if ( FAILED(hr) )
{
wxLogError(_("Could not obtain WebView2Settings3 (error code 0x%08lx)."), (long)hr);
return;
}
settings3->put_AreBrowserAcceleratorKeysEnabled(FALSE);
#endif // #if USING_WEBVIEW_EDGE
}
void wxEChartsMainFrame::OnGridCellChanging(wxGridEvent& e)
{
static constexpr double minAllowedValue = -100;
static constexpr double maxAllowedValue = 100;
double d;
if ( !e.GetString().ToDouble(&d)
|| d < minAllowedValue || d > maxAllowedValue )
{
e.Veto();
wxLogError(_("Invalid series value '%s' (col %d, row %d)."), e.GetString(), e.GetCol(), e.GetRow());
}
}
void wxEChartsMainFrame::OnGridCellChanged(wxGridEvent& e)
{
const int row = e.GetRow();
const int col = e.GetCol();
const wxString sVal = m_grid->GetCellValue(row, col);
vector<double> data;
if ( m_chartHelper.GetSeriesData(col, data) )
{
sVal.ToDouble(&data[row]);
m_chartHelper.SetSeriesData(col, data);
m_chartHelper.RunChartUpdateSeries();
}
}
void wxEChartsMainFrame::OnChartColors(wxCommandEvent&)
{
m_chartHelper.RunChartGetColors();
}
void wxEChartsMainFrame::OnChartSizingOptions(wxCommandEvent&)
{
m_chartHelper.RunChartGetSizingOptions();
}
void wxEChartsMainFrame::OnChartSave(wxCommandEvent&)
{
const int chartWidth = wxGetNumberFromUser(_("Enter chart width (height is computed with the width/height ratio"),
_("Width"), _("Save chart"),
1000, 400, 4000, this);
if ( chartWidth != -1 )
m_chartHelper.RunChartGetPNG(chartWidth);;
}
void wxEChartsMainFrame::OnShowDevTools(wxCommandEvent&)
{
void* nativeBackend = m_webView->GetNativeBackend();
if ( !nativeBackend )
return;
#if defined(__WXMSW__)
if ( m_webViewBackend == wxWebViewBackendEdge )
{
#if USING_WEBVIEW_EDGE
ICoreWebView2* webView2 = static_cast<ICoreWebView2*>(nativeBackend);
const HRESULT hr = webView2->OpenDevToolsWindow();
if ( FAILED(hr) )
wxLogError(_("Could not open DevTools window (error code 0x%08lx)."), (long)hr);
return;
#endif //#if USING_WEBVIEW_EDGE
}
#elif defined(__WXGTK__)
if ( m_webViewBackend == wxWebViewBackendWebKit )
{
WebKitWebView* wkv = static_cast<WebKitWebView*>(nativeBackend);
if ( wkv )
{
WebKitSettings* settings = webkit_web_view_get_settings(WEBKIT_WEB_VIEW(wkv));
if ( !settings )
{
wxLogError(_("Could not open DevTools (failed to obtain WebKitSettings)."));
return;
}
g_object_set(settings, "enable-developer-extras", TRUE, NULL);
WebKitWebInspector *inspector = webkit_web_view_get_inspector(WEBKIT_WEB_VIEW(wkv));
if ( !inspector )
{
wxLogError(_("Could not open DevTools (failed to obtain WebKitInspector)."));
return;
}
webkit_web_inspector_show(inspector);
return;
}
}
#endif // #elif defined(__WXGTK__)
wxLogMessage(_("Showing DevTools with this backend is not supported."));
}
void wxEChartsMainFrame::OnWebViewPageLoaded(wxWebViewEvent&)
{
ConfigureWebView();
m_chartHelper.SetWebView(m_webView);
m_chartHelper.RunChartGetEChartsVersion();
m_chartHelper.RunChartCreate();
m_chartHelper.RunChartUpdateVariableNames();
m_chartHelper.RunChartUpdateSeries();
}
void wxEChartsMainFrame::OnWebViewError(wxWebViewEvent&)
{
wxLogError(_("Could not initialize the chart."));
m_webView->SetPage(R"(<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body>)", "");
}
void wxEChartsMainFrame::OnWebViewScriptResult(wxWebViewEvent& evt)
{
const ChartHelper::ScriptResult result = static_cast<ChartHelper::ScriptResult>(reinterpret_cast<intptr_t>(evt.GetClientData()));
const bool isError = evt.IsError();
wxString failedScript;
// WebViewEdge does not like staying in the event handler too
// long, see https://github.com/wxWidgets/wxWidgets/issues/24843
// so we need to use CallAfter()
switch ( result )
{
case ChartHelper::CreateChart:
if ( isError )
failedScript = _("create the chart");
break;
case ChartHelper::UpdateSeries:
case ChartHelper::UpdateVariableNames:
if ( isError )
failedScript = _("update the chart data");
break;
case ChartHelper::GetColors:
if ( isError )
failedScript = _("obtain the chart colors");
else
CallAfter(&wxEChartsMainFrame::ChartChangeColors, evt.GetString());
break;
case ChartHelper::SetColors:
if ( isError )
failedScript = _("change the chart colors");
break;
case ChartHelper::GetSizingOptions:
if ( isError )
failedScript = _("obtain the chart sizing options");
else
//ChartChangeSizingOptions(evt.GetString());
CallAfter(&wxEChartsMainFrame::ChartChangeSizingOptions, evt.GetString());
break;
case ChartHelper::SetSizingOptions:
if ( isError )
failedScript = _("change chart sizing options");
break;
case ChartHelper::GetPNG:
if ( isError )
failedScript = _("obtain the chart as PNG image");
else
CallAfter(&wxEChartsMainFrame::ChartSavePNG, evt.GetString());
break;
case ChartHelper::GetEChartsVersion:
if ( isError )
failedScript = _("obtain the chart version");
else
CallAfter(&wxEChartsMainFrame::ChartShowVersion, evt.GetString());
break;
}
if ( isError )
wxLogError(_("Script failed: Could not %s."), failedScript);
}
void wxEChartsMainFrame::OnWebViewMessageReceived(wxWebViewEvent& evt)
{
wxString msg;
// all the chart messages start with "wxECharts::" and after that, the
// indivdual message fields are separated by \t, the first one being
// the message type and the rest message-type specific
if ( evt.GetString().StartsWith("wxECharts::", &msg) )
{
constexpr char msgFieldDelimiter = '\t';
wxArrayString msgFields = wxStringTokenize(msg, msgFieldDelimiter);
if ( msgFields.size() < 2 )
{
wxLogError(_("Invalid wxECharts message: '%s'."), msg);
return;
}
const wxString msgType = msgFields[0];
msgFields.erase(msgFields.begin()); // remove the message type item
if ( msgType == "error" )
{
OnMessageChartError(msgFields, msg);
}
else if ( msgType == "dblclick" )
{
OnMessageChartDoubleClick(msgFields, msg);
}
else if ( msgType == "contextmenu" )
{
OnMessageChartContextMenu();
}
else
{
wxLogMessage(_("Unknown wxECharts message type '%s' ('%s')."), msgType, msg);
}
}
}
void wxEChartsMainFrame::ChartChangeColors(const wxString& colorsJSONStr)
{
vector<wxColour> colors;
if ( !ChartHelper::JSONToColors(colorsJSONStr, colors) )
return;
ChartColorsDlg dlg(this, colors);
if ( dlg.ShowModal() == wxID_OK )
m_chartHelper.RunChartSetColors(dlg.GetColors());
}
void wxEChartsMainFrame::ChartChangeSizingOptions(const wxString& sizingOptionsJSONStr)
{
double widthToHeightRatio;
int minWidth, minHeight;
if ( !ChartHelper::JSONToSizingOptions(sizingOptionsJSONStr, widthToHeightRatio, minWidth, minHeight) )
return;
ChartSizingOptionsDlg dlg(this, widthToHeightRatio, minWidth, minHeight);
if ( dlg.ShowModal() == wxID_OK )
{
dlg.GetSizingOptions(widthToHeightRatio, minWidth, minHeight);
m_chartHelper.RunChartSetSizingOptions(widthToHeightRatio, minWidth, minHeight);
}
}
void wxEChartsMainFrame::ChartSavePNG(const wxString& PNGAsBase64Str)
{
wxString base64Str;
if ( !PNGAsBase64Str.StartsWith("data:image/png;base64,", &base64Str) )
{
wxLogError(_("Invalid chart data URL."));
return;
}
const wxMemoryBuffer data = wxBase64Decode(base64Str);
if ( data.IsEmpty() )
{
wxLogError(_("Could not decode the chart data URL."));
return;
}
const wxString fileName = wxFileSelector(_("Select file name for chart image"), "", "chart", "",
_("PNG files (*.png)|*.png"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, this);
if ( fileName.empty() )
return;
wxFFile file(fileName, "wb");
if ( file.IsOpened() )
file.Write(data.GetData(), data.GetDataLen());
}
void wxEChartsMainFrame::ChartShowVersion(const wxString& version)
{
wxLogMessage(_("Using Apache ECharts v%s."), version);
}
void wxEChartsMainFrame::OnMessageChartError(const wxArrayString& params, const wxString& msg)
{
constexpr size_t validMinParamsCount = 3;
if ( params.size() < validMinParamsCount )
{
wxLogError(_("Malformed wxECharts error message: '%s'"), msg);
return;
}
wxLogError(_("JavaScript error %s in %s: %s."), params[0], params[1], params[2]);
}
void wxEChartsMainFrame::OnMessageChartDoubleClick(const wxArrayString& params, const wxString& msg)
{
constexpr size_t validMinParamsCount = 2;
if ( params.size() < validMinParamsCount )
{
wxLogError(_("Malformed wxECharts dblclick message: '%s'"), msg);
return;
}
try
{
const json j = json::parse(string(params[1].utf8_string()));
if ( params[0] == "yAxis" )
{
wxLogMessage("yAxis doubleclicked: axis index = %d, target = %s",
j.at("yAxisIndex").get<int>(),
wxString::FromUTF8((j.at("targetType").get<string>())));
}
else if ( params[0] == "series" )
{
const size_t variableIdx = j.at("dataIndex").get<size_t>();
const size_t seriesIdx = j.at("seriesIndex").get<size_t>();
const wxString value = wxString::Format("%g", j.at("value").get<double>());
const wxColor color = wxColor(wxString::FromUTF8(j.at("color").get<string>()));
ChartHelper::ValueSeries series;
wxString variableName;
wxString seriesName;
ChartHelper::SeriesType seriesType;
int seriesTypeInt;
if ( m_chartHelper.GetVariableName(variableIdx, variableName)
&& m_chartHelper.GetSeriesName(seriesIdx, seriesName)
&& m_chartHelper.GetSeriesType(seriesIdx, seriesType) )
{
seriesTypeInt = static_cast<int>(seriesType);
ChartDataPropertiesDlg dlg(this, variableName, seriesName, seriesTypeInt, value, color);
if (dlg.ShowModal() != wxID_OK )
return;
if ( m_chartHelper.SetVariableName(variableIdx, variableName) )
{
m_chartHelper.RunChartUpdateVariableNames();
m_grid->SetRowLabelValue(variableIdx, variableName);
}
if ( m_chartHelper.SetSeriesName(seriesIdx, seriesName) )
m_grid->SetColLabelValue(seriesIdx, seriesName);
m_chartHelper.SetSeriesType(seriesIdx, static_cast<ChartHelper::SeriesType>(seriesTypeInt));
m_chartHelper.RunChartUpdateSeries();
}
}
else
{
wxLogMessage(_("Unexpected wxECharts dblclick message: '%s'"), msg);
}
}
catch (const json::exception& e)
{
wxLogError(_("JSON parsing error in %s (%s)."), __FUNCTION__, e.what());
}
}
void wxEChartsMainFrame::OnMessageChartContextMenu()
{
wxLogMessage(_("wxECharts 'contextmenu' message received."));
}