stipple 0.0.3

Stipple: a cross-platform, self-drawn UI toolkit in Rust.
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
//! A native iOS backend over the raw Objective-C runtime + UIKit/CoreGraphics.
//!
//! No `objc`/`uikit` crate — direct `objc_msgSend` FFI and framework links, the
//! same approach as the macOS backend (workspace policy in `ROADMAP.md` §1).
//! This module opts into `unsafe` for the crate.
//!
//! `UIApplicationMain` boots the app with a hand-built delegate class; the
//! delegate creates a `UIWindow` hosting a custom `UIView` whose `drawRect:`
//! blits the software [`Pixmap`] as a `CGImage`. `UIApplicationMain` never
//! returns, so the Rust handler (which outlives the call) is reached through a
//! stashed raw pointer.
//!
//! Touches arrive as [`Event::Touch`] for every finger, the first also as the
//! pointer. The view adopts `UIKeyInput` and holds the keyboard (first
//! responder) while a text input has focus.
//!
//! **Verification:** build-checked for `aarch64-apple-ios` by the `mobile`
//! cross-compile CI job; the `visual-ios` job runs it on a simulator, where
//! `touchdemo`'s self-test drives the keyboard methods and synthetic touches
//! through [`simulate`].
#![allow(unsafe_code)]

use std::cell::RefCell;
use std::ffi::{CString, c_void};

use crate::geometry::{PhysicalSize, Point, ScaleFactor};
use crate::platform::ControlFlow;
use crate::platform::error::PlatformError;
use crate::platform::event::{
    ButtonState, Event, KeyCode, Modifiers, PointerButton, Touch, TouchPhase, WindowId,
};
use crate::platform::input;
use crate::platform::window::{Window, WindowAttributes};
use crate::render::{Pixmap, Surface};

/// Pacing animation frames by the screen (`CADisplayLink`).
mod display_link;

type Id = *mut c_void;
type Sel = *mut c_void;
type Class = *mut c_void;

