famiq 0.3.1

Experimental GUI library, powered by Bevy engine.
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
use bevy::prelude::*;
use super::*;

#[cfg(target_arch = "wasm32")]
pub struct WasmPaste {
    text: String,
    entity: Entity,
}

/// Async channel for receiving from the clipboard in Wasm
#[cfg(target_arch = "wasm32")]
#[derive(Resource, Clone)]
pub struct WasmPasteAsyncChannel {
    pub tx: crossbeam_channel::Sender<WasmPaste>,
    pub rx: crossbeam_channel::Receiver<WasmPaste>,
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn write_clipboard_wasm(text: &str) {
    let clipboard = web_sys::window().unwrap().navigator().clipboard();
    let _result = clipboard.write_text(text);
}

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
pub fn read_clipboard_wasm() -> Promise {
    let clipboard = web_sys::window().unwrap().navigator().clipboard();
    clipboard.read_text()
}

pub(crate) fn on_mouse_over(
    mut trigger: Trigger<Pointer<Over>>,
    mut input_q: Query<
        (&mut BoxShadow, &BorderColor, Option<&WidgetId>, &GlobalTransform, Option<&TooltipEntity>),
        With<IsFamiqTextInput>
    >,
    mut param: InputPickingParam
) {
    if let Ok((mut box_shadow, border_color, id, transform, tooltip_entity)) = input_q.get_mut(trigger.target()) {
        box_shadow.0[0].color = border_color.0.clone();
        show_tooltip(tooltip_entity, &mut param.tooltip_q, transform.translation());
        _change_cursor_icon(&mut param.commands, &param.cursor_icons, *param.window, CursorType::Text);
        FaMouseEvent::send_event(
            &mut param.mouse_writer,
            EventType::Over,
            WidgetType::TextInput,
            trigger.target(),
            id
        );
    }
    trigger.propagate(false);
}

pub(crate) fn on_mouse_out(
    mut trigger: Trigger<Pointer<Out>>,
    mut input_q: Query<
        (&mut BoxShadow, Option<&WidgetId>, Option<&TooltipEntity>),
        With<IsFamiqTextInput>
    >,
    mut param: InputPickingParam
) {
    if let Ok((mut box_shadow, id, tooltip_entity)) = input_q.get_mut(trigger.target()) {
        box_shadow.0[0].color = Color::NONE;
        hide_tooltip(tooltip_entity, &mut param.tooltip_q);
        _change_cursor_icon(&mut param.commands, &param.cursor_icons, *param.window, CursorType::Default);
        FaMouseEvent::send_event(
            &mut param.mouse_writer,
            EventType::Out,
            WidgetType::TextInput,
            trigger.target(),
            id
        );
    }
    trigger.propagate(false);
}

pub(crate) fn on_mouse_down(
    mut trigger: Trigger<Pointer<Pressed>>,
    mut input_q: Query<(Option<&WidgetId>, &mut FaTextEdit, &mut CosmicData), With<IsFamiqTextInput>>,
    mut famiq_res: ResMut<FamiqResource>,
    mut writer: EventWriter<FaMouseEvent>,
) {
    if let Ok((id, mut text_edit, mut cosmic_data)) = input_q.get_mut(trigger.target()) {
        famiq_res.update_all_focus_states(false);
        famiq_res.update_or_insert_focus_state(trigger.target(), true);

        if let Some(editor) = cosmic_data.editor.as_mut() {
            editor.set_selection(Selection::None);
            text_edit.clear_selection();
        }
        if trigger.event().button == PointerButton::Secondary {
            FaMouseEvent::send_event(&mut writer, EventType::DownRight, WidgetType::TextInput, trigger.target(), id);
        } else {
            FaMouseEvent::send_event(&mut writer, EventType::DownLeft, WidgetType::TextInput, trigger.target(), id);
        }
    }
    trigger.propagate(false);
}

pub(crate) fn on_mouse_up(
    mut trigger: Trigger<Pointer<Released>>,
    mut input_q: Query<Option<&WidgetId>, With<IsFamiqTextInput>>,
    mut writer: EventWriter<FaMouseEvent>,
) {
    if let Ok(id) = input_q.get_mut(trigger.target()) {
        FaMouseEvent::send_event(
            &mut writer,
            EventType::Up,
            WidgetType::TextInput,
            trigger.target(),
            id
        );
    }
    trigger.propagate(false);
}

pub fn handle_cursor_blink_system(
    mut input_q: Query<
        (Entity, &mut CursorBlinkTimer, &mut CosmicDataColor),
        With<IsFamiqTextInput>
    >,
    mut request_redraw_buffer: EventWriter<RequestRedrawBuffer>,
    famiq_res: Res<FamiqResource>,
    time: Res<Time>,
) {
    input_q.iter_mut().for_each(|(entity, mut blink_timer, mut cosmic_color)| {
        let need_redraw;
        let is_focused = famiq_res.get_widget_focus_state(&entity) == Some(true);

        blink_timer.timer.tick(time.delta());

        if is_focused {
            need_redraw = helper::handle_cursor_blink_on_focused(
                &mut blink_timer,
                &mut cosmic_color
            );
        }
        else {
            need_redraw = helper::handle_cursor_blink_on_unfocused(
                &mut blink_timer,
                &mut cosmic_color
            );
        }
        if need_redraw {
            request_redraw_buffer.write(RequestRedrawBuffer::new(entity));
        }
        blink_timer.can_blink = true;
    });
}


pub(crate) fn handle_text_input_on_focused(
    mut input_q: Query<(Entity, &mut CursorBlinkTimer, &mut CosmicDataColor)>,
    famiq_res: Res<FamiqResource>
) {
    if !famiq_res.is_changed() || famiq_res.is_added() {
        return;
    }
    input_q.iter_mut().for_each(|(entity, mut cursor_blink, mut cosmic_color)| {
        if let Some(focused) = famiq_res.get_widget_focus_state(&entity) {
            if focused {
                cosmic_color.cursor_color = cosmic_color.text_color;
            }
            let duration =  cursor_blink.timer.duration();
            cursor_blink.timer.set_elapsed(duration);
        }
    });
}

pub(crate) fn on_request_redraw_editor_buffer(
    mut request: EventReader<RequestRedrawBuffer>,
    mut param: RequestRedrawBufferParam
) {
    for event in request.read() {
        if let Ok((mut cosmic_data, cosmic_color, texture_entity)) = param.input_q.get_mut(event.input_entity) {
            let CosmicData {editor, buffer_dim, .. } = &mut *cosmic_data;

            if let Some(editor) = editor.as_mut() {
                let pixels = helper::draw_editor_buffer(
                    buffer_dim,
                    &mut param.font_system.0,
                    &mut param.swash_cache.0,
                    editor,
                    cosmic_color
                );

                let (material_handle, image_node)= param.texture_q.get(texture_entity.0).unwrap();
                if let Some(material) = param.materials.get_mut(material_handle) {
                    if let Color::Srgba(value) = cosmic_rgba_to_bevy_srgba(cosmic_color.text_color) {
                        material.color = Vec4::new(value.red, value.green, value.blue, 0.0);
                    }
                    if let Some(texture) = param.image_asset.get_mut(material.texture.id()) {
                        let new_size = Extent3d {
                            width: buffer_dim.x as u32,
                            height: buffer_dim.y as u32,
                            depth_or_array_layers: 1,
                        };
                        if texture.texture_descriptor.size != new_size {
                            texture.resize(new_size);
                        }
                        if let Some(data) = texture.data.as_mut() {
                            data.copy_from_slice(&pixels);
                        }
                    }
                }
                // resize ImageNode so that it can grow the Node size automatically.
                // resizing Node directly will cause text shaking.
                if let Some(image) = param.image_asset.get_mut(image_node.image.id()) {
                    let new_size = Extent3d {
                        width: buffer_dim.x as u32,
                        height: buffer_dim.y as u32,
                        depth_or_array_layers: 1,
                    };
                    if image.texture_descriptor.size != new_size {
                        image.resize(new_size);
                    }
                }
            }
        }
    }
}

/// Internal system to detect text's style (font-size & color) changes
pub(crate) fn detect_text_input_text_style_change(mut param: DetectTextStyleChangeParam) {
    param.input_q.iter_mut().for_each(|(
        entity,
        mut cosmic_data,
        mut cosmic_color,
        mut text_edit,
        cosmic_text_data
    )| {
        if let Some(_cosmic_color) = bevy_color_to_cosmic_rgba(cosmic_text_data.color) {
            cosmic_color.text_color = _cosmic_color;
            cosmic_color.selected_text_color = _cosmic_color;

            if let Some(is_focused) = param.famiq_res.get_widget_focus_state(&entity) {
                if is_focused {
                    cosmic_color.cursor_color = _cosmic_color;
                } else {
                    cosmic_color.cursor_color = CURSOR_INVISIBLE;
                }
            }
        }
        let CosmicData { editor, attrs, buffer_dim, .. } = &mut *cosmic_data;

        if cosmic_text_data.size > 0.0 {
            if let Some(editor) = editor {
                let current_cursor = editor.cursor();
                let font_system = &mut param.font_system.0;

                editor.with_buffer_mut(|buffer| {
                    buffer.set_size(font_system, None, None); // reset

                    let new_metrics = Metrics::relative(cosmic_text_data.size, 1.2);
                    #[cfg(not(target_os = "macos"))] {
                        if let Some(window) = param.window.as_ref() {
                            new_metrics.scale(window.scale_factor());
                        }
                    }
                    buffer.set_metrics(font_system, new_metrics);

                    if text_edit.value.is_empty() {
                        buffer.set_text(font_system, &text_edit.placeholder, attrs.unwrap(), Shaping::Advanced);
                    } else {
                        buffer.set_text(font_system, &text_edit.value, attrs.unwrap(), Shaping::Advanced);
                    }
                    if let Some(layout) = buffer.line_layout(font_system, 0) {
                        text_edit.text_width = layout[0].w;
                        text_edit.text_height = new_metrics.line_height;

                        *buffer_dim = Vec2::new(
                            text_edit.text_width + 5.0,
                            text_edit.text_height + 5.0
                        );
                        buffer.set_size(font_system, Some(buffer_dim.x), Some(buffer_dim.y));
                        buffer.shape_until_scroll(font_system, true);
                        buffer.shape_until_cursor(font_system, current_cursor, true);
                    }
                });
            }
        }
        param.request_redraw.write(RequestRedrawBuffer::new(entity));
    });
}

