### Install create-gpui-app CLI Source: https://matinaniss.github.io/gpui-book/getting-started/create-gpui-app.html Installs the official GPUI scaffolding tool via Cargo. ```bash cargo install create-gpui-app ``` -------------------------------- ### Basic GPUI Hello World Application Source: https://matinaniss.github.io/gpui-book/getting-started/manual-project.html Implement a 'Hello World' application using GPUI. This example sets up the application, opens a window, and renders a simple text element. ```rust use gpui::prelude::*; struct HelloWorld { text: SharedString, } impl Render for HelloWorld { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .bg(white()) .flex() .justify_center() .items_center() .text_3xl() .child(format!("Hello, {}!", &self.text)) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| HelloWorld { text: SharedString::new_static("World") }) }) .unwrap(); }); } ``` -------------------------------- ### Initialize a basic Div element Source: https://matinaniss.github.io/gpui-book/elements/div.html Demonstrates the minimal setup required to render a single empty Div element within a GPUI application. ```rust use gpui::{AppContext, Application, Context, IntoElement, Render, Window, WindowOptions, div}; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Get Window Bounds in GPUI Source: https://matinaniss.github.io/gpui-book/architecture/window.html Use this snippet to retrieve the origin and size of a platform window. It requires setting up a basic GPUI application and opening a window. ```rust use gpui::{AppContext, Application, Context, Empty, IntoElement, Render, Window, WindowOptions}; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { Empty } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |window, app| { println!("{:?}", window.bounds()); app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Get Mouse Position in GPUI Window Source: https://matinaniss.github.io/gpui-book/architecture/window.html This code demonstrates how to get the mouse's position relative to the window. Ensure you have a GPUI application running and a window open. ```rust use gpui::{AppContext, Application, Context, Empty, IntoElement, Render, Window, WindowOptions}; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { Empty } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |window, app| { println!("{:?}", window.mouse_position()); app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Render Image from File Path in GPUI Source: https://matinaniss.github.io/gpui-book/elements/img.html Use the `img` element to render an image from a file system path. Ensure the image file exists at the specified path relative to the project root. This example uses `CARGO_MANIFEST_DIR` to locate the image. ```rust use std::path::Path; use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, img, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .child(img(Path::new(env!("CARGO_MANIFEST_DIR")).join("image.png")).size_full()) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Try to Get a Global State (Option) Source: https://matinaniss.github.io/gpui-book/print.html Attempts to retrieve a reference to the global state, returning `Some(T)` if set, and `None` otherwise. This is a safe way to access globals that might not have been initialized. ```rust use gpui::{Application, Global}; pub struct SomeState { some_value: bool, } implement Global for SomeState {} fn main() { Application::new().run(|app| { app.set_global::(SomeState { some_value: true }); let some_state = app.try_global::(); }); } ``` -------------------------------- ### Bind Hover Event Handler in GPUI Source: https://matinaniss.github.io/gpui-book/print.html The `on_hover` function allows binding callbacks for when a user's mouse pointer enters or leaves an element. The callback receives a boolean indicating if the hover started (true) or ended (false), along with `Window` and `App` context. ```Rust use gpui::{ AppContext, Application, Context, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, WindowOptions, div, red, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .child( div() .id("some_id") .bg(red()) .text_color(white()) .h_6() .child("Hover Here") .on_hover(|hovered, _window, _app| { println!( "{}", if *hovered { "Hover started" } else { "Hover ended" } ); }), ) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Create a 'Hello World!' Window in GPUI Source: https://matinaniss.github.io/gpui-book/examples/hello-world.html This snippet demonstrates how to create a basic 'Hello World!' application using the GPUI framework. It sets up a new application, opens a window, and renders a simple text view. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .bg(white()) .child("Hello World!") } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Simple 'Hello World!' GPUI Application Source: https://matinaniss.github.io/gpui-book/print.html A basic GPUI application that opens a window displaying 'Hello World!'. Requires importing necessary GPUI components. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .bg(white()) .child("Hello World!") } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Create a GPUI Application Source: https://matinaniss.github.io/gpui-book/architecture/application.html Use `Application::new()` to create an instance of the GPUI application. This is the initial step before running the application. ```rust use gpui::Application; fn main() { let application = Application::new(); } ``` -------------------------------- ### Initialize a GPUI Application Window Source: https://matinaniss.github.io/gpui-book/architecture/app.html Use the Application struct to run the app and open a new window with default options. ```rust use gpui::{Application, WindowOptions}; fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |window, app| { // Return root view }) .unwrap(); }); } ``` -------------------------------- ### Manually Initialize a GPUI Project Source: https://matinaniss.github.io/gpui-book/print.html Commands to create a new Rust project and add the GPUI dependency manually. ```bash cargo new my-app cd my-app ``` ```bash cargo add gpui ``` ```bash cargo add gpui --git https://github.com/zed-industries/zed ``` -------------------------------- ### Get a Mutable Global State Reference Source: https://matinaniss.github.io/gpui-book/print.html Retrieves a mutable reference to a global state. Accessing a global that has not been set will cause a panic. Modifications made through this reference will affect the global state. ```rust use gpui::{Application, Global}; pub struct SomeState { some_value: bool, } implement Global for SomeState {} fn main() { Application::new().run(|app| { app.set_global::(SomeState { some_value: true }); let some_state = app.global_mut::(); some_state.some_value = false; }); } ``` -------------------------------- ### Create a new GPUI application Source: https://matinaniss.github.io/gpui-book/getting-started/create-gpui-app.html Generates a new GPUI project with the specified name and navigates into the directory. ```bash create-gpui-app --name my-app cd my-app ``` -------------------------------- ### Get a Global State Reference Source: https://matinaniss.github.io/gpui-book/print.html Retrieves an immutable reference to a global state. Accessing a global that has not been set will cause a panic. This can be done using `app.global` or the type's static `global` method. ```rust use gpui::{Application, Global, ReadGlobal}; pub struct SomeState { some_value: bool, } implement Global for SomeState {} fn main() { Application::new().run(|app| { app.set_global::(SomeState { some_value: true }); let some_state = app.global::(); // OR let some_state = SomeState::global(app); }); } ``` -------------------------------- ### Project structure for a single-crate application Source: https://matinaniss.github.io/gpui-book/getting-started/create-gpui-app.html Displays the file hierarchy generated by the standard create-gpui-app command. ```text my-app ├── src │ └── main.rs ├── Cargo.toml └── README.md ``` -------------------------------- ### Compare styling approaches in GPUI Source: https://matinaniss.github.io/gpui-book/print.html Demonstrates the difference between using utility CSS-like functions and direct Style struct modification. ```rust impl Render for SomeView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().flex().flex_col().child("Hello").child("World") } } ``` ```rust impl Render for SomeView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { let mut element = div().child("Hello").child("World"); let style = element.style(); style.display = Some(Display::Flex); style.flex_direction = Some(FlexDirection::Column); element } } ``` -------------------------------- ### Implement a Basic Hello World View Source: https://matinaniss.github.io/gpui-book/print.html Define a simple component that renders text using the Render trait. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, SharedString, Styled, Window, WindowOptions, div, white, }; struct HelloWorld { text: SharedString, } impl Render for HelloWorld { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .bg(white()) .flex() .justify_center() .items_center() .text_3xl() .child(format!("Hello, {}!", &self.text)) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| HelloWorld { text: SharedString::new_static("World"), }) }) .unwrap(); }); } ``` -------------------------------- ### Project structure for a workspace application Source: https://matinaniss.github.io/gpui-book/getting-started/create-gpui-app.html Displays the file hierarchy generated by the workspace-based create-gpui-app command. ```text my-app ├── Cargo.toml ├── crates │ └── my-app │ ├── Cargo.toml │ └── src │ └── main.rs └── README.md ``` -------------------------------- ### Create a new Rust project Source: https://matinaniss.github.io/gpui-book/getting-started/manual-project.html Use Cargo to create a new binary project for your GPUI application. Navigate into the project directory. ```bash cargo new my-app cd my-app ``` -------------------------------- ### Scaffold a New GPUI Project Source: https://matinaniss.github.io/gpui-book/print.html Generate a new GPUI application or workspace using the CLI tool. ```bash create-gpui-app --name my-app cd my-app ``` ```bash create-gpui-app --workspace --name my-app cd my-app ``` -------------------------------- ### Run a GPUI Application with a Callback Source: https://matinaniss.github.io/gpui-book/architecture/application.html The `run` function consumes the `Application` and executes a callback once the application is loaded. This callback receives an `App` instance for further control. ```rust use gpui::Application; fn main() { let application = Application::new(); application.run(|_app| { // Entry point }); } ``` -------------------------------- ### Render static text in GPUI Source: https://matinaniss.github.io/gpui-book/elements/text.html Demonstrates basic text rendering using a static string within a GPUI RootView. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, rgb, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .bg(rgb(0xFFFFFF)) .flex() .justify_center() .items_center() .text_3xl() .child("Hello") } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Create an Entity with Initial State Source: https://matinaniss.github.io/gpui-book/state-management/entity.html Use `app.new` to create a new `Entity` and initialize its state. The state type `T` must implement `Render` if it's intended to be a view. ```rust use gpui::{AppContext, Application}; pub struct SomeState { some_value: bool, } fn main() { Application::new().run(|app| { let entity = app.new(|_cx| SomeState { some_value: true }); }); } ``` -------------------------------- ### Create a basic Animation Source: https://matinaniss.github.io/gpui-book/print.html Initializes an animation with a specified duration. ```rust use std::time::Duration; use gpui::Animation; fn main() { Animation::new(Duration::from_secs(1)); } ``` -------------------------------- ### Project Directory Structures Source: https://matinaniss.github.io/gpui-book/print.html Visual representation of the file structure generated by the CLI tool. ```text my-app ├── src │ └── main.rs ├── Cargo.toml └── README.md ``` ```text my-app ├── Cargo.toml ├── crates │ └── my-app │ ├── Cargo.toml │ └── src │ └── main.rs └── README.md ``` -------------------------------- ### Keyboard Navigation Source: https://matinaniss.github.io/gpui-book/styling/image.html Provides information on keyboard shortcuts for navigating the GPUI book. ```APIDOC ## Keyboard Shortcuts ### Navigation - Press `←` or `→` to navigate between chapters ### Search - Press `S` or `/` to search in the book ### Help - Press `?` to show this help - Press `Esc` to hide this help ``` -------------------------------- ### Bind keys to actions in the application Source: https://matinaniss.github.io/gpui-book/interactivity/keyboard.html Create a KeyBinding struct and register it with the application using bind_keys. ```rust use gpui::{Application, actions}; actions!(actions_namespace, [Enter]); fn main() { Application::new().run(|app| { app.bind_keys([gpui::KeyBinding::new("enter", Enter, None)]); }); } ``` -------------------------------- ### Create a new GPUI workspace Source: https://matinaniss.github.io/gpui-book/getting-started/create-gpui-app.html Generates a new GPUI project configured as a Cargo workspace. ```bash create-gpui-app --workspace --name my-app cd my-app ``` -------------------------------- ### Implement the RenderOnce Trait Source: https://matinaniss.github.io/gpui-book/print.html Creates an immediate mode component using RenderOnce, which takes ownership of self. ```rust use gpui::{ App, AppContext, Application, Context, IntoElement, ParentElement, Render, RenderOnce, Window, WindowOptions, div, }; #[derive(IntoElement)] struct SomeComponent; impl RenderOnce for SomeComponent { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { div() } } struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().child(SomeComponent) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Style elements using utility functions Source: https://matinaniss.github.io/gpui-book/styling/index.html Applies layout styles using the concise CSS-like shorthand methods available on elements. ```rust impl Render for SomeView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().flex().flex_col().child("Hello").child("World") } } ``` -------------------------------- ### Bind Global Actions in GPUI Source: https://matinaniss.github.io/gpui-book/architecture/app.html Register global actions and key bindings using the App context to trigger callbacks. ```rust use gpui::{ AppContext, Application, Context, Empty, IntoElement, Render, Window, WindowOptions, actions, }; actions!(actions_namespace, [Enter]); struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { Empty } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.bind_keys([gpui::KeyBinding::new("enter", Enter, None)]); app.on_action(|&Enter, _app| println!("Enter key hit!")); app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Render an image with GPUI Source: https://matinaniss.github.io/gpui-book/print.html Uses the img element to render an image from a file system path. ```rust use std::path::Path; use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, img, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .child(img(Path::new(env!("CARGO_MANIFEST_DIR")).join("image.png")).size_full()) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### GPUI Counter Application Source: https://matinaniss.github.io/gpui-book/print.html This snippet shows a complete GPUI application that implements a simple counter with increment and decrement buttons. It includes the necessary imports, view definition, and the main application loop. ```rust use gpui::{ AppContext, Application, ClickEvent, Context, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, WindowOptions, black, div, green, red, white, }; struct RootView { count: isize, } impl Render for RootView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .gap_5() .bg(white()) .child( div() .id("decrement_button") .cursor_pointer() .flex() .items_center() .justify_center() .size_8() .rounded_md() .border_1() .border_color(black()) .child("-") .hover(|style| style.bg(red())) .on_click(cx.listener(Self::decrement)), ) .child( div() .min_w_16() .text_3xl() .text_center() .child(self.count.to_string()), ) .child( div() .id("increment_button") .cursor_pointer() .flex() .items_center() .justify_center() .size_8() .rounded_md() .border_1() .border_color(black()) .child("+") .hover(|style| style.bg(green())) .on_click(cx.listener(Self::increment)), ) } } impl RootView { fn increment(&mut self, _event: &ClickEvent, _window: &mut Window, cx: &mut Context) { self.count += 1; cx.notify(); } fn decrement(&mut self, _event: &ClickEvent, _window: &mut Window, cx: &mut Context) { self.count -= 1; cx.notify(); } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView { count: 0 }) }) .unwrap(); }); } ``` -------------------------------- ### Render String in GPUI Source: https://matinaniss.github.io/gpui-book/elements/text.html Shows rendering a standard String, noting that this causes heap allocations on every re-render. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, rgb, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .bg(rgb(0xFFFFFF)) .flex() .justify_center() .items_center() .text_3xl() .child(String::from("Hello")) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Implement RenderOnce for Components in GPUI Source: https://matinaniss.github.io/gpui-book/rendering/render-once.html Use the RenderOnce trait to create components that are constructed, rendered, and then dropped. The render function takes ownership of self, suitable for components without mutable state. ```rust use gpui::{ App, AppContext, Application, Context, IntoElement, ParentElement, Render, RenderOnce, Window, WindowOptions, div, }; #[derive(IntoElement)] struct SomeComponent; impl RenderOnce for SomeComponent { fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement { div() } } struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().child(SomeComponent) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Handle actions with on_action and track_focus Source: https://matinaniss.github.io/gpui-book/interactivity/keyboard.html Use track_focus on an element to enable action dispatching and on_action to define a callback for specific actions. ```rust use gpui::{ AppContext, Application, Context, FocusHandle, InteractiveElement, IntoElement, Render, Window, WindowOptions, actions, div, }; actions!(actions_namespace, [Enter]); struct RootView { focus_handle: FocusHandle, } impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .track_focus(&self.focus_handle) .on_action(|&Enter, _window, _app| { println!("Enter key hit!"); }) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |window, app| { app.bind_keys([gpui::KeyBinding::new("enter", Enter, None)]); let focus_handle = app.focus_handle(); focus_handle.focus(window); app.new(|_cx| RootView { focus_handle }) }) .unwrap(); }); } ``` -------------------------------- ### Add GPUI as a Git dependency Source: https://matinaniss.github.io/gpui-book/getting-started/manual-project.html Alternatively, add GPUI directly from its git repository. This is useful for using unreleased versions or specific forks. ```bash cargo add gpui --git https://github.com/zed-industries/zed ``` -------------------------------- ### Add GPUI as a crates.io dependency Source: https://matinaniss.github.io/gpui-book/getting-started/manual-project.html Add the GPUI crate to your project's dependencies by running this Cargo command. This is the standard way to include external crates. ```bash cargo add gpui ``` -------------------------------- ### Updating an Entity and Triggering Notification in GPUI Source: https://matinaniss.github.io/gpui-book/architecture/context.html Demonstrates creating an entity and using the notify function within an update block to signal state changes. ```rust use gpui::{AppContext, Application}; pub struct SomeState { some_value: bool, } fn main() { Application::new().run(|app| { let entity = app.new(|_cx| SomeState { some_value: true }); entity.update(app, |this, cx| { this.some_value = false; cx.notify(); }); }); } ``` -------------------------------- ### Spawn Asynchronous Tasks in GPUI Source: https://matinaniss.github.io/gpui-book/architecture/app.html Enqueue asynchronous work on the main thread using the spawn function, which provides access to AsyncApp. ```rust use gpui::Application; fn main() { Application::new().run(|app| { app.spawn(async |app| { // Some asynchronous work }) .detach(); }); } ``` -------------------------------- ### Manage Entity State Source: https://matinaniss.github.io/gpui-book/print.html Create, read, and update entities to manage application state across different components. ```rust use gpui::{AppContext, Application}; pub struct SomeState { some_value: bool, } fn main() { Application::new().run(|app| { let entity = app.new(|_cx| SomeState { some_value: true }); }); } ``` ```rust use gpui::{AppContext, Application}; pub struct SomeState { some_value: bool, } fn main() { Application::new().run(|app| { let entity = app.new(|_cx| SomeState { some_value: true }); let some_state = entity.read(app); }); } ``` ```rust use gpui::{AppContext, Application}; pub struct SomeState { some_value: bool, } fn main() { Application::new().run(|app| { let entity = app.new(|_cx| SomeState { some_value: true }); entity.update(app, |some_state, _cx| { some_state.some_value = false; }); }); } ``` -------------------------------- ### Render Text in GPUI Source: https://matinaniss.github.io/gpui-book/print.html Renders text within a styled Div container. Using String is discouraged for performance reasons; consider SharedString instead. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, rgb, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .bg(rgb(0xFFFFFF)) .flex() .justify_center() .items_center() .text_3xl() .child("Hello") } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, rgb, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .bg(rgb(0xFFFFFF)) .flex() .justify_center() .items_center() .text_3xl() .child(String::from("Hello")) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Define actions with the actions macro Source: https://matinaniss.github.io/gpui-book/interactivity/keyboard.html Use the actions macro to define a namespace and a list of unit structs representing actions. ```rust use gpui::actions; actions!(actions_namespace, [Enter]); ``` -------------------------------- ### Implement a Counter Component in GPUI Source: https://matinaniss.github.io/gpui-book/examples/counter.html Defines a RootView struct with a counter state and implements the Render trait to display buttons and the current count. Uses event listeners to update state and trigger UI re-renders. ```rust use gpui::{ AppContext, Application, ClickEvent, Context, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, WindowOptions, black, div, green, red, white, }; struct RootView { count: isize, } impl Render for RootView { fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .gap_5() .bg(white()) .child( div() .id("decrement_button") .cursor_pointer() .flex() .items_center() .justify_center() .size_8() .rounded_md() .border_1() .border_color(black()) .child("-") .hover(|style| style.bg(red())) .on_click(cx.listener(Self::decrement)), ) .child( div() .min_w_16() .text_3xl() .text_center() .child(self.count.to_string()), ) .child( div() .id("increment_button") .cursor_pointer() .flex() .items_center() .justify_center() .size_8() .rounded_md() .border_1() .border_color(black()) .child("+") .hover(|style| style.bg(green())) .on_click(cx.listener(Self::increment)), ) } } impl RootView { fn increment(&mut self, _event: &ClickEvent, _window: &mut Window, cx: &mut Context) { self.count += 1; cx.notify(); } fn decrement(&mut self, _event: &ClickEvent, _window: &mut Window, cx: &mut Context) { self.count -= 1; cx.notify(); } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView { count: 0 }) }) .unwrap(); }); } ``` -------------------------------- ### Bind Click Event Handler in GPUI Source: https://matinaniss.github.io/gpui-book/print.html Use the `on_click` function to attach a callback that executes when a user releases the left mouse button on an element. The callback receives a `ClickEvent`, `Window`, and `App` context. ```Rust use gpui::{ AppContext, Application, Context, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, WindowOptions, div, red, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .child( div() .id("some_id") .bg(red()) .text_color(white()) .h_6() .child("Click Here") .on_click(|event, _window, _app| { println!(ירת{event:#?}); }), ) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Create a new animation with duration Source: https://matinaniss.github.io/gpui-book/animations/animation.html Use `Animation::new` with a `Duration` to create a basic animation. This sets the fundamental timing for the animation. ```rust use std::time::Duration; use gpui::Animation; fn main() { Animation::new(Duration::from_secs(1)); } ``` -------------------------------- ### Add GPUI as a Cargo Dependency Source: https://matinaniss.github.io/gpui-book/getting-started/index.html Specify GPUI as a dependency in your Cargo.toml file. You can either use a specific version from crates.io or a git dependency directly from the Zed repository. ```toml gpui = { version = "*" } # Specify a specific version # OR gpui = { git = "https://github.com/zed-industries/zed" } ``` -------------------------------- ### Binding Click Events in GPUI Source: https://matinaniss.github.io/gpui-book/interactivity/mouse.html Uses the on_click function to trigger a callback upon mouse release. Requires the element to be stateful via an ID. ```rust use gpui::{ AppContext, Application, Context, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, WindowOptions, div, red, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .child( div() .id("some_id") .bg(red()) .text_color(white()) .h_6() .child("Click Here") .on_click(|event, _window, _app| { println!("{event:#?}"); }), ) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Using Background Timers Source: https://matinaniss.github.io/gpui-book/async/background-executor.html Creates a timer that completes after a specified duration, allowing for delayed execution within asynchronous tasks. ```rust use std::time::Duration; use gpui::Application; fn main() { Application::new().run(|app| { let timer = app.background_executor().timer(Duration::from_secs(10)); app.background_executor() .spawn(async { timer.await; println!("Timer Finished!"); }) .detach(); }); } ``` -------------------------------- ### Configure a repeating Animation Source: https://matinaniss.github.io/gpui-book/print.html Sets an animation to repeat indefinitely. ```rust use std::time::Duration; use gpui::Animation; fn main() { Animation::new(Duration::from_secs(1)).repeat(); } ``` -------------------------------- ### Observe Global State Updates Source: https://matinaniss.github.io/gpui-book/state-management/global.html Registers a callback to be executed when the global state is updated. ```rust use gpui::{Application, Global}; pub struct SomeState { some_value: bool, } impl Global for SomeState {} fn main() { Application::new().run(|app| { app.set_global::(SomeState { some_value: true }); let subscription = app.observe_global::(|_app| { // Global update callback }); // OR app.observe_global::(|_app| { // Global update callback }) .detach(); }); } ``` -------------------------------- ### Add multiple children to a Div Source: https://matinaniss.github.io/gpui-book/elements/div.html Demonstrates using the children method to pass an array of elements to a parent Div. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Window, WindowOptions, div, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().children([div(), div()]) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Create a Weak Entity Pointer Source: https://matinaniss.github.io/gpui-book/state-management/entity.html Convert an `Entity` into a `WeakEntity` using the `downgrade` method. This creates a weak pointer that does not prevent the entity from being dropped. ```rust use gpui::{AppContext, Application}; pub struct SomeState { some_value: bool, } fn main() { Application::new().run(|app| { let entity = app.new(|_cx| SomeState { some_value: true }); let weak_entity = entity.downgrade(); }); } ``` -------------------------------- ### Add a single child to a Div Source: https://matinaniss.github.io/gpui-book/elements/div.html Shows how to use the child method to nest a single element inside a parent Div. ```rust use gpui::{ AppContext, Application, Context, IntoElement, ParentElement, Render, Window, WindowOptions, div, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div().child(div()) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Spawning Asynchronous Tasks Source: https://matinaniss.github.io/gpui-book/async/background-executor.html Enqueues a future to run on a background thread. Use detach to ensure the task runs to completion instead of being cancelled when dropped. ```rust use gpui::Application; fn main() { Application::new().run(|app| { app.background_executor() .spawn(async { // Some asynchronous work }) .detach(); }); } ``` -------------------------------- ### Apply easing to an animation Source: https://matinaniss.github.io/gpui-book/animations/animation.html Use the `.with_easing()` method with a closure that modifies the animation's delta. GPUI provides several predefined easing functions like `ease_in_out`. ```rust use std::time::Duration; use gpui::{Animation, ease_in_out}; fn main() { Animation::new(Duration::from_secs(1)).with_easing(ease_in_out); } ``` -------------------------------- ### Apply Animation to Element with GPUI Source: https://matinaniss.github.io/gpui-book/animations/with_animation.html Use `with_animation` to apply a repeating, easing animation to a div element. The animation's size is controlled by a delta value that ranges from 0.0 to 1.0. ```rust use std::time::Duration; use gpui::{ Animation, AnimationExt, AppContext, Application, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, blue, div, ease_in_out, rems, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .bg(white()) .size_full() .flex() .items_center() .justify_center() .child( div().bg(blue()).with_animation( "animation", Animation::new(Duration::from_secs(1)) .repeat() .with_easing(ease_in_out), |this, delta| this.size(rems(delta * 5.)), ), ) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Image Styling with Img Element Source: https://matinaniss.github.io/gpui-book/styling/image.html The Img element in GPUI implements the StyledImage trait, enabling various styling options through functions like .image_style() or utility CSS-like functions. ```APIDOC ## Image Styling with Img Element ### Description The `Img` element implements the `StyledImage` trait which allows styling of a image through the `.image_style()` function or with the utility CSS-like styling functions. ### Styles #### Grayscale - **grayscale** (boolean) - Controls if the image should be rendered in grayscale. #### Object Fit - **object_fit** (ObjectFit enum) - Controls how the image should fit in the parent element. The `ObjectFit` enum contains `Fill`, `Contain`, `Cover`, `ScaleDown`, `None`. #### Loading - **loading** (function) - Controls the optional loading function that allows you to render a loading element while the element is loading. #### Fallback - **fallback** (function) - Controls the optional fallback function that allows you to render a fallback element if the element fails to load. ``` -------------------------------- ### Set Global to Default if Not Set Source: https://matinaniss.github.io/gpui-book/print.html Ensures a global is set, initializing it with its `Default` implementation if it hasn't been set already. If it has been set, this operation has no effect. ```rust use gpui::{Application, Global}; #[derive(Default)] pub struct SomeState { some_value: bool, } implement Global for SomeState {} fn main() { Application::new().run(|app| { app.set_global::(SomeState { some_value: true }); app.default_global::(); }); } ``` -------------------------------- ### Binding Hover Events in GPUI Source: https://matinaniss.github.io/gpui-book/interactivity/mouse.html Uses the on_hover function to detect when a user enters or leaves an element. The callback receives a boolean indicating the hover state. ```rust use gpui::{ AppContext, Application, Context, InteractiveElement, IntoElement, ParentElement, Render, StatefulInteractiveElement, Styled, Window, WindowOptions, div, red, white, }; struct RootView; impl Render for RootView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { div() .size_full() .flex() .items_center() .justify_center() .child( div() .id("some_id") .bg(red()) .text_color(white()) .h_6() .child("Hover Here") .on_hover(|hovered, _window, _app| { println!( "{}", if *hovered { "Hover started" } else { "Hover ended" } ); }), ) } } fn main() { Application::new().run(|app| { app.open_window(WindowOptions::default(), |_window, app| { app.new(|_cx| RootView) }) .unwrap(); }); } ``` -------------------------------- ### Spawning Tasks on the Main Thread Source: https://matinaniss.github.io/gpui-book/async/foreground-executor.html Enqueues a future to run on the main thread and uses detach to ensure the task runs to completion. ```rust use gpui::Application; fn main() { Application::new().run(|app| { app.foreground_executor() .spawn(async { // Some asynchronous work }) .detach(); }); } ``` -------------------------------- ### Initialize Global State with Default Source: https://matinaniss.github.io/gpui-book/state-management/global.html Retrieves a mutable reference to the global state, initializing it with the type's Default implementation if it has not been set. ```rust use gpui::{Application, Global}; #[derive(Default)] pub struct SomeState { some_value: bool, } impl Global for SomeState {} fn main() { Application::new().run(|app| { app.set_global::(SomeState { some_value: true }); app.default_global::(); }); } ```