#[repr(C)]
#[derive(Clone, Copy)]
struct CgPoint {
    x: f64,
    y: f64,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct CgSize {
    width: f64,
    height: f64,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct EdgeInsets {
    top: f64,
    left: f64,
    bottom: f64,
    right: f64,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct CgRect {
    origin: CgPoint,
    size: CgSize,
}

#[link(name = "objc", kind = "dylib")]
unsafe extern "C" {
    fn objc_getClass(name: *const i8) -> Class;
    fn sel_registerName(name: *const i8) -> Sel;
    fn objc_msgSend();
    fn objc_allocateClassPair(superclass: Class, name: *const i8, extra: usize) -> Class;
    fn objc_registerClassPair(cls: Class);
    fn class_addMethod(cls: Class, name: Sel, imp: *const c_void, types: *const i8) -> bool;
    fn class_addProtocol(cls: Class, protocol: *mut c_void) -> bool;
    fn objc_getProtocol(name: *const i8) -> *mut c_void;
    fn objc_msgSendSuper();
}

/// `struct objc_super`, for messaging a method's UIKit implementation.
#[repr(C)]
struct ObjcSuper {
    receiver: Id,
    super_class: Class,
}

#[link(name = "UIKit", kind = "framework")]
unsafe extern "C" {
    fn UIApplicationMain(
        argc: i32,
        argv: *mut *mut i8,
        principal_class_name: Id,
        delegate_class_name: Id,
    ) -> i32;
    fn UIGraphicsGetCurrentContext() -> *mut c_void;
}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    fn CGColorSpaceCreateDeviceRGB() -> *mut c_void;
    fn CGColorSpaceRelease(space: *mut c_void);
    fn CGDataProviderCreateWithData(
        info: *mut c_void,
        data: *const c_void,
        size: usize,
        release: *const c_void,
    ) -> *mut c_void;
    fn CGDataProviderRelease(provider: *mut c_void);
    #[allow(clippy::too_many_arguments)]
    fn CGImageCreate(
        width: usize,
        height: usize,
        bits_per_component: usize,
        bits_per_pixel: usize,
        bytes_per_row: usize,
        space: *mut c_void,
        bitmap_info: u32,
        provider: *mut c_void,
        decode: *const f64,
        should_interpolate: bool,
        intent: i32,
    ) -> *mut c_void;
    fn CGImageRelease(image: *mut c_void);
    fn CGContextDrawImage(ctx: *mut c_void, rect: CgRect, image: *mut c_void);
    fn CGContextSaveGState(ctx: *mut c_void);
    fn CGContextRestoreGState(ctx: *mut c_void);
    fn CGContextTranslateCTM(ctx: *mut c_void, tx: f64, ty: f64);
    fn CGContextScaleCTM(ctx: *mut c_void, sx: f64, sy: f64);
}

// kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big — R,G,B,A in memory.
const CG_BITMAP_RGBA8: u32 = 1 | (4 << 12);

fn class(name: &str) -> Class {
    let c = CString::new(name).unwrap();
    unsafe { objc_getClass(c.as_ptr()) }
}
fn sel(name: &str) -> Sel {
    let c = CString::new(name).unwrap();
    unsafe { sel_registerName(c.as_ptr()) }
}

unsafe fn msg_id(obj: Id, s: Sel) -> Id {
    let f: unsafe extern "C" fn(Id, Sel) -> Id =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) }
}
unsafe fn msg_void(obj: Id, s: Sel) {
    let f: unsafe extern "C" fn(Id, Sel) =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) }
}
unsafe fn msg_void_id(obj: Id, s: Sel, a: Id) {
    let f: unsafe extern "C" fn(Id, Sel, Id) =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s, a) }
}
unsafe fn msg_void_bool(obj: Id, s: Sel, a: bool) {
    let f: unsafe extern "C" fn(Id, Sel, bool) =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s, a) }
}
unsafe fn msg_rect(obj: Id, s: Sel) -> CgRect {
    let f: unsafe extern "C" fn(Id, Sel) -> CgRect =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) }
}
unsafe fn msg_bool(obj: Id, s: Sel) -> bool {
    let f: unsafe extern "C" fn(Id, Sel) -> i8 =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) != 0 }
}
unsafe fn msg_usize(obj: Id, s: Sel) -> usize {
    let f: unsafe extern "C" fn(Id, Sel) -> usize =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) }
}
unsafe fn msg_id_usize(obj: Id, s: Sel, a: usize) -> Id {
    let f: unsafe extern "C" fn(Id, Sel, usize) -> Id =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s, a) }
}
unsafe fn msg_f64(obj: Id, s: Sel) -> f64 {
    let f: unsafe extern "C" fn(Id, Sel) -> f64 =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) }
}
unsafe fn msg_insets(obj: Id, s: Sel) -> EdgeInsets {
    let f: unsafe extern "C" fn(Id, Sel) -> EdgeInsets =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s) }
}
unsafe fn msg_void_rect(obj: Id, s: Sel, a: CgRect) {
    let f: unsafe extern "C" fn(Id, Sel, CgRect) =
        unsafe { std::mem::transmute(objc_msgSend as *const c_void) };
    unsafe { f(obj, s, a) }
}
unsafe fn msg_alloc_init_frame(cls: Class, frame: CgRect) -> Id {
    unsafe {
        let alloc = msg_id(cls, sel("alloc"));
        let f: unsafe extern "C" fn(Id, Sel, CgRect) -> Id =
            std::mem::transmute(objc_msgSend as *const c_void);
        f(alloc, sel("initWithFrame:"), frame)
    }
}

/// `[NSString stringWithUTF8String:s]`.
fn nsstring(s: &str) -> Id {
    let c = CString::new(s).unwrap();
    unsafe {
        let f: unsafe extern "C" fn(Id, Sel, *const i8) -> Id =
            std::mem::transmute(objc_msgSend as *const c_void);
        f(class("NSString"), sel("stringWithUTF8String:"), c.as_ptr())
    }
}

/// An `NSString`'s text (empty for `nil`).
unsafe fn string_of(s: Id) -> String {
    if s.is_null() {
        return String::new();
    }
    unsafe {
        let f: unsafe extern "C" fn(Id, Sel) -> *const std::ffi::c_char =
            std::mem::transmute(objc_msgSend as *const c_void);
        let p = f(s, sel("UTF8String"));
        if p.is_null() {
            String::new()
        } else {
            std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
        }
    }
}