pub(crate) fn detect_new_text_input_widget_system(
    mut input_q: Query<
        (
            Entity,
            &CosmicTextData,
            &CosmicDataColor,
            &mut FaTextEdit,
            &mut CosmicData,
        ),
        Added<IsFamiqTextInput>
    >,
    mut font_system: ResMut<CosmicFontSystem>,
    mut swash_cache: ResMut<CosmicSwashCache>,
    mut commands: Commands,
    mut image_assets: ResMut<Assets<Image>>,
    mut materials: ResMut<Assets<TextInputMaterial>>,
    font_assets: Res<Assets<Font>>,
    window: Option<Single<&Window>>
) {
    input_q.iter_mut().for_each(|(entity, text_data, cosmic_color, mut text_edit, mut cosmic_data)| {
        let mut attrs = Attrs::new();
        if let Some(font) = font_assets.get(&text_data.handle) {
            let data: Arc<dyn AsRef<[u8]> + Send + Sync> = Arc::new((*font.data).clone());

            let face_ids = font_system.0
                .db_mut()
                .load_font_source(cosmic_text::fontdb::Source::Binary(data));

            // Get face ID for Attrs.
            // ref: https://github.com/bevyengine/bevy/blob/main/crates/bevy_text/src/pipeline.rs#L170
            if let Some(&face_id) = face_ids.last() {
                let face = font_system.0.db().face(face_id).unwrap().clone();
                let family_name = face.families[0].0.clone();
                let family_name: &'static str = Box::leak(family_name.into_boxed_str());

                attrs = Attrs::new()
                    .family(Family::Name(family_name))
                    .weight(Weight(face.weight.0))
                    .stretch(face.stretch)
                    .style(face.style);
            }
        }

        let metrics = Metrics::relative(text_data.size, 1.2);

        #[cfg(not(target_os = "macos"))] {
            if let Some(window) = window.as_ref() {
                metrics.scale(window.scale_factor());
            }
        }

        let mut buffer = Buffer::new(&mut font_system.0, metrics);
        let mut buffer = buffer.borrow_with(&mut font_system.0);
        buffer.set_text(&text_edit.placeholder, attrs, Shaping::Advanced);

        if let Some(layout) = buffer.line_layout(0) {
            text_edit.text_width = layout[0].w;
            text_edit.text_height = metrics.line_height;

            let buffer_dim = Vec2::new(
                text_edit.text_width + 5.0,
                text_edit.text_height + 5.0
            );

            buffer.set_size(Some(buffer_dim.x), Some(buffer_dim.y));
            buffer.shape_until_scroll(true);
            buffer.shape_until_cursor(Cursor::new(0, 0), true);

            let mut editor = Editor::new(buffer.clone());

            let pixels= helper::draw_editor_buffer(
                &buffer_dim,
                &mut font_system.0,
                &mut swash_cache.0,
                &mut editor,
                cosmic_color
            );

            // need empty pixels at buffer size for ImageNode. see 'on_request_redraw_editor_buffer' system
            let empty_texture_handle = helper::create_empty_buffer_texture(&buffer_dim, &mut image_assets);
            let texture_handle = helper::create_buffer_texture(&buffer_dim, &pixels, &mut image_assets);

            if let Color::Srgba(value) = cosmic_rgba_to_bevy_srgba(cosmic_color.text_color) {
                let texture_image = commands
                .spawn((
                    ImageNode::new(empty_texture_handle),
                    MaterialNode(materials.add(TextInputMaterial {
                        color: Vec4::new(value.red, value.green, value.blue, 1.0),
                        texture: texture_handle
                    })),
                    Node {
                        left: Val::Px(0.0),
                        ..default()
                    },
                    IsFamiqTextInputBufferTexture
                ))
                .observe(handle_buffer_texture_on_mouse_down)
                .observe(handle_buffer_texture_on_start_selection)
                .observe(handle_buffer_texture_on_selecting)
                .id();

                commands.entity(entity)
                    .insert(FaTextInputBufferTextureEntity(texture_image))
                    .add_child(texture_image);

                commands.entity(texture_image).insert(FaTextInputEntity(entity));
            }
            cosmic_data.editor = Some(editor);
            cosmic_data.attrs = Some(attrs);
            cosmic_data.metrics = Some(metrics);
            cosmic_data.buffer_dim = buffer_dim;
        }
    });
}

