forked from cocos/cocos-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenHarmonyPlatform.cpp
More file actions
734 lines (654 loc) · 29.3 KB
/
Copy pathOpenHarmonyPlatform.cpp
File metadata and controls
734 lines (654 loc) · 29.3 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
/****************************************************************************
Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "platform/openharmony/OpenHarmonyPlatform.h"
#include "base/Macros.h"
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <napi/native_api.h>
#include "application/ApplicationManager.h"
#include "application/CocosApplication.h"
#include "platform/UniversalPlatform.h"
#include "platform/openharmony/modules/SystemWindow.h"
#include "platform/openharmony/modules/SystemWindowManager.h"
#include "platform/empty/modules/Accelerometer.h"
#include "platform/empty/modules/Battery.h"
#include "platform/empty/modules/Network.h"
#include "platform/empty/modules/Screen.h"
#include "platform/empty/modules/Vibrator.h"
#include "platform/openharmony/modules/System.h"
#if CC_USE_GAMEPAD
#include "platform/openharmony/OpenHarmonyGamepad.h"
#endif
#include "cocos/engine/EngineEvents.h"
#include <chrono>
#include <sstream>
namespace {
class SyncContext {
private:
std::atomic<int> _refCount{1};
uv_cond_t _cond{};
uv_mutex_t _mutex{};
bool _completed{false};
public:
enum class WAIT_RET_CODE {
SUCCEED = 0,
TIMEOUT,
};
SyncContext() {
CC_LOG_INFO("Create SyncContext: %p", this);
uv_mutex_init(&_mutex);
uv_cond_init(&_cond);
}
~SyncContext() {
CC_LOG_INFO("Destroy SyncContext: %p", this);
uv_mutex_destroy(&_mutex);
uv_cond_destroy(&_cond);
}
WAIT_RET_CODE wait_for(uint64_t nanoSeconds) {
WAIT_RET_CODE ret = WAIT_RET_CODE::SUCCEED;
uv_mutex_lock(&_mutex);
// Use a while loop to check the completed flag to avoid spurious wakeup.
while (!_completed) {
int r = uv_cond_timedwait(&_cond, &_mutex, nanoSeconds);
if (r == UV_ETIMEDOUT) {
ret = WAIT_RET_CODE::TIMEOUT;
break;
}
}
uv_mutex_unlock(&_mutex);
return ret;
}
void notify() {
uv_mutex_lock(&_mutex);
_completed = true;
uv_cond_signal(&_cond);
uv_mutex_unlock(&_mutex);
}
void addRef() {
++_refCount;
}
void release() {
--_refCount;
int ref = _refCount;
if (ref == 0) {
delete this;
}
}
};
void onSurfaceCreatedCB(OH_NativeXComponent* component, void* window) {
CC_LOG_INFO("onSurfaceCreatedCB, component: %p, window: %p");
// It is possible that when the message is sent, the worker thread has not yet started.
// sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_CREATED, component, window);
cc::ISystemWindowInfo info;
info.title = "";
info.x = 0;
info.y = 0;
info.width = 0;
info.height = 0;
info.flags = 0;
info.externalHandle = window;
cc::ISystemWindowManager* windowMgr =
cc::OpenHarmonyPlatform::getInstance()->getInterface<cc::ISystemWindowManager>();
windowMgr->createWindow(info);
}
void onSurfaceHideCB(OH_NativeXComponent* component, void* window) {
CC_LOG_INFO("onSurfaceHideCB begin, component: %p, window: %p");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
CC_LOG_ERROR("onSurfaceHideCB, OH_NativeXComponent_GetXComponentId failed: %d", ret);
return;
}
cc::OpenHarmonyPlatform::sendMsgToWorkerAndWait(cc::MessageType::WM_XCOMPONENT_SURFACE_HIDE, component, window);
CC_LOG_INFO("onSurfaceHideCB end, component: %p, window: %p");
}
void onSurfaceShowCB(OH_NativeXComponent* component, void* window) {
CC_LOG_INFO("onSurfaceShowCB, component: %p, window: %p");
int32_t ret;
char idStr[OH_XCOMPONENT_ID_LEN_MAX + 1] = {};
uint64_t idSize = OH_XCOMPONENT_ID_LEN_MAX + 1;
ret = OH_NativeXComponent_GetXComponentId(component, idStr, &idSize);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
cc::OpenHarmonyPlatform::sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_SHOW, component, window);
}
int ohKeyCodeToCocosKeyCode(OH_NativeXComponent_KeyCode ohKeyCode) {
static const int keyZeroInCocos = 48;
static const int keyF1InCocos = 112;
static const int keyAInCocos = 65;
static std::unordered_map<OH_NativeXComponent_KeyCode, cc::KeyCode> keyCodeMap = {
{KEY_ESCAPE, cc::KeyCode::ESCAPE},
{KEY_GRAVE, cc::KeyCode::BACKQUOTE},
{KEY_MINUS, cc::KeyCode::MINUS},
{KEY_EQUALS, cc::KeyCode::EQUAL},
{KEY_DEL, cc::KeyCode::BACKSPACE},
{KEY_TAB, cc::KeyCode::TAB},
{KEY_LEFT_BRACKET, cc::KeyCode::BRACKET_LEFT},
{KEY_RIGHT_BRACKET, cc::KeyCode::BRACKET_RIGHT},
{KEY_BACKSLASH, cc::KeyCode::BACKSLASH},
{KEY_CAPS_LOCK, cc::KeyCode::CAPS_LOCK},
{KEY_SEMICOLON, cc::KeyCode::SEMICOLON},
{KEY_APOSTROPHE, cc::KeyCode::QUOTE},
{KEY_ENTER, cc::KeyCode::ENTER},
{KEY_SHIFT_LEFT, cc::KeyCode::SHIFT_LEFT},
{KEY_COMMA, cc::KeyCode::COMMA},
{KEY_PERIOD, cc::KeyCode::PERIOD},
{KEY_SLASH, cc::KeyCode::SLASH},
{KEY_SHIFT_RIGHT, cc::KeyCode::SHIFT_RIGHT},
{KEY_CTRL_LEFT, cc::KeyCode::CONTROL_LEFT},
{KEY_ALT_LEFT, cc::KeyCode::ALT_LEFT},
{KEY_SPACE, cc::KeyCode::SPACE},
{KEY_ALT_RIGHT, cc::KeyCode::ALT_RIGHT},
{KEY_CTRL_RIGHT, cc::KeyCode::CONTROL_RIGHT},
{KEY_DPAD_LEFT, cc::KeyCode::ARROW_LEFT},
{KEY_DPAD_RIGHT, cc::KeyCode::ARROW_RIGHT},
{KEY_DPAD_DOWN, cc::KeyCode::ARROW_DOWN},
{KEY_DPAD_UP, cc::KeyCode::ARROW_UP},
{KEY_DPAD_CENTER, cc::KeyCode::DPAD_CENTER},
{KEY_MOVE_HOME, cc::KeyCode::HOME},
{KEY_MOVE_END, cc::KeyCode::END},
{KEY_FORWARD_DEL, cc::KeyCode::DELETE_KEY},
{KEY_INSERT, cc::KeyCode::INSERT},
{KEY_PAGE_UP, cc::KeyCode::PAGE_UP},
{KEY_PAGE_DOWN, cc::KeyCode::PAGE_DOWN},
{KEY_SCROLL_LOCK, cc::KeyCode::SCROLLLOCK},
{KEY_BREAK, cc::KeyCode::PAUSE},
// numpad
{KEY_NUM_LOCK, cc::KeyCode::NUM_LOCK},
{KEY_NUMPAD_DIVIDE, cc::KeyCode::NUMPAD_DIVIDE},
{KEY_NUMPAD_MULTIPLY, cc::KeyCode::NUMPAD_MULTIPLY},
{KEY_NUMPAD_SUBTRACT, cc::KeyCode::NUMPAD_MINUS},
{KEY_NUMPAD_ADD, cc::KeyCode::NUMPAD_PLUS},
{KEY_NUMPAD_ENTER, cc::KeyCode::NUMPAD_ENTER},
{KEY_NUMPAD_DOT, cc::KeyCode::NUMPAD_DECIMAL},
{KEY_NUMPAD_COMMA, cc::KeyCode::COMMA},
{KEY_NUMPAD_EQUALS, cc::KeyCode::EQUAL},
{KEY_NUMPAD_0, cc::KeyCode::NUMPAD_0},
{KEY_NUMPAD_1, cc::KeyCode::NUMPAD_1},
{KEY_NUMPAD_2, cc::KeyCode::NUMPAD_2},
{KEY_NUMPAD_3, cc::KeyCode::NUMPAD_3},
{KEY_NUMPAD_4, cc::KeyCode::NUMPAD_4},
{KEY_NUMPAD_5, cc::KeyCode::NUMPAD_5},
{KEY_NUMPAD_6, cc::KeyCode::NUMPAD_6},
{KEY_NUMPAD_7, cc::KeyCode::NUMPAD_7},
{KEY_NUMPAD_8, cc::KeyCode::NUMPAD_8},
{KEY_NUMPAD_9, cc::KeyCode::NUMPAD_9},
{KEY_MENU, cc::KeyCode::CONTEXT_MENU},
{KEY_SYSRQ, cc::KeyCode::PRINT_SCREEN},
{KEY_META_LEFT, cc::KeyCode::META_LEFT},
{KEY_META_RIGHT, cc::KeyCode::META_RIGHT},
};
if (keyCodeMap.find(ohKeyCode) != keyCodeMap.end()) {
return int(keyCodeMap[ohKeyCode]);
}
if (ohKeyCode >= KEY_0 && ohKeyCode <= KEY_9) {
return keyZeroInCocos + ohKeyCode - KEY_0;
}
if (ohKeyCode >= KEY_A && ohKeyCode <= KEY_Z) {
return keyAInCocos + ohKeyCode - KEY_A;
}
if (ohKeyCode >= KEY_F1 && ohKeyCode <= KEY_F12) {
return keyF1InCocos + ohKeyCode - KEY_F1;
}
return ohKeyCode;
}
void dispatchKeyEventCB(OH_NativeXComponent* component, void* window) {
OH_NativeXComponent_KeyEvent* keyEvent;
if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) {
static const int keyCodeUnknownInOH = -1;
static const int keyActionUnknownInOH = -1;
OH_NativeXComponent_KeyAction action;
OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
OH_NativeXComponent_KeyCode code;
OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
if (code == keyCodeUnknownInOH || action == keyActionUnknownInOH) {
CC_LOG_ERROR("unknown code and action don't callback");
return;
}
cc::KeyboardEvent* ev = new cc::KeyboardEvent;
ev->windowId = cc::ISystemWindow::mainWindowId;
ev->action = 0 == action ? cc::KeyboardEvent::Action::PRESS : cc::KeyboardEvent::Action::RELEASE;
ev->key = ohKeyCodeToCocosKeyCode(code);
cc::OpenHarmonyPlatform::sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_KEY_EVENT, reinterpret_cast<void*>(ev), window);
} else {
CC_LOG_ERROR("OpenHarmonyPlatform::getKeyEventError");
}
}
void dispatchMouseEventCB(OH_NativeXComponent* component, void* window) {
OH_NativeXComponent_MouseEvent mouseEvent;
int32_t ret = OH_NativeXComponent_GetMouseEvent(component, window, &mouseEvent);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
if (mouseEvent.action == OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_NONE)
return;
cc::MouseEvent* ev = new cc::MouseEvent;
ev->windowId = cc::ISystemWindow::mainWindowId;
ev->x = mouseEvent.x;
ev->y = mouseEvent.y;
switch (mouseEvent.action) {
case OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_PRESS:
ev->type = cc::MouseEvent::Type::DOWN;
break;
case OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_RELEASE:
ev->type = cc::MouseEvent::Type::UP;
break;
case OH_NativeXComponent_MouseEventAction::OH_NATIVEXCOMPONENT_MOUSE_MOVE:
ev->type = cc::MouseEvent::Type::MOVE;
break;
default:
ev->type = cc::MouseEvent::Type::UNKNOWN;
break;
}
switch (mouseEvent.button) {
case OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_LEFT_BUTTON:
ev->button = 0;
break;
case OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_RIGHT_BUTTON:
ev->button = 2;
break;
case OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_MIDDLE_BUTTON:
ev->button = 1;
break;
case OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_BACK_BUTTON:
ev->button = 3;
break;
case OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_FORWARD_BUTTON:
ev->button = 4;
break;
case OH_NativeXComponent_MouseEventButton::OH_NATIVEXCOMPONENT_NONE_BUTTON:
ev->button = -1;
break;
}
if (mouseEvent.action == 1 && mouseEvent.button == 1) {
cc::OpenHarmonyPlatform::getInstance()->isMouseLeftActive = true;
}
if (mouseEvent.action == 2 && mouseEvent.button == 1) {
cc::OpenHarmonyPlatform::getInstance()->isMouseLeftActive = false;
}
cc::OpenHarmonyPlatform::sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_MOUSE_EVENT, reinterpret_cast<void*>(ev), window);
} else {
CC_LOG_ERROR("OpenHarmonyPlatform::getMouseEventError");
}
}
void dispatchHoverEventCB(OH_NativeXComponent* component, bool isHover) {
// OpenharmonyPlatform::DispatchHoverEventCB
}
cc::TouchEvent::Type touchTypeTransform(OH_NativeXComponent_TouchEventType touchType) {
if (touchType == OH_NATIVEXCOMPONENT_DOWN) {
return cc::TouchEvent::Type::BEGAN;
} else if (touchType == OH_NATIVEXCOMPONENT_MOVE) {
return cc::TouchEvent::Type::MOVED;
} else if (touchType == OH_NATIVEXCOMPONENT_UP) {
return cc::TouchEvent::Type::ENDED;
} else if (touchType == OH_NATIVEXCOMPONENT_CANCEL) {
return cc::TouchEvent::Type::CANCELLED;
}
return cc::TouchEvent::Type::UNKNOWN;
}
void dispatchTouchEventCB(OH_NativeXComponent* component, void* window) {
OH_NativeXComponent_TouchEvent touchEvent;
int32_t ret = OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent);
if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
return;
}
// TODO(qgh):Is it possible to find an efficient way to do this, I thought about using a cache queue but it requires locking.
cc::TouchEvent* ev = new cc::TouchEvent;
cc::SystemWindowManager* windowMgr =
cc::OpenHarmonyPlatform::getInstance()->getInterface<cc::SystemWindowManager>();
CC_ASSERT_NOT_NULL(windowMgr);
cc::ISystemWindow* systemWindow = windowMgr->getWindowFromHandle(window);
CC_ASSERT_NOT_NULL(systemWindow);
ev->windowId = systemWindow->getWindowId();
if (touchEvent.type == OH_NATIVEXCOMPONENT_DOWN) {
ev->type = cc::TouchEvent::Type::BEGAN;
} else if (touchEvent.type == OH_NATIVEXCOMPONENT_MOVE) {
ev->type = cc::TouchEvent::Type::MOVED;
} else if (touchEvent.type == OH_NATIVEXCOMPONENT_UP) {
ev->type = cc::TouchEvent::Type::ENDED;
} else if (touchEvent.type == OH_NATIVEXCOMPONENT_CANCEL) {
ev->type = cc::TouchEvent::Type::CANCELLED;
}
for (int i = 0; i < touchEvent.numPoints; ++i) {
int32_t id = touchEvent.touchPoints[i].id;
if (touchEvent.id == id) {
ev->touches.emplace_back(touchEvent.touchPoints[i].x, touchEvent.touchPoints[i].y, id);
}
}
cc::OpenHarmonyPlatform::sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_TOUCH_EVENT, reinterpret_cast<void*>(ev), window);
}
void onSurfaceChangedCB(OH_NativeXComponent* component, void* window) {
cc::OpenHarmonyPlatform::sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_CHANGED, reinterpret_cast<void*>(component), window);
}
void onSurfaceDestroyedCB(OH_NativeXComponent* component, void* window) {
cc::OpenHarmonyPlatform::sendMsgToWorker(cc::MessageType::WM_XCOMPONENT_SURFACE_DESTROY, reinterpret_cast<void*>(component), window);
}
} // namespace
namespace cc {
OpenHarmonyPlatform::OpenHarmonyPlatform() {
registerInterface(std::make_shared<System>());
registerInterface(std::make_shared<Screen>());
registerInterface(std::make_shared<Vibrator>());
registerInterface(std::make_shared<Network>());
registerInterface(std::make_shared<Battery>());
registerInterface(std::make_shared<Accelerometer>());
registerInterface(std::make_shared<SystemWindowManager>());
_callback.OnSurfaceCreated = onSurfaceCreatedCB;
_callback.OnSurfaceChanged = onSurfaceChangedCB;
_callback.OnSurfaceDestroyed = onSurfaceDestroyedCB;
_callback.DispatchTouchEvent = dispatchTouchEventCB;
#if CC_USE_GAMEPAD
_gamePad = std::make_unique<OpenHarmonyGamePad>();
#endif
}
OpenHarmonyPlatform::~OpenHarmonyPlatform() {
}
int32_t OpenHarmonyPlatform::init() {
return 0;
}
OpenHarmonyPlatform* OpenHarmonyPlatform::getInstance() {
return dynamic_cast<OpenHarmonyPlatform*>(BasePlatform::getPlatform());
}
int32_t OpenHarmonyPlatform::run(int argc, const char** argv) {
UniversalPlatform::run(argc, argv);
/*
if (_workerLoop) {
// Todo: Starting the timer in this way is inaccurate and will be fixed later.
uv_timer_init(_workerLoop, &_timerHandle);
// 1s = 1000ms = 60fps;
// 1000ms / 60fps = 16 ms/fps
uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 16, true);
}
*/
return 0;
}
void OpenHarmonyPlatform::setNativeXComponent(OH_NativeXComponent* component) {
_component = component;
OH_NativeXComponent_RegisterCallback(_component, &_callback);
OH_NativeXComponent_RegisterSurfaceHideCallback(_component, onSurfaceHideCB);
OH_NativeXComponent_RegisterSurfaceShowCallback(_component, onSurfaceShowCB);
// register KeyEvent
OH_NativeXComponent_RegisterKeyEventCallback(_component, dispatchKeyEventCB);
// register mouseEvent
_mouseCallback.DispatchMouseEvent = dispatchMouseEventCB;
_mouseCallback.DispatchHoverEvent = dispatchHoverEventCB;
OH_NativeXComponent_RegisterMouseEventCallback(_component, &_mouseCallback);
}
void OpenHarmonyPlatform::enqueue(const WorkerMessageData& msg) {
_messageQueue.enqueue(msg);
triggerMessageSignal();
}
void OpenHarmonyPlatform::enqueueAndWait(WorkerMessageData& msg) {
SyncContext* syncContext = new SyncContext(); // ref -> 1
syncContext->addRef(); // ref -> 2
msg.syncContext = syncContext;
_messageQueue.enqueue(msg);
auto* oldWorkerLoop = _workerLoop;
triggerMessageSignal();
auto oldTime = std::chrono::steady_clock::now();
static const uint64_t SYNC_TIMEOUT_NANO_SECONDS = 300 * 1000 * 1000; // 300ms
static const uint32_t WAIT_COUNT = 10;
SyncContext::WAIT_RET_CODE waitRet = SyncContext::WAIT_RET_CODE::SUCCEED;
for (uint32_t i = 0; i < WAIT_COUNT; ++i) {
waitRet = syncContext->wait_for(SYNC_TIMEOUT_NANO_SECONDS); // not timeout, after wait: ref -> 1 ; timeout, after wait: ref still -> 2
if (waitRet == SyncContext::WAIT_RET_CODE::SUCCEED) {
break;
}
if (oldWorkerLoop == nullptr) {
CC_LOG_INFO("oldWorkerLoop is nullptr, current: %p", _workerLoop);
triggerMessageSignal();
oldWorkerLoop = _workerLoop;
}
CC_LOG_INFO("enqueueAndWait timeout 300ms, index: %u, try again", i);
}
auto nowTime = std::chrono::steady_clock::now();
auto interval = static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(nowTime - oldTime).count());
CC_LOG_INFO("enqueueAndWait: %.03f ms, waitRet: %d", interval / 1000 / 1000, static_cast<int>(waitRet));
syncContext->release(); // not timeout, ref -> 0; timeout, ref -> 1, will be released in event handle callback
}
void OpenHarmonyPlatform::triggerMessageSignal() {
if (_workerLoop != nullptr) {
// It is possible that when the message is sent, the worker thread has not yet started.
uv_async_send(&_messageSignal);
} else {
CC_LOG_WARNING("triggerMessageSignal, _workerLoop is not created");
}
}
bool OpenHarmonyPlatform::dequeue(WorkerMessageData* msg) {
return _messageQueue.dequeue(msg);
}
// static
void OpenHarmonyPlatform::onMessageCallback(const uv_async_t* /* req */) {
void* window = nullptr;
WorkerMessageData msgData;
OpenHarmonyPlatform* platform = OpenHarmonyPlatform::getInstance();
while (true) {
// loop until all msg dispatch
if (!platform->dequeue(reinterpret_cast<WorkerMessageData*>(&msgData))) {
// Queue has no data
break;
}
if ((msgData.type >= MessageType::WM_XCOMPONENT_SURFACE_CREATED) && (msgData.type <= MessageType::WM_XCOMPONENT_SURFACE_DESTROY)) {
if (msgData.type == MessageType::WM_XCOMPONENT_TOUCH_EVENT) {
TouchEvent* ev = reinterpret_cast<TouchEvent*>(msgData.data);
CC_ASSERT(ev != nullptr);
events::Touch::broadcast(*ev);
delete ev;
ev = nullptr;
} else if (msgData.type == MessageType::WM_XCOMPONENT_KEY_EVENT) {
KeyboardEvent* ev = reinterpret_cast<KeyboardEvent*>(msgData.data);
CC_ASSERT(ev != nullptr);
events::Keyboard::broadcast(*ev);
delete ev;
ev = nullptr;
} else if (msgData.type == MessageType::WM_XCOMPONENT_MOUSE_EVENT || msgData.type == MessageType::WM_XCOMPONENT_MOUSE_WHEEL_EVENT) {
MouseEvent* ev = reinterpret_cast<MouseEvent*>(msgData.data);
CC_ASSERT(ev != nullptr);
events::Mouse::broadcast(*ev);
delete ev;
ev = nullptr;
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CREATED) {
CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_CREATED ...");
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceCreated(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_CHANGED) {
CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_CHANGED ...");
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceChanged(nativexcomponet, msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_SHOW) {
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceShow(msgData.window);
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_HIDE) {
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceHide();
auto* ctx = reinterpret_cast<SyncContext*>(msgData.syncContext);
if (ctx) {
ctx->notify();
ctx->release();
}
} else if (msgData.type == MessageType::WM_XCOMPONENT_SURFACE_DESTROY) {
CC_LOG_INFO("onMessageCallback WM_XCOMPONENT_SURFACE_DESTROY ...");
OH_NativeXComponent* nativexcomponet = reinterpret_cast<OH_NativeXComponent*>(msgData.data);
CC_ASSERT(nativexcomponet != nullptr);
platform->onSurfaceDestroyed(nativexcomponet, msgData.window);
} else {
CC_ASSERT(false);
}
continue;
} else if (msgData.type == MessageType::WM_GAMEPAD_CONTROLLER_INPUT) {
CC_LOG_INFO("onMessageCallback GamePad ...");
ControllerEvent* ev = reinterpret_cast<ControllerEvent*>(msgData.data);
CC_ASSERT(ev != nullptr);
events::Controller::broadcast(*ev);
delete ev;
ev = nullptr;
} else if (msgData.type == MessageType::WM_GAMEPAD_CONTROLLER_CHANGE) {
CC_LOG_INFO("onMessageCallback GamePad ...");
ControllerChangeEvent* ev = reinterpret_cast<ControllerChangeEvent*>(msgData.data);
CC_ASSERT(ev != nullptr);
events::ControllerChange::broadcast(*ev);
delete ev;
ev = nullptr;
}
if (msgData.type == MessageType::WM_APP_SHOW) {
platform->onShowNative();
} else if (msgData.type == MessageType::WM_APP_HIDE) {
platform->onHideNative();
} else if (msgData.type == MessageType::WM_APP_DESTROY) {
platform->onDestroyNative();
}
if (msgData.type == MessageType::WM_VSYNC) {
platform->runTask();
}
}
}
void OpenHarmonyPlatform::onCreateNative(napi_env env, uv_loop_t* loop) {
}
void OpenHarmonyPlatform::onShowNative() {
CC_LOG_INFO("OpenHarmonyPlatform::onShowNative");
WindowEvent ev;
ev.type = WindowEvent::Type::SHOW;
ev.windowId = cc::ISystemWindow::mainWindowId;
events::WindowEvent::broadcast(ev);
onResume();
if (_timerInited) {
uv_timer_start(&_timerHandle, &OpenHarmonyPlatform::timerCb, 0, 1);
}
}
void OpenHarmonyPlatform::onHideNative() {
CC_LOG_INFO("OpenHarmonyPlatform::onHideNative");
WindowEvent ev;
ev.type = WindowEvent::Type::HIDDEN;
ev.windowId = cc::ISystemWindow::mainWindowId;
events::WindowEvent::broadcast(ev);
onPause();
if (_timerInited) {
uv_timer_stop(&_timerHandle);
}
}
void OpenHarmonyPlatform::onDestroyNative() {
CC_LOG_INFO("OpenHarmonyPlatform::onDestroyNative");
onDestroy();
if (_timerInited) {
uv_timer_stop(&_timerHandle);
}
}
void OpenHarmonyPlatform::timerCb(uv_timer_t* handle) {
OpenHarmonyPlatform::getInstance()->runTask();
}
void OpenHarmonyPlatform::restartJSVM() {
g_started = false;
}
void OpenHarmonyPlatform::workerInit(uv_loop_t* loop) {
CC_LOG_INFO("workerInit: %p", loop);
_workerLoop = loop;
if (_workerLoop) {
uv_timer_init(_workerLoop, &_timerHandle);
_timerInited = true;
uv_async_init(_workerLoop, &_messageSignal, reinterpret_cast<uv_async_cb>(OpenHarmonyPlatform::onMessageCallback));
if (!_messageQueue.empty()) {
triggerMessageSignal(); // trigger the signal to handle the pending message
}
}
}
void OpenHarmonyPlatform::requestVSync() {
}
int32_t OpenHarmonyPlatform::loop() {
return 0;
}
void OpenHarmonyPlatform::onSurfaceCreated(OH_NativeXComponent* component, void* window) {
}
void OpenHarmonyPlatform::onSurfaceChanged(OH_NativeXComponent* component, void* window) {
uint64_t width = 0;
uint64_t height = 0;
int32_t ret = OH_NativeXComponent_GetXComponentSize(_component, window, &width, &height);
CC_ASSERT(ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS);
WindowEvent ev;
ev.windowId = cc::ISystemWindow::mainWindowId;
ev.type = WindowEvent::Type::SIZE_CHANGED;
ev.width = width;
ev.height = height;
events::WindowEvent::broadcast(ev);
// Hack:On the PC platform, a resize message is sent, but this message occurs before initialization is complete, resulting in unprocessed messages.
// Therefore, an additional handling of the resize message is required here.
cc::SystemWindowManager* windowMgr = this->getInterface<cc::SystemWindowManager>();
CC_ASSERT_NOT_NULL(windowMgr);
auto systemWindow = windowMgr->getWindow(cc::ISystemWindow::mainWindowId);
CC_ASSERT_NOT_NULL(systemWindow);
systemWindow->setViewSize(width, height);
}
void OpenHarmonyPlatform::onSurfaceDestroyed(OH_NativeXComponent* component, void* window) {
cc::SystemWindowManager* windowMgr = this->getInterface<cc::SystemWindowManager>();
CC_ASSERT_NOT_NULL(windowMgr);
windowMgr->removeWindow(window);
}
void OpenHarmonyPlatform::onSurfaceHide() {
CC_LOG_INFO("OpenHarmonyPlatform::onSurfaceHide");
events::WindowDestroy::broadcast(ISystemWindow::mainWindowId);
}
void OpenHarmonyPlatform::onSurfaceShow(void* window) {
CC_LOG_INFO("OpenHarmonyPlatform::onSurfaceShow");
events::WindowRecreated::broadcast(ISystemWindow::mainWindowId);
}
void OpenHarmonyPlatform::dispatchMouseWheelCB(std::string eventType, float offsetY) {
if (isMouseLeftActive) {
return;
}
if (eventType == "actionUpdate") {
float moveScrollY = offsetY - scrollDistance;
scrollDistance = offsetY;
cc::MouseEvent* ev = new cc::MouseEvent;
ev->windowId = cc::ISystemWindow::mainWindowId;
ev->type = MouseEvent::Type::WHEEL;
ev->x = 0;
ev->y = moveScrollY;
sendMsgToWorker(MessageType::WM_XCOMPONENT_MOUSE_WHEEL_EVENT, reinterpret_cast<void*>(ev), nullptr);
} else {
scrollDistance = 0;
}
}
ISystemWindow* OpenHarmonyPlatform::createNativeWindow(uint32_t windowId, void* externalHandle) {
SystemWindow* window = ccnew SystemWindow(windowId, externalHandle);
uint64_t width = 0;
uint64_t height = 0;
CC_ASSERT_NOT_NULL(_component);
int32_t ret = OH_NativeXComponent_GetXComponentSize(_component, externalHandle, &width, &height);
CC_ASSERT(ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS);
window->setViewSize(width, height);
return window;
}
void OpenHarmonyPlatform::sendMsgToWorker(const cc::MessageType& type, void* data, void* window) {
cc::OpenHarmonyPlatform* platform = dynamic_cast<cc::OpenHarmonyPlatform*>(cc::BasePlatform::getPlatform());
CC_ASSERT(platform != nullptr);
cc::WorkerMessageData msg{type, static_cast<void*>(data), window};
platform->enqueue(msg);
}
void OpenHarmonyPlatform::sendMsgToWorkerAndWait(const cc::MessageType& type, void* data, void* window) {
cc::OpenHarmonyPlatform* platform = dynamic_cast<cc::OpenHarmonyPlatform*>(cc::BasePlatform::getPlatform());
CC_ASSERT(platform != nullptr);
cc::WorkerMessageData msg{type, static_cast<void*>(data), window};
platform->enqueueAndWait(msg);
}
}; // namespace cc