/// The objects of an `NSSet`.
unsafe fn set_objects(set: Id) -> Vec<Id> {
    if set.is_null() {
        return Vec::new();
    }
    unsafe {
        let all = msg_id(set, sel("allObjects"));
        (0..msg_usize(all, sel("count")))
            .map(|i| msg_id_usize(all, sel("objectAtIndex:"), i))
            .collect()
    }
}

// ---- Shared state -----------------------------------------------------------

type DynHandler = *mut dyn FnMut(Event, &dyn Window) -> ControlFlow;

#[derive(Default)]
struct IosCtx {
    fb: Vec<u8>, // straight RGBA8, top row first
    w: usize,
    h: usize,
    view: Id,
    window: Id,
    size: PhysicalSize,
    /// Physical pixels per logical pixel: `UIScreen.scale`.
    scale: f64,
    /// What shows around the safe area.
    background: Option<crate::render::Color>,
    /// Raw pointer to the (type-erased) handler. `UIApplicationMain` never
    /// returns, so the handler in `run`'s frame lives for the process lifetime.
    handler: *mut DynHandler,
    /// The touch that is also the pointer: the first finger down, until it
    /// lifts.
    primary: Option<u64>,
    /// Whether a text input has focus, so the view holds the keyboard.
    text_input: bool,
}

thread_local! {
    static CTX: RefCell<IosCtx> = RefCell::new(IosCtx::default());
}

/// `drawRect:` for our UIView subclass: blit the framebuffer as a CGImage.
extern "C" fn draw_rect(_this: Id, _cmd: Sel, _rect: CgRect) {
    CTX.with(|c| {
        let c = c.borrow();
        if c.fb.is_empty() {
            return;
        }
        unsafe {
            let cg = UIGraphicsGetCurrentContext();
            if cg.is_null() {
                return;
            }
            let space = CGColorSpaceCreateDeviceRGB();
            let provider = CGDataProviderCreateWithData(
                std::ptr::null_mut(),
                c.fb.as_ptr() as *const c_void,
                c.fb.len(),
                std::ptr::null(),
            );
            let image = CGImageCreate(
                c.w,
                c.h,
                8,
                32,
                c.w * 4,
                space,
                CG_BITMAP_RGBA8,
                provider,
                std::ptr::null(),
                false,
                0,
            );
            // The context is in points; the framebuffer is in pixels.
            let (width, height) = (c.w as f64 / c.scale, c.h as f64 / c.scale);
            let rect = CgRect {
                origin: CgPoint { x: 0.0, y: 0.0 },
                size: CgSize { width, height },
            };
            // The UIView draw context draws CGImages bottom-up; flip the CTM so
            // our top-row-first framebuffer lands upright (as in the macОS view).
            CGContextSaveGState(cg);
            CGContextTranslateCTM(cg, 0.0, height);
            CGContextScaleCTM(cg, 1.0, -1.0);
            CGContextDrawImage(cg, rect, image);
            CGContextRestoreGState(cg);
            CGImageRelease(image);
            CGDataProviderRelease(provider);
            CGColorSpaceRelease(space);
        }
    });
}