pub(crate) fn handle_buffer_texture_on_mouse_down(
    mut trigger: Trigger<Pointer<Pressed>>,
    mut param: BufTexturePickingParam
) {
    let (texture_node, input_entity) = param.texture_q.get(trigger.target()).unwrap();
    let (transform, computed, mut text_edit, mut cosmic_data) = param.input_q.get_mut(input_entity.0).unwrap();

    if text_edit.value.is_empty() {
        trigger.propagate(true);
        return;
    }
    let local_pointer_pos = mouse_pos_to_local_node_pos(
        &trigger.pointer_location.position,
        computed,
        transform
    );
    if let Some(editor) = cosmic_data.editor.as_mut() {
        let mut closest_glyph_index = None;

        editor.with_buffer_mut(|buffer| {
            closest_glyph_index = helper::find_glyph_index_on_mouse_down(
                buffer,
                &mut param.font_system.0,
                texture_node,
                &mut text_edit,
                local_pointer_pos.x
            );
        });
        if let Some(glyph_index) = closest_glyph_index {
            text_edit.cursor_index = glyph_index;
            text_edit.clear_selection();
            editor.set_cursor(Cursor::new(0, text_edit.cursor_index));
            editor.action(&mut param.font_system.0, Action::Escape);
            param.request_redraw.write(RequestRedrawBuffer::new(input_entity.0));
            param.famiq_res.update_all_focus_states(false);
            param.famiq_res.update_or_insert_focus_state(input_entity.0, true);
            trigger.propagate(false);
        }
    }
}

