-
Notifications
You must be signed in to change notification settings - Fork 553
Expand file tree
/
Copy pathguihtml.cpp
More file actions
1449 lines (1224 loc) · 52.6 KB
/
guihtml.cpp
File metadata and controls
1449 lines (1224 loc) · 52.6 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------
// The Emscripten-based implementation of platform-dependent GUI functionality.
//
// Copyright 2018 whitequark
//-----------------------------------------------------------------------------
#include <emscripten.h>
#include <emscripten/val.h>
#include <emscripten/html5.h>
#include <emscripten/bind.h>
#include "config.h"
#include "solvespace.h"
using namespace emscripten;
EMSCRIPTEN_BINDINGS(solvespace) {
emscripten::class_<std::function<void()>>("VoidFunctor")
.constructor<>()
.function("opcall", &std::function<void()>::operator());
emscripten::class_<std::function<void(val)>>("Void1Functor")
.constructor<>()
.function("opcall", &std::function<void(val)>::operator());
}
namespace SolveSpace {
namespace Platform {
//-----------------------------------------------------------------------------
// Emscripten API bridging
//-----------------------------------------------------------------------------
#define sscheck(expr) do { \
EMSCRIPTEN_RESULT emResult = (EMSCRIPTEN_RESULT)(expr); \
if(emResult < 0) \
HandleError(__FILE__, __LINE__, __func__, #expr, emResult); \
} while(0)
static void HandleError(const char *file, int line, const char *function, const char *expr,
EMSCRIPTEN_RESULT emResult) {
const char *error = "Unknown error";
switch(emResult) {
case EMSCRIPTEN_RESULT_DEFERRED: error = "Deferred"; break;
case EMSCRIPTEN_RESULT_NOT_SUPPORTED: error = "Not supported"; break;
case EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED: error = "Failed (not deferred)"; break;
case EMSCRIPTEN_RESULT_INVALID_TARGET: error = "Invalid target"; break;
case EMSCRIPTEN_RESULT_UNKNOWN_TARGET: error = "Unknown target"; break;
case EMSCRIPTEN_RESULT_INVALID_PARAM: error = "Invalid parameter"; break;
case EMSCRIPTEN_RESULT_FAILED: error = "Failed"; break;
case EMSCRIPTEN_RESULT_NO_DATA: error = "No data"; break;
}
std::string message;
message += ssprintf("File %s, line %u, function %s:\n", file, line, function);
message += ssprintf("Emscripten API call failed: %s.\n", expr);
message += ssprintf("Error: %s\n", error);
FatalError(message);
}
static val Wrap(const std::function<void()> &functor) {
return val(functor)["opcall"].call<val>("bind", val(functor));
}
static void RegisterEventListener(const val &target, std::string event, std::function<void()> functor) {
std::function<void(val)> wrapper = [functor](val) { if(functor) functor(); };
val wrapped = val(wrapper)["opcall"].call<val>("bind", val(wrapper));
target.call<void>("addEventListener", event, wrapped);
}
//-----------------------------------------------------------------------------
// Fatal errors
//-----------------------------------------------------------------------------
void FatalError(const std::string &message) {
dbp("%s", message.c_str());
#ifndef NDEBUG
emscripten_debugger();
#endif
abort();
}
//-----------------------------------------------------------------------------
// Settings
//-----------------------------------------------------------------------------
class SettingsImplHtml : public Settings {
public:
void FreezeInt(const std::string &key, uint32_t value) {
val::global("localStorage").call<void>("setItem", key, value);
}
uint32_t ThawInt(const std::string &key, uint32_t defaultValue = 0) {
val value = val::global("localStorage").call<val>("getItem", key);
if(value == val::null())
return defaultValue;
return val::global("parseInt")(value, 0).as<int>();
}
void FreezeFloat(const std::string &key, double value) {
val::global("localStorage").call<void>("setItem", key, value);
}
double ThawFloat(const std::string &key, double defaultValue = 0.0) {
val value = val::global("localStorage").call<val>("getItem", key);
if(value == val::null())
return defaultValue;
return val::global("parseFloat")(value).as<double>();
}
void FreezeString(const std::string &key, const std::string &value) {
val::global("localStorage").call<void>("setItem", key, value);
}
std::string ThawString(const std::string &key,
const std::string &defaultValue = "") {
val value = val::global("localStorage").call<val>("getItem", key);
if(value == val::null()) {
return defaultValue;
}
return value.as<std::string>();
}
};
SettingsRef GetSettings() {
return std::make_shared<SettingsImplHtml>();
}
//-----------------------------------------------------------------------------
// Timers
//-----------------------------------------------------------------------------
class TimerImplHtml : public Timer {
public:
static void Callback(void *arg) {
TimerImplHtml *timer = (TimerImplHtml *)arg;
if(timer->onTimeout) {
timer->onTimeout();
}
}
void RunAfter(unsigned milliseconds) override {
emscripten_async_call(TimerImplHtml::Callback, this, milliseconds + 1);
}
void RunAfterNextFrame() override {
emscripten_async_call(TimerImplHtml::Callback, this, 0);
}
void RunAfterProcessingEvents() override {
emscripten_push_uncounted_main_loop_blocker(TimerImplHtml::Callback, this);
}
};
TimerRef CreateTimer() {
return std::unique_ptr<TimerImplHtml>(new TimerImplHtml);
}
//-----------------------------------------------------------------------------
// Menus
//-----------------------------------------------------------------------------
class MenuItemImplHtml : public MenuItem {
public:
val htmlMenuItem;
MenuItemImplHtml() :
htmlMenuItem(val::global("document").call<val>("createElement", val("li")))
{}
void SetAccelerator(KeyboardEvent accel) override {
val htmlAccel = htmlMenuItem.call<val>("querySelector", val(".accel"));
if(htmlAccel.as<bool>()) {
htmlAccel.call<void>("remove");
}
htmlAccel = val::global("document").call<val>("createElement", val("span"));
htmlAccel.call<void>("setAttribute", val("class"), val("accel"));
htmlAccel.set("innerText", AcceleratorDescription(accel));
htmlMenuItem.call<void>("appendChild", htmlAccel);
}
void SetIndicator(Indicator type) override {
val htmlClasses = htmlMenuItem["classList"];
htmlClasses.call<void>("remove", val("check"));
htmlClasses.call<void>("remove", val("radio"));
switch(type) {
case Indicator::NONE:
break;
case Indicator::CHECK_MARK:
htmlClasses.call<void>("add", val("check"));
break;
case Indicator::RADIO_MARK:
htmlClasses.call<void>("add", val("radio"));
break;
}
}
void SetEnabled(bool enabled) override {
if(enabled) {
htmlMenuItem["classList"].call<void>("remove", val("disabled"));
} else {
htmlMenuItem["classList"].call<void>("add", val("disabled"));
}
}
void SetActive(bool active) override {
if(active) {
htmlMenuItem["classList"].call<void>("add", val("active"));
} else {
htmlMenuItem["classList"].call<void>("remove", val("active"));
}
}
};
class MenuImplHtml;
static std::shared_ptr<MenuImplHtml> popupMenuOnScreen;
class MenuImplHtml : public Menu,
public std::enable_shared_from_this<MenuImplHtml> {
public:
val htmlMenu;
std::vector<std::shared_ptr<MenuItemImplHtml>> menuItems;
std::vector<std::shared_ptr<MenuImplHtml>> subMenus;
std::function<void()> popupDismissFunc;
MenuImplHtml() :
htmlMenu(val::global("document").call<val>("createElement", val("ul")))
{
htmlMenu["classList"].call<void>("add", val("menu"));
}
MenuItemRef AddItem(const std::string &label, std::function<void()> onTrigger,
bool mnemonics = true) override {
std::shared_ptr<MenuItemImplHtml> menuItem = std::make_shared<MenuItemImplHtml>();
menuItems.push_back(menuItem);
menuItem->onTrigger = onTrigger;
if(mnemonics) {
val::global("window").call<void>("setLabelWithMnemonic", menuItem->htmlMenuItem,
label);
} else {
val htmlLabel = val::global("document").call<val>("createElement", val("span"));
htmlLabel["classList"].call<void>("add", val("label"));
htmlLabel.set("innerText", label);
menuItem->htmlMenuItem.call<void>("appendChild", htmlLabel);
}
RegisterEventListener(menuItem->htmlMenuItem, "trigger", [menuItem]() {
if(menuItem->onTrigger) {
menuItem->onTrigger();
}
});
htmlMenu.call<void>("appendChild", menuItem->htmlMenuItem);
return menuItem;
}
std::shared_ptr<Menu> AddSubMenu(const std::string &label) override {
val htmlMenuItem = val::global("document").call<val>("createElement", val("li"));
val::global("window").call<void>("setLabelWithMnemonic", htmlMenuItem, label);
htmlMenuItem["classList"].call<void>("add", val("has-submenu"));
htmlMenu.call<void>("appendChild", htmlMenuItem);
std::shared_ptr<MenuImplHtml> subMenu = std::make_shared<MenuImplHtml>();
subMenus.push_back(subMenu);
htmlMenuItem.call<void>("appendChild", subMenu->htmlMenu);
return subMenu;
}
void AddSeparator() override {
val htmlSeparator = val::global("document").call<val>("createElement", val("li"));
htmlSeparator["classList"].call<void>("add", val("separator"));
htmlMenu.call<void>("appendChild", htmlSeparator);
}
void PopUp() override {
if(popupMenuOnScreen) {
popupMenuOnScreen->htmlMenu.call<void>("remove");
popupMenuOnScreen = NULL;
}
EmscriptenMouseEvent emStatus = {};
sscheck(emscripten_get_mouse_status(&emStatus));
htmlMenu["classList"].call<void>("add", val("popup"));
htmlMenu["style"].set("left", std::to_string(emStatus.clientX) + "px");
htmlMenu["style"].set("top", std::to_string(emStatus.clientY) + "px");
val::global("document")["body"].call<void>("appendChild", htmlMenu);
popupMenuOnScreen = shared_from_this();
}
void Clear() override {
while(htmlMenu["childElementCount"].as<int>() > 0) {
htmlMenu["firstChild"].call<void>("remove");
}
}
};
MenuRef CreateMenu() {
return std::make_shared<MenuImplHtml>();
}
class MenuBarImplHtml final : public MenuBar {
public:
val htmlMenuBar;
std::vector<std::shared_ptr<MenuImplHtml>> subMenus;
MenuBarImplHtml() :
htmlMenuBar(val::global("document").call<val>("createElement", val("ul")))
{
htmlMenuBar["classList"].call<void>("add", val("menu"));
htmlMenuBar["classList"].call<void>("add", val("menubar"));
}
std::shared_ptr<Menu> AddSubMenu(const std::string &label) override {
val htmlMenuItem = val::global("document").call<val>("createElement", val("li"));
val::global("window").call<void>("setLabelWithMnemonic", htmlMenuItem, label);
htmlMenuBar.call<void>("appendChild", htmlMenuItem);
std::shared_ptr<MenuImplHtml> subMenu = std::make_shared<MenuImplHtml>();
subMenus.push_back(subMenu);
htmlMenuItem.call<void>("appendChild", subMenu->htmlMenu);
return subMenu;
}
void Clear() override {
while(htmlMenuBar["childElementCount"].as<int>() > 0) {
htmlMenuBar["firstChild"].call<void>("remove");
}
}
};
MenuBarRef GetOrCreateMainMenu(bool *unique) {
*unique = false;
return std::make_shared<MenuBarImplHtml>();
}
//-----------------------------------------------------------------------------
// Windows
//-----------------------------------------------------------------------------
class TouchEventHelper {
public:
// FIXME(emscripten): Workaround. touchstart and touchend repeats two times.
bool touchActionStarted = false;
int previousNumTouches = 0;
double centerX = 0;
double centerY = 0;
// double startPinchDistance = 0;
double previousPinchDistance = 0;
std::function<void(MouseEvent*, void*)> onPointerDown;
std::function<void(MouseEvent*, void*)> onPointerMove;
std::function<void(MouseEvent*, void*)> onPointerUp;
std::function<void(MouseEvent*, void*)> onScroll;
void clear(void) {
touchActionStarted = false;
previousNumTouches = 0;
centerX = 0;
centerY = 0;
// startPinchDistance = 0;
previousPinchDistance = 0;
}
void calculateCenterPosition(const EmscriptenTouchEvent& emEvent, double& dst_x, double& dst_y) {
double x = 0;
double y = 0;
for (int i = 0; i < emEvent.numTouches; i++) {
x += emEvent.touches[i].targetX;
y += emEvent.touches[i].targetY;
}
dst_x = x / emEvent.numTouches;
dst_y = y / emEvent.numTouches;
}
void calculatePinchDistance(const EmscriptenTouchEvent& emEvent, double& dst_distance) {
if (emEvent.numTouches < 2) {
return;
}
double x1 = emEvent.touches[0].targetX;
double y1 = emEvent.touches[0].targetY;
double x2 = emEvent.touches[1].targetX;
double y2 = emEvent.touches[1].targetY;
dst_distance = std::sqrt(std::pow(x1 - x2, 2) + std::pow(y1 - y2, 2));
}
void createMouseEventPRESS(const EmscriptenTouchEvent& emEvent, MouseEvent& dst_mouseevent) {
double x = 0, y = 0;
this->calculateCenterPosition(emEvent, x, y);
this->centerX = x;
this->centerY = y;
this->touchActionStarted = true;
this->previousNumTouches = emEvent.numTouches;
dst_mouseevent.type = MouseEvent::Type::PRESS;
dst_mouseevent.x = x;
dst_mouseevent.y = y;
dst_mouseevent.shiftDown = emEvent.shiftKey;
dst_mouseevent.controlDown = emEvent.ctrlKey;
switch(emEvent.numTouches) {
case 1:
dst_mouseevent.button = MouseEvent::Button::LEFT;
break;
case 2: {
dst_mouseevent.button = MouseEvent::Button::RIGHT;
// double distance = 0;
this->calculatePinchDistance(emEvent, this->previousPinchDistance);
// this->startPinchDistance = distance;
// this->previousPinchDistance = distance;
break;
}
default:
dst_mouseevent.button = MouseEvent::Button::MIDDLE;
break;
}
}
void createMouseEventRELEASE(const EmscriptenTouchEvent& emEvent, MouseEvent& dst_mouseevent) {
this->calculateCenterPosition(emEvent, this->centerX, this->centerY);
this->previousNumTouches = 0;
dst_mouseevent.type = MouseEvent::Type::RELEASE;
dst_mouseevent.x = this->centerX;
dst_mouseevent.y = this->centerY;
dst_mouseevent.shiftDown = emEvent.shiftKey;
dst_mouseevent.controlDown = emEvent.ctrlKey;
switch(this->previousNumTouches) {
case 1:
dst_mouseevent.button = MouseEvent::Button::LEFT;
break;
case 2:
dst_mouseevent.button = MouseEvent::Button::RIGHT;
break;
default:
dst_mouseevent.button = MouseEvent::Button::MIDDLE;
break;
}
}
void createMouseEventMOTION(const EmscriptenTouchEvent& emEvent, MouseEvent& dst_mouseevent) {
dst_mouseevent.type = MouseEvent::Type::MOTION;
this->calculateCenterPosition(emEvent, this->centerX, this->centerY);
dst_mouseevent.x = this->centerX;
dst_mouseevent.y = this->centerY;
dst_mouseevent.shiftDown = emEvent.shiftKey;
dst_mouseevent.controlDown = emEvent.ctrlKey;
switch(emEvent.numTouches) {
case 1:
dst_mouseevent.button = MouseEvent::Button::LEFT;
break;
case 2:
dst_mouseevent.button = MouseEvent::Button::RIGHT;
break;
default:
dst_mouseevent.button = MouseEvent::Button::MIDDLE;
break;
}
}
void createMouseEventSCROLL(const EmscriptenTouchEvent& emEvent, MouseEvent& event) {
event.type = MouseEvent::Type::SCROLL_VERT;
double newDistance = 0;
this->calculatePinchDistance(emEvent, newDistance);
this->calculateCenterPosition(emEvent, this->centerX, this->centerY);
event.x = this->centerX;
event.y = this->centerY;
event.shiftDown = emEvent.shiftKey;
event.controlDown = emEvent.ctrlKey;
// FIXME(emscripten): best value range for scrollDelta ?
event.scrollDelta = (newDistance - this->previousPinchDistance) / 25.0;
if (std::abs(event.scrollDelta) > 2) {
event.scrollDelta = 2;
if (std::signbit(event.scrollDelta)) {
event.scrollDelta *= -1.0;
}
}
this->previousPinchDistance = newDistance;
}
void onTouchStart(const EmscriptenTouchEvent& emEvent, void* callbackParameter) {
if (this->touchActionStarted) {
// dbp("onTouchStart(): Break due to already started.");
return;
}
MouseEvent event;
this->createMouseEventPRESS(emEvent, event);
this->previousNumTouches = emEvent.numTouches;
if (this->onPointerDown) {
// dbp("onPointerDown(): numTouches=%d, timestamp=%f", emEvent.numTouches, emEvent.timestamp);
this->onPointerDown(&event, callbackParameter);
}
}
void onTouchMove(const EmscriptenTouchEvent& emEvent, void* callbackParameter) {
this->calculateCenterPosition(emEvent, this->centerX, this->centerY);
int newNumTouches = emEvent.numTouches;
if (newNumTouches != this->previousNumTouches) {
MouseEvent releaseEvent;
this->createMouseEventRELEASE(emEvent, releaseEvent);
if (this->onPointerUp) {
// dbp("onPointerUp(): numTouches=%d, timestamp=%f", emEvent.numTouches, emEvent.timestamp);
this->onPointerUp(&releaseEvent, callbackParameter);
}
MouseEvent pressEvent;
this->createMouseEventPRESS(emEvent, pressEvent);
if (this->onPointerDown) {
// dbp("onPointerDown(): numTouches=%d, timestamp=%f", emEvent.numTouches, emEvent.timestamp);
this->onPointerDown(&pressEvent, callbackParameter);
}
}
MouseEvent motionEvent = { };
this->createMouseEventMOTION(emEvent, motionEvent);
if (this->onPointerMove) {
// dbp("onPointerMove(): numTouches=%d, timestamp=%f", emEvent.numTouches, emEvent.timestamp);
this->onPointerMove(&motionEvent, callbackParameter);
}
if (emEvent.numTouches == 2) {
MouseEvent scrollEvent;
this->createMouseEventSCROLL(emEvent, scrollEvent);
if (scrollEvent.scrollDelta != 0) {
if (this->onScroll) {
// dbp("Scroll %f", scrollEvent.scrollDelta);
this->onScroll(&scrollEvent, callbackParameter);
}
}
}
this->previousNumTouches = e
A36F
mEvent.numTouches;
}
void onTouchEnd(const EmscriptenTouchEvent& emEvent, void* callbackParameter) {
if (!this->touchActionStarted) {
return;
}
MouseEvent releaseEvent = { };
this->createMouseEventRELEASE(emEvent, releaseEvent);
if (this->onPointerUp) {
// dbp("onPointerUp(): numTouches=%d, timestamp=%d", emEvent.numTouches, emEvent.timestamp);
this->onPointerUp(&releaseEvent, callbackParameter);
}
this->clear();
}
void onTouchCancel(const EmscriptenTouchEvent& emEvent, void* callbackParameter) {
this->onTouchEnd(emEvent, callbackParameter);
}
};
static TouchEventHelper touchEventHelper;
static KeyboardEvent handledKeyboardEvent;
class WindowImplHtml final : public Window {
public:
std::string emCanvasSel;
EMSCRIPTEN_WEBGL_CONTEXT_HANDLE emContext = 0;
val htmlContainer;
val htmlEditor;
val scrollbarHelper;
std::shared_ptr<MenuBarImplHtml> menuBar;
WindowImplHtml(val htmlContainer, std::string emCanvasSel) :
emCanvasSel(emCanvasSel),
htmlContainer(htmlContainer),
htmlEditor(val::global("document").call<val>("createElement", val("input")))
{
htmlEditor["classList"].call<void>("add", val("editor"));
htmlEditor["style"].set("display", "none");
auto editingDoneFunc = [this] {
if(onEditingDone) {
onEditingDone(htmlEditor["value"].as<std::string>());
}
};
RegisterEventListener(htmlEditor, "trigger", editingDoneFunc);
htmlContainer["parentElement"].call<void>("appendChild", htmlEditor);
std::string scrollbarElementQuery = emCanvasSel + "scrollbar";
dbp("scrollbar element query: \"%s\"", scrollbarElementQuery.c_str());
val scrollbarElement = val::global("document").call<val>("querySelector", val(scrollbarElementQuery));
if (scrollbarElement == val::null()) {
// dbp("scrollbar element is null.");
this->scrollbarHelper = val::null();
} else {
dbp("scrollbar element OK.");
this->scrollbarHelper = val::global("window")["ScrollbarHelper"].new_(val(scrollbarElementQuery));
static std::function<void()> onScrollCallback = [this] {
// dbp("onScrollCallback std::function this=%p", (void*)this);
if (this->onScrollbarAdjusted) {
double newpos = this->scrollbarHelper.call<double>("getScrollbarPosition");
// dbp(" call onScrollbarAdjusted(%f)", newpos);
this->onScrollbarAdjusted(newpos);
}
this->Invalidate();
};
this->scrollbarHelper.set("onScrollCallback", Wrap(onScrollCallback));
}
sscheck(emscripten_set_resize_callback(
EMSCRIPTEN_EVENT_TARGET_WINDOW, this, /*useCapture=*/false,
WindowImplHtml::ResizeCallback));
sscheck(emscripten_set_resize_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::ResizeCallback));
sscheck(emscripten_set_mousemove_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::MouseCallback));
sscheck(emscripten_set_mousedown_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::MouseCallback));
sscheck(emscripten_set_click_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::MouseCallback));
sscheck(emscripten_set_dblclick_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::MouseCallback));
sscheck(emscripten_set_mouseup_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::MouseCallback));
sscheck(emscripten_set_mouseleave_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::MouseCallback));
sscheck(emscripten_set_touchstart_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::TouchCallback));
sscheck(emscripten_set_touchmove_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::TouchCallback));
sscheck(emscripten_set_touchend_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::TouchCallback));
sscheck(emscripten_set_touchcancel_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::TouchCallback));
sscheck(emscripten_set_wheel_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::WheelCallback));
sscheck(emscripten_set_keydown_callback(
EMSCRIPTEN_EVENT_TARGET_WINDOW, this, /*useCapture=*/false,
WindowImplHtml::KeyboardCallback));
sscheck(emscripten_set_keyup_callback(
EMSCRIPTEN_EVENT_TARGET_WINDOW, this, /*useCapture=*/false,
WindowImplHtml::KeyboardCallback));
sscheck(emscripten_set_webglcontextlost_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::ContextLostCallback));
sscheck(emscripten_set_webglcontextrestored_callback(
emCanvasSel.c_str(), this, /*useCapture=*/false,
WindowImplHtml::ContextRestoredCallback));
ResizeCanvasElement();
SetupWebGLContext();
}
~WindowImplHtml() {
if(emContext != 0) {
sscheck(emscripten_webgl_destroy_context(emContext));
}
}
static EM_BOOL ResizeCallback(int emEventType, const EmscriptenUiEvent *emEvent, void *data) {
WindowImplHtml *window = (WindowImplHtml *)data;
window->Invalidate();
return EM_TRUE;
}
static EM_BOOL MouseCallback(int emEventType, const EmscriptenMouseEvent *emEvent,
void *data) {
if(val::global("window").call<bool>("isModal")) return EM_FALSE;
WindowImplHtml *window = (WindowImplHtml *)data;
MouseEvent event = {};
switch(emEventType) {
case EMSCRIPTEN_EVENT_MOUSEMOVE:
event.type = MouseEvent::Type::MOTION;
break;
case EMSCRIPTEN_EVENT_MOUSEDOWN:
event.type = MouseEvent::Type::PRESS;
break;
case EMSCRIPTEN_EVENT_DBLCLICK:
event.type = MouseEvent::Type::DBL_PRESS;
break;
case EMSCRIPTEN_EVENT_MOUSEUP:
event.type = MouseEvent::Type::RELEASE;
break;
case EMSCRIPTEN_EVENT_MOUSELEAVE:
event.type = MouseEvent::Type::LEAVE;
break;
default:
return EM_FALSE;
}
switch(emEventType) {
case EMSCRIPTEN_EVENT_MOUSEMOVE:
if(emEvent->buttons & 1) {
event.button = MouseEvent::Button::LEFT;
} else if(emEvent->buttons & 2) {
event.button = MouseEvent::Button::RIGHT;
} else if(emEvent->buttons & 4) {
event.button = MouseEvent::Button::MIDDLE;
}
break;
case EMSCRIPTEN_EVENT_MOUSEDOWN:
case EMSCRIPTEN_EVENT_DBLCLICK:
case EMSCRIPTEN_EVENT_MOUSEUP:
switch(emEvent->button) {
case 0: event.button = MouseEvent::Button::LEFT; break;
case 1: event.button = MouseEvent::Button::MIDDLE; break;
case 2: event.button = MouseEvent::Button::RIGHT; break;
}
break;
default:
return EM_FALSE;
}
event.x = emEvent->targetX;
event.y = emEvent->targetY;
event.shiftDown = emEvent->shiftKey || emEvent->altKey;
event.controlDown = emEvent->ctrlKey;
if(window->onMouseEvent) {
return window->onMouseEvent(event);
}
return EM_FALSE;
}
static EM_BOOL TouchCallback(int emEventType, const EmscriptenTouchEvent *emEvent,
void *data) {
if(val::global("window").call<bool>("isModal")) return EM_FALSE;
static bool initialized = false;
WindowImplHtml *window = (WindowImplHtml *)data;
if (!initialized) {
touchEventHelper.onPointerDown = [](MouseEvent* event, void* param) -> void {
WindowImplHtml* window = (WindowImplHtml*)param;
if (window->onMouseEvent) {
window->onMouseEvent(*event);
}
};
touchEventHelper.onPointerMove = [](MouseEvent* event, void* param) -> void {
WindowImplHtml* window = (WindowImplHtml*)param;
if (window->onMouseEvent) {
window->onMouseEvent(*event);
}
};
touchEventHelper.onPointerUp = [](MouseEvent* event, void* param) -> void {
WindowImplHtml* window = (WindowImplHtml*)param;
if (window->onMouseEvent) {
window->onMouseEvent(*event);
}
};
touchEventHelper.onScroll = [](MouseEvent* event, void* param) -> void {
WindowImplHtml* window = (WindowImplHtml*)param;
if (window->onMouseEvent) {
window->onMouseEvent(*event);
}
};
initialized = true;
}
switch(emEventType) {
case EMSCRIPTEN_EVENT_TOUCHSTART:
touchEventHelper.onTouchStart(*emEvent, window);
break;
case EMSCRIPTEN_EVENT_TOUCHMOVE:
touchEventHelper.onTouchMove(*emEvent, window);
break;
case EMSCRIPTEN_EVENT_TOUCHEND:
touchEventHelper.onTouchEnd(*emEvent, window);
break;
case EMSCRIPTEN_EVENT_TOUCHCANCEL:
touchEventHelper.onTouchCancel(*emEvent, window);
break;
default:
return EM_FALSE;
}
return true;
}
static EM_BOOL WheelCallback(int emEventType, const EmscriptenWheelEvent *emEvent,
void *data) {
if(val::global("window").call<bool>("isModal")) return EM_FALSE;
WindowImplHtml *window = (WindowImplHtml *)data;
MouseEvent event = {};
if(emEvent->deltaY != 0) {
event.type = MouseEvent::Type::SCROLL_VERT;
// FIXME(emscripten):
// Pay attention to:
// dbp("Mouse wheel delta mode: %lu", emEvent->deltaMode);
// https://emscripten.org/docs/api_reference/html5.h.html#id11
// https://www.w3.org/TR/DOM-Level-3-Events/#dom-wheelevent-deltamode
// and adjust the 0.01 below. deltaMode == 0 on a Firefox on a Windows.
event.scrollDelta = -emEvent->deltaY * 0.01;
} else {
return EM_FALSE;
}
const EmscriptenMouseEvent &emStatus = emEvent->mouse;
event.x = emStatus.targetX;
event.y = emStatus.targetY;
event.shiftDown = emStatus.shiftKey;
event.controlDown = emStatus.ctrlKey;
if(window->onMouseEvent) {
return window->onMouseEvent(event);
}
return EM_FALSE;
}
static EM_BOOL KeyboardCallback(int emEventType, const EmscriptenKeyboardEvent *emEvent,
void *data) {
if(emEvent->altKey) return EM_FALSE;
if(emEvent->repeat) return EM_FALSE;
WindowImplHtml *window = (WindowImplHtml *)data;
KeyboardEvent event = {};
switch(emEventType) {
case EMSCRIPTEN_EVENT_KEYDOWN:
event.type = KeyboardEvent::Type::PRESS;
break;
case EMSCRIPTEN_EVENT_KEYUP:
event.type = KeyboardEvent::Type::RELEASE;
break;
default:
return EM_FALSE;
}
event.shiftDown = emEvent->shiftKey;
event.controlDown = emEvent->ctrlKey;
std::string key = emEvent->key;
if(key[0] == 'F' && isdigit(key[1])) {
event.key = KeyboardEvent::Key::FUNCTION;
event.num = std::stol(key.substr(1));
} else {
event.key = KeyboardEvent::Key::CHARACTER;
auto utf8 = ReadUTF8(key);
if(++utf8.begin() == utf8.end()) {
event.chr = tolower(*utf8.begin());
} else if(key == "Escape") {
event.chr = '\e';
} else if(key == "Tab") {
event.chr = '\t';
} else if(key == "Backspace") {
event.chr = '\b';
} else if(key == "Delete") {
event.chr = '\x7f';
} else {
return EM_FALSE;
}
if(event.chr == '>' && event.shiftDown) {
event.shiftDown = false;
}
}
if(event.Equals(handledKeyboardEvent)) return EM_FALSE;
if(val::global("window").call<bool>("isModal")) {
handledKeyboardEvent = {};
return EM_FALSE;
}
if(window->onKeyboardEvent) {
if(window->onKeyboardEvent(event)) {
handledKeyboardEvent = event;
return EM_TRUE;
}
}
return EM_FALSE;
}
void SetupWebGLContext() {
EmscriptenWebGLContextAttributes emAttribs = {};
emscripten_webgl_init_context_attributes(&emAttribs);
emAttribs.alpha = false;
emAttribs.failIfMajorPerformanceCaveat = true;
sscheck(emContext = emscripten_webgl_create_context(emCanvasSel.c_str(), &emAttribs));
dbp("Canvas %s: got context %d", emCanvasSel.c_str(), emContext);
}
static bool ContextLostCallback(int eventType, const void *reserved, void *data) {
WindowImplHtml *window = (WindowImplHtml *)data;
dbp("Canvas %s: context lost", window->emCanvasSel.c_str());
window->emContext = 0;
if(window->onContextLost) {
window->onContextLost();
}
return EM_TRUE;
}
static bool ContextRestoredCallback(int eventType, const void *reserved, void *data) {
WindowImplHtml *window = (WindowImplHtml *)data;
dbp("Canvas %s: context restored", window->emCanvasSel.c_str());
window->SetupWebGLContext();
return EM_TRUE;
}
void ResizeCanvasElement() {
double width, height;
std::string htmlContainerSel = "#" + htmlContainer["id"].as<std::string>();
sscheck(emscripten_get_element_css_size(htmlContainerSel.c_str(), &width, &height));
// sscheck(emscripten_get_element_css_size(emCanvasSel.c_str(), &width, &height));
double devicePixelRatio = GetDevicePixelRatio();
width *= devicePixelRatio;
height *= devicePixelRatio;
int currentWidth = 0, currentHeight = 0;
sscheck(emscripten_get_canvas_element_size(emCanvasSel.c_str(), ¤tWidth, ¤tHeight));
if ((int)width != currentWidth || (int)height != currentHeight) {
// dbp("Canvas %s container current size: (%d, %d)", emCanvasSel.c_str(), (int)currentWidth, (int)currentHeight);
// dbp("Canvas %s: resizing to (%d, %d)", emCanvasSel.c_str(), (int)width, (int)height);
sscheck(emscripten_set_canvas_element_size(emCanvasSel.c_str(), (int)width, (int)height));
}
}
static void RenderCallback(void *data) {
WindowImplHtml *window = (WindowImplHtml *)data;
if(window->emContext == 0) {
dbp("Canvas %s: cannot render: no context", window->emCanvasSel.c_str());
return;
}
window->ResizeCanvasElement();
sscheck(emscripten_webgl_make_context_current(window->emContext));
if(window->onRender) {
window->onRender();
}
}
double GetPixelDensity() override {
return 96.0 * GetD
5977
evicePixelRatio();
}
double GetDevicePixelRatio() override {
return emscripten_get_device_pixel_ratio();
}
bool IsVisible() override {
// FIXME(emscripten): implement
return true;
}
void SetVisible(bool visible) override {
// FIXME(emscripten): implement
}
void Focus() override {
// Do nothing, we can't affect focus of browser windows.
}
bool IsFullScreen() override {
EmscriptenFullscreenChangeEvent emEvent = {};
sscheck(emscripten_get_fullscreen_status(&emEvent));
return emEvent.isFullscreen;
}
void SetFullScreen(bool fullScreen) override {
if(fullScreen) {
EmscriptenFullscreenStrategy emStrategy = {};
emStrategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
emStrategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_HIDEF;
emStrategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
sscheck(emscripten_request_fullscreen_strategy(
emCanvasSel.c_str(), /*deferUntilInEventHandler=*/true, &emStrategy));
} else {
sscheck(emscripten_exit_fullscreen());
}
}
void SetTitle(const std::string &title) override {
// FIXME(emscripten): implement
}
void SetMenuBar(MenuBarRef menuBar) override {