/// `application:didFinishLaunchingWithOptions:` — build the window + view, draw
/// the first frame, and show it.
extern "C" fn did_finish_launching(_this: Id, _cmd: Sel, _app: Id, _opts: Id) -> bool {
    unsafe {
        let bounds = msg_rect(msg_id(class("UIScreen"), sel("mainScreen")), sel("bounds"));
        let scale = msg_f64(msg_id(class("UIScreen"), sel("mainScreen")), sel("scale"));
        let window = msg_alloc_init_frame(class("UIWindow"), bounds);
        // The root view fills the screen behind the status bar and home indicator;
        // our view sits inside the safe area on top of it.
        let root = msg_alloc_init_frame(class("UIView"), bounds);
        let background = match CTX.with(|c| c.borrow().background) {
            Some(color) => {
                let (r, g, b, a) = (color.r, color.g, color.b, color.a);
                let c = |v: u8| v as f64 / 255.0;
                let f: unsafe extern "C" fn(Id, Sel, f64, f64, f64, f64) -> Id =
                    std::mem::transmute(objc_msgSend as *const c_void);
                f(
                    class("UIColor"),
                    sel("colorWithRed:green:blue:alpha:"),
                    c(r),
                    c(g),
                    c(b),
                    c(a),
                )
            }
            None => msg_id(class("UIColor"), sel("systemBackgroundColor")),
        };
        msg_void_id(root, sel("setBackgroundColor:"), background);
        let view = msg_alloc_init_frame(register_view_class(), bounds);
        // Every finger, not just the first.
        msg_void_bool(view, sel("setMultipleTouchEnabled:"), true);
        msg_void_id(root, sel("addSubview:"), view);
        let vc = msg_id(msg_id(class("UIViewController"), sel("alloc")), sel("init"));
        msg_void_id(vc, sel("setView:"), root);
        msg_void_id(window, sel("setRootViewController:"), vc);

        CTX.with(|c| {
            let mut c = c.borrow_mut();
            c.view = view;
            c.window = window;
            c.scale = scale;
        });

        // Show the window first: the safe area is only known once it's visible,
        // and OS-drawn controls are captured through it.
        msg_void(window, sel("makeKeyAndVisible"));
        let safe = msg_insets(window, sel("safeAreaInsets"));
        let frame = CgRect {
            origin: CgPoint {
                x: bounds.origin.x + safe.left,
                y: bounds.origin.y + safe.top,
            },
            size: CgSize {
                width: bounds.size.width - safe.left - safe.right,
                height: bounds.size.height - safe.top - safe.bottom,
            },
        };
        msg_void_rect(view, sel("setFrame:"), frame);

        let size = PhysicalSize::new(
            (frame.size.width * scale).round() as u32,
            (frame.size.height * scale).round() as u32,
        );
        CTX.with(|c| c.borrow_mut().size = size);
        let win = IosWindow { size };
        // The app starts with its requested size; on iOS the screen decides.
        call_handler(Event::Resized(size), &win);
        call_handler(Event::RedrawRequested, &win);

        // UIKit owns the run loop, so wakeups and timers go through the main
        // dispatch queue, which it drains.
        crate::platform::wake::install(
            std::sync::Arc::new(|| {
                dispatch_async_f(main_queue(), std::ptr::null_mut(), on_wake);
            }),
            Some(std::sync::Arc::new(|at: std::time::Instant| {
                let delay = at.saturating_duration_since(std::time::Instant::now());
                let ns = delay.as_nanos().min(i64::MAX as u128) as i64;
                dispatch_after_f(
                    dispatch_time(DISPATCH_TIME_NOW, ns),
                    main_queue(),
                    std::ptr::null_mut(),
                    on_wake,
                );
            })),
        );
        // Animation frames are paced by the screen, through a CADisplayLink.
        display_link::install();
        msg_void_bool(view, sel("setNeedsDisplay"), true);

        // Runtime marker for CI: confirms the UIKit backend booted, built the
        // window, and the handler rendered a frame into the shared framebuffer.
        // Written to the app's tmp dir (which CI reads back from the simulator
        // container) since app stdout isn't reliably captured headlessly.
        let (w, h) = CTX.with(|c| {
            let c = c.borrow();
            (c.w, c.h)
        });
        let marker = format!("Stipple iOS: window shown, framebuffer {w}x{h}");
        println!("{marker}");
        let _ = std::fs::write(std::env::temp_dir().join("stipple-ios.txt"), &marker);
    }
    true
}

/// Each touch in `touches` (an `NSSet` of `UITouch`): its id (the `UITouch`,
/// which stays the same object while the finger is down) and its position in
/// `view`.
unsafe fn touches_in(view: Id, touches: Id) -> Vec<(u64, Point)> {
    unsafe {
        let location: unsafe extern "C" fn(Id, Sel, Id) -> CgPoint =
            std::mem::transmute(objc_msgSend as *const c_void);
        set_objects(touches)
            .into_iter()
            .map(|touch| {
                let p = location(touch, sel("locationInView:"), view);
                (touch as u64, Point::new(p.x, p.y))
            })
            .collect()
    }
}

fn current_window() -> IosWindow {
    IosWindow {
        size: CTX.with(|c| c.borrow().size),
    }
}

