gpui_rn 0.1.1

Zed's GPU-accelerated UI framework (fork for React Native GPUI)
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
//! Example demonstrating GPUI's testing infrastructure.
//!
//! When run normally, this displays an interactive counter window.
//! The tests below demonstrate various GPUI testing patterns.
//!
//! Run the app: cargo run -p gpui --example testing
//! Run tests:   cargo test -p gpui --example testing --features test-support

use gpui::{
    App, Application, Bounds, Context, FocusHandle, Focusable, Render, Task, Window, WindowBounds,
    WindowOptions, actions, div, prelude::*, px, rgb, size,
};

actions!(counter, [Increment, Decrement]);

struct Counter {
    count: i32,
    focus_handle: FocusHandle,
    _subscription: gpui::Subscription,
}

/// Event emitted by Counter
struct CounterEvent;

impl gpui::EventEmitter<CounterEvent> for Counter {}

impl Counter {
    fn new(cx: &mut Context<Self>) -> Self {
        let subscription = cx.subscribe_self(|this: &mut Self, _event: &CounterEvent, _cx| {
            this.count = 999;
        });

        Self {
            count: 0,
            focus_handle: cx.focus_handle(),
            _subscription: subscription,
        }
    }

    fn increment(&mut self, _: &Increment, _window: &mut Window, cx: &mut Context<Self>) {
        self.count += 1;
        cx.notify();
    }

    fn decrement(&mut self, _: &Decrement, _window: &mut Window, cx: &mut Context<Self>) {
        self.count -= 1;
        cx.notify();
    }

    fn load(&self, cx: &mut Context<Self>) -> Task<()> {
        cx.spawn(async move |this, cx| {
            // Simulate loading data (e.g., from disk or network)
            this.update(cx, |counter, _| {
                counter.count = 100;
            })
            .ok();
        })
    }

    fn reload(&self, cx: &mut Context<Self>) {
        cx.spawn(async move |this, cx| {
            // Simulate reloading data in the background
            this.update(cx, |counter, _| {
                counter.count += 50;
            })
            .ok();
        })
        .detach();
    }
}

impl Focusable for Counter {
    fn focus_handle(&self, _cx: &App) -> FocusHandle {
        self.focus_handle.clone()
    }
}

impl Render for Counter {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        div()
            .id("counter")
            .key_context("Counter")
            .on_action(cx.listener(Self::increment))
            .on_action(cx.listener(Self::decrement))
            .track_focus(&self.focus_handle)
            .flex()
            .flex_col()
            .gap_4()
            .bg(rgb(0x1e1e2e))
            .size_full()
            .justify_center()
            .items_center()
            .child(
                div()
                    .text_3xl()
                    .text_color(rgb(0xcdd6f4))
                    .child(format!("{}", self.count)),
            )
            .child(
                div()
                    .flex()
                    .gap_2()
                    .child(
                        div()
                            .id("decrement")
                            .px_4()
                            .py_2()
                            .bg(rgb(0x313244))
                            .hover(|s| s.bg(rgb(0x45475a)))
                            .rounded_md()
                            .cursor_pointer()
                            .text_color(rgb(0xcdd6f4))
                            .on_click(cx.listener(|this, _, window, cx| {
                                this.decrement(&Decrement, window, cx)
                            }))
                            .child("−"),
                    )
                    .child(
                        div()
                            .id("increment")
                            .px_4()
                            .py_2()
                            .bg(rgb(0x313244))
                            .hover(|s| s.bg(rgb(0x45475a)))
                            .rounded_md()
                            .cursor_pointer()
                            .text_color(rgb(0xcdd6f4))
                            .on_click(cx.listener(|this, _, window, cx| {
                                this.increment(&Increment, window, cx)
                            }))
                            .child("+"),
                    ),
            )
            .child(
                div()
                    .flex()
                    .gap_2()
                    .child(
                        div()
                            .id("load")
                            .px_4()
                            .py_2()
                            .bg(rgb(0x313244))
                            .hover(|s| s.bg(rgb(0x45475a)))
                            .rounded_md()
                            .cursor_pointer()
                            .text_color(rgb(0xcdd6f4))
                            .on_click(cx.listener(|this, _, _, cx| {
                                this.load(cx).detach();
                            }))
                            .child("Load"),
                    )
                    .child(
                        div()
                            .id("reload")
                            .px_4()
                            .py_2()
                            .bg(rgb(0x313244))
                            .hover(|s| s.bg(rgb(0x45475a)))
                            .rounded_md()
                            .cursor_pointer()
                            .text_color(rgb(0xcdd6f4))
                            .on_click(cx.listener(|this, _, _, cx| {
                                this.reload(cx);
                            }))
                            .child("Reload"),
                    ),
            )
            .child(
                div()
                    .text_sm()
                    .text_color(rgb(0x6c7086))
                    .child("Press ↑/↓ or click buttons"),
            )
    }
}

