euv-cli 0.51.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
#include <EGL/egl.h>
#include <GLES3/gl3.h>
#include <ace/xcomponent/native_interface_xcomponent.h>
#include <ace/xcomponent/native_xcomponent_key_event.h>
#include <napi/native_api.h>
#include <native_vsync/native_vsync.h>
#include <native_window/external_window.h>

#include <atomic>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <string>

struct EuvHarmonyHost;

struct EuvHarmonyBatchRange {
    uint32_t base_instance;
    uint32_t instance_count;
    uint32_t scissor_x;
    uint32_t scissor_y;
    uint32_t scissor_w;
    uint32_t scissor_h;
    float scroll_x;
    float scroll_y;
    uint8_t layer_id;
    uint8_t has_blur;
    uint8_t pad[2];
};

struct EuvHarmonyDirectFrameDesc {
    uint32_t viewport_w;
    uint32_t viewport_h;
    float clear_rgba[4];
    const void *primitives_ptr;
    size_t primitives_len;
    const EuvHarmonyBatchRange *ranges_ptr;
    size_t ranges_len;
    const uint8_t *glyph_r8_ptr;
    uint32_t glyph_r8_w;
    uint32_t glyph_r8_h;
    uint64_t glyph_r8_rev;
    uint32_t glyph_r8_dirty_y;
    uint32_t glyph_r8_dirty_h;
    const uint8_t *image_rgba8_ptr;
    uint32_t image_rgba8_w;
    uint32_t image_rgba8_h;
    uint64_t image_rgba8_rev;
    uint32_t image_rgba8_dirty_y;
    uint32_t image_rgba8_dirty_h;
};

extern "C" {
EuvHarmonyHost *euv_harmony_host_create(const char *device_type, uint32_t phys_w, uint32_t phys_h, float density);
void euv_harmony_host_destroy(EuvHarmonyHost *ptr);
void euv_harmony_host_attach_surface(EuvHarmonyHost *ptr, void *native_window, void *xcomponent, uint32_t phys_w, uint32_t phys_h);
void euv_harmony_host_detach_surface(EuvHarmonyHost *ptr);
void euv_harmony_host_lifecycle(EuvHarmonyHost *ptr, int32_t hook_tag, const char *payload);
int32_t euv_harmony_host_back_press(EuvHarmonyHost *ptr);
void euv_harmony_host_resize(EuvHarmonyHost *ptr, uint32_t phys_w, uint32_t phys_h, float density);
void euv_harmony_host_set_avoid_area(EuvHarmonyHost *ptr, float top_vp, float right_vp, float bottom_vp, float left_vp, int32_t immersive);
void euv_harmony_host_config_update(EuvHarmonyHost *ptr, int32_t is_dark, const char *locale, float density, int32_t fold_tag);
void euv_harmony_host_memory_level(EuvHarmonyHost *ptr, int32_t level);
void euv_harmony_host_keyboard_height(EuvHarmonyHost *ptr, float height_vp);
void euv_harmony_host_text_input(EuvHarmonyHost *ptr, const char *text);
void euv_harmony_host_touch(EuvHarmonyHost *ptr, int32_t touch_type, int32_t pointer_id, float phys_x, float phys_y);
void euv_harmony_host_mouse(EuvHarmonyHost *ptr, int32_t action, int32_t button, float phys_x, float phys_y);
void euv_harmony_host_scroll(EuvHarmonyHost *ptr, float dx, float dy);
void euv_harmony_host_key(EuvHarmonyHost *ptr, int32_t key_code, int32_t is_down, int32_t shift, int32_t ctrl, int32_t alt, int32_t meta, int32_t repeat);
void euv_harmony_host_crown(EuvHarmonyHost *ptr, float delta);
void euv_harmony_host_window_mode(EuvHarmonyHost *ptr, int32_t mode_tag);
void euv_harmony_host_network(EuvHarmonyHost *ptr, int32_t status_tag);
void euv_harmony_host_device_motion(
    EuvHarmonyHost *ptr,
    float gx, float gy, float gz,
    float lx, float ly, float lz,
    float wx, float wy, float wz,
    uint64_t timestamp_ns);
const char *euv_harmony_host_gles3_ui_vs(EuvHarmonyHost *ptr);
const char *euv_harmony_host_gles3_ui_fs(EuvHarmonyHost *ptr);
int32_t euv_harmony_host_needs_frame(EuvHarmonyHost *ptr);
int32_t euv_harmony_host_has_pending_commands(EuvHarmonyHost *ptr);
int32_t euv_harmony_host_step_direct_gpu(EuvHarmonyHost *ptr, float dt_sec, EuvHarmonyDirectFrameDesc *out_desc);
int32_t euv_harmony_host_render_rgba(
    EuvHarmonyHost *ptr,
    float dt_sec,
    const uint8_t **out_pixels,
    uint32_t *out_w,
    uint32_t *out_h,
    uint32_t *out_dx,
    uint32_t *out_dy,
    uint32_t *out_dw,
    uint32_t *out_dh);
int32_t euv_harmony_host_step_frame(EuvHarmonyHost *ptr, float dt_sec);
const char *euv_harmony_host_drain_commands_json(EuvHarmonyHost *ptr);
int32_t euv_harmony_host_is_paused(EuvHarmonyHost *ptr);
}