pub(crate) fn handle_buffer_texture_on_start_selection(
    mut trigger: Trigger<Pointer<DragStart>>,
    mut param: BufTexturePickingParam
) {
    let (texture_node, input_entity) = param.texture_q.get(trigger.target()).unwrap();
    let (transform, computed, mut text_edit, mut cosmic_data) = param.input_q.get_mut(input_entity.0).unwrap();

    if text_edit.value.is_empty() {
        trigger.propagate(true);
        return;
    }
    let local_pointer_pos = mouse_pos_to_local_node_pos(
        &trigger.pointer_location.position,
        computed,
        transform
    );
    if let Some(editor) = cosmic_data.editor.as_mut() {
        let mut closest_glyph_index = None;

        editor.with_buffer_mut(|buffer| {
            closest_glyph_index = helper::find_glyph_index_on_mouse_down(
                buffer,
                &mut param.font_system.0,
                texture_node,
                &mut text_edit,
                local_pointer_pos.x
            );
        });
        if let Some(glyph_index) = closest_glyph_index {
            text_edit.cursor_index = glyph_index;
            text_edit.selection_start_index = Some(glyph_index);
            editor.set_cursor(Cursor::new(0, text_edit.cursor_index));
            param.request_redraw.write(RequestRedrawBuffer::new(input_entity.0));
            param.famiq_res.update_all_focus_states(false);
            param.famiq_res.update_or_insert_focus_state(input_entity.0, true);
            trigger.propagate(false);
        }
    }
}