/// Deliver touches that changed: each as an [`Event::Touch`], then the
/// pointer events of the first finger, which is also the pointer.
fn touch_input(phase: TouchPhase, touches: &[(u64, Point)]) {
    let win = current_window();
    for &(id, position) in touches {
        call_handler(
            Event::Touch(Touch {
                id,
                phase,
                position,
            }),
            &win,
        );
    }
    let primary = CTX.with(|c| c.borrow().primary);
    let pressed = |position| Event::PointerButton {
        button: PointerButton::Left,
        state: ButtonState::Pressed,
        position,
    };
    let released = |position| Event::PointerButton {
        button: PointerButton::Left,
        state: ButtonState::Released,
        position,
    };
    match phase {
        TouchPhase::Started => {
            if let (None, Some(&(id, position))) = (primary, touches.first()) {
                CTX.with(|c| c.borrow_mut().primary = Some(id));
                call_handler(Event::PointerMoved { position }, &win);
                call_handler(pressed(position), &win);
            }
        }
        TouchPhase::Moved => {
            if let Some(&(_, position)) = touches.iter().find(|t| Some(t.0) == primary) {
                call_handler(Event::PointerMoved { position }, &win);
            }
        }
        TouchPhase::Ended | TouchPhase::Cancelled => {
            if let Some(&(_, position)) = touches.iter().find(|t| Some(t.0) == primary) {
                CTX.with(|c| c.borrow_mut().primary = None);
                // A cancelled touch is released far away, so it doesn't click.
                let at = if phase == TouchPhase::Cancelled {
                    Point::new(-1.0e9, -1.0e9)
                } else {
                    position
                };
                call_handler(released(at), &win);
                // A finger that lifts leaves no hover behind.
                call_handler(Event::PointerLeft, &win);
            }
        }
    }
}

extern "C" fn touches_began(this: Id, _cmd: Sel, touches: Id, _event: Id) {
    touch_input(TouchPhase::Started, &unsafe { touches_in(this, touches) });
}

extern "C" fn touches_moved(this: Id, _cmd: Sel, touches: Id, _event: Id) {
    touch_input(TouchPhase::Moved, &unsafe { touches_in(this, touches) });
}

extern "C" fn touches_ended(this: Id, _cmd: Sel, touches: Id, _event: Id) {
    touch_input(TouchPhase::Ended, &unsafe { touches_in(this, touches) });
}

extern "C" fn touches_cancelled(this: Id, _cmd: Sel, touches: Id, _event: Id) {
    touch_input(TouchPhase::Cancelled, &unsafe { touches_in(this, touches) });
}

// ---- The keyboard (UIKeyInput) ------------------------------------------------

/// `canBecomeFirstResponder`: the view takes the keyboard while a text input
/// has focus.
extern "C" fn can_become_first_responder(_this: Id, _cmd: Sel) -> bool {
    true
}

/// `hasText`: always, so Backspace on an empty-looking field still reaches the
/// app (UIKit only sends `deleteBackward` when there's text).
extern "C" fn has_text(_this: Id, _cmd: Sel) -> bool {
    true
}

/// `insertText:`, from the on-screen keyboard (and a hardware one): the text
/// to type. Return arrives as a newline and becomes the Enter key.
extern "C" fn insert_text(_this: Id, _cmd: Sel, text: Id) {
    let text = unsafe { string_of(text) };
    let win = current_window();
    for (i, line) in text.split('\n').enumerate() {
        if i > 0 {
            key_tap(KeyCode::Enter, Modifiers::default(), &win);
        }
        if !line.is_empty() {
            call_handler(Event::Text(line.to_string()), &win);
        }
    }
}

/// `deleteBackward`: the keyboard's delete key.
extern "C" fn delete_backward(_this: Id, _cmd: Sel) {
    key_tap(KeyCode::Backspace, Modifiers::default(), &current_window());
}

fn key_tap(code: KeyCode, modifiers: Modifiers, win: &IosWindow) {
    for state in [ButtonState::Pressed, ButtonState::Released] {
        call_handler(
            Event::Key {
                code,
                state,
                modifiers,
            },
            win,
        );
    }
}