namespace {

struct HarmonyEglState {
    EGLDisplay display = EGL_NO_DISPLAY;
    EGLContext context = EGL_NO_CONTEXT;
    EGLSurface surface = EGL_NO_SURFACE;
    GLuint program = 0;
    GLuint vao = 0;
    GLuint texture = 0;
    uint32_t tex_w = 0;
    uint32_t tex_h = 0;
    GLuint direct_program = 0;
    GLuint direct_vao = 0;
    GLuint quad_vbo = 0;
    GLuint instance_vbo = 0;
    size_t instance_vbo_cap = 0;
    GLint direct_viewport_loc = -1;
    GLint direct_scroll_loc = -1;
    GLuint glyph_r8_tex = 0;
    uint32_t glyph_r8_w = 0;
    uint32_t glyph_r8_h = 0;
    GLuint glyph_rgba8_tex = 0;
    GLuint image_tex = 0;
    uint32_t image_w = 0;
    uint32_t image_h = 0;
    GLuint external_tex = 0;
    bool direct_ready = false;
    bool ready = false;
};

static std::mutex g_host_mutex;
static EuvHarmonyHost *g_active_host = nullptr;
static void *g_active_window = nullptr;
static OH_NativeXComponent *g_active_xcomponent = nullptr;
static OH_NativeVSync *g_vsync = nullptr;
static std::atomic<bool> g_vsync_armed{false};
static int64_t g_last_vsync_ns = 0;
static HarmonyEglState g_egl;
static napi_threadsafe_function g_cmd_tsfn = nullptr;

static void callCommandHandlerJs(napi_env env, napi_value js_cb, void * /*ctx*/, void * /*data*/) {
    if (env == nullptr || js_cb == nullptr) return;
    napi_value undef = nullptr;
    napi_get_undefined(env, &undef);
    napi_call_function(env, undef, js_cb, 0, nullptr, nullptr);
}

static void notifyPendingCommandsLocked() {
    if (g_cmd_tsfn == nullptr || g_active_host == nullptr) return;
    if (euv_harmony_host_has_pending_commands(g_active_host) != 0) {
        napi_call_threadsafe_function(g_cmd_tsfn, nullptr, napi_tsfn_nonblocking);
    }
}

static const char *kBlitVs =
    "#version 300 es\n"
    "out vec2 v_uv;\n"
    "void main() {\n"
    "  vec2 p = vec2((gl_VertexID == 1) ? 3.0 : -1.0, (gl_VertexID == 2) ? -3.0 : 1.0);\n"
    "  v_uv = vec2(p.x * 0.5 + 0.5, 0.5 - p.y * 0.5);\n"
    "  gl_Position = vec4(p, 0.0, 1.0);\n"
    "}\n";

static const char *kBlitFs =
    "#version 300 es\n"
    "precision mediump float;\n"
    "in vec2 v_uv;\n"
    "uniform sampler2D u_tex;\n"
    "out vec4 o_color;\n"
    "void main() {\n"
    "  o_color = texture(u_tex, v_uv);\n"
    "}\n";

static GLuint compileShader(GLenum type, const char *src) {
    GLuint shader = glCreateShader(type);
    glShaderSource(shader, 1, &src, nullptr);
    glCompileShader(shader);
    GLint ok = 0;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
    if (!ok) {
        glDeleteShader(shader);
        return 0;
    }
    return shader;
}

static GLuint createImmutableTex(GLenum internal_fmt, GLenum fmt, uint32_t w, uint32_t h, const uint8_t *init_pixels) {
    GLuint tex = 0;
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexStorage2D(GL_TEXTURE_2D, 1, internal_fmt, static_cast<GLsizei>(w), static_cast<GLsizei>(h));
    if (init_pixels != nullptr) {
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), fmt, GL_UNSIGNED_BYTE, init_pixels);
    }
    return tex;
}

static void bindInstanceAttribsAt(GLuint instance_vbo, size_t base_bytes) {
    glBindBuffer(GL_ARRAY_BUFFER, instance_vbo);
    const GLsizei stride = 64;
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<const void *>(base_bytes + 0));
    glVertexAttribDivisor(1, 1);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<const void *>(base_bytes + 16));
    glVertexAttribDivisor(2, 1);
    glEnableVertexAttribArray(3);
    glVertexAttribIPointer(3, 4, GL_UNSIGNED_INT, stride, reinterpret_cast<const void *>(base_bytes + 32));
    glVertexAttribDivisor(3, 1);
    glEnableVertexAttribArray(4);
    glVertexAttribPointer(4, 2, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<const void *>(base_bytes + 48));
    glVertexAttribDivisor(4, 1);
    glEnableVertexAttribArray(5);
    glVertexAttribPointer(5, 2, GL_FLOAT, GL_FALSE, stride, reinterpret_cast<const void *>(base_bytes + 56));
    glVertexAttribDivisor(5, 1);
}