pub(crate) fn handle_buffer_texture_on_selecting(
    mut trigger: Trigger<Pointer<Drag>>,
    mut param: BufTexturePickingParam
) {
    let (texture_node, input_entity) = param.texture_q.get(trigger.target()).unwrap();
    let (transform, computed, mut text_edit, mut cosmic_data) = param.input_q.get_mut(input_entity.0).unwrap();

    if text_edit.value.is_empty() {
        trigger.propagate(true);
        return;
    }
    let local_pointer_pos = mouse_pos_to_local_node_pos(
        &trigger.pointer_location.position,
        computed,
        transform
    );
    if let Some(editor) = cosmic_data.editor.as_mut() {
        let mut closest_glyph_index = None;

        editor.with_buffer_mut(|buffer| {
            closest_glyph_index = helper::find_glyph_index_on_mouse_down(
                buffer,
                &mut param.font_system.0,
                texture_node,
                &mut text_edit,
                local_pointer_pos.x
            );
        });
        if let Some(glyph_index) = closest_glyph_index {
            if let Some(start_index) = text_edit.selection_start_index {
                text_edit.cursor_index = glyph_index;
                text_edit.selection_end_index = Some(glyph_index);
                editor.set_cursor(Cursor::new(0, text_edit.cursor_index));
                editor.set_selection(Selection::Normal(Cursor::new(0, start_index)));
                param.request_redraw.write(RequestRedrawBuffer::new(input_entity.0));

                if start_index > glyph_index {
                    text_edit.selected_text = text_edit.value[glyph_index..start_index].to_owned();
                }
                else if start_index < glyph_index {
                    text_edit.selected_text = text_edit.value[start_index..glyph_index].to_owned();
                }
            }
            param.famiq_res.update_all_focus_states(false);
            param.famiq_res.update_or_insert_focus_state(input_entity.0, true);
            trigger.propagate(false);
        }
    }
}