/// `pressesBegan:withEvent:` and friends, from a hardware keyboard while the
/// view is first responder. Keys the text system doesn't type (arrows,
/// Home/End, Escape, Tab, F-keys, shortcuts) become [`Event::Key`]; the rest go
/// on to UIKit, which types them through `insertText:` / `deleteBackward`.
unsafe fn presses(this: Id, cmd: Sel, presses: Id, event: Id, state: ButtonState) {
    let win = current_window();
    let mut to_uikit = false;
    for press in unsafe { set_objects(presses) } {
        let key = unsafe { msg_id(press, sel("key")) };
        if key.is_null() {
            to_uikit = true;
            continue;
        }
        let usage = unsafe { msg_usize(key, sel("keyCode")) } as isize;
        let modifiers = input::ios_modifiers(unsafe { msg_usize(key, sel("modifierFlags")) });
        let chars = unsafe { string_of(msg_id(key, sel("charactersIgnoringModifiers"))) };
        match input::ios_key(usage, &chars, modifiers) {
            Some(code) => call_handler(
                Event::Key {
                    code,
                    state,
                    modifiers,
                },
                &win,
            ),
            None => to_uikit = true,
        }
    }
    if to_uikit {
        unsafe {
            let sup = ObjcSuper {
                receiver: this,
                super_class: class("UIView"),
            };
            let f: unsafe extern "C" fn(*const ObjcSuper, Sel, Id, Id) =
                std::mem::transmute(objc_msgSendSuper as *const c_void);
            f(&sup, cmd, presses, event);
        }
    }
}

extern "C" fn presses_began(this: Id, cmd: Sel, set: Id, event: Id) {
    unsafe { presses(this, cmd, set, event, ButtonState::Pressed) }
}

extern "C" fn presses_ended(this: Id, cmd: Sel, set: Id, event: Id) {
    unsafe { presses(this, cmd, set, event, ButtonState::Released) }
}

/// Hold the keyboard (become first responder) while a text input has focus,
/// and let it go when focus leaves.
fn set_text_input(active: bool) {
    let (view, was) = CTX.with(|c| {
        let mut c = c.borrow_mut();
        let was = c.text_input;
        c.text_input = active;
        (c.view, was)
    });
    if view.is_null() || was == active {
        return;
    }
    unsafe {
        if active {
            msg_bool(view, sel("becomeFirstResponder"));
        } else {
            msg_bool(view, sel("resignFirstResponder"));
        }
    }
}

/// Drive the view the way UIKit does, for self-tests on a simulator, which
/// can't script touches or the keyboard: a touch through the same path as
/// `touchesBegan:withEvent:` and friends, and text and Backspace through
/// `insertText:` and `deleteBackward` messages sent to the view. Each runs on
/// the main queue after the current event, so they can be called from an app's
/// callbacks; they run in the order they're called.
pub mod simulate {
    use super::*;

    /// Run `f` on the main queue, after whatever is running now.
    fn later(f: impl FnOnce() + 'static) {
        extern "C" fn trampoline(context: *mut c_void) {
            let f = unsafe { Box::from_raw(context.cast::<Box<dyn FnOnce()>>()) };
            f();
        }
        let f: Box<Box<dyn FnOnce()>> = Box::new(Box::new(f));
        unsafe { dispatch_async_f(main_queue(), Box::into_raw(f).cast(), trampoline) };
    }

    /// A finger `id` at `position` (logical pixels, in the app's content).
    pub fn touch(id: u64, phase: TouchPhase, position: Point) {
        later(move || touch_input(phase, &[(id, position)]));
    }

    /// Type `text`, as `[view insertText:text]`.
    pub fn insert_text(text: &str) {
        let text = text.to_string();
        later(move || {
            let view = CTX.with(|c| c.borrow().view);
            if !view.is_null() {
                unsafe { msg_void_id(view, sel("insertText:"), nsstring(&text)) };
            }
        });
    }

    /// Press the keyboard's delete key, as `[view deleteBackward]`.
    pub fn delete_backward() {
        later(|| {
            let view = CTX.with(|c| c.borrow().view);
            if !view.is_null() {
                unsafe { msg_void(view, sel("deleteBackward")) };
            }
        });
    }