static void ensureDirectPipelineLocked(EuvHarmonyHost *host) {
    if (!g_egl.ready || g_egl.direct_ready || host == nullptr) return;
    const char *vs_src = euv_harmony_host_gles3_ui_vs(host);
    const char *fs_src = euv_harmony_host_gles3_ui_fs(host);
    if (!vs_src || !fs_src || vs_src[0] == '\0' || fs_src[0] == '\0') return;
    if (!eglMakeCurrent(g_egl.display, g_egl.surface, g_egl.surface, g_egl.context)) return;
    GLuint vs = compileShader(GL_VERTEX_SHADER, vs_src);
    GLuint fs = compileShader(GL_FRAGMENT_SHADER, fs_src);
    if (!vs || !fs) {
        if (vs) glDeleteShader(vs);
        if (fs) glDeleteShader(fs);
        return;
    }
    GLuint prog = glCreateProgram();
    glAttachShader(prog, vs);
    glAttachShader(prog, fs);
    glLinkProgram(prog);
    glDeleteShader(vs);
    glDeleteShader(fs);
    GLint linked = 0;
    glGetProgramiv(prog, GL_LINK_STATUS, &linked);
    if (!linked) {
        glDeleteProgram(prog);
        return;
    }
    glUseProgram(prog);
    GLint vp_loc = glGetUniformLocation(prog, "u_viewport");
    GLint sc_loc = glGetUniformLocation(prog, "u_scroll_offset");
    GLint u0 = glGetUniformLocation(prog, "u_glyph_r8");
    GLint u1 = glGetUniformLocation(prog, "u_glyph_rgba8");
    GLint u2 = glGetUniformLocation(prog, "u_image_tex");
    GLint u3 = glGetUniformLocation(prog, "u_external_tex");
    if (u0 >= 0) glUniform1i(u0, 0);
    if (u1 >= 0) glUniform1i(u1, 1);
    if (u2 >= 0) glUniform1i(u2, 2);
    if (u3 >= 0) glUniform1i(u3, 3);
    GLuint dvao = 0, qvbo = 0, ivbo = 0;
    glGenVertexArrays(1, &dvao);
    glBindVertexArray(dvao);
    glGenBuffers(1, &qvbo);
    const float corners[12] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f };
    glBindBuffer(GL_ARRAY_BUFFER, qvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(corners), corners, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 8, nullptr);
    glVertexAttribDivisor(0, 0);
    glGenBuffers(1, &ivbo);
    bindInstanceAttribsAt(ivbo, 0);
    const uint8_t white[4] = { 255, 255, 255, 255 };
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    g_egl.direct_program = prog;
    g_egl.direct_vao = dvao;
    g_egl.quad_vbo = qvbo;
    g_egl.instance_vbo = ivbo;
    g_egl.instance_vbo_cap = 0;
    g_egl.direct_viewport_loc = vp_loc;
    g_egl.direct_scroll_loc = sc_loc;
    g_egl.glyph_r8_tex = createImmutableTex(GL_R8, GL_RED, 1, 1, white);
    g_egl.glyph_r8_w = 1;
    g_egl.glyph_r8_h = 1;
    g_egl.glyph_rgba8_tex = createImmutableTex(GL_RGBA8, GL_RGBA, 1, 1, white);
    g_egl.image_tex = createImmutableTex(GL_RGBA8, GL_RGBA, 1, 1, white);
    g_egl.image_w = 1;
    g_egl.image_h = 1;
    g_egl.external_tex = createImmutableTex(GL_RGBA8, GL_RGBA, 1, 1, white);
    g_egl.direct_ready = true;
}

