Eliminate GPUI View, ViewContext, and WindowContext types (#22632)

There's still a bit more work to do on this, but this PR is compiling
(with warnings) after eliminating the key types. When the tasks below
are complete, this will be the new narrative for GPUI:

- `Entity<T>` - This replaces `View<T>`/`Model<T>`. It represents a unit
of state, and if `T` implements `Render`, then `Entity<T>` implements
`Element`.
- `&mut App` This replaces `AppContext` and represents the app.
- `&mut Context<T>` This replaces `ModelContext` and derefs to `App`. It
is provided by the framework when updating an entity.
- `&mut Window` Broken out of `&mut WindowContext` which no longer
exists. Every method that once took `&mut WindowContext` now takes `&mut
Window, &mut App` and every method that took `&mut ViewContext<T>` now
takes `&mut Window, &mut Context<T>`

Not pictured here are the two other failed attempts. It's been quite a
month!

Tasks:

- [x] Remove `View`, `ViewContext`, `WindowContext` and thread through
`Window`
- [x] [@cole-miller @mikayla-maki] Redraw window when entities change
- [x] [@cole-miller @mikayla-maki] Get examples and Zed running
- [x] [@cole-miller @mikayla-maki] Fix Zed rendering
- [x] [@mikayla-maki] Fix todo! macros and comments
- [x] Fix a bug where the editor would not be redrawn because of view
caching
- [x] remove publicness window.notify() and replace with
`AppContext::notify`
- [x] remove `observe_new_window_models`, replace with
`observe_new_models` with an optional window
- [x] Fix a bug where the project panel would not be redrawn because of
the wrong refresh() call being used
- [x] Fix the tests
- [x] Fix warnings by eliminating `Window` params or using `_`
- [x] Fix conflicts
- [x] Simplify generic code where possible
- [x] Rename types
- [ ] Update docs

### issues post merge

- [x] Issues switching between normal and insert mode
- [x] Assistant re-rendering failure
- [x] Vim test failures
- [x] Mac build issue



Release Notes:

- N/A

---------

Co-authored-by: Antonio Scandurra <me@as-cii.com>
Co-authored-by: Cole Miller <cole@zed.dev>
Co-authored-by: Mikayla <mikayla@zed.dev>
Co-authored-by: Joseph <joseph@zed.dev>
Co-authored-by: max <max@zed.dev>
Co-authored-by: Michael Sloan <michael@zed.dev>
Co-authored-by: Mikayla Maki <mikaylamaki@Mikaylas-MacBook-Pro.local>
Co-authored-by: Mikayla <mikayla.c.maki@gmail.com>
Co-authored-by: joão <joao@zed.dev>
This commit is contained in:
Nathan Sobo 2025-01-25 20:02:45 -07:00 committed by GitHub
parent 21b4a0d50e
commit 6fca1d2b0b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
648 changed files with 36248 additions and 28208 deletions

View file

@ -3,8 +3,8 @@ use std::time::Duration;
use anyhow::Result;
use gpui::{
black, bounce, div, ease_in_out, percentage, prelude::*, px, rgb, size, svg, Animation,
AnimationExt as _, App, AppContext, AssetSource, Bounds, SharedString, Transformation,
ViewContext, WindowBounds, WindowOptions,
AnimationExt as _, App, Application, AssetSource, Bounds, Context, SharedString,
Transformation, Window, WindowBounds, WindowOptions,
};
struct Assets {}
@ -36,7 +36,7 @@ const ARROW_CIRCLE_SVG: &str = concat!(
struct AnimationExample {}
impl Render for AnimationExample {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().flex().flex_col().size_full().justify_around().child(
div().flex().flex_row().w_full().justify_around().child(
div()
@ -72,9 +72,9 @@ impl Render for AnimationExample {
}
fn main() {
App::new()
Application::new()
.with_assets(Assets {})
.run(|cx: &mut AppContext| {
.run(|cx: &mut App| {
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
@ -83,9 +83,9 @@ fn main() {
))),
..Default::default()
};
cx.open_window(options, |cx| {
cx.open_window(options, |_, cx| {
cx.activate(false);
cx.new_view(|_cx| AnimationExample {})
cx.new(|_| AnimationExample {})
})
.unwrap();
});

View file

@ -1,4 +1,4 @@
use gpui::{div, img, prelude::*, App, AppContext, Render, ViewContext, WindowOptions};
use gpui::{div, img, prelude::*, App, Application, Context, Render, Window, WindowOptions};
use std::path::PathBuf;
struct GifViewer {
@ -12,7 +12,7 @@ impl GifViewer {
}
impl Render for GifViewer {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
img(self.gif_path.clone())
.size_full()
@ -24,7 +24,7 @@ impl Render for GifViewer {
fn main() {
env_logger::init();
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let cwd = std::env::current_dir().expect("Failed to get current working directory");
let gif_path = cwd.join("crates/gpui/examples/image/black-cat-typing.gif");
@ -40,7 +40,7 @@ fn main() {
focus: true,
..Default::default()
},
|cx| cx.new_view(|_cx| GifViewer::new(gif_path)),
|_, cx| cx.new(|_| GifViewer::new(gif_path)),
)
.unwrap();
cx.activate(true);

View file

@ -1,6 +1,6 @@
use gpui::{
canvas, div, linear_color_stop, linear_gradient, point, prelude::*, px, size, App, AppContext,
Bounds, ColorSpace, Half, Render, ViewContext, WindowOptions,
canvas, div, linear_color_stop, linear_gradient, point, prelude::*, px, size, App, Application,
Bounds, ColorSpace, Context, Half, Render, Window, WindowOptions,
};
struct GradientViewer {
@ -16,7 +16,7 @@ impl GradientViewer {
}
impl Render for GradientViewer {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let color_space = self.color_space;
div()
@ -46,7 +46,7 @@ impl Render for GradientViewer {
.text_color(gpui::white())
.child(format!("{}", color_space))
.active(|this| this.opacity(0.8))
.on_click(cx.listener(move |this, _, cx| {
.on_click(cx.listener(move |this, _, _, cx| {
this.color_space = match this.color_space {
ColorSpace::Oklab => ColorSpace::Srgb,
ColorSpace::Srgb => ColorSpace::Oklab,
@ -205,8 +205,8 @@ impl Render for GradientViewer {
),
)
.child(div().h_24().child(canvas(
move |_, _| {},
move |bounds, _, cx| {
move |_, _, _| {},
move |bounds, _, window, _| {
let size = size(bounds.size.width * 0.8, px(80.));
let square_bounds = Bounds {
origin: point(
@ -225,7 +225,7 @@ impl Render for GradientViewer {
);
path.line_to(square_bounds.bottom_right());
path.line_to(square_bounds.bottom_left());
cx.paint_path(
window.paint_path(
path,
linear_gradient(
180.,
@ -240,13 +240,13 @@ impl Render for GradientViewer {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
cx.open_window(
WindowOptions {
focus: true,
..Default::default()
},
|cx| cx.new_view(|_| GradientViewer::new()),
|_, cx| cx.new(|_| GradientViewer::new()),
)
.unwrap();
cx.activate(true);

View file

@ -1,5 +1,5 @@
use gpui::{
div, prelude::*, px, rgb, size, App, AppContext, Bounds, SharedString, ViewContext,
div, prelude::*, px, rgb, size, App, Application, Bounds, Context, SharedString, Window,
WindowBounds, WindowOptions,
};
@ -8,7 +8,7 @@ struct HelloWorld {
}
impl Render for HelloWorld {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
@ -38,15 +38,15 @@ impl Render for HelloWorld {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(500.), px(500.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| {
cx.new_view(|_cx| HelloWorld {
|_, cx| {
cx.new(|_| HelloWorld {
text: "World".into(),
})
},

View file

@ -5,9 +5,9 @@ use std::sync::Arc;
use anyhow::Result;
use gpui::{
actions, div, img, prelude::*, px, rgb, size, App, AppContext, AssetSource, Bounds,
ImageSource, KeyBinding, Menu, MenuItem, Point, SharedString, SharedUri, TitlebarOptions,
ViewContext, WindowBounds, WindowContext, WindowOptions,
actions, div, img, prelude::*, px, rgb, size, App, AppContext, Application, AssetSource,
Bounds, Context, ImageSource, KeyBinding, Menu, MenuItem, Point, SharedString, SharedUri,
TitlebarOptions, Window, WindowBounds, WindowOptions,
};
struct Assets {
@ -53,7 +53,7 @@ impl ImageContainer {
}
impl RenderOnce for ImageContainer {
fn render(self, _: &mut WindowContext) -> impl IntoElement {
fn render(self, _window: &mut Window, _: &mut App) -> impl IntoElement {
div().child(
div()
.flex_row()
@ -72,7 +72,7 @@ struct ImageShowcase {
}
impl Render for ImageShowcase {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
@ -127,11 +127,11 @@ actions!(image, [Quit]);
fn main() {
env_logger::init();
App::new()
Application::new()
.with_assets(Assets {
base: PathBuf::from("crates/gpui/examples"),
})
.run(|cx: &mut AppContext| {
.run(|cx: &mut App| {
cx.activate(true);
cx.on_action(|_: &Quit, cx| cx.quit());
cx.bind_keys([KeyBinding::new("cmd-q", Quit, None)]);
@ -155,8 +155,8 @@ fn main() {
..Default::default()
};
cx.open_window(window_options, |cx| {
cx.new_view(|_cx| ImageShowcase {
cx.open_window(window_options, |_, cx| {
cx.new(|_| ImageShowcase {
// Relative path to your root project path
local_resource: PathBuf::from_str("crates/gpui/examples/image/app-icon.png")
.unwrap()

View file

@ -3,9 +3,9 @@ use std::{path::Path, sync::Arc, time::Duration};
use anyhow::anyhow;
use gpui::{
black, div, img, prelude::*, pulsating_between, px, red, size, Animation, AnimationExt, App,
AppContext, Asset, AssetLogger, AssetSource, Bounds, Hsla, ImageAssetLoader, ImageCacheError,
ImgResourceLoader, Length, Pixels, RenderImage, Resource, SharedString, ViewContext,
WindowBounds, WindowContext, WindowOptions, LOADING_DELAY,
Application, Asset, AssetLogger, AssetSource, Bounds, Context, Hsla, ImageAssetLoader,
ImageCacheError, ImgResourceLoader, Length, Pixels, RenderImage, Resource, SharedString,
Window, WindowBounds, WindowOptions, LOADING_DELAY,
};
struct Assets {}
@ -46,7 +46,7 @@ impl Asset for LoadImageWithParameters {
fn load(
parameters: Self::Source,
cx: &mut AppContext,
cx: &mut App,
) -> impl std::future::Future<Output = Self::Output> + Send + 'static {
let timer = cx.background_executor().timer(parameters.timeout);
let data = AssetLogger::<ImageAssetLoader>::load(
@ -100,7 +100,7 @@ impl ImageLoadingExample {
}
impl Render for ImageLoadingExample {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().flex().flex_col().size_full().justify_around().child(
div().flex().flex_row().w_full().justify_around().child(
div()
@ -116,8 +116,8 @@ impl Render for ImageLoadingExample {
};
// Load within the 'loading delay', should not show loading fallback
img(move |cx: &mut WindowContext| {
cx.use_asset::<LoadImageWithParameters>(&image_source)
img(move |window: &mut Window, cx: &mut App| {
window.use_asset::<LoadImageWithParameters>(&image_source, cx)
})
.id("image-1")
.border_1()
@ -125,7 +125,7 @@ impl Render for ImageLoadingExample {
.with_fallback(|| Self::fallback_element().into_any_element())
.border_color(red())
.with_loading(|| Self::loading_element().into_any_element())
.on_click(move |_, cx| {
.on_click(move |_, _, cx| {
cx.remove_asset::<LoadImageWithParameters>(&image_source);
})
})
@ -136,8 +136,8 @@ impl Render for ImageLoadingExample {
fail: false,
};
img(move |cx: &mut WindowContext| {
cx.use_asset::<LoadImageWithParameters>(&image_source)
img(move |window: &mut Window, cx: &mut App| {
window.use_asset::<LoadImageWithParameters>(&image_source, cx)
})
.id("image-2")
.with_fallback(|| Self::fallback_element().into_any_element())
@ -145,7 +145,7 @@ impl Render for ImageLoadingExample {
.size_12()
.border_1()
.border_color(red())
.on_click(move |_, cx| {
.on_click(move |_, _, cx| {
cx.remove_asset::<LoadImageWithParameters>(&image_source);
})
})
@ -157,8 +157,8 @@ impl Render for ImageLoadingExample {
};
// Fail to load after a long delay
img(move |cx: &mut WindowContext| {
cx.use_asset::<LoadImageWithParameters>(&image_source)
img(move |window: &mut Window, cx: &mut App| {
window.use_asset::<LoadImageWithParameters>(&image_source, cx)
})
.id("image-3")
.with_fallback(|| Self::fallback_element().into_any_element())
@ -166,7 +166,7 @@ impl Render for ImageLoadingExample {
.size_12()
.border_1()
.border_color(red())
.on_click(move |_, cx| {
.on_click(move |_, _, cx| {
cx.remove_asset::<LoadImageWithParameters>(&image_source);
})
})
@ -183,7 +183,7 @@ impl Render for ImageLoadingExample {
.with_fallback(|| Self::fallback_element().into_any_element())
.border_color(red())
.with_loading(|| Self::loading_element().into_any_element())
.on_click(move |_, cx| {
.on_click(move |_, _, cx| {
cx.remove_asset::<ImgResourceLoader>(&image_source.clone().into());
})
}),
@ -194,9 +194,9 @@ impl Render for ImageLoadingExample {
fn main() {
env_logger::init();
App::new()
Application::new()
.with_assets(Assets {})
.run(|cx: &mut AppContext| {
.run(|cx: &mut App| {
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
@ -205,9 +205,9 @@ fn main() {
))),
..Default::default()
};
cx.open_window(options, |cx| {
cx.open_window(options, |_, cx| {
cx.activate(false);
cx.new_view(|_cx| ImageLoadingExample {})
cx.new(|_| ImageLoadingExample {})
})
.unwrap();
});

View file

@ -2,11 +2,11 @@ use std::ops::Range;
use gpui::{
actions, black, div, fill, hsla, opaque_grey, point, prelude::*, px, relative, rgb, rgba, size,
white, yellow, App, AppContext, Bounds, ClipboardItem, CursorStyle, ElementId,
ElementInputHandler, FocusHandle, FocusableView, GlobalElementId, KeyBinding, Keystroke,
white, yellow, App, Application, Bounds, ClipboardItem, Context, CursorStyle, ElementId,
ElementInputHandler, Entity, FocusHandle, Focusable, GlobalElementId, KeyBinding, Keystroke,
LayoutId, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, Pixels, Point,
ShapedLine, SharedString, Style, TextRun, UTF16Selection, UnderlineStyle, View, ViewContext,
ViewInputHandler, WindowBounds, WindowContext, WindowOptions,
ShapedLine, SharedString, Style, TextRun, UTF16Selection, UnderlineStyle, ViewInputHandler,
Window, WindowBounds, WindowOptions,
};
use unicode_segmentation::*;
@ -42,7 +42,7 @@ struct TextInput {
}
impl TextInput {
fn left(&mut self, _: &Left, cx: &mut ViewContext<Self>) {
fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.move_to(self.previous_boundary(self.cursor_offset()), cx);
} else {
@ -50,7 +50,7 @@ impl TextInput {
}
}
fn right(&mut self, _: &Right, cx: &mut ViewContext<Self>) {
fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.move_to(self.next_boundary(self.selected_range.end), cx);
} else {
@ -58,42 +58,47 @@ impl TextInput {
}
}
fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
self.select_to(self.previous_boundary(self.cursor_offset()), cx);
}
fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
self.select_to(self.next_boundary(self.cursor_offset()), cx);
}
fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
self.move_to(0, cx);
self.select_to(self.content.len(), cx)
}
fn home(&mut self, _: &Home, cx: &mut ViewContext<Self>) {
fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
self.move_to(0, cx);
}
fn end(&mut self, _: &End, cx: &mut ViewContext<Self>) {
fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
self.move_to(self.content.len(), cx);
}
fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.select_to(self.previous_boundary(self.cursor_offset()), cx)
}
self.replace_text_in_range(None, "", cx)
self.replace_text_in_range(None, "", window, cx)
}
fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
if self.selected_range.is_empty() {
self.select_to(self.next_boundary(self.cursor_offset()), cx)
}
self.replace_text_in_range(None, "", cx)
self.replace_text_in_range(None, "", window, cx)
}
fn on_mouse_down(&mut self, event: &MouseDownEvent, cx: &mut ViewContext<Self>) {
fn on_mouse_down(
&mut self,
event: &MouseDownEvent,
_window: &mut Window,
cx: &mut Context<Self>,
) {
self.is_selecting = true;
if event.modifiers.shift {
@ -103,43 +108,48 @@ impl TextInput {
}
}
fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut ViewContext<Self>) {
fn on_mouse_up(&mut self, _: &MouseUpEvent, _window: &mut Window, _: &mut Context<Self>) {
self.is_selecting = false;
}
fn on_mouse_move(&mut self, event: &MouseMoveEvent, cx: &mut ViewContext<Self>) {
fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
if self.is_selecting {
self.select_to(self.index_for_mouse_position(event.position), cx);
}
}
fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
cx.show_character_palette();
fn show_character_palette(
&mut self,
_: &ShowCharacterPalette,
window: &mut Window,
_: &mut Context<Self>,
) {
window.show_character_palette();
}
fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
if let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) {
self.replace_text_in_range(None, &text.replace("\n", " "), cx);
self.replace_text_in_range(None, &text.replace("\n", " "), window, cx);
}
}
fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
if !self.selected_range.is_empty() {
cx.write_to_clipboard(ClipboardItem::new_string(
(&self.content[self.selected_range.clone()]).to_string(),
));
}
}
fn cut(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
fn cut(&mut self, _: &Copy, window: &mut Window, cx: &mut Context<Self>) {
if !self.selected_range.is_empty() {
cx.write_to_clipboard(ClipboardItem::new_string(
(&self.content[self.selected_range.clone()]).to_string(),
));
self.replace_text_in_range(None, "", cx)
self.replace_text_in_range(None, "", window, cx)
}
}
fn move_to(&mut self, offset: usize, cx: &mut ViewContext<Self>) {
fn move_to(&mut self, offset: usize, cx: &mut Context<Self>) {
self.selected_range = offset..offset;
cx.notify()
}
@ -170,7 +180,7 @@ impl TextInput {
line.closest_index_for_x(position.x - bounds.left())
}
fn select_to(&mut self, offset: usize, cx: &mut ViewContext<Self>) {
fn select_to(&mut self, offset: usize, cx: &mut Context<Self>) {
if self.selection_reversed {
self.selected_range.start = offset
} else {
@ -252,7 +262,8 @@ impl ViewInputHandler for TextInput {
&mut self,
range_utf16: Range<usize>,
actual_range: &mut Option<Range<usize>>,
_cx: &mut ViewContext<Self>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<String> {
let range = self.range_from_utf16(&range_utf16);
actual_range.replace(self.range_to_utf16(&range));
@ -262,7 +273,8 @@ impl ViewInputHandler for TextInput {
fn selected_text_range(
&mut self,
_ignore_disabled_input: bool,
_cx: &mut ViewContext<Self>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<UTF16Selection> {
Some(UTF16Selection {
range: self.range_to_utf16(&self.selected_range),
@ -270,13 +282,17 @@ impl ViewInputHandler for TextInput {
})
}
fn marked_text_range(&self, _cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
fn marked_text_range(
&self,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<Range<usize>> {
self.marked_range
.as_ref()
.map(|range| self.range_to_utf16(range))
}
fn unmark_text(&mut self, _cx: &mut ViewContext<Self>) {
fn unmark_text(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {
self.marked_range = None;
}
@ -284,7 +300,8 @@ impl ViewInputHandler for TextInput {
&mut self,
range_utf16: Option<Range<usize>>,
new_text: &str,
cx: &mut ViewContext<Self>,
_: &mut Window,
cx: &mut Context<Self>,
) {
let range = range_utf16
.as_ref()
@ -305,7 +322,8 @@ impl ViewInputHandler for TextInput {
range_utf16: Option<Range<usize>>,
new_text: &str,
new_selected_range_utf16: Option<Range<usize>>,
cx: &mut ViewContext<Self>,
_window: &mut Window,
cx: &mut Context<Self>,
) {
let range = range_utf16
.as_ref()
@ -330,7 +348,8 @@ impl ViewInputHandler for TextInput {
&mut self,
range_utf16: Range<usize>,
bounds: Bounds<Pixels>,
_cx: &mut ViewContext<Self>,
_window: &mut Window,
_cx: &mut Context<Self>,
) -> Option<Bounds<Pixels>> {
let last_layout = self.last_layout.as_ref()?;
let range = self.range_from_utf16(&range_utf16);
@ -348,7 +367,7 @@ impl ViewInputHandler for TextInput {
}
struct TextElement {
input: View<TextInput>,
input: Entity<TextInput>,
}
struct PrepaintState {
@ -377,12 +396,13 @@ impl Element for TextElement {
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
let mut style = Style::default();
style.size.width = relative(1.).into();
style.size.height = cx.line_height().into();
(cx.request_layout(style, []), ())
style.size.height = window.line_height().into();
(window.request_layout(style, [], cx), ())
}
fn prepaint(
@ -390,13 +410,14 @@ impl Element for TextElement {
_id: Option<&GlobalElementId>,
bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
let input = self.input.read(cx);
let content = input.content.clone();
let selected_range = input.selected_range.clone();
let cursor = input.cursor_offset();
let style = cx.text_style();
let style = window.text_style();
let (display_text, text_color) = if content.is_empty() {
(input.placeholder.clone(), hsla(0., 0., 0., 0.2))
@ -439,8 +460,8 @@ impl Element for TextElement {
vec![run]
};
let font_size = style.font_size.to_pixels(cx.rem_size());
let line = cx
let font_size = style.font_size.to_pixels(window.rem_size());
let line = window
.text_system()
.shape_line(display_text, font_size, &runs)
.unwrap();
@ -488,22 +509,25 @@ impl Element for TextElement {
bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
prepaint: &mut Self::PrepaintState,
cx: &mut WindowContext,
window: &mut Window,
cx: &mut App,
) {
let focus_handle = self.input.read(cx).focus_handle.clone();
cx.handle_input(
window.handle_input(
&focus_handle,
ElementInputHandler::new(bounds, self.input.clone()),
cx,
);
if let Some(selection) = prepaint.selection.take() {
cx.paint_quad(selection)
window.paint_quad(selection)
}
let line = prepaint.line.take().unwrap();
line.paint(bounds.origin, cx.line_height(), cx).unwrap();
line.paint(bounds.origin, window.line_height(), window, cx)
.unwrap();
if focus_handle.is_focused(cx) {
if focus_handle.is_focused(window) {
if let Some(cursor) = prepaint.cursor.take() {
cx.paint_quad(cursor);
window.paint_quad(cursor);
}
}
@ -515,7 +539,7 @@ impl Element for TextElement {
}
impl Render for TextInput {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.key_context("TextInput")
@ -548,32 +572,32 @@ impl Render for TextInput {
.p(px(4.))
.bg(white())
.child(TextElement {
input: cx.view().clone(),
input: cx.model().clone(),
}),
)
}
}
impl FocusableView for TextInput {
fn focus_handle(&self, _: &AppContext) -> FocusHandle {
impl Focusable for TextInput {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
struct InputExample {
text_input: View<TextInput>,
text_input: Entity<TextInput>,
recent_keystrokes: Vec<Keystroke>,
focus_handle: FocusHandle,
}
impl FocusableView for InputExample {
fn focus_handle(&self, _: &AppContext) -> FocusHandle {
impl Focusable for InputExample {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl InputExample {
fn on_reset_click(&mut self, _: &MouseUpEvent, cx: &mut ViewContext<Self>) {
fn on_reset_click(&mut self, _: &MouseUpEvent, _window: &mut Window, cx: &mut Context<Self>) {
self.recent_keystrokes.clear();
self.text_input
.update(cx, |text_input, _cx| text_input.reset());
@ -582,7 +606,7 @@ impl InputExample {
}
impl Render for InputExample {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.bg(rgb(0xaaaaaa))
.track_focus(&self.focus_handle(cx))
@ -629,7 +653,7 @@ impl Render for InputExample {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(300.0), px(300.0)), cx);
cx.bind_keys([
KeyBinding::new("backspace", Backspace, None),
@ -653,8 +677,8 @@ fn main() {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| {
let text_input = cx.new_view(|cx| TextInput {
|_, cx| {
let text_input = cx.new(|cx| TextInput {
focus_handle: cx.focus_handle(),
content: "".into(),
placeholder: "Type here...".into(),
@ -665,7 +689,7 @@ fn main() {
last_bounds: None,
is_selecting: false,
});
cx.new_view(|cx| InputExample {
cx.new(|cx| InputExample {
text_input,
recent_keystrokes: vec![],
focus_handle: cx.focus_handle(),
@ -673,25 +697,24 @@ fn main() {
},
)
.unwrap();
cx.observe_keystrokes(move |ev, cx| {
window
.update(cx, |view, cx| {
view.recent_keystrokes.push(ev.keystroke.clone());
cx.notify();
})
.unwrap();
let view = window.root_model(cx).unwrap();
cx.observe_keystrokes(move |ev, _, cx| {
view.update(cx, |view, cx| {
view.recent_keystrokes.push(ev.keystroke.clone());
cx.notify();
})
})
.detach();
cx.on_keyboard_layout_change({
move |cx| {
window.update(cx, |_, cx| cx.notify()).ok();
window.update(cx, |_, _, cx| cx.notify()).ok();
}
})
.detach();
window
.update(cx, |view, cx| {
cx.focus_view(&view.text_input);
.update(cx, |view, window, cx| {
window.focus(&view.text_input.focus_handle(cx));
cx.activate(true);
})
.unwrap();

View file

@ -2,8 +2,8 @@ use std::{fs, path::PathBuf, time::Duration};
use anyhow::Result;
use gpui::{
div, hsla, img, point, prelude::*, px, rgb, size, svg, App, AppContext, AssetSource, Bounds,
BoxShadow, ClickEvent, SharedString, Task, Timer, ViewContext, WindowBounds, WindowOptions,
div, hsla, img, point, prelude::*, px, rgb, size, svg, App, Application, AssetSource, Bounds,
BoxShadow, ClickEvent, Context, SharedString, Task, Timer, Window, WindowBounds, WindowOptions,
};
struct Assets {
@ -39,22 +39,22 @@ struct HelloWorld {
}
impl HelloWorld {
fn new(_: &mut ViewContext<Self>) -> Self {
fn new(_window: &mut Window, _: &mut Context<Self>) -> Self {
Self {
_task: None,
opacity: 0.5,
}
}
fn change_opacity(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
fn change_opacity(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
self.opacity = 0.0;
cx.notify();
self._task = Some(cx.spawn(|view, mut cx| async move {
self._task = Some(cx.spawn_in(window, |view, mut cx| async move {
loop {
Timer::after(Duration::from_secs_f32(0.05)).await;
let mut stop = false;
let _ = cx.update(|cx| {
let _ = cx.update(|_, cx| {
view.update(cx, |view, cx| {
if view.opacity >= 1.0 {
stop = true;
@ -75,7 +75,7 @@ impl HelloWorld {
}
impl Render for HelloWorld {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_row()
@ -157,18 +157,18 @@ impl Render for HelloWorld {
}
fn main() {
App::new()
Application::new()
.with_assets(Assets {
base: PathBuf::from("crates/gpui/examples"),
})
.run(|cx: &mut AppContext| {
.run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(500.0), px(500.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| cx.new_view(HelloWorld::new),
|window, cx| cx.new(|cx| HelloWorld::new(window, cx)),
)
.unwrap();
});

View file

@ -1,4 +1,4 @@
use gpui::{prelude::*, App, AppContext, EventEmitter, Model, ModelContext};
use gpui::{prelude::*, App, Application, Context, Entity, EventEmitter};
struct Counter {
count: usize,
@ -11,9 +11,9 @@ struct Change {
impl EventEmitter<Change> for Counter {}
fn main() {
App::new().run(|cx: &mut AppContext| {
let counter: Model<Counter> = cx.new_model(|_cx| Counter { count: 0 });
let subscriber = cx.new_model(|cx: &mut ModelContext<Counter>| {
Application::new().run(|cx: &mut App| {
let counter: Entity<Counter> = cx.new(|_cx| Counter { count: 0 });
let subscriber = cx.new(|cx: &mut Context<Counter>| {
cx.subscribe(&counter, |subscriber, _emitter, event, _cx| {
subscriber.count += event.increment * 2;
})

View file

@ -1,6 +1,6 @@
use gpui::{
canvas, div, point, prelude::*, px, size, App, AppContext, Bounds, MouseDownEvent, Path,
Pixels, Point, Render, ViewContext, WindowOptions,
canvas, div, point, prelude::*, px, size, App, Application, Bounds, Context, MouseDownEvent,
Path, Pixels, Point, Render, Window, WindowOptions,
};
struct PaintingViewer {
default_lines: Vec<Path<Pixels>>,
@ -70,13 +70,13 @@ impl PaintingViewer {
}
}
fn clear(&mut self, cx: &mut ViewContext<Self>) {
fn clear(&mut self, cx: &mut Context<Self>) {
self.lines.clear();
cx.notify();
}
}
impl Render for PaintingViewer {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let default_lines = self.default_lines.clone();
let lines = self.lines.clone();
div()
@ -103,7 +103,7 @@ impl Render for PaintingViewer {
.flex()
.px_3()
.py_1()
.on_click(cx.listener(|this, _, cx| {
.on_click(cx.listener(|this, _, _, cx| {
this.clear(cx);
})),
),
@ -113,11 +113,11 @@ impl Render for PaintingViewer {
.size_full()
.child(
canvas(
move |_, _| {},
move |_, _, cx| {
move |_, _, _| {},
move |_, _, window, _| {
const STROKE_WIDTH: Pixels = px(2.0);
for path in default_lines {
cx.paint_path(path, gpui::black());
window.paint_path(path, gpui::black());
}
for points in lines {
let mut path = Path::new(points[0]);
@ -135,7 +135,7 @@ impl Render for PaintingViewer {
last = p;
}
cx.paint_path(path, gpui::black());
window.paint_path(path, gpui::black());
}
},
)
@ -143,14 +143,14 @@ impl Render for PaintingViewer {
)
.on_mouse_down(
gpui::MouseButton::Left,
cx.listener(|this, ev: &MouseDownEvent, _| {
cx.listener(|this, ev: &MouseDownEvent, _, _| {
this._painting = true;
this.start = ev.position;
let path = vec![ev.position];
this.lines.push(path);
}),
)
.on_mouse_move(cx.listener(|this, ev: &gpui::MouseMoveEvent, cx| {
.on_mouse_move(cx.listener(|this, ev: &gpui::MouseMoveEvent, _, cx| {
if !this._painting {
return;
}
@ -176,7 +176,7 @@ impl Render for PaintingViewer {
}))
.on_mouse_up(
gpui::MouseButton::Left,
cx.listener(|this, _, _| {
cx.listener(|this, _, _, _| {
this._painting = false;
}),
),
@ -185,13 +185,13 @@ impl Render for PaintingViewer {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
cx.open_window(
WindowOptions {
focus: true,
..Default::default()
},
|cx| cx.new_view(|_| PaintingViewer::new()),
|_, cx| cx.new(|_| PaintingViewer::new()),
)
.unwrap();
cx.activate(true);

View file

@ -1,11 +1,11 @@
use gpui::{
actions, div, prelude::*, rgb, App, AppContext, Menu, MenuItem, ViewContext, WindowOptions,
actions, div, prelude::*, rgb, App, Application, Context, Menu, MenuItem, Window, WindowOptions,
};
struct SetMenus;
impl Render for SetMenus {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.bg(rgb(0x2e7d32))
@ -19,7 +19,7 @@ impl Render for SetMenus {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
// Bring the menu bar to the foreground (so you can see the menu bar)
cx.activate(true);
// Register the `quit` function so it can be referenced by the `MenuItem::action` in the menu bar
@ -29,10 +29,8 @@ fn main() {
name: "set_menus".into(),
items: vec![MenuItem::action("Quit", Quit)],
}]);
cx.open_window(WindowOptions::default(), |cx| {
cx.new_view(|_cx| SetMenus {})
})
.unwrap();
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| SetMenus {}))
.unwrap();
});
}
@ -40,7 +38,7 @@ fn main() {
actions!(set_menus, [Quit]);
// Define the quit function that is registered with the AppContext
fn quit(_: &Quit, cx: &mut AppContext) {
fn quit(_: &Quit, cx: &mut App) {
println!("Gracefully quitting the application . . .");
cx.quit();
}

View file

@ -1,6 +1,6 @@
use gpui::{
div, hsla, point, prelude::*, px, relative, rgb, size, App, AppContext, Bounds, BoxShadow, Div,
SharedString, ViewContext, WindowBounds, WindowOptions,
div, hsla, point, prelude::*, px, relative, rgb, size, App, Application, Bounds, BoxShadow,
Context, Div, SharedString, Window, WindowBounds, WindowOptions,
};
use smallvec::smallvec;
@ -86,7 +86,7 @@ fn example(label: impl Into<SharedString>, example: impl IntoElement) -> impl In
}
impl Render for Shadow {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("shadow-example")
.overflow_y_scroll()
@ -567,14 +567,14 @@ impl Render for Shadow {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(1000.0), px(800.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| cx.new_view(|_cx| Shadow {}),
|_, cx| cx.new(|_| Shadow {}),
)
.unwrap();

View file

@ -3,8 +3,8 @@ use std::path::PathBuf;
use anyhow::Result;
use gpui::{
div, prelude::*, px, rgb, size, svg, App, AppContext, AssetSource, Bounds, SharedString,
ViewContext, WindowBounds, WindowOptions,
div, prelude::*, px, rgb, size, svg, App, Application, AssetSource, Bounds, Context,
SharedString, Window, WindowBounds, WindowOptions,
};
struct Assets {
@ -37,7 +37,7 @@ impl AssetSource for Assets {
struct SvgExample;
impl Render for SvgExample {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_row()
@ -68,18 +68,18 @@ impl Render for SvgExample {
}
fn main() {
App::new()
Application::new()
.with_assets(Assets {
base: PathBuf::from("crates/gpui/examples"),
})
.run(|cx: &mut AppContext| {
.run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(300.0), px(300.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| cx.new_view(|_cx| SvgExample),
|_, cx| cx.new(|_| SvgExample),
)
.unwrap();
});

View file

@ -1,11 +1,12 @@
use gpui::{
div, prelude::*, px, size, App, AppContext, Bounds, ViewContext, WindowBounds, WindowOptions,
div, prelude::*, px, size, App, Application, Bounds, Context, Window, WindowBounds,
WindowOptions,
};
struct HelloWorld {}
impl Render for HelloWorld {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let text = "The longest word 你好世界这段是中文,こんにちはこの段落は日本語です in any of the major English language dictionaries is pneumonoultramicroscopicsilicovolcanoconiosis, a word that refers to a lung disease contracted from the inhalation of very fine silica particles, specifically from a volcano; medically, it is the same as silicosis.";
div()
.id("page")
@ -78,14 +79,14 @@ impl Render for HelloWorld {
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(600.0), px(480.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| cx.new_view(|_cx| HelloWorld {}),
|_, cx| cx.new(|_| HelloWorld {}),
)
.unwrap();
});

View file

@ -1,45 +1,50 @@
use gpui::{
div, prelude::*, px, rgb, size, uniform_list, App, AppContext, Bounds, ViewContext,
div, prelude::*, px, rgb, size, uniform_list, App, Application, Bounds, Context, Window,
WindowBounds, WindowOptions,
};
struct UniformListExample {}
impl Render for UniformListExample {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().bg(rgb(0xffffff)).child(
uniform_list(cx.view().clone(), "entries", 50, |_this, range, _cx| {
let mut items = Vec::new();
for ix in range {
let item = ix + 1;
uniform_list(
cx.model().clone(),
"entries",
50,
|_this, range, _window, _cx| {
let mut items = Vec::new();
for ix in range {
let item = ix + 1;
items.push(
div()
.id(ix)
.px_2()
.cursor_pointer()
.on_click(move |_event, _cx| {
println!("clicked Item {item:?}");
})
.child(format!("Item {item}")),
);
}
items
})
items.push(
div()
.id(ix)
.px_2()
.cursor_pointer()
.on_click(move |_event, _window, _cx| {
println!("clicked Item {item:?}");
})
.child(format!("Item {item}")),
);
}
items
},
)
.h_full(),
)
}
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(300.0), px(300.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| cx.new_view(|_cx| UniformListExample {}),
|_, cx| cx.new(|_| UniformListExample {}),
)
.unwrap();
});

View file

@ -1,13 +1,13 @@
use gpui::{
div, prelude::*, px, rgb, size, App, AppContext, Bounds, SharedString, Timer, ViewContext,
WindowBounds, WindowContext, WindowKind, WindowOptions,
div, prelude::*, px, rgb, size, App, Application, Bounds, Context, SharedString, Timer, Window,
WindowBounds, WindowKind, WindowOptions,
};
struct SubWindow {
custom_titlebar: bool,
}
fn button(text: &str, on_click: impl Fn(&mut WindowContext) + 'static) -> impl IntoElement {
fn button(text: &str, on_click: impl Fn(&mut Window, &mut App) + 'static) -> impl IntoElement {
div()
.id(SharedString::from(text.to_string()))
.flex_none()
@ -19,11 +19,11 @@ fn button(text: &str, on_click: impl Fn(&mut WindowContext) + 'static) -> impl I
.rounded_md()
.cursor_pointer()
.child(text.to_string())
.on_click(move |_, cx| on_click(cx))
.on_click(move |_, window, cx| on_click(window, cx))
}
impl Render for SubWindow {
fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
@ -54,8 +54,8 @@ impl Render for SubWindow {
.p_8()
.gap_2()
.child("SubWindow")
.child(button("Close", |cx| {
cx.remove_window();
.child(button("Close", |window, _| {
window.remove_window();
})),
)
}
@ -64,7 +64,7 @@ impl Render for SubWindow {
struct WindowDemo {}
impl Render for WindowDemo {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let window_bounds =
WindowBounds::Windowed(Bounds::centered(None, size(px(300.0), px(300.0)), cx));
@ -77,66 +77,66 @@ impl Render for WindowDemo {
.justify_center()
.items_center()
.gap_2()
.child(button("Normal", move |cx| {
.child(button("Normal", move |_, cx| {
cx.open_window(
WindowOptions {
window_bounds: Some(window_bounds),
..Default::default()
},
|cx| {
cx.new_view(|_cx| SubWindow {
|_, cx| {
cx.new(|_| SubWindow {
custom_titlebar: false,
})
},
)
.unwrap();
}))
.child(button("Popup", move |cx| {
.child(button("Popup", move |_, cx| {
cx.open_window(
WindowOptions {
window_bounds: Some(window_bounds),
kind: WindowKind::PopUp,
..Default::default()
},
|cx| {
cx.new_view(|_cx| SubWindow {
|_, cx| {
cx.new(|_| SubWindow {
custom_titlebar: false,
})
},
)
.unwrap();
}))
.child(button("Custom Titlebar", move |cx| {
.child(button("Custom Titlebar", move |_, cx| {
cx.open_window(
WindowOptions {
titlebar: None,
window_bounds: Some(window_bounds),
..Default::default()
},
|cx| {
cx.new_view(|_cx| SubWindow {
|_, cx| {
cx.new(|_| SubWindow {
custom_titlebar: true,
})
},
)
.unwrap();
}))
.child(button("Invisible", move |cx| {
.child(button("Invisible", move |_, cx| {
cx.open_window(
WindowOptions {
show: false,
window_bounds: Some(window_bounds),
..Default::default()
},
|cx| {
cx.new_view(|_cx| SubWindow {
|_, cx| {
cx.new(|_| SubWindow {
custom_titlebar: false,
})
},
)
.unwrap();
}))
.child(button("Unmovable", move |cx| {
.child(button("Unmovable", move |_, cx| {
cx.open_window(
WindowOptions {
is_movable: false,
@ -144,38 +144,39 @@ impl Render for WindowDemo {
window_bounds: Some(window_bounds),
..Default::default()
},
|cx| {
cx.new_view(|_cx| SubWindow {
|_, cx| {
cx.new(|_| SubWindow {
custom_titlebar: false,
})
},
)
.unwrap();
}))
.child(button("Hide Application", |cx| {
.child(button("Hide Application", |window, cx| {
cx.hide();
// Restore the application after 3 seconds
cx.spawn(|mut cx| async move {
Timer::after(std::time::Duration::from_secs(3)).await;
cx.update(|cx| {
cx.activate(false);
window
.spawn(cx, |mut cx| async move {
Timer::after(std::time::Duration::from_secs(3)).await;
cx.update(|_, cx| {
cx.activate(false);
})
})
})
.detach();
.detach();
}))
}
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(800.0), px(600.0)), cx);
cx.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
},
|cx| cx.new_view(|_cx| WindowDemo {}),
|_, cx| cx.new(|_| WindowDemo {}),
)
.unwrap();
});

View file

@ -1,6 +1,6 @@
use gpui::{
div, point, prelude::*, px, rgb, App, AppContext, Bounds, DisplayId, Hsla, Pixels,
SharedString, Size, ViewContext, WindowBackgroundAppearance, WindowBounds, WindowKind,
div, point, prelude::*, px, rgb, App, Application, Bounds, Context, DisplayId, Hsla, Pixels,
SharedString, Size, Window, WindowBackgroundAppearance, WindowBounds, WindowKind,
WindowOptions,
};
@ -11,8 +11,8 @@ struct WindowContent {
}
impl Render for WindowContent {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let window_bounds = cx.bounds();
fn render(&mut self, window: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let window_bounds = window.bounds();
div()
.flex()
@ -66,7 +66,7 @@ fn build_window_options(display_id: DisplayId, bounds: Bounds<Pixels>) -> Window
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
// Create several new windows, positioned in the top right corner of each screen
let size = Size {
width: px(350.),
@ -80,8 +80,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Top Left {:?}", screen.id()).into(),
bg: gpui::red(),
bounds,
@ -95,8 +95,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Top Right {:?}", screen.id()).into(),
bg: gpui::red(),
bounds,
@ -110,8 +110,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Bottom Left {:?}", screen.id()).into(),
bg: gpui::blue(),
bounds,
@ -125,8 +125,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Bottom Right {:?}", screen.id()).into(),
bg: gpui::blue(),
bounds,
@ -139,8 +139,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Top Center {:?}", screen.id()).into(),
bg: gpui::black(),
bounds,
@ -153,8 +153,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Left Center {:?}", screen.id()).into(),
bg: gpui::black(),
bounds,
@ -170,8 +170,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Center {:?}", screen.id()).into(),
bg: gpui::black(),
bounds,
@ -187,8 +187,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Right Center {:?}", screen.id()).into(),
bg: gpui::black(),
bounds,
@ -204,8 +204,8 @@ fn main() {
size,
};
cx.open_window(build_window_options(screen.id(), bounds), |cx| {
cx.new_view(|_| WindowContent {
cx.open_window(build_window_options(screen.id(), bounds), |_, cx| {
cx.new(|_| WindowContent {
text: format!("Bottom Center {:?}", screen.id()).into(),
bg: gpui::black(),
bounds,

View file

@ -1,7 +1,8 @@
use gpui::{
black, canvas, div, green, point, prelude::*, px, rgb, size, transparent_black, white, App,
AppContext, Bounds, CursorStyle, Decorations, Hsla, MouseButton, Pixels, Point, ResizeEdge,
Size, ViewContext, WindowBackgroundAppearance, WindowBounds, WindowDecorations, WindowOptions,
Application, Bounds, Context, CursorStyle, Decorations, Hsla, MouseButton, Pixels, Point,
ResizeEdge, Size, Window, WindowBackgroundAppearance, WindowBounds, WindowDecorations,
WindowOptions,
};
struct WindowShadow {}
@ -13,13 +14,13 @@ struct WindowShadow {}
// 3. We need to implement the techniques in here in Zed
impl Render for WindowShadow {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let decorations = cx.window_decorations();
fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let decorations = window.window_decorations();
let rounding = px(10.0);
let shadow_size = px(10.0);
let border_size = px(1.0);
let grey = rgb(0x808080);
cx.set_client_inset(shadow_size);
window.set_client_inset(shadow_size);
div()
.id("window-backdrop")
@ -30,22 +31,22 @@ impl Render for WindowShadow {
.bg(gpui::transparent_black())
.child(
canvas(
|_bounds, cx| {
cx.insert_hitbox(
|_bounds, window, _cx| {
window.insert_hitbox(
Bounds::new(
point(px(0.0), px(0.0)),
cx.window_bounds().get_bounds().size,
window.window_bounds().get_bounds().size,
),
false,
)
},
move |_bounds, hitbox, cx| {
let mouse = cx.mouse_position();
let size = cx.window_bounds().get_bounds().size;
move |_bounds, hitbox, window, _cx| {
let mouse = window.mouse_position();
let size = window.window_bounds().get_bounds().size;
let Some(edge) = resize_edge(mouse, shadow_size, size) else {
return;
};
cx.set_cursor_style(
window.set_cursor_style(
match edge {
ResizeEdge::Top | ResizeEdge::Bottom => {
CursorStyle::ResizeUpDown
@ -75,14 +76,14 @@ impl Render for WindowShadow {
.when(!tiling.bottom, |div| div.pb(shadow_size))
.when(!tiling.left, |div| div.pl(shadow_size))
.when(!tiling.right, |div| div.pr(shadow_size))
.on_mouse_move(|_e, cx| cx.refresh())
.on_mouse_down(MouseButton::Left, move |e, cx| {
let size = cx.window_bounds().get_bounds().size;
.on_mouse_move(|_e, window, _cx| window.refresh())
.on_mouse_down(MouseButton::Left, move |e, window, _cx| {
let size = window.window_bounds().get_bounds().size;
let pos = e.position;
match resize_edge(pos, shadow_size, size) {
Some(edge) => cx.start_window_resize(edge),
None => cx.start_window_move(),
Some(edge) => window.start_window_resize(edge),
None => window.start_window_move(),
};
}),
})
@ -116,7 +117,7 @@ impl Render for WindowShadow {
}])
}),
})
.on_mouse_move(|_e, cx| {
.on_mouse_move(|_e, _, cx| {
cx.stop_propagation();
})
.bg(gpui::rgb(0xCCCCFF))
@ -157,12 +158,15 @@ impl Render for WindowShadow {
.map(|div| match decorations {
Decorations::Server => div,
Decorations::Client { .. } => div
.on_mouse_down(MouseButton::Left, |_e, cx| {
cx.start_window_move();
})
.on_click(|e, cx| {
.on_mouse_down(
MouseButton::Left,
|_e, window, _| {
window.start_window_move();
},
)
.on_click(|e, window, _| {
if e.down.button == MouseButton::Right {
cx.show_window_menu(e.up.position);
window.show_window_menu(e.up.position);
}
})
.text_color(black())
@ -199,7 +203,7 @@ fn resize_edge(pos: Point<Pixels>, shadow_size: Pixels, size: Size<Pixels>) -> O
}
fn main() {
App::new().run(|cx: &mut AppContext| {
Application::new().run(|cx: &mut App| {
let bounds = Bounds::centered(None, size(px(600.0), px(600.0)), cx);
cx.open_window(
WindowOptions {
@ -208,10 +212,10 @@ fn main() {
window_decorations: Some(WindowDecorations::Client),
..Default::default()
},
|cx| {
cx.new_view(|cx| {
cx.observe_window_appearance(|_, cx| {
cx.refresh();
|window, cx| {
cx.new(|cx| {
cx.observe_window_appearance(window, |_, window, _| {
window.refresh();
})
.detach();
WindowShadow {}