    /// The view's keyboard state, read through objc dispatch: whether it
    /// conforms to `UIKeyInput`, can become and is first responder (holding
    /// the keyboard), and has text.
    pub fn keyboard_status() -> String {
        let view = CTX.with(|c| c.borrow().view);
        if view.is_null() {
            return "no view".into();
        }
        unsafe {
            let protocol = objc_getProtocol(c"UIKeyInput".as_ptr());
            let conforms = {
                let f: unsafe extern "C" fn(Id, Sel, *mut c_void) -> i8 =
                    std::mem::transmute(objc_msgSend as *const c_void);
                !protocol.is_null() && f(view, sel("conformsToProtocol:"), protocol) != 0
            };
            format!(
                "key_input={conforms} can_become={} first_responder={} has_text={}",
                msg_bool(view, sel("canBecomeFirstResponder")),
                msg_bool(view, sel("isFirstResponder")),
                msg_bool(view, sel("hasText")),
            )
        }
    }
}

// libdispatch, part of libSystem.
const DISPATCH_TIME_NOW: u64 = 0;
unsafe extern "C" {
    static _dispatch_main_q: u8;
    fn dispatch_async_f(
        queue: *const c_void,
        context: *mut c_void,
        work: extern "C" fn(*mut c_void),
    );
    fn dispatch_after_f(
        when: u64,
        queue: *const c_void,
        context: *mut c_void,
        work: extern "C" fn(*mut c_void),
    );
    fn dispatch_time(when: u64, delta_ns: i64) -> u64;
}

/// `dispatch_get_main_queue()`, which is a macro over this symbol.
fn main_queue() -> *const c_void {
    (&raw const _dispatch_main_q).cast()
}

/// Runs on the main queue: deliver a wake if one is due. A timer that was
/// rescheduled may still fire here early, which `take` sees and ignores.
extern "C" fn on_wake(_context: *mut c_void) {
    if crate::platform::wake::take(std::time::Instant::now()) {
        call_handler(Event::Wake, &current_window());
    }
}

/// Invoke the stashed Rust handler (if any).
fn call_handler(event: Event, win: &dyn Window) {
    let ptr = CTX.with(|c| c.borrow().handler);
    if ptr.is_null() {
        return;
    }
    unsafe {
        let fat = *ptr;
        let handler: &mut dyn FnMut(Event, &dyn Window) -> ControlFlow = &mut *fat;
        let _ = handler(event, win);
    }
}

fn register_view_class() -> Class {
    let name = c"StippleUIView";
    unsafe {
        let existing = objc_getClass(name.as_ptr());
        if !existing.is_null() {
            return existing;
        }
        let cls = objc_allocateClassPair(class("UIView"), name.as_ptr(), 0);
        let draw_types = c"v@:{CGRect={CGPoint=dd}{CGSize=dd}}";
        class_addMethod(
            cls,
            sel("drawRect:"),
            draw_rect as *const c_void,
            draw_types.as_ptr(),
        );
        let touch_types = c"v@:@@";
        let touches: [(&str, extern "C" fn(Id, Sel, Id, Id)); 7] = [
            ("touchesBegan:withEvent:", touches_began),
            ("touchesMoved:withEvent:", touches_moved),
            ("touchesEnded:withEvent:", touches_ended),
            ("touchesCancelled:withEvent:", touches_cancelled),
            ("pressesBegan:withEvent:", presses_began),
            ("pressesEnded:withEvent:", presses_ended),
            ("pressesCancelled:withEvent:", presses_ended),
        ];
        for (name, imp) in touches {
            class_addMethod(cls, sel(name), imp as *const c_void, touch_types.as_ptr());
        }
        // The keyboard: UIKeyInput, so the view can hold it as first responder.
        let flags: [(&str, extern "C" fn(Id, Sel) -> bool); 2] = [
            ("canBecomeFirstResponder", can_become_first_responder),
            ("hasText", has_text),
        ];
        for (name, imp) in flags {
            class_addMethod(cls, sel(name), imp as *const c_void, c"B@:".as_ptr());
        }
        class_addMethod(
            cls,
            sel("insertText:"),
            insert_text as *const c_void,
            c"v@:@".as_ptr(),
        );
        class_addMethod(
            cls,
            sel("deleteBackward"),
            delete_backward as *const c_void,
            c"v@:".as_ptr(),
        );
        let key_input = objc_getProtocol(c"UIKeyInput".as_ptr());
        if !key_input.is_null() {
            class_addProtocol(cls, key_input);
        }
        objc_registerClassPair(cls);
        cls
    }
}