static void destroyEglLocked() {
    if (g_egl.display != EGL_NO_DISPLAY) {
        eglMakeCurrent(g_egl.display, g_egl.surface, g_egl.surface, g_egl.context);
        if (g_egl.texture) glDeleteTextures(1, &g_egl.texture);
        if (g_egl.glyph_r8_tex) glDeleteTextures(1, &g_egl.glyph_r8_tex);
        if (g_egl.glyph_rgba8_tex) glDeleteTextures(1, &g_egl.glyph_rgba8_tex);
        if (g_egl.image_tex) glDeleteTextures(1, &g_egl.image_tex);
        if (g_egl.external_tex) glDeleteTextures(1, &g_egl.external_tex);
        if (g_egl.quad_vbo) glDeleteBuffers(1, &g_egl.quad_vbo);
        if (g_egl.instance_vbo) glDeleteBuffers(1, &g_egl.instance_vbo);
        if (g_egl.vao) glDeleteVertexArrays(1, &g_egl.vao);
        if (g_egl.direct_vao) glDeleteVertexArrays(1, &g_egl.direct_vao);
        if (g_egl.program) glDeleteProgram(g_egl.program);
        if (g_egl.direct_program) glDeleteProgram(g_egl.direct_program);
        eglMakeCurrent(g_egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        if (g_egl.surface != EGL_NO_SURFACE) eglDestroySurface(g_egl.display, g_egl.surface);
        if (g_egl.context != EGL_NO_CONTEXT) eglDestroyContext(g_egl.display, g_egl.context);
        eglTerminate(g_egl.display);
    }
    g_egl = HarmonyEglState{};
}

static bool initEglLocked(void *native_window) {
    destroyEglLocked();
    if (!native_window) return false;
    EGLDisplay dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    if (dpy == EGL_NO_DISPLAY || !eglInitialize(dpy, nullptr, nullptr)) return false;
    const EGLint cfg_attribs[] = {
        EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
        EGL_RED_SIZE, 8,
        EGL_GREEN_SIZE, 8,
        EGL_BLUE_SIZE, 8,
        EGL_ALPHA_SIZE, 8,
        EGL_NONE
    };
    EGLConfig cfg = nullptr;
    EGLint count = 0;
    if (!eglChooseConfig(dpy, cfg_attribs, &cfg, 1, &count) || count < 1) {
        eglTerminate(dpy);
        return false;
    }
    const EGLint ctx_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
    EGLContext ctx = eglCreateContext(dpy, cfg, EGL_NO_CONTEXT, ctx_attribs);
    EGLSurface surf = eglCreateWindowSurface(dpy, cfg, reinterpret_cast<EGLNativeWindowType>(native_window), nullptr);
    if (ctx == EGL_NO_CONTEXT || surf == EGL_NO_SURFACE || !eglMakeCurrent(dpy, surf, surf, ctx)) {
        if (surf != EGL_NO_SURFACE) eglDestroySurface(dpy, surf);
        if (ctx != EGL_NO_CONTEXT) eglDestroyContext(dpy, ctx);
        eglTerminate(dpy);
        return false;
    }
    eglSwapInterval(dpy, 1);
    GLuint vs = compileShader(GL_VERTEX_SHADER, kBlitVs);
    GLuint fs = compileShader(GL_FRAGMENT_SHADER, kBlitFs);
    GLuint prog = glCreateProgram();
    glAttachShader(prog, vs);
    glAttachShader(prog, fs);
    glLinkProgram(prog);
    glDeleteShader(vs);
    glDeleteShader(fs);
    GLint linked = 0;
    glGetProgramiv(prog, GL_LINK_STATUS, &linked);
    if (!linked) {
        glDeleteProgram(prog);
        eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        eglDestroySurface(dpy, surf);
        eglDestroyContext(dpy, ctx);
        eglTerminate(dpy);
        return false;
    }
    GLuint vao = 0;
    GLuint tex = 0;
    glGenVertexArrays(1, &vao);
    glGenTextures(1, &tex);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    g_egl.display = dpy;
    g_egl.context = ctx;
    g_egl.surface = surf;
    g_egl.program = prog;
    g_egl.vao = vao;
    g_egl.texture = tex;
    g_egl.ready = true;
    return true;
}

static bool presentDirectGpuLocked(const EuvHarmonyDirectFrameDesc &desc) {
    if (!g_egl.ready || !g_egl.direct_ready || desc.viewport_w == 0 || desc.viewport_h == 0) return false;
    if (!eglMakeCurrent(g_egl.display, g_egl.surface, g_egl.surface, g_egl.context)) return false;
    if (desc.glyph_r8_ptr != nullptr && desc.glyph_r8_w > 0 && desc.glyph_r8_h > 0) {
        bool resized = (g_egl.glyph_r8_w != desc.glyph_r8_w || g_egl.glyph_r8_h != desc.glyph_r8_h);
        glActiveTexture(GL_TEXTURE0);
        if (resized) {
            if (g_egl.glyph_r8_tex) glDeleteTextures(1, &g_egl.glyph_r8_tex);
            g_egl.glyph_r8_tex = createImmutableTex(GL_R8, GL_RED, desc.glyph_r8_w, desc.glyph_r8_h, nullptr);
            g_egl.glyph_r8_w = desc.glyph_r8_w;
            g_egl.glyph_r8_h = desc.glyph_r8_h;
        } else {
            glBindTexture(GL_TEXTURE_2D, g_egl.glyph_r8_tex);
        }
        uint32_t dy = resized ? 0u : desc.glyph_r8_dirty_y;
        uint32_t dh = resized ? desc.glyph_r8_h : desc.glyph_r8_dirty_h;
        if (dh > 0 && dy < desc.glyph_r8_h) {
            if (dy + dh > desc.glyph_r8_h) dh = desc.glyph_r8_h - dy;
            glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
            glTexSubImage2D(
                GL_TEXTURE_2D, 0, 0, static_cast<GLint>(dy),
                static_cast<GLsizei>(desc.glyph_r8_w), static_cast<GLsizei>(dh),
                GL_RED, GL_UNSIGNED_BYTE,
                desc.glyph_r8_ptr + static_cast<size_t>(dy) * static_cast<size_t>(desc.glyph_r8_w));
        }
    }
    if (desc.image_rgba8_ptr != nullptr && desc.image_rgba8_w > 0 && desc.image_rgba8_h > 0) {
        bool resized = (g_egl.image_w != desc.image_rgba8_w || g_egl.image_h != desc.image_rgba8_h);
        glActiveTexture(GL_TEXTURE2);
        if (resized) {
            if (g_egl.image_tex) glDeleteTextures(1, &g_egl.image_tex);
            g_egl.image_tex = createImmutableTex(GL_RGBA8, GL_RGBA, desc.image_rgba8_w, desc.image_rgba8_h, nullptr);
            g_egl.image_w = desc.image_rgba8_w;
            g_egl.image_h = desc.image_rgba8_h;
        } else {
            glBindTexture(GL_TEXTURE_2D, g_egl.image_tex);
        }
        uint32_t dy = resized ? 0u : desc.image_rgba8_dirty_y;
        uint32_t dh = resized ? desc.image_rgba8_h : desc.image_rgba8_dirty_h;
        if (dh > 0 && dy < desc.image_rgba8_h) {
            if (dy + dh > desc.image_rgba8_h) dh = desc.image_rgba8_h - dy;
            glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
            glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
            glTexSubImage2D(
                GL_TEXTURE_2D, 0, 0, static_cast<GLint>(dy),
                static_cast<GLsizei>(desc.image_rgba8_w), static_cast<GLsizei>(dh),
                GL_RGBA, GL_UNSIGNED_BYTE,
                desc.image_rgba8_ptr + static_cast<size_t>(dy) * static_cast<size_t>(desc.image_rgba8_w) * 4u);
        }
    }
    size_t byte_len = desc.primitives_len * 64u;
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport(0, 0, static_cast<GLsizei>(desc.viewport_w), static_cast<GLsizei>(desc.viewport_h));
    glDisable(GL_SCISSOR_TEST);
    glClearColor(desc.clear_rgba[0], desc.clear_rgba[1], desc.clear_rgba[2], desc.clear_rgba[3]);
    glClear(GL_COLOR_BUFFER_BIT);
    if (byte_len > 0 && desc.primitives_ptr != nullptr && desc.ranges_ptr != nullptr && desc.ranges_len > 0) {
        glBindBuffer(GL_ARRAY_BUFFER, g_egl.instance_vbo);
        if (byte_len > g_egl.instance_vbo_cap) {
            size_t cap = byte_len < 4096u ? 4096u : byte_len;
            if (g_egl.instance_vbo_cap * 2u > cap) cap = g_egl.instance_vbo_cap * 2u;
            glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(cap), nullptr, GL_STREAM_DRAW);
            g_egl.instance_vbo_cap = cap;
        }
        glBufferSubData(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(byte_len), desc.primitives_ptr);
        glEnable(GL_BLEND);
        glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
        glEnable(GL_SCISSOR_TEST);
        glUseProgram(g_egl.direct_program);
        if (g_egl.direct_viewport_loc >= 0) {
            glUniform2f(g_egl.direct_viewport_loc, static_cast<float>(desc.viewport_w), static_cast<float>(desc.viewport_h));
        }
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, g_egl.glyph_r8_tex);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, g_egl.glyph_rgba8_tex);
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, g_egl.image_tex);
        glActiveTexture(GL_TEXTURE3);
        glBindTexture(GL_TEXTURE_2D, g_egl.external_tex);
        glBindVertexArray(g_egl.direct_vao);
        for (size_t i = 0; i < desc.ranges_len; ++i) {
            const EuvHarmonyBatchRange &r = desc.ranges_ptr[i];
            if (r.instance_count == 0 || r.base_instance >= desc.primitives_len) continue;
            size_t draw_count = r.instance_count;
            if (r.base_instance + draw_count > desc.primitives_len) {
                draw_count = desc.primitives_len - r.base_instance;
            }
            GLint sy = static_cast<GLint>(desc.viewport_h) - static_cast<GLint>(r.scissor_y + r.scissor_h);
            if (sy < 0) sy = 0;
            glScissor(static_cast<GLint>(r.scissor_x), sy, static_cast<GLsizei>(r.scissor_w), static_cast<GLsizei>(r.scissor_h));
            if (g_egl.direct_scroll_loc >= 0) {
                glUniform2f(g_egl.direct_scroll_loc, r.scroll_x, r.scroll_y);
            }
            bindInstanceAttribsAt(g_egl.instance_vbo, static_cast<size_t>(r.base_instance) * 64u);
            glDrawArraysInstanced(GL_TRIANGLES, 0, 6, static_cast<GLsizei>(draw_count));
        }
        glDisable(GL_SCISSOR_TEST);
        glDisable(GL_BLEND);
    }
    return eglSwapBuffers(g_egl.display, g_egl.surface) == EGL_TRUE;
}

