### opacity method example with blue color Source: https://docs.rs/gpui-pre/latest/gpui/struct.Rgba.html Demonstrates using the opacity method to scale the alpha channel. The example starts with a light blue at 80% opacity and multiplies by 0.5, resulting in 40% opacity, verified with a floating-point tolerance. ```rust use gpui::rgba; let color = rgba(0x3399FFCC); // A light blue with 80% opacity let faded = color.opacity(0.5); assert!((faded.a - 0.4).abs() < 1e-6); ``` -------------------------------- ### opacity method example with red color Source: https://docs.rs/gpui-pre/latest/gpui/struct.Rgba.html Shows how to use the opacity method to multiply the alpha channel by a factor. The example starts with a fully opaque red and multiplies its alpha by 0.5, resulting in 50% opacity. ```rust use gpui::rgba; let color = rgba(0xFF0000FF); // Fully opaque red let faded = color.opacity(0.5); assert_eq!(faded.a, 0.5); ``` -------------------------------- ### Size::min example Source: https://docs.rs/gpui-pre/latest/gpui/struct.Size.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example usage of the min method to get a new Size with the minimum width and height from two sizes. ```rust let size1 = Size { width: 30, height: 40 }; let size2 = Size { width: 50, height: 20 }; let min_size = size1.min(&size2); assert_eq!(min_size, Size { width: 30, height: 20 }); ``` -------------------------------- ### alpha method example with transparent blue Source: https://docs.rs/gpui-pre/latest/gpui/struct.Rgba.html Demonstrates using the alpha method to make a color fully transparent by setting the alpha to 0.0. The example starts with a blue color and verifies the resulting alpha is 0.0. ```rust use gpui::rgba; let color = rgba(0x3399FFCC); let transparent = color.alpha(0.0); assert_eq!(transparent.a, 0.0); ``` -------------------------------- ### AvailableSpace::min_size() example Source: https://docs.rs/gpui-pre/latest/gpui/enum.AvailableSpace.html?search= Example usage of AvailableSpace::min_size() to create a Size with both width and height set to AvailableSpace::MinContent. The example asserts that the resulting size has MinContent for both dimensions. ```rust use gpui::AvailableSpace; let min_content_size = AvailableSpace::min_size(); assert_eq!(min_content_size.width, AvailableSpace::MinContent); assert_eq!(min_content_size.height, AvailableSpace::MinContent); ``` -------------------------------- ### Size::max example Source: https://docs.rs/gpui-pre/latest/gpui/struct.Size.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example usage of the max method to get a new Size with the maximum width and height from two sizes. ```rust let size1 = Size { width: 30, height: 40 }; let size2 = Size { width: 50, height: 20 }; let max_size = size1.max(&size2); assert_eq!(max_size, Size { width: 50, height: 40 }); ``` -------------------------------- ### Test module setup: imports, actions!, test_dispatch_tree helper, test view structs Source: https://docs.rs/gpui-pre/latest/src/gpui/key_dispatch.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts the test module for dispatch tree functionality. It imports the necessary GPUI types, defines test actions via the actions! macro, and provides a helper to create a DispatchTree with a given set of key bindings. The test view structs PendingInputTestView and PendingTextInputTestView are declared for use in tests. ```rust #[cfg(test)] mod tests { use crate::{ self as gpui, AppContext, DispatchResult, Element, ElementId, GlobalElementId, InspectorElementId, Keystroke, LayoutId, Style, }; use core::panic; use smallvec::SmallVec; use std::{ cell::{Cell, RefCell}, ops::Range, rc::Rc, }; use crate::{ ActionRegistry, App, Bounds, Context, DispatchPhase, DispatchTree, FocusHandle, InputHandler, IntoElement, KeyBinding, KeyContext, Keymap, Pixels, PlatformWindow, Point, Render, Subscription, TestAppContext, UTF16Selection, Unbind, VisualContext, VisualTestContext, Window, }; actions!(dispatch_test, [TestAction, SecondaryTestAction]); fn test_dispatch_tree(bindings: Vec) -> DispatchTree { let registry = ActionRegistry::default(); DispatchTree::new( Rc::new(RefCell::new(Keymap::new(bindings))), Rc::new(registry), ) } struct PendingInputTestView { focus_handle: FocusHandle, action_count: Rc>, secondary_action_count: Rc>, } #[derive(Clone)] struct PendingTextInputTestView { focus_handle: FocusHandle, ``` -------------------------------- ### Size::scale example Source: https://docs.rs/gpui-pre/latest/gpui/struct.Size.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example usage of the scale method to multiply width and height by a factor, producing a Size. ```rust let size = Size { width: Pixels::from(100.0), height: Pixels::from(50.0) }; let scaled_size = size.scale(2.0); assert_eq!(scaled_size, Size { width: ScaledPixels::from(200.0), height: ScaledPixels::from(100.0) }); ``` -------------------------------- ### size function usage example Source: https://docs.rs/gpui-pre/latest/gpui/fn.size.html?search=std%3A%3Avec Example usage of the gpui::size function, creating a Size with width 10 and height 20, and asserting the values. ```rust use gpui::size; let my_size = size(10, 20); assert_eq!(my_size.width, 10); assert_eq!(my_size.height, 20); ``` -------------------------------- ### iter_mut example Source: https://docs.rs/gpui-pre/latest/gpui/type.Result.html?search=std%3A%3Avec Example for `Result::iter_mut`, showing how to get a mutable iterator over the possibly contained value. ```rust let mut x: Result = Ok(7); match x.iter_mut().next() { Some(v) => *v = 40, None => {}, } assert_eq!(x, Ok(40)); let mut x: Result = Err("nothing!"); assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Setting Up Window and Focus for Keystroke Simulation Source: https://docs.rs/gpui-pre/latest/src/gpui/key_dispatch.rs.html?search=u32+-%3E+bool Creates a window with a custom element, obtains its focus handle, and sets up an observer for pending input changes. The focus is then activated to prepare for keystroke simulation. ```rust let (test, cx) = cx.add_window_view(|_, cx| CustomElement::new(cx)); let focus_handle = test.update(cx, |test, _| test.focus_handle.clone()); ``` ```rust let pending_input_changed_count = Rc::new(RefCell::new(0usize)); let pending_input_changed_count_for_observer = pending_input_changed_count.clone(); struct PendingInputObserver { _subscription: Subscription, } let _observer = cx.update(|window, cx| { cx.new(|cx| PendingInputObserver { _subscription: cx.observe_pending_input(window, move |_, _, _| { *pending_input_changed_count_for_observer.borrow_mut() += 1; }), }) }); cx.update(|window, cx| { window.focus(&focus_handle, cx); window.activate_window(); }); ``` -------------------------------- ### Application::run Source: https://docs.rs/gpui-pre/latest/gpui/struct.Application.html?search=std%3A%3Avec Starts the application. The provided callback is called once the app is fully launched. ```APIDOC ## Application::run ### Description Start the application. The provided callback will be called once the app is fully launched. On WebAssembly, this returns immediately and retains the app for the lifetime of the Wasm instance. ### Method run ### Signature pub fn run(self, on_finish_launching: F) where F: 'static + FnOnce(&mut App) ### Parameters - **on_finish_launching** (F) - Required - Callback invoked once the app is fully launched. ### Returns - **()** - Nothing. ``` -------------------------------- ### Application constructors and configuration methods Source: https://docs.rs/gpui-pre/latest/src/gpui/app.rs.html?search= Methods to build and configure an Application: with_platform, new_inaccessible, with_assets, with_restart_arguments, with_http_client, with_quit_mode, and run. ```rust impl Application { /// Builds an app with a caller-provided platform implementation. pub fn with_platform(platform: Rc) -> Self { Self(App::new_app( platform, Arc::new(()), Arc::new(NullHttpClient), )) } /// Builds an app with accessibility (AccessKit) integration forcibly /// disabled. /// /// In this mode, accessibility APIs (e.g. /// [`div().role()`][crate::StatefulInteractiveElement::role]) silently /// no-op. /// /// See the [accessibility guide](crate::_accessibility) for an overview of /// the features this disables. pub fn new_inaccessible(platform: Rc) -> Self { let this = Self::with_platform(platform); this.0.borrow_mut().accessibility_force_disabled = true; this } /// Assigns the source of assets for the application. pub fn with_assets(self, asset_source: impl AssetSource) -> Self { let mut context_lock = self.0.borrow_mut(); let asset_source = Arc::new(asset_source); context_lock.asset_source = asset_source.clone(); context_lock.svg_renderer = SvgRenderer::new(asset_source); drop(context_lock); self } /// Configures arguments to pass when restarting the application. pub fn with_restart_arguments(self, arguments: Vec) -> Self { self.0.borrow_mut().restart_arguments = arguments; self } /// Sets the HTTP client for the application. pub fn with_http_client(self, http_client: Arc) -> Self { let mut context_lock = self.0.borrow_mut(); context_lock.http_client = http_client; drop(context_lock); self } /// Configures when the application should automatically quit. /// By default, [`QuitMode::Default`] is used. pub fn with_quit_mode(self, mode: QuitMode) -> Self { self.0.borrow_mut().quit_mode = mode; self } /// Start the application. The provided callback will be called once the /// app is fully launched. /// /// On WebAssembly, this returns immediately and retains the app for the lifetime /// of the Wasm instance. Use [`Self::run_embedded`] to control its lifetime explicitly. pub fn run(self, on_finish_launching: F) where F: 'static + FnOnce(&mut App), { let this = self.0.clone(); let platform = self.0.borrow().platform.clone(); platform.run(Box::new(move || { let cx = &mut *this.borrow_mut(); on_finish_launching(cx); })); #[cfg(target_family = "wasm")] std::mem::forget(self); } } ``` -------------------------------- ### Application::run Source: https://docs.rs/gpui-pre/latest/gpui/struct.Application.html?search=u32+-%3E+bool Start the application. The provided callback will be called once the app is fully launched. On WebAssembly, this returns immediately and retains the app for the lifetime of the Wasm instance. ```APIDOC ## Application::run ### Description Start the application. The provided callback will be called once the app is fully launched. On WebAssembly, this returns immediately and retains the app for the lifetime of the Wasm instance. ### Method run ### Signature pub fn run(self, on_finish_launching: F) where F: 'static + FnOnce(&mut App) ### Parameters - **on_finish_launching** (F) - Required - Callback invoked once the app is fully launched. ### Returns None ``` -------------------------------- ### trim_start directionality example Source: https://docs.rs/gpui-pre/latest/gpui/struct.SharedUri.html?search=u32+-%3E+bool Demonstrates the directionality of trim_start: it removes leading whitespace from the start of the byte string. The example asserts that the first character after trimming is 'E'. ```rust let s = " English "; assert!(Some('E') == s.trim_start().chars().next()); ``` -------------------------------- ### replace example Source: https://docs.rs/gpui-pre/latest/gpui/struct.SharedUri.html Shows how replace creates a new String and replaces all matches of a pattern with another string. The example is incomplete in the source, showing only the start of a string variable. ```rust let s = "this is old"; ``` -------------------------------- ### Create and run a GPUI Application Source: https://docs.rs/gpui-pre/0.3.6/index.html Creates an Application with gpui_platform::application() and runs it with a callback. Inside the callback, you can open windows and register root views. ```rust use gpui::*; fn main() { gpui_platform::application().run(|cx: &mut App| { // .. }); } ``` -------------------------------- ### begin_input_at helper Source: https://docs.rs/gpui-pre/latest/src/gpui/profiler.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Records an input activity for a window profiler. ```rust fn begin_input_at(window_profiler: &mut WindowProfiler, started_at: Instant) { window_profiler .active_activities .push(WindowActivity::Input { started_at, kind: "test", }); } ``` -------------------------------- ### substr_range example Source: https://docs.rs/gpui-pre/latest/gpui/struct.SharedUri.html Shows how substr_range returns the range that a substring points to using pointer arithmetic, not searching. The example uses split and unwrap to get ranges for each substring. ```rust use core::range::Range; let data = "a, b, b, a"; let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap()); assert_eq!(iter.next(), Some(Range { start: 0, end: 1 })); assert_eq!(iter.next(), Some(Range { start: 3, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 6, end: 7 })); assert_eq!(iter.next(), Some(Range { start: 9, end: 10 })); ``` -------------------------------- ### Example: using Pixels Source: https://docs.rs/gpui-pre/latest/gpui/struct.Pixels.html?search= Shows how to create a `Pixels` value from an `f32`, scale it by a factor, and assert equality with `ScaledPixels`. ```rust use gpui::{Pixels, ScaledPixels}; // Define a length of 10 pixels let length = Pixels::from(10.0); // Define a length and scale it by a factor of 2 let scaled_length = length.scale(2.0); assert_eq!(scaled_length, ScaledPixels::from(20.0)); ``` -------------------------------- ### Application run method Source: https://docs.rs/gpui-pre/latest/src/gpui/app.rs.html?search=std%3A%3Avec Starts the application, invoking the provided callback once launched. On WebAssembly, returns immediately and retains the app for the lifetime of the Wasm instance. ```rust /// Start the application. The provided callback will be called once the /// app is fully launched. /// /// On WebAssembly, this returns immediately and retains the app for the lifetime /// of the Wasm instance. Use [`Self::run_embedded`] to control its lifetime explicitly. pub fn run(self, on_finish_launching: F) where F: 'static + FnOnce(&mut App), { let this = self.0.clone(); let platform = self.0.borrow().platform.clone(); platform.run(Box::new(move || { let cx = &mut *this.borrow_mut(); on_finish_launching(cx); })); #[cfg(target_family = "wasm")] std::mem::forget(self); } ``` -------------------------------- ### Manually create a Box from scratch using Box::from_raw_in Source: https://docs.rs/gpui-pre/latest/gpui/type.ExternalDragPayloadSource.html?search=std%3A%3Avec Shows how to manually allocate memory and construct a Box using the system allocator. ```rust #![feature(allocator_api, slice_ptr_get)] use std::alloc::{Allocator, Layout, System}; unsafe { let ptr = System.allocate(Layout::new::())?.as_mut_ptr() as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw_in(ptr, System); } ``` -------------------------------- ### init Source: https://docs.rs/gpui-pre/latest/gpui/struct.SystemWindowTabController.html Initializes the global window tab controller. ```APIDOC ## init ### Description Initializes the global window tab controller. ### Method `pub fn init(cx: &mut App)` ### Parameters - `cx` (`&mut App`) - The application context. ### Returns None. ``` -------------------------------- ### Get other side along axis Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html Returns the anchor on the other side along the specified axis (Horizontal or Vertical). For example, TopLeft.other_side_along(Axis::Horizontal) returns TopRight. ```rust pub fn other_side_along(self, axis: Axis) -> Self { match axis { Axis::Vertical => match self { Anchor::TopLeft => Anchor::BottomLeft, Anchor::TopRight => Anchor::BottomRight, Anchor::BottomLeft => Anchor::TopLeft, Anchor::BottomRight => Anchor::TopRight, Anchor::TopCenter => Anchor::BottomCenter, Anchor::BottomCenter => Anchor::TopCenter, Anchor::LeftCenter => Anchor::LeftCenter, Anchor::RightCenter => Anchor::RightCenter, }, Axis::Horizontal => match self { Anchor::TopLeft => Anchor::TopRight, Anchor::TopRight => Anchor::TopLeft, Anchor::BottomLeft => Anchor::BottomRight, Anchor::BottomRight => Anchor::BottomLeft, Anchor::TopCenter => Anchor::TopCenter, Anchor::BottomCenter => Anchor::BottomCenter, Anchor::LeftCenter => Anchor::RightCenter, Anchor::RightCenter => Anchor::LeftCenter, }, } } ``` -------------------------------- ### Get min Size component-wise Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html Returns a new Size with the minimum width and height from self and other. The example shows comparing two sizes and asserting the result. ```rust /// # use gpui::Size; let size1 = Size { width: 30, height: 40 }; let size2 = Size { width: 50, height: 20 }; let min_size = size1.min(&size2); assert_eq!(min_size, Size { width: 30, height: 20 }); ``` -------------------------------- ### run Source: https://docs.rs/gpui-pre/latest/gpui/trait.Platform.html Runs the platform with a callback that is invoked when launching is finished. ```APIDOC ## run ### Description Runs the platform with a callback that is invoked when launching is finished. ### Signature ```rust fn run(&self, on_finish_launching: Box); ``` ### Parameters - **on_finish_launching** (Box) - Required - Callback invoked when launching is finished. ``` -------------------------------- ### begin_input_at: push input activity to window profiler Source: https://docs.rs/gpui-pre/latest/src/gpui/profiler.rs.html?search=std%3A%3Avec Pushes a WindowActivity::Input with the given start time and kind "test" onto the window profiler's active activities. Used to simulate input activity in tests. ```rust fn begin_input_at(window_profiler: &mut WindowProfiler, started_at: Instant) { window_profiler .active_activities .push(WindowActivity::Input { started_at, kind: "test", }); } ``` -------------------------------- ### Get max Size component-wise Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html Returns a new Size with the maximum width and height from self and other. The example shows comparing two sizes and asserting the result. ```rust /// # use gpui::Size; let size1 = Size { width: 30, height: 40 }; let size2 = Size { width: 50, height: 20 }; let max_size = size1.max(&size2); assert_eq!(max_size, Size { width: 50, height: 40 }); ``` -------------------------------- ### Scale Size by factor Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html Multiplies width and height by a factor, returning Size. The example shows scaling a 100x50 size by 2.0 to get 200x100. ```rust /// # use gpui::{Size, Pixels, ScaledPixels}; let size = Size { width: Pixels::from(100.0), height: Pixels::from(50.0) }; let scaled_size = size.scale(2.0); assert_eq!(scaled_size, Size { width: ScaledPixels::from(200.0), height: ScaledPixels::from(100.0) }); ``` -------------------------------- ### Set up follow-tail list Source: https://docs.rs/gpui-pre/latest/src/gpui/elements/list.rs.html?search=u32+-%3E+bool Sets up a GPUI list with follow-tail mode and a fixed-height item renderer. The comment indicates the scroll is anchored to the bottom. ```rust let cx = cx.add_empty_window(); // 10 items × 50px = 500px total, 200px viewport. let state = ListState::new(10, crate::ListAlignment::Top, px(0.)); struct TestView(ListState); impl Render for TestView { fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { list(self.0.clone(), |_, _, _| { div().h(px(50.)).w_full().into_any() }) .w_full() .h_full() } } state.set_follow_mode(FollowMode::Tail); // Paint with follow-tail — scroll anchored to the bottom. ``` -------------------------------- ### Setup function for keyboard activation test Source: https://docs.rs/gpui-pre/latest/src/gpui/elements/div.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a test app with a KeyboardActivationTest window, returning the app context, window handle, clicks vector, and two focus handles. Used to test keyboard activation behavior. ```rust fn setup_keyboard_activation_test() -> ( TestAppContext, AnyWindowHandle, Rc>>, FocusHandle, FocusHandle, ) { let mut cx = TestAppContext::single(); let (focus_a, focus_b) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle())); let clicks: Rc>> = Rc::new(RefCell::new(Vec::new())); let window = cx.add_window({ let focus_a = focus_a.clone(); let focus_b = focus_b.clone(); let clicks = clicks.clone(); move |_, _| KeyboardActivationTest { focus_a, focus_b, clicks, } }); (cx, window.into(), clicks, focus_a, focus_b) ``` -------------------------------- ### Get a Waker and Reschedule a Runnable Source: https://docs.rs/gpui-pre/latest/gpui/type.RunnableVariant.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Shows how to obtain a Waker from a Runnable and use it to reschedule the task. The example uses a pending future, runs the task, then wakes it and verifies the schedule channel receives it again. ```rust use smol::future; // A function that schedules the task when it gets woken up. let (s, r) = flume::unbounded(); let schedule = move |runnable| s.send(runnable).unwrap(); // Create a task with a simple future and the schedule function. let (runnable, task) = async_task::spawn(future::pending::<()>(), schedule); // Take a waker and run the task. let waker = runnable.waker(); runnable.run(); // Reschedule the task by waking it. assert_eq!(r.len(), 0); waker.wake(); assert_eq!(r.len(), 1); ``` -------------------------------- ### pub fn start_picking(&mut self) Source: https://docs.rs/gpui-pre/latest/gpui/struct.Inspector.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts element picking mode, allowing the user to select elements by clicking. ```APIDOC ## start_picking ### Description Starts element picking mode, allowing the user to select elements by clicking. ### Method `pub fn start_picking(&mut self)` ### Parameters None. ### Returns Nothing. ``` -------------------------------- ### scrollbar_drag_started Source: https://docs.rs/gpui-pre/latest/gpui/struct.ListState.html?search= Call this method when the user starts dragging the scrollbar. This prevents the height reported to the scrollbar from changing during the drag as items in the overdraw get measured, and helps offset scroll position changes accordingly. ```APIDOC ## scrollbar_drag_started ### Description Call this method when the user starts dragging the scrollbar. This will prevent the height reported to the scrollbar from changing during the drag as items in the overdraw get measured, and help offset scroll position changes accordingly. ### Method `pub fn scrollbar_drag_started(&self)` ### Parameters None. ### Returns `()` (unit) ``` -------------------------------- ### Rust: remove_range usage with assertions Source: https://docs.rs/gpui-pre-sum-tree/0.3.6/src/sum_tree/tree_map.rs.html Demonstrates removing a range of entries from a `TreeMap` using `remove_range` with a start key and a `PathDescendants` iterator. The example inserts several entries, removes ranges, and asserts the resulting map state. ```rust map.insert(PathBuf::from("b/a/a/a/b"), 4); map.insert(PathBuf::from("c"), 5); map.insert(PathBuf::from("c/a"), 6); map.remove_range( &PathBuf::from("b/a"), &PathDescendants(&PathBuf::from("b/a")), ); assert_eq!(map.get(&PathBuf::from("a")), Some(&1)); assert_eq!(map.get(&PathBuf::from("a/a")), Some(&1)); assert_eq!(map.get(&PathBuf::from("b")), Some(&2)); assert_eq!(map.get(&PathBuf::from("b/a/a")), None); assert_eq!(map.get(&PathBuf::from("b/a/a/a/b")), None); assert_eq!(map.get(&PathBuf::from("c")), Some(&5)); assert_eq!(map.get(&PathBuf::from("c/a")), Some(&6)); map.remove_range(&PathBuf::from("c"), &PathDescendants(&PathBuf::from("c"))); assert_eq!(map.get(&PathBuf::from("a")), Some(&1)); assert_eq!(map.get(&PathBuf::from("a/a")), Some(&1)); assert_eq!(map.get(&PathBuf::from("b")), Some(&2)); assert_eq!(map.get(&PathBuf::from("c")), None); assert_eq!(map.get(&PathBuf::from("c/a")), None); map.remove_range(&PathBuf::from("a"), &PathDescendants(&PathBuf::from("a"))); assert_eq!(map.get(&PathBuf::from("a")), None); assert_eq!(map.get(&PathBuf::from("a/a")), None); assert_eq!(map.get(&PathBuf::from("b")), Some(&2)); map.remove_range(&PathBuf::from("b"), &PathDescendants(&PathBuf::from("b"))); assert_eq!(map.get(&PathBuf::from("b")), None); ``` -------------------------------- ### Test module setup with GroupHoverTestView Source: https://docs.rs/gpui-pre/latest/src/gpui/elements/div.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a test module for the scroll container, importing necessary GPUI test utilities and defining a GroupHoverTestView struct with render counts and a stateful width. The Render implementation is incomplete in the source. ```rust #[cfg(test)] mod tests { use super::*; use crate::{ AnyWindowHandle, AppContext as _, Context, GestureTuning, InputEvent, Keystroke, MouseMoveEvent, TestAppContext, TouchEvent, TouchId, canvas, util::FluentBuilder as _, }; use std::{cell::Cell, rc::Weak}; struct GroupHoverTestView { render_count: Rc>, anonymous_paint_count: Rc>, stateful_width: Rc>, } impl Render for GroupHoverTestView { fn render(&mut self, _window: &mut Window, _cx: &mut Context) -> impl IntoElement { ``` -------------------------------- ### pub fn start_window_move(&self) Source: https://docs.rs/gpui-pre/latest/gpui/struct.Window.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Handle window movement for Linux and macOS. Tells the compositor to take control of window movement (Wayland and X11). Events may not be received during a move operation. ```APIDOC ## pub fn start_window_move(&self) ### Description Handle window movement for Linux and macOS. Tells the compositor to take control of window movement (Wayland and X11). Events may not be received during a move operation. ### Method `start_window_move` ### Parameters None ### Returns None ``` -------------------------------- ### Setup pending input test with ambiguous bindings Source: https://docs.rs/gpui-pre/latest/src/gpui/key_dispatch.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a pending input test with two key bindings: 'ctrl-b h' for SecondaryTestAction and 'ctrl-b h j' for TestAction. This is used to test that the timeout starts when the binding becomes ambiguous. ```rust let (cx, action_count, secondary_action_count) = setup_pending_input_test( cx, [ KeyBinding::new("ctrl-b h", SecondaryTestAction, Some("Terminal")), KeyBinding::new("ctrl-b h j", TestAction, Some("Terminal")), ], ); ``` -------------------------------- ### new Source: https://docs.rs/gpui-pre/latest/gpui/struct.KeyBinding.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructs a new keybinding from the given keystrokes, action, and optional context. Panics on parse error. ```APIDOC ## new ### Description Constructs a new keybinding from the given data. Panics on parse error. ### Method `pub fn new(keystrokes: &str, action: A, context: Option<&str>) -> Self` ### Parameters - `keystrokes` (&str) - Required - The keystrokes string for the binding. - `action` (A) - Required - The action to associate with the binding, where A implements the `Action` trait. - `context` (Option<&str>) - Optional - The context predicate string. ### Returns Returns a new `KeyBinding` instance. ### Panics Panics if the keystrokes string fails to parse. ``` -------------------------------- ### Get a specific corner of Bounds using Anchor Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html?search=std%3A%3Avec Returns the corner point of the bounds as specified by an Anchor parameter. The example creates a Bounds with origin (0,0) and size (10,20), then asserts that corner(Anchor::BottomLeft) equals Point { x: 0, y: 20 }. ```rust /// # Examples /// /// ``` /// use gpui::{Bounds, Anchor, Point, Size}; /// let bounds = Bounds { /// origin: Point { x: 0, y: 0 }, /// size: Size { width: 10, height: 20 }, /// }; /// let bottom_left = bounds.corner(Anchor::BottomLeft); /// assert_eq!(bottom_left, Point { x: 0, y: 20 }); /// ``` ``` -------------------------------- ### open_with_system Source: https://docs.rs/gpui-pre/latest/gpui/struct.App.html?search=u32+-%3E+bool Opens a path with the system's default application. ```APIDOC ## `open_with_system` ### Description Opens the specified path with the system's default application. ### Signature ```rust pub fn open_with_system(&self, path: &Path) ``` ### Parameters - `path` (`&Path`) - The path to open. ### Returns - `()` - No return value. ``` -------------------------------- ### Truncate line from start Source: https://docs.rs/gpui-pre/latest/src/gpui/text_system/line_wrapper.rs.html?search=u32+-%3E+bool Starts a test for truncating a line from the start, with a helper function marked with #[track_caller]. ```rust let mut wrapper = build_wrapper(); #[track_caller] fn perform_test( wrapper: &mut LineWrapper, ``` -------------------------------- ### start_window_move Source: https://docs.rs/gpui-pre/latest/gpui/struct.Window.html Handles window movement for Linux and macOS. ```APIDOC ## `pub fn start_window_move(&self)` ### Description Handles window movement for Linux and macOS. Tells the compositor to take control of window movement (Wayland and X11). Events may not be received during a move operation. ### Signature `pub fn start_window_move(&self)` ### Parameters None. ### Returns None. ``` -------------------------------- ### Claim a touch drag and verify its start event Source: https://docs.rs/gpui-pre/latest/src/gpui/gestures.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a touch drag by sending a Started event, then claims the drag via offer_touch_drag and verifies the returned phase and start position. Resolves the drag with resolve_touch_drag(true) to complete the gesture. ```rust let mut recognizer = TouchGestureRecognizer::new(GestureTuning::default()); let touch = TouchId(1); let now = Instant::now(); recognizer.handle_event_at(&touch_event(touch, TouchPhase::Started, 10., 20.), now); let Some(RecognizedTouchGesture::TouchDrag(started)) = recognizer.offer_touch_drag(touch) else { panic!("expected touch drag"); }; assert_eq!(started.phase, TouchPhase::Started); assert_eq!(started.start_position, point(px(10.), px(20.))); recognizer.resolve_touch_drag(true); ``` -------------------------------- ### GPUI App initialization with platform callbacks Source: https://docs.rs/gpui-pre/latest/src/gpui/app.rs.html?search=u32+-%3E+bool Initialization of the GPUI application context, including field initialization, menu setup, and platform event handlers. The first block sets up the App struct fields; the second initializes menus and the window tab controller; the third and fourth register keyboard layout and thermal state change callbacks. ```rust text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())), mode: GpuiMode::Production, actions: Rc::new(ActionRegistry::default()), flushing_effects: false, pending_updates: 0, active_drag: None, platform_owned_drag: None, background_executor, foreground_executor, #[cfg(feature = "profiler")] foreground_journal, svg_renderer: SvgRenderer::new(asset_source.clone()), loading_assets: Default::default(), asset_source, http_client, globals_by_type: Default::default(), entities, new_entity_observers: SubscriberSet::new(), windows: SlotMap::with_key(), window_update_stack: Vec::new(), window_handles: FxHashMap::default(), focus_handles: Arc::new(RwLock::new(SlotMap::with_key())), keymap: Rc::new(RefCell::new(Keymap::default())), keyboard_layout, keyboard_mapper, global_action_listeners: Default::default(), pending_effects: VecDeque::new(), pending_notifications: FxHashSet::default(), pending_global_notifications: Default::default(), observers: SubscriberSet::new(), tracked_entities: FxHashMap::default(), window_invalidators_by_entity: FxHashMap::default(), current_window_by_entity: FxHashMap::default(), event_listeners: SubscriberSet::new(), release_listeners: SubscriberSet::new(), keystroke_observers: SubscriberSet::new(), keystroke_interceptors: SubscriberSet::new(), keyboard_layout_observers: SubscriberSet::new(), missing_glyph_callback: Rc::default(), thermal_state_observers: SubscriberSet::new(), system_sleep_observers: SubscriberSet::new(), system_wake_observers: SubscriberSet::new(), global_observers: SubscriberSet::new(), quit_observers: SubscriberSet::new(), restart_observers: SubscriberSet::new(), restart_path: None, restart_arguments: Vec::new(), window_closed_observers: SubscriberSet::new(), layout_id_buffer: Default::default(), propagate_event: true, prompt_builder: Some(PromptBuilder::Default), #[cfg(any(feature = "inspector", debug_assertions))] inspector_renderer: None, #[cfg(any(feature = "inspector", debug_assertions))] inspector_element_registry: InspectorElementRegistry::default(), quit_mode: QuitMode::default(), quitting: false, cursor_hide_mode: CursorHideMode::default(), reduce_motion: false, synced_animation_epoch, accessibility_force_disabled: false #[cfg(any(test, feature = "test-support", debug_assertions))] name: None, element_arena: RefCell::new(Arena::new(1024 * 1024)), event_arena: Arena::new(1024 * 1024), #[cfg(any(test, feature = "leak-detection"))] _ref_counts, ``` ```rust init_app_menus(platform.as_ref(), &app.borrow()); SystemWindowTabController::init(&mut app.borrow_mut()); #[cfg(feature = "profiler")] crate::profiler::journal::observe_power(&app.borrow()); ``` ```rust platform.on_keyboard_layout_change(Box::new({ let app = Rc::downgrade(&app); move || { if let Some(app) = app.upgrade() { let cx = &mut app.borrow_mut(); cx.keyboard_layout = cx.platform.keyboard_layout(); cx.keyboard_mapper = cx.platform.keyboard_mapper(); cx.keyboard_layout_observers .clone() .retain(&(), move |callback| (callback)(cx)); } } })); ``` ```rust platform.on_thermal_state_change(Box::new({ let app = Rc::downgrade(&app); move || { if let Some(app) = app.upgrade() { let cx = &mut app.borrow_mut(); cx.thermal_state_observers .clone() ``` -------------------------------- ### get Source: https://docs.rs/gpui-pre/latest/gpui/struct.KeyContext.html?search=u32+-%3E+bool Gets the associated value for a given identifier or key. ```APIDOC ## get ### Description Get the associated value for a given identifier or key. ### Method `pub fn get(&self, key: &str) -> Option<&SharedString>` ### Parameters - **key** (`&str`) - The identifier or key to look up. ### Returns - **Option<&SharedString>** - The associated value if found, otherwise `None`. ``` -------------------------------- ### Initialize Edges Source: https://docs.rs/gpui-pre/latest/gpui/struct.Edges.html Example showing how to manually initialize an Edges struct. ```rust let edges = Edges { top: 10.0, right: 20.0, bottom: 30.0, left: 40.0, }; assert_eq!(edges.top, 10.0); assert_eq!(edges.right, 20.0); assert_eq!(edges.bottom, 30.0); assert_eq!(edges.left, 40.0); ``` -------------------------------- ### Setup pending input test with key bindings Source: https://docs.rs/gpui-pre/latest/src/gpui/key_dispatch.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a test window with a PendingInputTestView, binds the given key bindings, and returns the visual test context and action counters. The view is focused and the window activated to simulate user interaction. ```rust fn setup_pending_input_test( cx: &mut TestAppContext, bindings: impl IntoIterator, ) -> (&mut VisualTestContext, Rc>, Rc>) { cx.update(|cx| cx.bind_keys(bindings)); let action_count = Rc::new(Cell::new(0)); let secondary_action_count = Rc::new(Cell::new(0)); let (view, cx) = cx.add_window_view(|_, cx| PendingInputTestView { focus_handle: cx.focus_handle(), action_count: action_count.clone(), secondary_action_count: secondary_action_count.clone(), }); let focus_handle = cx.update(|_, cx| view.read(cx).focus_handle.clone()); cx.update(|window, cx| { window.focus(&focus_handle, cx); window.activate_window(); }); (cx, action_count, secondary_action_count) } ``` -------------------------------- ### Edges::any example: predicate check Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example for Edges::any, which returns true if any edge field satisfies the given predicate. The example checks for zero, positive, and greater-than-10 values. ```rust /// # use gpui::Edges; /// let edges = Edges { /// top: 10, /// right: 0, /// bottom: 5, /// left: 0, /// }; /// /// assert!(edges.any(|value| *value == 0)); /// assert!(edges.any(|value| *value > 0)); /// assert!(!edges.any(|value| *value > 10)); ``` -------------------------------- ### opacity method example with gpui::red() Source: https://docs.rs/gpui-pre/latest/gpui/struct.Hsla.html?search= Shows how to use the opacity method to multiply the alpha value of a color. The example creates a red color and fades it to half opacity, asserting the resulting alpha is 0.5. ```rust let color = gpui::red(); let faded_color = color.opacity(0.5); assert_eq!(faded_color.a, 0.5); ``` -------------------------------- ### Anchor::opposite example Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example for `Anchor::opposite`, asserting that `TopLeft` maps to `BottomRight`. ```rust /// # use gpui::Anchor; /// assert_eq!(Anchor::TopLeft.opposite(), Anchor::BottomRight); /// ``` ``` -------------------------------- ### center method example Source: https://docs.rs/gpui-pre/latest/gpui/struct.Bounds.html?search=std%3A%3Avec Shows how to use the center method to calculate the center point of a Bounds instance. The example creates a bounds with origin (0,0) and size (10,20) and asserts that the center is (5,10). ```rust let bounds = Bounds { origin: Point { x: 0, y: 0 }, size: Size { width: 10, height: 20 }, }; let center = bounds.center(); assert_eq!(center, Point { x: 5, y: 10 }); ``` -------------------------------- ### iter example Source: https://docs.rs/gpui-pre/latest/gpui/type.Result.html?search=std%3A%3Avec Example for `Result::iter`, showing how to iterate over the possibly contained value. ```rust let x: Result = Ok(7); assert_eq!(x.iter().next(), Some(&7)); let x: Result = Err("nothing!"); assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Example: is_ok() on Result Source: https://docs.rs/gpui-pre/latest/gpui/type.Result.html?search=std%3A%3Avec Examples of using is_ok to check if a result is Ok. ```rust let x: Result = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` -------------------------------- ### Create an entity with `cx.new` inside `App::run` Source: https://docs.rs/gpui-pre/latest/gpui/_ownership_and_data_flow/index.html Shows the basic setup: `gpui_platform::application().run` passes an `App` reference, and `cx.new` creates an entity (`Counter`) and returns an `Entity` handle. The handle is inert without an `App` reference. ```rust gpui_platform::application().run(|cx: &mut App| { let _counter: Entity = cx.new(|_cx| Counter { count: 0 }); // ... }); ``` -------------------------------- ### Example: transpose() on Result, E> Source: https://docs.rs/gpui-pre/latest/gpui/type.Result.html?search=std%3A%3Avec Example of transposing a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result, SomeErr> = Ok(Some(5)); let y: Option> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Path::new Source: https://docs.rs/gpui-pre/latest/gpui/struct.Path.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new path with the given starting point. ```APIDOC ## Path::new ### Description Creates a new path with the given starting point. ### Method pub fn new(start: Point) -> Self ### Parameters - **start** (Point) - The starting point of the path. ### Returns - **Self** - A new Path instance. ``` -------------------------------- ### pub fn open_window(&mut self, options: WindowOptions, build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity) -> Result> Source: https://docs.rs/gpui-pre/latest/gpui/struct.App.html?search=u32+-%3E+bool Opens a new window with the given option and the root view returned by the given function. The function is invoked with a Window, which can be used to interact with window-specific functionality. ```APIDOC ## pub fn open_window(&mut self, options: WindowOptions, build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity) -> Result> ### Description Opens a new window with the given option and the root view returned by the given function. The function is invoked with a `Window`, which can be used to interact with window-specific functionality. ### Method `open_window` ### Parameters - `self` (`&mut self`) - Required - The mutable reference to the App instance. - `options` (`WindowOptions`) - Required - The options for the new window. - `build_root_view` (`impl FnOnce(&mut Window, &mut App) -> Entity`) - Required - A function that builds the root view for the window. ### Returns `Result>` - A result containing a handle to the new window, or an error. ``` -------------------------------- ### Example usage of block_on Source: https://docs.rs/gpui-pre/latest/gpui/fn.block_on.html A simple example that creates an async block and runs it with pollster::block_on. ```rust let my_fut = async {}; let result = pollster::block_on(my_fut); ``` -------------------------------- ### new Source: https://docs.rs/gpui-pre/latest/gpui/struct.SystemWindowTabController.html Creates a new instance of the window tab controller. ```APIDOC ## new ### Description Creates a new instance of the window tab controller. ### Method `pub fn new() -> Self` ### Parameters None. ### Returns - `Self` - A new `SystemWindowTabController` instance. ``` -------------------------------- ### Anchor::opposite example Source: https://docs.rs/gpui-pre/latest/gpui/enum.Anchor.html Example for the opposite method, showing that TopLeft's opposite is BottomRight. ```rust assert_eq!(Anchor::TopLeft.opposite(), Anchor::BottomRight); ``` -------------------------------- ### Edges::map example with gpui::Edges Source: https://docs.rs/gpui-pre/latest/src/gpui/geometry.rs.html Example usage of the map method on Edges, converting integer edges to floats and applying a multiplier. The example uses the gpui::Edges type and demonstrates the map function with a closure. ```rust /// # use gpui::Edges; /// let edges = Edges { top: 10, right: 20, bottom: 30, left: 40 }; /// let edges_float = edges.map(|&value| value as f32 * 1.1); /// assert_eq!(edges_float, Edges { top: 11.0, right: 22.0, bottom: 33.0, left: 44.0 }); ``` -------------------------------- ### KeyContext::new_with_defaults Source: https://docs.rs/gpui-pre/latest/gpui/struct.KeyContext.html?search= Initializes a new KeyContext that contains an 'os' key set to either 'macos', 'linux', 'windows' or 'unknown'. ```APIDOC ## KeyContext::new_with_defaults ### Description Initializes a new `KeyContext` that contains an `os` key set to either `macos`, `linux`, `windows` or `unknown`. ### Method `pub fn new_with_defaults() -> Self` ### Parameters None. ### Returns - `Self` - A new `KeyContext` instance with the `os` key set. ``` -------------------------------- ### new Source: https://docs.rs/gpui-pre/latest/gpui/struct.WindowTextSystem.html Creates a new WindowTextSystem with the given TextSystem. ```APIDOC ## new ### Description Creates a new WindowTextSystem with the given TextSystem. ### Method new ### Signature pub fn new(text_system: Arc) -> Self ### Parameters - **text_system** (Arc) - Required - The TextSystem to use. ### Returns Self - A new WindowTextSystem instance. ```