fn register_app_delegate() -> Class {
    let name = c"StippleAppDelegate";
    unsafe {
        let existing = objc_getClass(name.as_ptr());
        if !existing.is_null() {
            return existing;
        }
        let cls = objc_allocateClassPair(class("UIResponder"), name.as_ptr(), 0);
        class_addMethod(
            cls,
            sel("application:didFinishLaunchingWithOptions:"),
            did_finish_launching as *const c_void,
            c"c@:@@".as_ptr(),
        );
        objc_registerClassPair(cls);
        cls
    }
}

#[derive(Debug)]
struct IosWindow {
    size: PhysicalSize,
}

impl Window for IosWindow {
    fn id(&self) -> WindowId {
        WindowId(1)
    }
    fn inner_size(&self) -> PhysicalSize {
        self.size
    }
    fn scale_factor(&self) -> ScaleFactor {
        ScaleFactor::new(CTX.with(|c| c.borrow().scale))
    }
    fn request_redraw(&self) {
        CTX.with(|c| {
            let view = c.borrow().view;
            if !view.is_null() {
                unsafe { msg_void_bool(view, sel("setNeedsDisplay"), true) };
            }
        });
    }
    fn set_title(&self, _title: &str) {}
    fn clipboard(&self) -> Option<String> {
        crate::platform::clipboard::text()
    }
    fn set_clipboard(&self, text: &str) {
        crate::platform::clipboard::set_text(text);
    }
    fn set_text_input_active(&self, active: bool) {
        set_text_input(active);
    }
    fn create_surface(&self) -> Box<dyn Surface> {
        Box::new(IosSurface { size: self.size })
    }
}

#[derive(Debug)]
struct IosSurface {
    size: PhysicalSize,
}

impl Surface for IosSurface {
    fn resize(&mut self, size: PhysicalSize) {
        self.size = size;
    }
    fn size(&self) -> PhysicalSize {
        self.size
    }
    fn present(&mut self, pixmap: &Pixmap, _damage: &[crate::geometry::Rect]) {
        let size = pixmap.size();
        CTX.with(|c| {
            let mut c = c.borrow_mut();
            c.fb = pixmap.as_bytes().to_vec();
            c.w = size.width as usize;
            c.h = size.height as usize;
            if !c.view.is_null() {
                unsafe { msg_void_bool(c.view, sel("setNeedsDisplay"), true) };
            }
        });
    }
}

/// Boot the iOS app: stash the handler, register our classes, and hand control
/// to `UIApplicationMain` (which does not return).
pub fn run<H>(attrs: WindowAttributes, mut handler: H) -> Result<(), PlatformError>
where
    H: FnMut(Event, &dyn Window) -> ControlFlow,
{
    let size = ScaleFactor::IDENTITY.to_physical(attrs.logical_size);

    // Type-erase the handler and stash a raw pointer. `H` is not `'static`, but
    // `UIApplicationMain` never returns, so `handler` lives for the process
    // lifetime — we launder the borrow lifetime to the `'static` raw pointer the
    // stash holds, which is therefore sound in practice.
    let dyn_ref: &mut (dyn FnMut(Event, &dyn Window) -> ControlFlow + '_) = &mut handler;
    let fat: DynHandler = unsafe { std::mem::transmute(dyn_ref) };
    let boxed: *mut DynHandler = Box::into_raw(Box::new(fat));

    CTX.with(|c| {
        let mut c = c.borrow_mut();
        c.size = size;
        c.background = attrs.background;
        c.handler = boxed;
    });

    register_view_class();
    register_app_delegate();

    unsafe {
        let delegate_name = nsstring("StippleAppDelegate");
        // UIApplicationMain owns argv for the process lifetime; pass none.
        UIApplicationMain(0, std::ptr::null_mut(), std::ptr::null_mut(), delegate_name);
    }
    Ok(())
}