static bool presentEglLocked(const uint8_t *pixels, uint32_t w, uint32_t h, uint32_t dx, uint32_t dy, uint32_t dw, uint32_t dh) {
    if (!g_egl.ready || !pixels || w == 0 || h == 0) return false;
    if (!eglMakeCurrent(g_egl.display, g_egl.surface, g_egl.surface, g_egl.context)) return false;
    glActiveTexture(GL_TEXTURE0);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    if (g_egl.tex_w != w || g_egl.tex_h != h) {
        if (g_egl.texture) glDeleteTextures(1, &g_egl.texture);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
        g_egl.texture = createImmutableTex(GL_RGBA8, GL_RGBA, w, h, pixels);
        g_egl.tex_w = w;
        g_egl.tex_h = h;
    } else if (dw > 0 && dh > 0 && dx + dw <= w && dy + dh <= h && !(dx == 0 && dy == 0 && dw == w && dh == h)) {
        glBindTexture(GL_TEXTURE_2D, g_egl.texture);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, static_cast<GLint>(w));
        const uint8_t *sub = pixels + (static_cast<size_t>(dy) * static_cast<size_t>(w) + static_cast<size_t>(dx)) * 4u;
        glTexSubImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(dx), static_cast<GLint>(dy), static_cast<GLsizei>(dw), static_cast<GLsizei>(dh), GL_RGBA, GL_UNSIGNED_BYTE, sub);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
    } else {
        glBindTexture(GL_TEXTURE_2D, g_egl.texture);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h), GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    }
    glViewport(0, 0, static_cast<GLsizei>(w), static_cast<GLsizei>(h));
    glUseProgram(g_egl.program);
    glBindVertexArray(g_egl.vao);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, g_egl.texture);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    return eglSwapBuffers(g_egl.display, g_egl.surface) == EGL_TRUE;
}

static void onVsyncCallback(long long timestamp_ns, void *data);

static void armVsyncLocked() {
    if (!g_vsync || g_vsync_armed.load() || !g_active_host || !g_active_window) return;
    if (euv_harmony_host_is_paused(g_active_host) != 0) return;
    g_vsync_armed.store(true);
    OH_NativeVSync_RequestFrame(g_vsync, onVsyncCallback, nullptr);
}

static void onVsyncCallback(long long timestamp_ns, void * /*data*/) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_vsync_armed.store(false);
    if (!g_active_host || !g_active_window || euv_harmony_host_is_paused(g_active_host) != 0) {
        g_last_vsync_ns = 0;
        return;
    }
    float dt = 1.0f / 60.0f;
    if (g_last_vsync_ns > 0 && timestamp_ns > g_last_vsync_ns) {
        dt = static_cast<float>(timestamp_ns - g_last_vsync_ns) / 1.0e9f;
        if (dt < 0.002f) dt = 0.002f;
        if (dt > 0.05f) dt = 0.05f;
    }
    g_last_vsync_ns = timestamp_ns;
    int32_t rendered = 0;
    if (g_egl.ready) {
        ensureDirectPipelineLocked(g_active_host);
        if (g_egl.direct_ready) {
            EuvHarmonyDirectFrameDesc desc{};
            rendered = euv_harmony_host_step_direct_gpu(g_active_host, dt, &desc);
            if (rendered > 0) {
                presentDirectGpuLocked(desc);
            }
        } else {
            const uint8_t *px = nullptr;
            uint32_t w = 0, h = 0, dx = 0, dy = 0, dw = 0, dh = 0;
            rendered = euv_harmony_host_render_rgba(g_active_host, dt, &px, &w, &h, &dx, &dy, &dw, &dh);
            if (rendered > 0 && px != nullptr) {
                presentEglLocked(px, w, h, dx, dy, dw, dh);
            }
        }
    } else {
        rendered = euv_harmony_host_step_frame(g_active_host, dt);
    }
    notifyPendingCommandsLocked();
    if (rendered > 0 || euv_harmony_host_needs_frame(g_active_host) != 0) {
        armVsyncLocked();
    } else {
        g_last_vsync_ns = 0;
    }
}

static void onSurfaceCreatedCB(OH_NativeXComponent *component, void *window) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_active_xcomponent = component;
    g_active_window = window;
    uint64_t w = 0, h = 0;
    OH_NativeXComponent_GetXComponentSize(component, window, &w, &h);
    initEglLocked(window);
    if (g_active_host) {
        euv_harmony_host_attach_surface(g_active_host, window, component, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
    }
    if (!g_vsync) {
        const char *name = "euv_harmony_vsync";
        g_vsync = OH_NativeVSync_Create(name, static_cast<unsigned int>(std::strlen(name)));
    }
    armVsyncLocked();
}