pub(crate) fn handle_text_input_on_typing(
    mut param: TypingParam,
    #[cfg(target_arch = "wasm32")] wasm_channel: Option<Res<WasmPasteAsyncChannel>>,
) {
    for e in param.evr_kbd.read() {
        if e.state == ButtonState::Released { // it's key up? nevermind
            continue;
        }

        for(
            entity,
            computed,
            texture_entity,
            mut blink_timer,
            mut cosmic_data,
            mut text_edit,
            model_key
        ) in param.input_q.iter_mut() {
            let Some(focused) = param.famiq_res.get_widget_focus_state(&entity) else { continue };

            if !focused {
                continue;
            }
            let mut texture_node = param.texture_q.get_mut(texture_entity.0).unwrap();

            text_edit.widget_computed = computed.clone();
            text_edit.set_min_max_cursor_pos();

            let CosmicData { buffer_dim, attrs, editor, .. } = &mut *cosmic_data;

            if let Some(mut editor) = editor.as_mut() {
                let mut skip_typing = false;
                let current_cursor = editor.cursor();
                let font_system = &mut param.font_system.0;

                if text_edit.is_ctrl_a_pressed(&param.keys, e.key_code) {
                    if text_edit.select_all(&mut editor) {
                        helper::scroll_left_end(&mut texture_node);
                        param.request_redraw.write(RequestRedrawBuffer::new(entity));
                        continue;
                    }
                }

                #[cfg(not(target_arch = "wasm32"))]
                {
                    if text_edit.is_ctrl_c_pressed(&param.keys, e.key_code) {
                        if let Some(copied_text) = text_edit.copy_text() {
                            param.famiq_res.copied_text = copied_text;
                            continue;
                        }
                    }
                    else if text_edit.is_ctrl_v_pressed(&param.keys, e.key_code) {
                        // TODO: proper scroll after pasted long text
                        let mut ctx = Clipboard::new().unwrap();
                        let mut copied_text = ctx.get_text().ok();

                        if copied_text.as_ref().map_or(true, |s| s.is_empty()) {
                            if !param.famiq_res.copied_text.is_empty() {
                                copied_text = Some(param.famiq_res.copied_text.clone());
                            }
                        }
                        if let Some(text) = copied_text {
                            if text.is_empty() {
                                continue;
                            }
                            helper::clear_buffer_before_insert(&mut editor, &mut text_edit, font_system, attrs.unwrap());

                            let index = text_edit.cursor_index;
                            text_edit.value.insert_str(index, &text);
                            text_edit.cursor_index += text.len();

                            editor.with_buffer_mut(|buffer| {
                                buffer.set_size(font_system, None, None); // reset
                                buffer.set_text(font_system, &text_edit.value, attrs.unwrap(), Shaping::Advanced);
                                helper::update_buffer_text_layout(
                                    font_system,
                                    &mut text_edit,
                                    buffer_dim,
                                    buffer,
                                    &texture_node
                                );
                            });
                            skip_typing = true;
                        }
                    }
                }

                #[cfg(target_arch = "wasm32")]
                {
                    if text_edit.is_ctrl_c_pressed(&param.keys, e.key_code) {
                        if !text_edit.selected_text.trim().is_empty() {
                            write_clipboard_wasm(&text_edit.selected_text);
                            continue;
                        }
                    }
                    else if text_edit.is_ctrl_v_pressed(&param.keys, e.key_code) {
                        let tx = wasm_channel.as_ref().unwrap().tx.clone();
                        let _task = AsyncComputeTaskPool::get().spawn(async move {
                            let promise = read_clipboard_wasm();

                            let result = JsFuture::from(promise).await;

                            if let Ok(js_text) = result {
                                if let Some(text) = js_text.as_string() {
                                    let _ = tx.try_send(WasmPaste { text, entity });
                                }
                            }
                        });
                    }
                }

                if !skip_typing {
                    match &e.logical_key {
                        Key::Character(key_input) => text_edit.insert_char(&mut editor, font_system, key_input, *attrs),
                        Key::Space => text_edit.insert_space(&mut editor, font_system, *attrs),
                        Key::Backspace => text_edit.backspace(&mut editor, font_system),
                        Key::Escape => text_edit.escape(&mut editor, font_system),
                        Key::ArrowLeft => text_edit.arrow_left(&mut editor),
                        Key::ArrowRight => text_edit.arrow_right(&mut editor),
                        _ => {}
                    }
                }

                editor.with_buffer_mut(|buffer| {
                    buffer.set_size(font_system, None, None); // Reset

                    if text_edit.value.is_empty() {
                        text_edit.buffer_empty = false;
                        buffer.set_text(font_system, &text_edit.placeholder, attrs.unwrap(), Shaping::Advanced);
                    }
                    helper::update_buffer_text_layout(
                        font_system,
                        &mut text_edit,
                        buffer_dim,
                        buffer,
                        &texture_node
                    );
                    buffer.shape_until_scroll(font_system, true);
                    buffer.shape_until_cursor(font_system, current_cursor, true);
                });
                editor.set_cursor(Cursor::new(0, text_edit.cursor_index));

                match text_edit.need_scroll {
                    NeedScroll::Right => helper::scroll_right(&mut texture_node, &text_edit),
                    NeedScroll::Left => helper::scroll_left(&mut texture_node, &text_edit),
                    _ => {}
                }
                if let Some(value) = param.fa_query.get_data_mut(&model_key.0) {
                    match value {
                        RVal::Str(v) => {
                            *v = text_edit.value.to_owned();
                        }
                        _ => {}
                    }
                }
                param.request_redraw.write(RequestRedrawBuffer::new(entity));
                blink_timer.can_blink = false;
            }
        }
    }
}