fn main() {
    Application::new().run(|cx: &mut App| {
        cx.bind_keys([
            gpui::KeyBinding::new("up", Increment, Some("Counter")),
            gpui::KeyBinding::new("down", Decrement, Some("Counter")),
        ]);

        let bounds = Bounds::centered(None, size(px(300.), px(200.)), cx);
        cx.open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(bounds)),
                ..Default::default()
            },
            |window, cx| {
                let counter = cx.new(|cx| Counter::new(cx));
                counter.focus_handle(cx).focus(window, cx);
                counter
            },
        )
        .unwrap();
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{TestAppContext, VisualTestContext};
    use rand::prelude::*;

    /// Here's a basic GPUI test. Just add the macro and take a TestAppContext as an argument!
    ///
    /// Note that synchronous side effects run immediately after your "update*" calls complete.
    #[gpui::test]
    fn basic_testing(cx: &mut TestAppContext) {
        let counter = cx.new(|cx| Counter::new(cx));

        counter.update(cx, |counter, _| {
            counter.count = 42;
        });

        // Note that TestAppContext doesn't support `read(cx)`
        let updated = counter.read_with(cx, |counter, _| counter.count);
        assert_eq!(updated, 42);

        // Emit an event - the subscriber will run immediately after the update finishes
        counter.update(cx, |_, cx| {
            cx.emit(CounterEvent);
        });

        let count_after_update = counter.read_with(cx, |counter, _| counter.count);
        assert_eq!(
            count_after_update, 999,
            "Side effects should run after update completes"
        );
    }

    /// Tests which involve the window require you to construct a VisualTestContext.
    /// Just like synchronous side effects, the window will be drawn after every "update*"
    /// call, so you can test render-dependent behavior.
    #[gpui::test]
    fn test_counter_in_window(cx: &mut TestAppContext) {
        let window = cx.update(|cx| {
            cx.open_window(Default::default(), |_, cx| cx.new(|cx| Counter::new(cx)))
                .unwrap()
        });

        let mut cx = VisualTestContext::from_window(window.into(), cx);
        let counter = window.root(&mut cx).unwrap();

        // Action dispatch depends on the element tree to resolve which action handler
        // to call, and this works exactly as you'd expect in a test.
        let focus_handle = counter.read_with(&cx, |counter, _| counter.focus_handle.clone());
        cx.update(|window, cx| {
            focus_handle.dispatch_action(&Increment, window, cx);
        });

        let count_after = counter.read_with(&cx, |counter, _| counter.count);
        assert_eq!(
            count_after, 1,
            "Action dispatched via focus handle should increment"
        );
    }

    /// GPUI tests can also be async, simply add the async keyword before the test.
    /// Note that the test executor is single thread, so async side effects (including
    /// background tasks) won't run until you explicitly yield control.
    #[gpui::test]
    async fn test_async_operations(cx: &mut TestAppContext) {
        let counter = cx.new(|cx| Counter::new(cx));

        // Tasks can be awaited directly
        counter.update(cx, |counter, cx| counter.load(cx)).await;

        let count = counter.read_with(cx, |counter, _| counter.count);
        assert_eq!(count, 100, "Load task should have set count to 100");

        // But side effects don't run until you yield control
        counter.update(cx, |counter, cx| counter.reload(cx));

        let count = counter.read_with(cx, |counter, _| counter.count);
        assert_eq!(count, 100, "Detached reload task shouldn't have run yet");

        // This runs all pending tasks
        cx.run_until_parked();

        let count = counter.read_with(cx, |counter, _| counter.count);
        assert_eq!(count, 150, "Reload task should have run after parking");
    }

    /// Note that the test executor panics if you await a future that waits on
    /// something outside GPUI's control, like a reading a file or network IO.
    /// You should mock external systems where possible, as this feature can be used
    /// to detect potential deadlocks in your async code.
    ///
    /// However, if you want to disable this check use `allow_parking()`
    #[gpui::test]
    async fn test_allow_parking(cx: &mut TestAppContext) {
        // Allow the thread to park
        cx.executor().allow_parking();

        // Simulate an external system (like a file system) with an OS thread
        let (tx, rx) = futures::channel::oneshot::channel();
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(5));
            tx.send(42).ok();
        });

        // Without allow_parking(), this await would panic because GPUI's
        // scheduler runs out of tasks while waiting for the external thread.
        let result = rx.await.unwrap();
        assert_eq!(result, 42);
    }

    /// GPUI also provides support for property testing, via the iterations flag
    #[gpui::test(iterations = 10)]
    fn test_counter_random_operations(cx: &mut TestAppContext, mut rng: StdRng) {
        let counter = cx.new(|cx| Counter::new(cx));

        // Perform random increments/decrements
        let mut expected = 0i32;
        for _ in 0..100 {
            if rng.random_bool(0.5) {
                expected += 1;
                counter.update(cx, |counter, _| counter.count += 1);
            } else {
                expected -= 1;
                counter.update(cx, |counter, _| counter.count -= 1);
            }
        }

        let actual = counter.read_with(cx, |counter, _| counter.count);
        assert_eq!(
            actual, expected,
            "Counter should match expected after random ops"
        );
    }

    /// Now, all of those tests are good, but GPUI also provides strong support for testing distributed systems.
    /// Let's setup a mock network and enhance the counter to send messages over it.
    mod distributed_systems {
        use std::sync::{Arc, Mutex};

        /// A mock network that delivers messages between two peers.
        struct MockNetwork {
            a_to_b: Vec<i32>,
            b_to_a: Vec<i32>,
        }

        impl MockNetwork {
            fn new() -> Arc<Mutex<Self>> {
                Arc::new(Mutex::new(Self {
                    a_to_b: Vec::new(),
                    b_to_a: Vec::new(),
                }))
            }

            fn a_client(network: &Arc<Mutex<Self>>) -> NetworkClient {
                NetworkClient {
                    network: network.clone(),
                    is_a: true,
                }
            }

            fn b_client(network: &Arc<Mutex<Self>>) -> NetworkClient {
                NetworkClient {
                    network: network.clone(),
                    is_a: false,
                }
            }
        }

        /// A client handle for sending/receiving messages over the mock network.
        #[derive(Clone)]
        struct NetworkClient {
            network: Arc<Mutex<MockNetwork>>,
            is_a: bool,
        }

        impl NetworkClient {
            fn send(&self, value: i32) {
                let mut network = self.network.lock().unwrap();
                if self.is_a {
                    network.b_to_a.push(value);
                } else {
                    network.a_to_b.push(value);
                }
            }

            fn receive_all(&self) -> Vec<i32> {
                let mut network = self.network.lock().unwrap();
                if self.is_a {
                    network.a_to_b.drain(..).collect()
                } else {
                    network.b_to_a.drain(..).collect()
                }
            }
        }

        use gpui::Context;

        /// A networked counter that can send/receive over a mock network.
        struct NetworkedCounter {
            count: i32,
            client: NetworkClient,
        }

        impl NetworkedCounter {
            fn new(client: NetworkClient) -> Self {
                Self { count: 0, client }
            }

            /// Increment the counter and broadcast the change.
            fn increment(&mut self, delta: i32, cx: &mut Context<Self>) {
                self.count += delta;

                cx.background_spawn({
                    let client = self.client.clone();
                    async move {
                        client.send(delta);
                    }
                })
                .detach();
            }

            /// Process incoming increment requests.
            fn sync(&mut self) {
                for delta in self.client.receive_all() {
                    self.count += delta;
                }
            }

            /// Like increment, but tracks when the background send executes.
            fn increment_tracked(
                &mut self,
                delta: i32,
                cx: &mut Context<Self>,
                order: Arc<Mutex<Vec<i32>>>,
            ) {
                self.count += delta;

                cx.background_spawn({
                    let client = self.client.clone();
                    async move {
                        order.lock().unwrap().push(delta);
                        client.send(delta);
                    }
                })
                .detach();
            }
        }

        use super::*;

        /// You can simulate distributed systems with multiple app contexts, simply by adding
        /// additional parameters.
        #[gpui::test]
        fn test_app_sync(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
            let network = MockNetwork::new();

            let a = cx_a.new(|_| NetworkedCounter::new(MockNetwork::a_client(&network)));
            let b = cx_b.new(|_| NetworkedCounter::new(MockNetwork::b_client(&network)));

            // B increments locally and broadcasts the delta
            b.update(cx_b, |b, cx| b.increment(42, cx));
            b.read_with(cx_b, |b, _| assert_eq!(b.count, 42)); // B's count is set immediately
            a.read_with(cx_a, |a, _| assert_eq!(a.count, 0)); // A's count is in a side effect

            cx_b.run_until_parked(); // Send the delta from B
            a.update(cx_a, |a, _| a.sync()); // Receive the delta at A

            b.read_with(cx_b, |b, _| assert_eq!(b.count, 42)); // Both counts now match
            a.read_with(cx_a, |a, _| assert_eq!(a.count, 42));
        }

        /// Multiple apps can run concurrently, and to capture this each test app shares
        /// a dispatcher. Whenever you call `run_until_parked`, the dispatcher will randomly
        /// pick which app's tasks to run next. This allows you to test that your distributed code
        /// is robust to different execution orderings.
        #[gpui::test(iterations = 10)]
        fn test_random_interleaving(
            cx_a: &mut TestAppContext,
            cx_b: &mut TestAppContext,
            mut rng: StdRng,
        ) {
            let network = MockNetwork::new();

            // Track execution order
            let actual_order = Arc::new(Mutex::new(Vec::new()));
            let mut original_order = Vec::new();
            let a = cx_a.new(|_| NetworkedCounter::new(MockNetwork::a_client(&network)));
            let b = cx_b.new(|_| NetworkedCounter::new(MockNetwork::b_client(&network)));

            let num_operations: usize = rng.random_range(3..8);

            for i in 0..num_operations {
                let id = i as i32;
                let which = rng.random_bool(0.5);

                original_order.push(id);
                if which {
                    b.update(cx_b, |b, cx| {
                        b.increment_tracked(id, cx, actual_order.clone())
                    });
                } else {
                    a.update(cx_a, |a, cx| {
                        a.increment_tracked(id, cx, actual_order.clone())
                    });
                }
            }

            // This will send all of the pending increment messages, from both a and b
            cx_a.run_until_parked();

            a.update(cx_a, |a, _| a.sync());
            b.update(cx_b, |b, _| b.sync());

            let a_count = a.read_with(cx_a, |a, _| a.count);
            let b_count = b.read_with(cx_b, |b, _| b.count);

            assert_eq!(a_count, b_count, "A and B should have the same count");

            // Nicely format the execution order output.
            // Run this test with `-- --nocapture` to see it!
            let actual = actual_order.lock().unwrap();
            let spawned: Vec<_> = original_order.iter().map(|n| format!("{}", n)).collect();
            let ran: Vec<_> = actual.iter().map(|n| format!("{}", n)).collect();
            let diff: Vec<_> = original_order
                .iter()
                .zip(actual.iter())
                .map(|(o, a)| {
                    if o == a {
                        " ".to_string()
                    } else {
                        "^".to_string()
                    }
                })
                .collect();
            println!("spawned: [{}]", spawned.join(", "));
            println!("ran:     [{}]", ran.join(", "));
            println!("         [{}]", diff.join(", "));
        }
    }
}