static void onSurfaceChangedCB(OH_NativeXComponent *component, void *window) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_active_window = window;
    uint64_t w = 0, h = 0;
    OH_NativeXComponent_GetXComponentSize(component, window, &w, &h);
    if (g_active_host) {
        euv_harmony_host_attach_surface(g_active_host, window, component, static_cast<uint32_t>(w), static_cast<uint32_t>(h));
    }
    armVsyncLocked();
}

static void onSurfaceDestroyedCB(OH_NativeXComponent * /*component*/, void * /*window*/) {
    std::lock_guard<std::mutex> lock(g_host_mutex);
    g_active_window = nullptr;
    destroyEglLocked();
    if (g_active_host) {
        euv_harmony_host_detach_surface(g_active_host);
    }
}

static void dispatchTouchEventCB(OH_NativeXComponent *component, void *window) {
    OH_NativeXComponent_TouchEvent ev{};
    if (OH_NativeXComponent_GetTouchEvent(component, window, &ev) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        return;
    }
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (!g_active_host) return;
    if (ev.numPoints > 0) {
        uint32_t count = ev.numPoints < OH_MAX_TOUCH_POINTS_NUMBER ? ev.numPoints : OH_MAX_TOUCH_POINTS_NUMBER;
        for (uint32_t i = 0; i < count; ++i) {
            const auto &pt = ev.touchPoints[i];
            euv_harmony_host_touch(g_active_host, static_cast<int32_t>(pt.type), pt.id, pt.x, pt.y);
        }
    } else {
        euv_harmony_host_touch(g_active_host, static_cast<int32_t>(ev.type), ev.id, ev.x, ev.y);
    }
    armVsyncLocked();
}

static void dispatchMouseEventCB(OH_NativeXComponent *component, void *window) {
    OH_NativeXComponent_MouseEvent ev{};
    if (OH_NativeXComponent_GetMouseEvent(component, window, &ev) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
        return;
    }
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (!g_active_host) return;
    euv_harmony_host_mouse(g_active_host, static_cast<int32_t>(ev.action), static_cast<int32_t>(ev.button), ev.x, ev.y);
    armVsyncLocked();
}

static void dispatchHoverEventCB(OH_NativeXComponent * /*component*/, bool /*isHover*/) {}

static void dispatchKeyEventCB(OH_NativeXComponent *component, void * /*window*/) {
    OH_NativeXComponent_KeyEvent *keyEvent = nullptr;
    if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) != OH_NATIVEXCOMPONENT_RESULT_SUCCESS || !keyEvent) {
        return;
    }
    OH_NativeXComponent_KeyAction action = OH_NATIVEXCOMPONENT_KEY_ACTION_UNKNOWN;
    OH_NativeXComponent_KeyCode code = KEY_UNKNOWN;
    OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
    OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (!g_active_host) return;
    bool is_down = (action == OH_NATIVEXCOMPONENT_KEY_ACTION_DOWN);
    euv_harmony_host_key(g_active_host, static_cast<int32_t>(code), is_down ? 1 : 0, 0, 0, 0, 0, 0);
    armVsyncLocked();
}

static OH_NativeXComponent_Callback g_xc_callbacks = {
    onSurfaceCreatedCB,
    onSurfaceChangedCB,
    onSurfaceDestroyedCB,
    dispatchTouchEventCB
};

static OH_NativeXComponent_MouseEvent_Callback g_mouse_callbacks = {
    dispatchMouseEventCB,
    dispatchHoverEventCB
};

static std::string getNapiString(napi_env env, napi_value val) {
    size_t len = 0;
    if (napi_get_value_string_utf8(env, val, nullptr, 0, &len) != napi_ok || len == 0) {
        return {};
    }
    std::string out(len, '\0');
    napi_get_value_string_utf8(env, val, out.data(), len + 1, &len);
    return out;
}

static EuvHarmonyHost *getHostFromArg(napi_env env, napi_value val) {
    int64_t raw = 0;
    if (napi_get_value_int64(env, val, &raw) != napi_ok || raw == 0) return nullptr;
    return reinterpret_cast<EuvHarmonyHost *>(static_cast<uintptr_t>(raw));
}

static napi_value napiCreate(napi_env env, napi_callback_info info) {
    size_t argc = 4;
    napi_value argv[4];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::string dev = argc >= 1 ? getNapiString(env, argv[0]) : "phone";
    uint32_t w = 1080, h = 2340;
    double d = 3.0;
    if (argc >= 2) napi_get_value_uint32(env, argv[1], &w);
    if (argc >= 3) napi_get_value_uint32(env, argv[2], &h);
    if (argc >= 4) napi_get_value_double(env, argv[3], &d);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = euv_harmony_host_create(dev.c_str(), w, h, static_cast<float>(d));
    g_active_host = host;
    if (host && g_active_window && g_active_xcomponent) {
        uint64_t sw = w, sh = h;
        OH_NativeXComponent_GetXComponentSize(g_active_xcomponent, g_active_window, &sw, &sh);
        euv_harmony_host_attach_surface(host, g_active_window, g_active_xcomponent, static_cast<uint32_t>(sw), static_cast<uint32_t>(sh));
        armVsyncLocked();
    }
    napi_value res = nullptr;
    napi_create_int64(env, static_cast<int64_t>(reinterpret_cast<uintptr_t>(host)), &res);
    return res;
}

static napi_value napiDestroy(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    if (host == g_active_host) g_active_host = nullptr;
    if (g_cmd_tsfn != nullptr) {
        napi_release_threadsafe_function(g_cmd_tsfn, napi_tsfn_abort);
        g_cmd_tsfn = nullptr;
    }
    if (g_vsync) {
        OH_NativeVSync_Destroy(g_vsync);
        g_vsync = nullptr;
    }
    destroyEglLocked();
    euv_harmony_host_destroy(host);
    return nullptr;
}