#[cfg(target_arch = "wasm32")]
pub fn on_wasm_paste(
    channel: Res<WasmPasteAsyncChannel>,
    mut input_q: Query<
        (
            Entity,
            &ComputedNode,
            &FaTextInputBufferTextureEntity,
            &mut CursorBlinkTimer,
            &mut CosmicData,
            &mut FaTextEdit,
            &ReactiveModelKey
        ),
        With<IsFamiqTextInput>
    >,
    mut texture_q: Query<&mut Node, (With<IsFamiqTextInputBufferTexture>, Without<MainWidget>)>,
    mut famiq_res: ResMut<FamiqResource>,
    mut font_system: ResMut<CosmicFontSystem>,
    mut request_redraw: EventWriter<RequestRedrawBuffer>,
    mut fa_query: FaQuery,
) {
    let inlet = channel.rx.try_recv();
    match inlet {
        Ok(inlet) => {
            if inlet.text.is_empty() {
                return;
            }

            if let Ok((
                entity,
                computed,
                texture_entity,
                mut blink_timer,
                mut cosmic_data,
                mut text_edit,
                model_key
            )) = input_q.get_mut(inlet.entity) {
                let Some(focused) = famiq_res.get_widget_focus_state(&entity) else { return };

                if !focused {
                    return;
                }
                let mut texture_node = texture_q.get_mut(texture_entity.0).unwrap();

                let CosmicData { buffer_dim, attrs, editor, .. } = &mut *cosmic_data;

                if let Some(mut editor) = editor.as_mut() {
                    let font_system = &mut font_system.0;
                    helper::clear_buffer_before_insert(&mut editor, &mut text_edit, font_system, attrs.unwrap());
                    let index = text_edit.cursor_index;
                    text_edit.value.insert_str(index, &inlet.text);
                    text_edit.cursor_index += inlet.text.len();

                    editor.with_buffer_mut(|buffer| {
                        buffer.set_size(font_system, None, None); // reset
                        buffer.set_text(font_system, &text_edit.value, attrs.unwrap(), Shaping::Advanced);
                        helper::update_buffer_text_layout(
                            font_system,
                            &mut text_edit,
                            buffer_dim,
                            buffer,
                            &texture_node
                        );
                    });
                    editor.set_cursor(Cursor::new(0, text_edit.cursor_index));

                    if let Some(value) = fa_query.get_data_mut(&model_key.0) {
                        match value {
                            RVal::Str(v) =>  *v = text_edit.value.to_owned(),
                            _ => {}
                        }
                    }
                    request_redraw.write(RequestRedrawBuffer::new(entity));
                    blink_timer.can_blink = false;
                }
            }
        }
        Err(_) => {}
    }
}

pub fn cosmic_font_system_exists(font_system: Option<Res<CosmicFontSystem>>) -> bool {
    font_system.is_some()
}

/// Determines if text_input internal system(s) can run.
///
/// True only if there is a text_input widget created.
pub fn can_run_text_input_systems(input_q: Query<&IsFamiqTextInput>) -> bool {
    !input_q.is_empty()
}