static napi_value napiOnLifecycle(napi_env env, napi_callback_info info) {
    size_t argc = 3;
    napi_value argv[3];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    std::string hook = argc >= 2 ? getNapiString(env, argv[1]) : "";
    std::string payload = argc >= 3 ? getNapiString(env, argv[2]) : "";
    int32_t tag = 0;
    if (hook == "onCreate") tag = 1;
    else if (hook == "onForeground") tag = 2;
    else if (hook == "onWindowActive") tag = 3;
    else if (hook == "onWindowInactive") tag = 4;
    else if (hook == "onBackground") tag = 5;
    else if (hook == "onWindowStageDestroy") tag = 6;
    else if (hook == "onDestroy") tag = 7;
    else if (hook == "onBackPress") tag = 8;
    else if (hook == "onNewWant") tag = 9;
    if (host && tag != 0) {
        euv_harmony_host_lifecycle(host, tag, payload.c_str());
        if (tag == 2 || tag == 3) armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiSetAvoidArea(napi_env env, napi_callback_info info) {
    size_t argc = 6;
    napi_value argv[6];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double top = 0, right = 0, bottom = 0, left = 0;
    bool imm = false;
    if (argc >= 2) napi_get_value_double(env, argv[1], &top);
    if (argc >= 3) napi_get_value_double(env, argv[2], &right);
    if (argc >= 4) napi_get_value_double(env, argv[3], &bottom);
    if (argc >= 5) napi_get_value_double(env, argv[4], &left);
    if (argc >= 6) napi_get_value_bool(env, argv[5], &imm);
    if (host) {
        euv_harmony_host_set_avoid_area(host, static_cast<float>(top), static_cast<float>(right), static_cast<float>(bottom), static_cast<float>(left), imm ? 1 : 0);
    }
    return nullptr;
}

static napi_value napiResize(napi_env env, napi_callback_info info) {
    size_t argc = 4;
    napi_value argv[4];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    uint32_t w = 1, h = 1;
    double d = 2.0;
    if (argc >= 2) napi_get_value_uint32(env, argv[1], &w);
    if (argc >= 3) napi_get_value_uint32(env, argv[2], &h);
    if (argc >= 4) napi_get_value_double(env, argv[3], &d);
    if (host) {
        euv_harmony_host_resize(host, w, h, static_cast<float>(d));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnMemoryLevel(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t lvl = 0;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &lvl);
    if (host) euv_harmony_host_memory_level(host, lvl);
    return nullptr;
}

static napi_value napiOnConfigUpdate(napi_env env, napi_callback_info info) {
    size_t argc = 5;
    napi_value argv[5];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    bool is_dark = false;
    std::string locale = argc >= 3 ? getNapiString(env, argv[2]) : "en-US";
    double d = 2.0;
    int32_t fold = 0;
    if (argc >= 2) napi_get_value_bool(env, argv[1], &is_dark);
    if (argc >= 4) napi_get_value_double(env, argv[3], &d);
    if (argc >= 5) napi_get_value_int32(env, argv[4], &fold);
    if (host) {
        euv_harmony_host_config_update(host, is_dark ? 1 : 0, locale.c_str(), static_cast<float>(d), fold);
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnKeyboardHeight(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double h = 0.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &h);
    if (host) euv_harmony_host_keyboard_height(host, static_cast<float>(h));
    return nullptr;
}

static napi_value napiTextInput(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    std::string text = argc >= 2 ? getNapiString(env, argv[1]) : "";
    if (host && !text.empty()) {
        euv_harmony_host_text_input(host, text.c_str());
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiBackPress(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    bool handled = host ? (euv_harmony_host_back_press(host) != 0) : false;
    napi_value res = nullptr;
    napi_get_boolean(env, handled, &res);
    return res;
}

static napi_value napiOnDeviceMotion(napi_env env, napi_callback_info info) {
    size_t argc = 11;
    napi_value argv[11];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double v[9] = {0};
    int64_t ts = 0;
    for (size_t i = 0; i < 9 && (i + 1) < argc; ++i) napi_get_value_double(env, argv[i + 1], &v[i]);
    if (argc >= 11) napi_get_value_int64(env, argv[10], &ts);
    if (host) {
        euv_harmony_host_device_motion(
            host,
            static_cast<float>(v[0]), static_cast<float>(v[1]), static_cast<float>(v[2]),
            static_cast<float>(v[3]), static_cast<float>(v[4]), static_cast<float>(v[5]),
            static_cast<float>(v[6]), static_cast<float>(v[7]), static_cast<float>(v[8]),
            static_cast<uint64_t>(ts > 0 ? ts : 0));
    }
    return nullptr;
}

static napi_value napiOnMouse(napi_env env, napi_callback_info info) {
    size_t argc = 5;
    napi_value argv[5];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t action = 3, button = 0;
    double x = 0.0, y = 0.0;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &action);
    if (argc >= 3) napi_get_value_int32(env, argv[2], &button);
    if (argc >= 4) napi_get_value_double(env, argv[3], &x);
    if (argc >= 5) napi_get_value_double(env, argv[4], &y);
    if (host) {
        euv_harmony_host_mouse(host, action, button, static_cast<float>(x), static_cast<float>(y));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnScroll(napi_env env, napi_callback_info info) {
    size_t argc = 3;
    napi_value argv[3];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double dx = 0.0, dy = 0.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &dx);
    if (argc >= 3) napi_get_value_double(env, argv[2], &dy);
    if (host) {
        euv_harmony_host_scroll(host, static_cast<float>(dx), static_cast<float>(dy));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnKey(napi_env env, napi_callback_info info) {
    size_t argc = 8;
    napi_value argv[8];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t code = 0;
    bool down = false, sh = false, ct = false, al = false, mt = false, rp = false;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &code);
    if (argc >= 3) napi_get_value_bool(env, argv[2], &down);
    if (argc >= 4) napi_get_value_bool(env, argv[3], &sh);
    if (argc >= 5) napi_get_value_bool(env, argv[4], &ct);
    if (argc >= 6) napi_get_value_bool(env, argv[5], &al);
    if (argc >= 7) napi_get_value_bool(env, argv[6], &mt);
    if (argc >= 8) napi_get_value_bool(env, argv[7], &rp);
    if (host) {
        euv_harmony_host_key(host, code, down ? 1 : 0, sh ? 1 : 0, ct ? 1 : 0, al ? 1 : 0, mt ? 1 : 0, rp ? 1 : 0);
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnCrown(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double delta = 0.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &delta);
    if (host) {
        euv_harmony_host_crown(host, static_cast<float>(delta));
        armVsyncLocked();
    }
    return nullptr;
}

static napi_value napiOnWindowMode(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t mode = 0;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &mode);
    if (host) euv_harmony_host_window_mode(host, mode);
    return nullptr;
}

static napi_value napiOnNetwork(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    int32_t st = 1;
    if (argc >= 2) napi_get_value_int32(env, argv[1], &st);
    if (host) euv_harmony_host_network(host, st);
    return nullptr;
}

static napi_value napiDrainHostCommands(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    const char *json = host ? euv_harmony_host_drain_commands_json(host) : "[]";
    napi_value res = nullptr;
    napi_create_string_utf8(env, json ? json : "[]", NAPI_AUTO_LENGTH, &res);
    return res;
}

static napi_value napiSetCommandHandler(napi_env env, napi_callback_info info) {
    size_t argc = 1;
    napi_value argv[1];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    if (g_cmd_tsfn != nullptr) {
        napi_release_threadsafe_function(g_cmd_tsfn, napi_tsfn_abort);
        g_cmd_tsfn = nullptr;
    }
    if (argc >= 1) {
        napi_valuetype vtype = napi_undefined;
        napi_typeof(env, argv[0], &vtype);
        if (vtype == napi_function) {
            napi_value res_name = nullptr;
            napi_create_string_utf8(env, "euvHarmonyCmd", NAPI_AUTO_LENGTH, &res_name);
            napi_create_threadsafe_function(
                env, argv[0], nullptr, res_name, 0, 1, nullptr, nullptr, nullptr, callCommandHandlerJs, &g_cmd_tsfn);
            notifyPendingCommandsLocked();
        }
    }
    return nullptr;
}

static napi_value napiStepFrame(napi_env env, napi_callback_info info) {
    size_t argc = 2;
    napi_value argv[2];
    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
    std::lock_guard<std::mutex> lock(g_host_mutex);
    EuvHarmonyHost *host = argc >= 1 ? getHostFromArg(env, argv[0]) : nullptr;
    double dt = 1.0 / 60.0;
    if (argc >= 2) napi_get_value_double(env, argv[1], &dt);
    int32_t rc = 0;
    if (host) {
        if (g_egl.ready) {
            ensureDirectPipelineLocked(host);
            if (g_egl.direct_ready) {
                EuvHarmonyDirectFrameDesc desc{};
                rc = euv_harmony_host_step_direct_gpu(host, static_cast<float>(dt), &desc);
                if (rc > 0) presentDirectGpuLocked(desc);
            } else {
                const uint8_t *px = nullptr;
                uint32_t w = 0, h = 0, dx = 0, dy = 0, dw = 0, dh = 0;
                rc = euv_harmony_host_render_rgba(host, static_cast<float>(dt), &px, &w, &h, &dx, &dy, &dw, &dh);
                if (rc > 0 && px != nullptr) presentEglLocked(px, w, h, dx, dy, dw, dh);
            }
        } else {
            rc = euv_harmony_host_step_frame(host, static_cast<float>(dt));
        }
        notifyPendingCommandsLocked();
    }
    napi_value res = nullptr;
    napi_create_int32(env, rc, &res);
    return res;
}

static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        { "euvHarmonyCreate", nullptr, napiCreate, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyDestroy", nullptr, napiDestroy, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnLifecycle", nullptr, napiOnLifecycle, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonySetAvoidArea", nullptr, napiSetAvoidArea, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyResize", nullptr, napiResize, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnMemoryLevel", nullptr, napiOnMemoryLevel, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnConfigUpdate", nullptr, napiOnConfigUpdate, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnKeyboardHeight", nullptr, napiOnKeyboardHeight, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyTextInput", nullptr, napiTextInput, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyBackPress", nullptr, napiBackPress, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnDeviceMotion", nullptr, napiOnDeviceMotion, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnMouse", nullptr, napiOnMouse, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnScroll", nullptr, napiOnScroll, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnKey", nullptr, napiOnKey, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnCrown", nullptr, napiOnCrown, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnWindowMode", nullptr, napiOnWindowMode, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyOnNetwork", nullptr, napiOnNetwork, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyDrainHostCommands", nullptr, napiDrainHostCommands, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonySetCommandHandler", nullptr, napiSetCommandHandler, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "euvHarmonyStepFrame", nullptr, napiStepFrame, nullptr, nullptr, nullptr, napi_default, nullptr },
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);

    napi_value xc_val = nullptr;
    if (napi_get_named_property(env, exports, OH_NATIVE_XCOMPONENT_OBJ, &xc_val) == napi_ok && xc_val != nullptr) {
        OH_NativeXComponent *xc = nullptr;
        if (napi_unwrap(env, xc_val, reinterpret_cast<void **>(&xc)) == napi_ok && xc != nullptr) {
            OH_NativeXComponent_RegisterCallback(xc, &g_xc_callbacks);
            OH_NativeXComponent_RegisterMouseEventCallback(xc, &g_mouse_callbacks);
            OH_NativeXComponent_RegisterKeyEventCallback(xc, dispatchKeyEventCB);
        }
    }
    return exports;
}

static napi_module g_euv_harmony_module = {
    1,
    0,
    nullptr,
    Init,
    "euv_harmony_host",
    nullptr,
    { nullptr },
};

} // namespace

extern "C" __attribute__((constructor)) void RegisterEuvHarmonyHostModule(void) {
    napi_module_register(&g_euv_harmony_module);
}