Merge branch 'main' into file_finder

This commit is contained in:
Conrad Irwin 2023-11-14 13:34:25 -07:00
commit 80b7f75d24
51 changed files with 1938 additions and 1355 deletions

34
Cargo.lock generated
View file

@ -4223,6 +4223,7 @@ dependencies = [
"anyhow", "anyhow",
"gpui2", "gpui2",
"log", "log",
"serde",
"smol", "smol",
"util", "util",
] ]
@ -6633,6 +6634,36 @@ dependencies = [
"workspace", "workspace",
] ]
[[package]]
name = "project_panel2"
version = "0.1.0"
dependencies = [
"anyhow",
"client2",
"collections",
"context_menu",
"db2",
"editor2",
"futures 0.3.28",
"gpui2",
"language2",
"menu2",
"postage",
"pretty_assertions",
"project2",
"schemars",
"serde",
"serde_derive",
"serde_json",
"settings2",
"smallvec",
"theme2",
"ui2",
"unicase",
"util",
"workspace2",
]
[[package]] [[package]]
name = "project_symbols" name = "project_symbols"
version = "0.1.0" version = "0.1.0"
@ -11428,7 +11459,7 @@ dependencies = [
"ignore", "ignore",
"image", "image",
"indexmap 1.9.3", "indexmap 1.9.3",
"install_cli", "install_cli2",
"isahc", "isahc",
"journal2", "journal2",
"language2", "language2",
@ -11443,6 +11474,7 @@ dependencies = [
"parking_lot 0.11.2", "parking_lot 0.11.2",
"postage", "postage",
"project2", "project2",
"project_panel2",
"rand 0.8.5", "rand 0.8.5",
"regex", "regex",
"rope2", "rope2",

View file

@ -80,6 +80,7 @@ members = [
"crates/project", "crates/project",
"crates/project2", "crates/project2",
"crates/project_panel", "crates/project_panel",
"crates/project_panel2",
"crates/project_symbols", "crates/project_symbols",
"crates/recent_projects", "crates/recent_projects",
"crates/rope", "crates/rope",

View file

@ -1,38 +0,0 @@
[package]
name = "ai"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/ai.rs"
doctest = false
[features]
test-support = []
[dependencies]
gpui = { path = "../gpui" }
util = { path = "../util" }
language = { path = "../language" }
async-trait.workspace = true
anyhow.workspace = true
futures.workspace = true
lazy_static.workspace = true
ordered-float.workspace = true
parking_lot.workspace = true
isahc.workspace = true
regex.workspace = true
serde.workspace = true
serde_json.workspace = true
postage.workspace = true
rand.workspace = true
log.workspace = true
parse_duration = "2.1.1"
tiktoken-rs.workspace = true
matrixmultiply = "0.3.7"
rusqlite = { version = "0.29.0", features = ["blob", "array", "modern_sqlite"] }
bincode = "1.3.3"
[dev-dependencies]
gpui = { path = "../gpui", features = ["test-support"] }

View file

@ -4,7 +4,7 @@ use super::{
}; };
use crate::{Anchor, Editor, ExcerptId, ExcerptRange, ToPoint as _}; use crate::{Anchor, Editor, ExcerptId, ExcerptRange, ToPoint as _};
use collections::{Bound, HashMap, HashSet}; use collections::{Bound, HashMap, HashSet};
use gpui::{AnyElement, ViewContext}; use gpui::{AnyElement, Pixels, ViewContext};
use language::{BufferSnapshot, Chunk, Patch, Point}; use language::{BufferSnapshot, Chunk, Patch, Point};
use parking_lot::Mutex; use parking_lot::Mutex;
use std::{ use std::{
@ -82,12 +82,11 @@ pub enum BlockStyle {
pub struct BlockContext<'a, 'b> { pub struct BlockContext<'a, 'b> {
pub view_context: &'b mut ViewContext<'a, Editor>, pub view_context: &'b mut ViewContext<'a, Editor>,
pub anchor_x: f32, pub anchor_x: Pixels,
pub scroll_x: f32, pub gutter_width: Pixels,
pub gutter_width: f32, pub gutter_padding: Pixels,
pub gutter_padding: f32, pub em_width: Pixels,
pub em_width: f32, pub line_height: Pixels,
pub line_height: f32,
pub block_id: usize, pub block_id: usize,
} }

View file

@ -22,7 +22,7 @@ mod editor_tests;
pub mod test; pub mod test;
use ::git::diff::DiffHunk; use ::git::diff::DiffHunk;
use aho_corasick::AhoCorasick; use aho_corasick::AhoCorasick;
use anyhow::{Context as _, Result}; use anyhow::{anyhow, Context as _, Result};
use blink_manager::BlinkManager; use blink_manager::BlinkManager;
use client::{ClickhouseEvent, Client, Collaborator, ParticipantIndex, TelemetrySettings}; use client::{ClickhouseEvent, Client, Collaborator, ParticipantIndex, TelemetrySettings};
use clock::ReplicaId; use clock::ReplicaId;
@ -43,8 +43,8 @@ use gpui::{
AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Component, Context, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Component, Context,
EventEmitter, FocusHandle, FontFeatures, FontStyle, FontWeight, HighlightStyle, Hsla, EventEmitter, FocusHandle, FontFeatures, FontStyle, FontWeight, HighlightStyle, Hsla,
InputHandler, KeyContext, Model, MouseButton, ParentElement, Pixels, Render, InputHandler, KeyContext, Model, MouseButton, ParentElement, Pixels, Render,
StatelessInteractive, Styled, Subscription, Task, TextStyle, UniformListScrollHandle, View, StatefulInteractive, StatelessInteractive, Styled, Subscription, Task, TextStyle,
ViewContext, VisualContext, WeakView, WindowContext, UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WindowContext,
}; };
use highlight_matching_bracket::refresh_matching_bracket_highlights; use highlight_matching_bracket::refresh_matching_bracket_highlights;
use hover_popover::{hide_hover, HoverState}; use hover_popover::{hide_hover, HoverState};
@ -69,7 +69,7 @@ pub use multi_buffer::{
}; };
use ordered_float::OrderedFloat; use ordered_float::OrderedFloat;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use project::{FormatTrigger, Location, Project, ProjectTransaction}; use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
use rand::prelude::*; use rand::prelude::*;
use rpc::proto::*; use rpc::proto::*;
use scroll::{ use scroll::{
@ -97,7 +97,7 @@ use text::{OffsetUtf16, Rope};
use theme::{ use theme::{
ActiveTheme, DiagnosticStyle, PlayerColor, SyntaxTheme, Theme, ThemeColors, ThemeSettings, ActiveTheme, DiagnosticStyle, PlayerColor, SyntaxTheme, Theme, ThemeColors, ThemeSettings,
}; };
use ui::{IconButton, StyledExt}; use ui::{v_stack, HighlightedLabel, IconButton, StyledExt, TextTooltip};
use util::{post_inc, RangeExt, ResultExt, TryFutureExt}; use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
use workspace::{ use workspace::{
item::ItemEvent, searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, item::ItemEvent, searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace,
@ -7588,53 +7588,47 @@ impl Editor {
}) })
} }
// pub fn find_all_references( pub fn find_all_references(
// workspace: &mut Workspace, &mut self,
// _: &FindAllReferences, _: &FindAllReferences,
// cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// let active_item = workspace.active_item(cx)?; let buffer = self.buffer.read(cx);
// let editor_handle = active_item.act_as::<Self>(cx)?; let head = self.selections.newest::<usize>(cx).head();
let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
let replica_id = self.replica_id(cx);
// let editor = editor_handle.read(cx); let workspace = self.workspace()?;
// let buffer = editor.buffer.read(cx); let project = workspace.read(cx).project().clone();
// let head = editor.selections.newest::<usize>(cx).head(); let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
// let (buffer, head) = buffer.text_anchor_for_position(head, cx)?; Some(cx.spawn(|_, mut cx| async move {
// let replica_id = editor.replica_id(cx); let locations = references.await?;
if locations.is_empty() {
return Ok(());
}
// let project = workspace.project().clone(); workspace.update(&mut cx, |workspace, cx| {
// let references = project.update(cx, |project, cx| project.references(&buffer, head, cx)); let title = locations
// Some(cx.spawn_labeled( .first()
// "Finding All References...", .as_ref()
// |workspace, mut cx| async move { .map(|location| {
// let locations = references.await?; let buffer = location.buffer.read(cx);
// if locations.is_empty() { format!(
// return Ok(()); "References to `{}`",
// } buffer
.text_for_range(location.range.clone())
.collect::<String>()
)
})
.unwrap();
Self::open_locations_in_multibuffer(
workspace, locations, replica_id, title, false, cx,
);
})?;
// workspace.update(&mut cx, |workspace, cx| { Ok(())
// let title = locations }))
// .first() }
// .as_ref()
// .map(|location| {
// let buffer = location.buffer.read(cx);
// format!(
// "References to `{}`",
// buffer
// .text_for_range(location.range.clone())
// .collect::<String>()
// )
// })
// .unwrap();
// Self::open_locations_in_multibuffer(
// workspace, locations, replica_id, title, false, cx,
// );
// })?;
// Ok(())
// },
// ))
// }
/// Opens a multibuffer with the given project locations in it /// Opens a multibuffer with the given project locations in it
pub fn open_locations_in_multibuffer( pub fn open_locations_in_multibuffer(
@ -7685,7 +7679,7 @@ impl Editor {
editor.update(cx, |editor, cx| { editor.update(cx, |editor, cx| {
editor.highlight_background::<Self>( editor.highlight_background::<Self>(
ranges_to_highlight, ranges_to_highlight,
|theme| todo!("theme.editor.highlighted_line_background"), |theme| theme.editor_highlighted_line_background,
cx, cx,
); );
}); });
@ -8869,46 +8863,50 @@ impl Editor {
// }); // });
// } // }
// fn jump( fn jump(
// workspace: &mut Workspace, &mut self,
// path: ProjectPath, path: ProjectPath,
// position: Point, position: Point,
// anchor: language::Anchor, anchor: language::Anchor,
// cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Self>,
// ) { ) {
// let editor = workspace.open_path(path, None, true, cx); let workspace = self.workspace();
// cx.spawn(|_, mut cx| async move { cx.spawn(|_, mut cx| async move {
// let editor = editor let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
// .await? let editor = workspace.update(&mut cx, |workspace, cx| {
// .downcast::<Editor>() workspace.open_path(path, None, true, cx)
// .ok_or_else(|| anyhow!("opened item was not an editor"))? })?;
// .downgrade(); let editor = editor
// editor.update(&mut cx, |editor, cx| { .await?
// let buffer = editor .downcast::<Editor>()
// .buffer() .ok_or_else(|| anyhow!("opened item was not an editor"))?
// .read(cx) .downgrade();
// .as_singleton() editor.update(&mut cx, |editor, cx| {
// .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?; let buffer = editor
// let buffer = buffer.read(cx); .buffer()
// let cursor = if buffer.can_resolve(&anchor) { .read(cx)
// language::ToPoint::to_point(&anchor, buffer) .as_singleton()
// } else { .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
// buffer.clip_point(position, Bias::Left) let buffer = buffer.read(cx);
// }; let cursor = if buffer.can_resolve(&anchor) {
language::ToPoint::to_point(&anchor, buffer)
} else {
buffer.clip_point(position, Bias::Left)
};
// let nav_history = editor.nav_history.take(); let nav_history = editor.nav_history.take();
// editor.change_selections(Some(Autoscroll::newest()), cx, |s| { editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
// s.select_ranges([cursor..cursor]); s.select_ranges([cursor..cursor]);
// }); });
// editor.nav_history = nav_history; editor.nav_history = nav_history;
// anyhow::Ok(()) anyhow::Ok(())
// })??; })??;
// anyhow::Ok(()) anyhow::Ok(())
// }) })
// .detach_and_log_err(cx); .detach_and_log_err(cx);
// } }
fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> { fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
let snapshot = self.buffer.read(cx).read(cx); let snapshot = self.buffer.read(cx).read(cx);
@ -9973,43 +9971,22 @@ pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> Rend
} }
let message = diagnostic.message; let message = diagnostic.message;
Arc::new(move |cx: &mut BlockContext| { Arc::new(move |cx: &mut BlockContext| {
todo!() let message = message.clone();
// let message = message.clone(); v_stack()
// let settings = ThemeSettings::get_global(cx); .id(cx.block_id)
// let tooltip_style = settings.theme.tooltip.clone(); .size_full()
// let theme = &settings.theme.editor; .bg(gpui::red())
// let style = diagnostic_style(diagnostic.severity, is_valid, theme); .children(highlighted_lines.iter().map(|(line, highlights)| {
// let font_size = (style.text_scale_factor * settings.buffer_font_size(cx)).round(); div()
// let anchor_x = cx.anchor_x; .child(HighlightedLabel::new(line.clone(), highlights.clone()))
// enum BlockContextToolip {} .ml(cx.anchor_x)
// MouseEventHandler::new::<BlockContext, _>(cx.block_id, cx, |_, _| { }))
// Flex::column() .cursor_pointer()
// .with_children(highlighted_lines.iter().map(|(line, highlights)| { .on_click(move |_, _, cx| {
// Label::new( cx.write_to_clipboard(ClipboardItem::new(message.clone()));
// line.clone(), })
// style.message.clone().with_font_size(font_size), .tooltip(|_, cx| cx.build_view(|cx| TextTooltip::new("Copy diagnostic message")))
// ) .render()
// .with_highlights(highlights.clone())
// .contained()
// .with_margin_left(anchor_x)
// }))
// .aligned()
// .left()
// .into_any()
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_click(MouseButton::Left, move |_, _, cx| {
// cx.write_to_clipboard(ClipboardItem::new(message.clone()));
// })
// // We really need to rethink this ID system...
// .with_tooltip::<BlockContextToolip>(
// cx.block_id,
// "Copy diagnostic message",
// None,
// tooltip_style,
// cx,
// )
// .into_any()
}) })
} }

View file

@ -1,5 +1,8 @@
use crate::{ use crate::{
display_map::{BlockStyle, DisplaySnapshot, FoldStatus, HighlightedChunk, ToDisplayPoint}, display_map::{
BlockContext, BlockStyle, DisplaySnapshot, FoldStatus, HighlightedChunk, ToDisplayPoint,
TransformBlock,
},
editor_settings::ShowScrollbar, editor_settings::ShowScrollbar,
git::{diff_hunk_to_display, DisplayDiffHunk}, git::{diff_hunk_to_display, DisplayDiffHunk},
hover_popover::hover_at, hover_popover::hover_at,
@ -15,17 +18,19 @@ use crate::{
use anyhow::Result; use anyhow::Result;
use collections::{BTreeMap, HashMap}; use collections::{BTreeMap, HashMap};
use gpui::{ use gpui::{
black, hsla, point, px, relative, size, transparent_black, Action, AnyElement, AvailableSpace, point, px, relative, size, transparent_black, Action, AnyElement, AvailableSpace, BorrowWindow,
BorrowAppContext, BorrowWindow, Bounds, ContentMask, Corners, DispatchPhase, Edges, Element, Bounds, Component, ContentMask, Corners, DispatchPhase, Edges, Element, ElementId,
ElementId, ElementInputHandler, Entity, FocusHandle, GlobalElementId, Hsla, InputHandler, ElementInputHandler, Entity, Hsla, Line, MouseButton, MouseDownEvent, MouseMoveEvent,
KeyContext, KeyDownEvent, KeyMatch, Line, LineLayout, Modifiers, MouseButton, MouseDownEvent, MouseUpEvent, ParentElement, Pixels, ScrollWheelEvent, Size, Style, Styled, TextRun, TextStyle,
MouseMoveEvent, MouseUpEvent, Pixels, ScrollWheelEvent, ShapedGlyph, Size, Style, TextRun, ViewContext, WindowContext,
TextStyle, TextSystem, ViewContext, WindowContext, WrappedLineLayout,
}; };
use itertools::Itertools; use itertools::Itertools;
use language::language_settings::ShowWhitespaceSetting; use language::language_settings::ShowWhitespaceSetting;
use multi_buffer::Anchor; use multi_buffer::Anchor;
use project::project_settings::{GitGutterSetting, ProjectSettings}; use project::{
project_settings::{GitGutterSetting, ProjectSettings},
ProjectPath,
};
use settings::Settings; use settings::Settings;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{ use std::{
@ -39,6 +44,7 @@ use std::{
}; };
use sum_tree::Bias; use sum_tree::Bias;
use theme::{ActiveTheme, PlayerColor}; use theme::{ActiveTheme, PlayerColor};
use ui::{h_stack, IconButton};
use util::ResultExt; use util::ResultExt;
use workspace::item::Item; use workspace::item::Item;
@ -1171,30 +1177,31 @@ impl EditorElement {
} }
} }
// fn paint_blocks( fn paint_blocks(
// &mut self, &mut self,
// bounds: Bounds<Pixels>, bounds: Bounds<Pixels>,
// visible_bounds: Bounds<Pixels>, layout: &mut LayoutState,
// layout: &mut LayoutState, editor: &mut Editor,
// editor: &mut Editor, cx: &mut ViewContext<Editor>,
// cx: &mut ViewContext<Editor>, ) {
// ) { let scroll_position = layout.position_map.snapshot.scroll_position();
// let scroll_position = layout.position_map.snapshot.scroll_position(); let scroll_left = scroll_position.x * layout.position_map.em_width;
// let scroll_left = scroll_position.x * layout.position_map.em_width; let scroll_top = scroll_position.y * layout.position_map.line_height;
// let scroll_top = scroll_position.y * layout.position_map.line_height;
// for block in &mut layout.blocks { for block in &mut layout.blocks {
// let mut origin = bounds.origin let mut origin = bounds.origin
// + point( + point(
// 0., Pixels::ZERO,
// block.row as f32 * layout.position_map.line_height - scroll_top, block.row as f32 * layout.position_map.line_height - scroll_top,
// ); );
// if !matches!(block.style, BlockStyle::Sticky) { if !matches!(block.style, BlockStyle::Sticky) {
// origin += point(-scroll_left, 0.); origin += point(-scroll_left, Pixels::ZERO);
// } }
// block.element.paint(origin, visible_bounds, editor, cx); block
// } .element
// } .draw(origin, block.available_space, editor, cx);
}
}
fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> Pixels { fn column_pixels(&self, column: usize, cx: &ViewContext<Editor>) -> Pixels {
let style = &self.style; let style = &self.style;
@ -1741,22 +1748,22 @@ impl EditorElement {
.unwrap() .unwrap()
.width; .width;
let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width; let scroll_width = longest_line_width.max(max_visible_line_width) + overscroll.width;
// todo!("blocks")
// let (scroll_width, blocks) = self.layout_blocks( let (scroll_width, blocks) = self.layout_blocks(
// start_row..end_row, start_row..end_row,
// &snapshot, &snapshot,
// size.x, bounds.size.width,
// scroll_width, scroll_width,
// gutter_padding, gutter_padding,
// gutter_width, gutter_width,
// em_width, em_width,
// gutter_width + gutter_margin, gutter_width + gutter_margin,
// line_height, line_height,
// &style, &style,
// &line_layouts, &line_layouts,
// editor, editor,
// cx, cx,
// ); );
let scroll_max = point( let scroll_max = point(
f32::from((scroll_width - text_size.width) / em_width).max(0.0), f32::from((scroll_width - text_size.width) / em_width).max(0.0),
@ -1937,7 +1944,7 @@ impl EditorElement {
fold_ranges, fold_ranges,
line_number_layouts, line_number_layouts,
display_hunks, display_hunks,
// blocks, blocks,
selections, selections,
context_menu, context_menu,
code_actions_indicator, code_actions_indicator,
@ -1948,226 +1955,177 @@ impl EditorElement {
} }
} }
// #[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
// fn layout_blocks( fn layout_blocks(
// &mut self, &mut self,
// rows: Range<u32>, rows: Range<u32>,
// snapshot: &EditorSnapshot, snapshot: &EditorSnapshot,
// editor_width: f32, editor_width: Pixels,
// scroll_width: f32, scroll_width: Pixels,
// gutter_padding: f32, gutter_padding: Pixels,
// gutter_width: f32, gutter_width: Pixels,
// em_width: f32, em_width: Pixels,
// text_x: f32, text_x: Pixels,
// line_height: f32, line_height: Pixels,
// style: &EditorStyle, style: &EditorStyle,
// line_layouts: &[LineWithInvisibles], line_layouts: &[LineWithInvisibles],
// editor: &mut Editor, editor: &mut Editor,
// cx: &mut ViewContext<Editor>, cx: &mut ViewContext<Editor>,
// ) -> (f32, Vec<BlockLayout>) { ) -> (Pixels, Vec<BlockLayout>) {
// let mut block_id = 0; let mut block_id = 0;
// let scroll_x = snapshot.scroll_anchor.offset.x; let scroll_x = snapshot.scroll_anchor.offset.x;
// let (fixed_blocks, non_fixed_blocks) = snapshot let (fixed_blocks, non_fixed_blocks) = snapshot
// .blocks_in_range(rows.clone()) .blocks_in_range(rows.clone())
// .partition::<Vec<_>, _>(|(_, block)| match block { .partition::<Vec<_>, _>(|(_, block)| match block {
// TransformBlock::ExcerptHeader { .. } => false, TransformBlock::ExcerptHeader { .. } => false,
// TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed, TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
// }); });
// let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| { let mut render_block = |block: &TransformBlock,
// let mut element = match block { available_space: Size<AvailableSpace>,
// TransformBlock::Custom(block) => { block_id: usize,
// let align_to = block editor: &mut Editor,
// .position() cx: &mut ViewContext<Editor>| {
// .to_point(&snapshot.buffer_snapshot) let mut element = match block {
// .to_display_point(snapshot); TransformBlock::Custom(block) => {
// let anchor_x = text_x let align_to = block
// + if rows.contains(&align_to.row()) { .position()
// line_layouts[(align_to.row() - rows.start) as usize] .to_point(&snapshot.buffer_snapshot)
// .line .to_display_point(snapshot);
// .x_for_index(align_to.column() as usize) let anchor_x = text_x
// } else { + if rows.contains(&align_to.row()) {
// layout_line(align_to.row(), snapshot, style, cx.text_layout_cache()) line_layouts[(align_to.row() - rows.start) as usize]
// .x_for_index(align_to.column() as usize) .line
// }; .x_for_index(align_to.column() as usize)
} else {
layout_line(align_to.row(), snapshot, style, cx)
.unwrap()
.x_for_index(align_to.column() as usize)
};
// block.render(&mut BlockContext { block.render(&mut BlockContext {
// view_context: cx, view_context: cx,
// anchor_x, anchor_x,
// gutter_padding, gutter_padding,
// line_height, line_height,
// scroll_x, // scroll_x,
// gutter_width, gutter_width,
// em_width, em_width,
// block_id, block_id,
// }) })
// } }
// TransformBlock::ExcerptHeader { TransformBlock::ExcerptHeader {
// id, id,
// buffer, buffer,
// range, range,
// starts_new_buffer, starts_new_buffer,
// .. ..
// } => { } => {
// let tooltip_style = theme::current(cx).tooltip.clone(); let include_root = editor
// let include_root = editor .project
// .project .as_ref()
// .as_ref() .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
// .map(|project| project.read(cx).visible_worktrees(cx).count() > 1) .unwrap_or_default();
// .unwrap_or_default(); let jump_icon = project::File::from_dyn(buffer.file()).map(|file| {
// let jump_icon = project::File::from_dyn(buffer.file()).map(|file| { let jump_path = ProjectPath {
// let jump_path = ProjectPath { worktree_id: file.worktree_id(cx),
// worktree_id: file.worktree_id(cx), path: file.path.clone(),
// path: file.path.clone(), };
// }; let jump_anchor = range
// let jump_anchor = range .primary
// .primary .as_ref()
// .as_ref() .map_or(range.context.start, |primary| primary.start);
// .map_or(range.context.start, |primary| primary.start); let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
// let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
// enum JumpIcon {} // todo!("avoid ElementId collision risk here")
// MouseEventHandler::new::<JumpIcon, _>((*id).into(), cx, |state, _| { let icon_button_id: usize = id.clone().into();
// let style = style.jump_icon.style_for(state); IconButton::new(icon_button_id, ui::Icon::ArrowUpRight)
// Svg::new("icons/arrow_up_right.svg") .on_click(move |editor: &mut Editor, cx| {
// .with_color(style.color) editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
// .constrained() })
// .with_width(style.icon_width) .tooltip("Jump to Buffer") // todo!(pass an action as well to show key binding)
// .aligned() });
// .contained()
// .with_style(style.container)
// .constrained()
// .with_width(style.button_width)
// .with_height(style.button_width)
// })
// .with_cursor_style(CursorStyle::PointingHand)
// .on_click(MouseButton::Left, move |_, editor, cx| {
// if let Some(workspace) = editor
// .workspace
// .as_ref()
// .and_then(|(workspace, _)| workspace.upgrade(cx))
// {
// workspace.update(cx, |workspace, cx| {
// Editor::jump(
// workspace,
// jump_path.clone(),
// jump_position,
// jump_anchor,
// cx,
// );
// });
// }
// })
// .with_tooltip::<JumpIcon>(
// (*id).into(),
// "Jump to Buffer".to_string(),
// Some(Box::new(crate::OpenExcerpts)),
// tooltip_style.clone(),
// cx,
// )
// .aligned()
// .flex_float()
// });
// if *starts_new_buffer { let element = if *starts_new_buffer {
// let editor_font_size = style.text.font_size; let path = buffer.resolve_file_path(cx, include_root);
// let style = &style.diagnostic_path_header; let mut filename = None;
// let font_size = (style.text_scale_factor * editor_font_size).round(); let mut parent_path = None;
// Can't use .and_then() because `.file_name()` and `.parent()` return references :(
if let Some(path) = path {
filename = path.file_name().map(|f| f.to_string_lossy().to_string());
parent_path =
path.parent().map(|p| p.to_string_lossy().to_string() + "/");
}
// let path = buffer.resolve_file_path(cx, include_root); h_stack()
// let mut filename = None; .size_full()
// let mut parent_path = None; .bg(gpui::red())
// // Can't use .and_then() because `.file_name()` and `.parent()` return references :( .child(filename.unwrap_or_else(|| "untitled".to_string()))
// if let Some(path) = path { .children(parent_path)
// filename = path.file_name().map(|f| f.to_string_lossy.to_string()); .children(jump_icon) // .p_x(gutter_padding)
// parent_path = } else {
// path.parent().map(|p| p.to_string_lossy.to_string() + "/"); let text_style = style.text.clone();
// } h_stack()
.size_full()
.bg(gpui::red())
.child("")
.children(jump_icon) // .p_x(gutter_padding)
};
element.render()
}
};
// Flex::row() let size = element.measure(available_space, editor, cx);
// .with_child( (element, size)
// Label::new( };
// filename.unwrap_or_else(|| "untitled".to_string()),
// style.filename.text.clone().with_font_size(font_size),
// )
// .contained()
// .with_style(style.filename.container)
// .aligned(),
// )
// .with_children(parent_path.map(|path| {
// Label::new(path, style.path.text.clone().with_font_size(font_size))
// .contained()
// .with_style(style.path.container)
// .aligned()
// }))
// .with_children(jump_icon)
// .contained()
// .with_style(style.container)
// .with_padding_left(gutter_padding)
// .with_padding_right(gutter_padding)
// .expanded()
// .into_any_named("path header block")
// } else {
// let text_style = style.text.clone();
// Flex::row()
// .with_child(Label::new("⋯", text_style))
// .with_children(jump_icon)
// .contained()
// .with_padding_left(gutter_padding)
// .with_padding_right(gutter_padding)
// .expanded()
// .into_any_named("collapsed context")
// }
// }
// };
// element.layout( let mut fixed_block_max_width = Pixels::ZERO;
// SizeConstraint { let mut blocks = Vec::new();
// min: gpui::Point::<Pixels>::zero(), for (row, block) in fixed_blocks {
// max: point(width, block.height() as f32 * line_height), let available_space = size(
// }, AvailableSpace::MinContent,
// editor, AvailableSpace::Definite(block.height() as f32 * line_height),
// cx, );
// ); let (element, element_size) =
// element render_block(block, available_space, block_id, editor, cx);
// }; block_id += 1;
fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
// let mut fixed_block_max_width = 0f32; blocks.push(BlockLayout {
// let mut blocks = Vec::new(); row,
// for (row, block) in fixed_blocks { element,
// let element = render_block(block, f32::INFINITY, block_id); available_space,
// block_id += 1; style: BlockStyle::Fixed,
// fixed_block_max_width = fixed_block_max_width.max(element.size().x + em_width); });
// blocks.push(BlockLayout { }
// row, for (row, block) in non_fixed_blocks {
// element, let style = match block {
// style: BlockStyle::Fixed, TransformBlock::Custom(block) => block.style(),
// }); TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
// } };
// for (row, block) in non_fixed_blocks { let width = match style {
// let style = match block { BlockStyle::Sticky => editor_width,
// TransformBlock::Custom(block) => block.style(), BlockStyle::Flex => editor_width
// TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky, .max(fixed_block_max_width)
// }; .max(gutter_width + scroll_width),
// let width = match style { BlockStyle::Fixed => unreachable!(),
// BlockStyle::Sticky => editor_width, };
// BlockStyle::Flex => editor_width let available_space = size(
// .max(fixed_block_max_width) AvailableSpace::Definite(width),
// .max(gutter_width + scroll_width), AvailableSpace::Definite(block.height() as f32 * line_height),
// BlockStyle::Fixed => unreachable!(), );
// }; let (element, _) = render_block(block, available_space, block_id, editor, cx);
// let element = render_block(block, width, block_id); block_id += 1;
// block_id += 1; blocks.push(BlockLayout {
// blocks.push(BlockLayout { row,
// row, element,
// element, available_space,
// style, style,
// }); });
// } }
// ( (
// scroll_width.max(fixed_block_max_width - gutter_width), scroll_width.max(fixed_block_max_width - gutter_width),
// blocks, blocks,
// ) )
// } }
fn paint_mouse_listeners( fn paint_mouse_listeners(
&mut self, &mut self,
@ -2613,7 +2571,11 @@ impl Element<Editor> for EditorElement {
}); });
// on_action(cx, Editor::rename); todo!() // on_action(cx, Editor::rename); todo!()
// on_action(cx, Editor::confirm_rename); todo!() // on_action(cx, Editor::confirm_rename); todo!()
// on_action(cx, Editor::find_all_references); todo!() register_action(cx, |editor, action, cx| {
editor
.find_all_references(action, cx)
.map(|task| task.detach_and_log_err(cx));
});
register_action(cx, Editor::next_copilot_suggestion); register_action(cx, Editor::next_copilot_suggestion);
register_action(cx, Editor::previous_copilot_suggestion); register_action(cx, Editor::previous_copilot_suggestion);
register_action(cx, Editor::copilot_suggest); register_action(cx, Editor::copilot_suggest);
@ -2670,11 +2632,18 @@ impl Element<Editor> for EditorElement {
&layout.position_map, &layout.position_map,
cx, cx,
); );
self.paint_background(gutter_bounds, text_bounds, &layout, cx); self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO { if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, editor, cx); self.paint_gutter(gutter_bounds, &mut layout, editor, cx);
} }
self.paint_text(text_bounds, &mut layout, editor, cx); self.paint_text(text_bounds, &mut layout, editor, cx);
if !layout.blocks.is_empty() {
self.paint_blocks(bounds, &mut layout, editor, cx);
}
let input_handler = ElementInputHandler::new(bounds, cx); let input_handler = ElementInputHandler::new(bounds, cx);
cx.handle_input(&editor.focus_handle, input_handler); cx.handle_input(&editor.focus_handle, input_handler);
}); });
@ -3295,7 +3264,7 @@ pub struct LayoutState {
highlighted_rows: Option<Range<u32>>, highlighted_rows: Option<Range<u32>>,
line_number_layouts: Vec<Option<gpui::Line>>, line_number_layouts: Vec<Option<gpui::Line>>,
display_hunks: Vec<DisplayDiffHunk>, display_hunks: Vec<DisplayDiffHunk>,
// blocks: Vec<BlockLayout>, blocks: Vec<BlockLayout>,
highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>, highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>, fold_ranges: Vec<(BufferRow, Range<DisplayPoint>, Hsla)>,
selections: Vec<(PlayerColor, Vec<SelectionLayout>)>, selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
@ -3398,6 +3367,7 @@ impl PositionMap {
struct BlockLayout { struct BlockLayout {
row: u32, row: u32,
element: AnyElement<Editor>, element: AnyElement<Editor>,
available_space: Size<AvailableSpace>,
style: BlockStyle, style: BlockStyle,
} }

View file

@ -30,7 +30,7 @@ use std::{
}; };
use text::Selection; use text::Selection;
use theme::{ActiveTheme, Theme}; use theme::{ActiveTheme, Theme};
use ui::{Label, LabelColor}; use ui::{Label, TextColor};
use util::{paths::PathExt, ResultExt, TryFutureExt}; use util::{paths::PathExt, ResultExt, TryFutureExt};
use workspace::item::{BreadcrumbText, FollowEvent, FollowableEvents, FollowableItemHandle}; use workspace::item::{BreadcrumbText, FollowEvent, FollowableEvents, FollowableItemHandle};
use workspace::{ use workspace::{
@ -607,7 +607,7 @@ impl Item for Editor {
&description, &description,
MAX_TAB_TITLE_LEN, MAX_TAB_TITLE_LEN,
)) ))
.color(LabelColor::Muted), .color(TextColor::Muted),
), ),
) )
})), })),

View file

@ -5,7 +5,7 @@ use gpui::{
}; };
use text::{Bias, Point}; use text::{Bias, Point};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::{h_stack, v_stack, Label, LabelColor, StyledExt}; use ui::{h_stack, v_stack, Label, StyledExt, TextColor};
use util::paths::FILE_ROW_COLUMN_DELIMITER; use util::paths::FILE_ROW_COLUMN_DELIMITER;
use workspace::{Modal, ModalEvent, Workspace}; use workspace::{Modal, ModalEvent, Workspace};
@ -176,7 +176,7 @@ impl Render for GoToLine {
.justify_between() .justify_between()
.px_2() .px_2()
.py_1() .py_1()
.child(Label::new(self.current_text.clone()).color(LabelColor::Muted)), .child(Label::new(self.current_text.clone()).color(TextColor::Muted)),
), ),
) )
} }

View file

@ -2112,6 +2112,10 @@ impl AppContext {
AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap()) AsyncAppContext(self.weak_self.as_ref().unwrap().upgrade().unwrap())
} }
pub fn open_url(&self, url: &str) {
self.platform.open_url(url)
}
pub fn write_to_clipboard(&self, item: ClipboardItem) { pub fn write_to_clipboard(&self, item: ClipboardItem) {
self.platform.write_to_clipboard(item); self.platform.write_to_clipboard(item);
} }

View file

@ -68,8 +68,12 @@ where
A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static, A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + std::fmt::Debug + 'static,
{ {
fn qualified_name() -> SharedString { fn qualified_name() -> SharedString {
let name = type_name::<A>();
let mut separator_matches = name.rmatch_indices("::");
separator_matches.next().unwrap();
let name_start_ix = separator_matches.next().map_or(0, |(ix, _)| ix + 2);
// todo!() remove the 2 replacement when migration is done // todo!() remove the 2 replacement when migration is done
type_name::<A>().replace("2::", "::").into() name[name_start_ix..].replace("2::", "::").into()
} }
fn build(params: Option<serde_json::Value>) -> Result<Box<dyn Action>> fn build(params: Option<serde_json::Value>) -> Result<Box<dyn Action>>

View file

@ -431,6 +431,18 @@ impl AppContext {
self.platform.activate(ignoring_other_apps); self.platform.activate(ignoring_other_apps);
} }
pub fn hide(&self) {
self.platform.hide();
}
pub fn hide_other_apps(&self) {
self.platform.hide_other_apps();
}
pub fn unhide_other_apps(&self) {
self.platform.unhide_other_apps();
}
/// Returns the list of currently active displays. /// Returns the list of currently active displays.
pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> { pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
self.platform.displays() self.platform.displays()

View file

@ -293,7 +293,16 @@ pub fn blue() -> Hsla {
pub fn green() -> Hsla { pub fn green() -> Hsla {
Hsla { Hsla {
h: 0.3, h: 0.33,
s: 1.,
l: 0.5,
a: 1.,
}
}
pub fn yellow() -> Hsla {
Hsla {
h: 0.16,
s: 1., s: 1.,
l: 0.5, l: 0.5,
a: 1., a: 1.,

View file

@ -54,9 +54,9 @@ impl LineLayout {
pub fn closest_index_for_x(&self, x: Pixels) -> usize { pub fn closest_index_for_x(&self, x: Pixels) -> usize {
let mut prev_index = 0; let mut prev_index = 0;
let mut prev_x = px(0.); let mut prev_x = px(0.);
for run in self.runs.iter() { for run in self.runs.iter() {
for glyph in run.glyphs.iter() { for glyph in run.glyphs.iter() {
glyph.index;
if glyph.position.x >= x { if glyph.position.x >= x {
if glyph.position.x - x < x - prev_x { if glyph.position.x - x < x - prev_x {
return glyph.index; return glyph.index;
@ -68,7 +68,8 @@ impl LineLayout {
prev_x = glyph.position.x; prev_x = glyph.position.x;
} }
} }
prev_index + 1
self.len
} }
pub fn x_for_index(&self, index: usize) -> Pixels { pub fn x_for_index(&self, index: usize) -> Pixels {

View file

@ -1365,6 +1365,14 @@ impl<'a> WindowContext<'a> {
self.window.platform_window.activate(); self.window.platform_window.activate();
} }
pub fn minimize_window(&self) {
self.window.platform_window.minimize();
}
pub fn toggle_full_screen(&self) {
self.window.platform_window.toggle_full_screen();
}
pub fn prompt( pub fn prompt(
&self, &self,
level: PromptLevel, level: PromptLevel,
@ -2360,6 +2368,12 @@ impl<V: 'static + Render> WindowHandle<V> {
{ {
cx.read_window(self, |root_view, _cx| root_view.clone()) cx.read_window(self, |root_view, _cx| root_view.clone())
} }
pub fn is_active(&self, cx: &WindowContext) -> Option<bool> {
cx.windows
.get(self.id)
.and_then(|window| window.as_ref().map(|window| window.active))
}
} }
impl<V> Copy for WindowHandle<V> {} impl<V> Copy for WindowHandle<V> {}

View file

@ -14,5 +14,6 @@ test-support = []
smol.workspace = true smol.workspace = true
anyhow.workspace = true anyhow.workspace = true
log.workspace = true log.workspace = true
serde.workspace = true
gpui = { package = "gpui2", path = "../gpui2" } gpui = { package = "gpui2", path = "../gpui2" }
util = { path = "../util" } util = { path = "../util" }

View file

@ -1,10 +1,9 @@
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use gpui::AsyncAppContext; use gpui::{actions, AsyncAppContext};
use std::path::Path; use std::path::Path;
use util::ResultExt; use util::ResultExt;
// todo!() actions!(Install);
// actions!(cli, [Install]);
pub async fn install_cli(cx: &AsyncAppContext) -> Result<()> { pub async fn install_cli(cx: &AsyncAppContext) -> Result<()> {
let cli_path = cx.update(|cx| cx.path_for_auxiliary_executable("cli"))??; let cli_path = cx.update(|cx| cx.path_for_auxiliary_executable("cli"))??;

View file

@ -4,7 +4,7 @@ use gpui::{
Styled, Task, UniformListScrollHandle, View, ViewContext, VisualContext, WindowContext, Styled, Task, UniformListScrollHandle, View, ViewContext, VisualContext, WindowContext,
}; };
use std::{cmp, sync::Arc}; use std::{cmp, sync::Arc};
use ui::{prelude::*, v_stack, Divider, Label, LabelColor}; use ui::{prelude::*, v_stack, Divider, Label, TextColor};
pub struct Picker<D: PickerDelegate> { pub struct Picker<D: PickerDelegate> {
pub delegate: D, pub delegate: D,
@ -238,7 +238,7 @@ impl<D: PickerDelegate> Render for Picker<D> {
v_stack().p_1().grow().child( v_stack().p_1().grow().child(
div() div()
.px_1() .px_1()
.child(Label::new("No matches").color(LabelColor::Muted)), .child(Label::new("No matches").color(TextColor::Muted)),
), ),
) )
}) })

View file

@ -0,0 +1,41 @@
[package]
name = "project_panel2"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/project_panel.rs"
doctest = false
[dependencies]
context_menu = { path = "../context_menu" }
collections = { path = "../collections" }
db = { path = "../db2", package = "db2" }
editor = { path = "../editor2", package = "editor2" }
gpui = { path = "../gpui2", package = "gpui2" }
menu = { path = "../menu2", package = "menu2" }
project = { path = "../project2", package = "project2" }
settings = { path = "../settings2", package = "settings2" }
theme = { path = "../theme2", package = "theme2" }
ui = { path = "../ui2", package = "ui2" }
util = { path = "../util" }
workspace = { path = "../workspace2", package = "workspace2" }
anyhow.workspace = true
postage.workspace = true
futures.workspace = true
serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true
schemars.workspace = true
smallvec.workspace = true
pretty_assertions.workspace = true
unicase = "2.6"
[dev-dependencies]
client = { path = "../client2", package = "client2", features = ["test-support"] }
language = { path = "../language2", package = "language2", features = ["test-support"] }
editor = { path = "../editor2", package = "editor2", features = ["test-support"] }
gpui = { path = "../gpui2", package = "gpui2", features = ["test-support"] }
workspace = { path = "../workspace2", package = "workspace2", features = ["test-support"] }
serde_json.workspace = true

View file

@ -0,0 +1,96 @@
use std::{path::Path, str, sync::Arc};
use collections::HashMap;
use gpui::{AppContext, AssetSource};
use serde_derive::Deserialize;
use util::{maybe, paths::PathExt};
#[derive(Deserialize, Debug)]
struct TypeConfig {
icon: Arc<str>,
}
#[derive(Deserialize, Debug)]
pub struct FileAssociations {
suffixes: HashMap<String, String>,
types: HashMap<String, TypeConfig>,
}
const COLLAPSED_DIRECTORY_TYPE: &'static str = "collapsed_folder";
const EXPANDED_DIRECTORY_TYPE: &'static str = "expanded_folder";
const COLLAPSED_CHEVRON_TYPE: &'static str = "collapsed_chevron";
const EXPANDED_CHEVRON_TYPE: &'static str = "expanded_chevron";
pub const FILE_TYPES_ASSET: &'static str = "icons/file_icons/file_types.json";
pub fn init(assets: impl AssetSource, cx: &mut AppContext) {
cx.set_global(FileAssociations::new(assets))
}
impl FileAssociations {
pub fn new(assets: impl AssetSource) -> Self {
assets
.load("icons/file_icons/file_types.json")
.and_then(|file| {
serde_json::from_str::<FileAssociations>(str::from_utf8(&file).unwrap())
.map_err(Into::into)
})
.unwrap_or_else(|_| FileAssociations {
suffixes: HashMap::default(),
types: HashMap::default(),
})
}
pub fn get_icon(path: &Path, cx: &AppContext) -> Arc<str> {
maybe!({
let this = cx.has_global::<Self>().then(|| cx.global::<Self>())?;
// FIXME: Associate a type with the languages and have the file's langauge
// override these associations
maybe!({
let suffix = path.icon_suffix()?;
this.suffixes
.get(suffix)
.and_then(|type_str| this.types.get(type_str))
.map(|type_config| type_config.icon.clone())
})
.or_else(|| this.types.get("default").map(|config| config.icon.clone()))
})
.unwrap_or_else(|| Arc::from("".to_string()))
}
pub fn get_folder_icon(expanded: bool, cx: &AppContext) -> Arc<str> {
maybe!({
let this = cx.has_global::<Self>().then(|| cx.global::<Self>())?;
let key = if expanded {
EXPANDED_DIRECTORY_TYPE
} else {
COLLAPSED_DIRECTORY_TYPE
};
this.types
.get(key)
.map(|type_config| type_config.icon.clone())
})
.unwrap_or_else(|| Arc::from("".to_string()))
}
pub fn get_chevron_icon(expanded: bool, cx: &AppContext) -> Arc<str> {
maybe!({
let this = cx.has_global::<Self>().then(|| cx.global::<Self>())?;
let key = if expanded {
EXPANDED_CHEVRON_TYPE
} else {
COLLAPSED_CHEVRON_TYPE
};
this.types
.get(key)
.map(|type_config| type_config.icon.clone())
})
.unwrap_or_else(|| Arc::from("".to_string()))
}
}

View file

@ -8,10 +8,10 @@ use file_associations::FileAssociations;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use gpui::{ use gpui::{
actions, div, px, svg, uniform_list, Action, AppContext, AssetSource, AsyncAppContext, actions, div, px, rems, svg, uniform_list, Action, AppContext, AssetSource, AsyncWindowContext,
AsyncWindowContext, ClipboardItem, Div, Element, Entity, EventEmitter, FocusEnabled, ClipboardItem, Component, Div, EventEmitter, FocusHandle, FocusableKeyDispatch, Model,
FocusHandle, Model, ParentElement as _, Pixels, Point, PromptLevel, Render, MouseButton, ParentElement as _, Pixels, Point, PromptLevel, Render, StatefulInteractive,
StatefulInteractive, StatefulInteractivity, Styled, Task, UniformListScrollHandle, View, StatefulInteractivity, StatelessInteractive, Styled, Task, UniformListScrollHandle, View,
ViewContext, VisualContext as _, WeakView, WindowContext, ViewContext, VisualContext as _, WeakView, WindowContext,
}; };
use menu::{Confirm, SelectNext, SelectPrev}; use menu::{Confirm, SelectNext, SelectPrev};
@ -31,9 +31,9 @@ use std::{
sync::Arc, sync::Arc,
}; };
use theme::ActiveTheme as _; use theme::ActiveTheme as _;
use ui::{h_stack, v_stack}; use ui::{h_stack, v_stack, Label};
use unicase::UniCase; use unicase::UniCase;
use util::TryFutureExt; use util::{maybe, TryFutureExt};
use workspace::{ use workspace::{
dock::{DockPosition, PanelEvent}, dock::{DockPosition, PanelEvent},
Workspace, Workspace,
@ -54,8 +54,8 @@ pub struct ProjectPanel {
edit_state: Option<EditState>, edit_state: Option<EditState>,
filename_editor: View<Editor>, filename_editor: View<Editor>,
clipboard_entry: Option<ClipboardEntry>, clipboard_entry: Option<ClipboardEntry>,
dragged_entry_destination: Option<Arc<Path>>, _dragged_entry_destination: Option<Arc<Path>>,
workspace: WeakView<Workspace>, _workspace: WeakView<Workspace>,
has_focus: bool, has_focus: bool,
width: Option<f32>, width: Option<f32>,
pending_serialization: Task<Option<()>>, pending_serialization: Task<Option<()>>,
@ -131,31 +131,6 @@ pub fn init_settings(cx: &mut AppContext) {
pub fn init(assets: impl AssetSource, cx: &mut AppContext) { pub fn init(assets: impl AssetSource, cx: &mut AppContext) {
init_settings(cx); init_settings(cx);
file_associations::init(assets, cx); file_associations::init(assets, cx);
// cx.add_action(ProjectPanel::expand_selected_entry);
// cx.add_action(ProjectPanel::collapse_selected_entry);
// cx.add_action(ProjectPanel::collapse_all_entries);
// cx.add_action(ProjectPanel::select_prev);
// cx.add_action(ProjectPanel::select_next);
// cx.add_action(ProjectPanel::new_file);
// cx.add_action(ProjectPanel::new_directory);
// cx.add_action(ProjectPanel::rename);
// cx.add_async_action(ProjectPanel::delete);
// cx.add_async_action(ProjectPanel::confirm);
// cx.add_async_action(ProjectPanel::open_file);
// cx.add_action(ProjectPanel::cancel);
// cx.add_action(ProjectPanel::cut);
// cx.add_action(ProjectPanel::copy);
// cx.add_action(ProjectPanel::copy_path);
// cx.add_action(ProjectPanel::copy_relative_path);
// cx.add_action(ProjectPanel::reveal_in_finder);
// cx.add_action(ProjectPanel::open_in_terminal);
// cx.add_action(ProjectPanel::new_search_in_directory);
// cx.add_action(
// |this: &mut ProjectPanel, action: &Paste, cx: &mut ViewContext<ProjectPanel>| {
// this.paste(action, cx);
// },
// );
} }
#[derive(Debug)] #[derive(Debug)]
@ -244,7 +219,6 @@ impl ProjectPanel {
// }) // })
// .detach(); // .detach();
let view_id = cx.view().entity_id();
let mut this = Self { let mut this = Self {
project: project.clone(), project: project.clone(),
fs: workspace.app_state().fs.clone(), fs: workspace.app_state().fs.clone(),
@ -258,8 +232,8 @@ impl ProjectPanel {
filename_editor, filename_editor,
clipboard_entry: None, clipboard_entry: None,
// context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)), // context_menu: cx.add_view(|cx| ContextMenu::new(view_id, cx)),
dragged_entry_destination: None, _dragged_entry_destination: None,
workspace: workspace.weak_handle(), _workspace: workspace.weak_handle(),
has_focus: false, has_focus: false,
width: None, width: None,
pending_serialization: Task::ready(None), pending_serialization: Task::ready(None),
@ -311,8 +285,8 @@ impl ProjectPanel {
} }
} }
&Event::SplitEntry { entry_id } => { &Event::SplitEntry { entry_id } => {
// if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx) { if let Some(worktree) = project.read(cx).worktree_for_entry(entry_id, cx) {
// if let Some(entry) = worktree.read(cx).entry_for_id(entry_id) { if let Some(_entry) = worktree.read(cx).entry_for_id(entry_id) {
// workspace // workspace
// .split_path( // .split_path(
// ProjectPath { // ProjectPath {
@ -322,8 +296,8 @@ impl ProjectPanel {
// cx, // cx,
// ) // )
// .detach_and_log_err(cx); // .detach_and_log_err(cx);
// } }
// } }
} }
_ => {} _ => {}
} }
@ -391,10 +365,11 @@ impl ProjectPanel {
fn deploy_context_menu( fn deploy_context_menu(
&mut self, &mut self,
position: Point<Pixels>, _position: Point<Pixels>,
entry_id: ProjectEntryId, _entry_id: ProjectEntryId,
cx: &mut ViewContext<Self>, _cx: &mut ViewContext<Self>,
) { ) {
todo!()
// let project = self.project.read(cx); // let project = self.project.read(cx);
// let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) { // let worktree_id = if let Some(id) = project.worktree_id_for_entry(entry_id, cx) {
@ -579,22 +554,18 @@ impl ProjectPanel {
} }
} }
fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> { fn confirm(&mut self, _: &Confirm, cx: &mut ViewContext<Self>) {
if let Some(task) = self.confirm_edit(cx) { if let Some(task) = self.confirm_edit(cx) {
return Some(task); task.detach_and_log_err(cx);
}
} }
None fn open_file(&mut self, _: &Open, cx: &mut ViewContext<Self>) {
}
fn open_file(&mut self, _: &Open, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
if let Some((_, entry)) = self.selected_entry(cx) { if let Some((_, entry)) = self.selected_entry(cx) {
if entry.is_file() { if entry.is_file() {
self.open_entry(entry.id, true, cx); self.open_entry(entry.id, true, cx);
} }
} }
None
} }
fn confirm_edit(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> { fn confirm_edit(&mut self, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
@ -800,17 +771,19 @@ impl ProjectPanel {
} }
} }
fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> { fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
maybe!({
let Selection { entry_id, .. } = self.selection?; let Selection { entry_id, .. } = self.selection?;
let path = self.project.read(cx).path_for_entry(entry_id, cx)?.path; let path = self.project.read(cx).path_for_entry(entry_id, cx)?.path;
let file_name = path.file_name()?; let file_name = path.file_name()?;
let mut answer = cx.prompt( let answer = cx.prompt(
PromptLevel::Info, PromptLevel::Info,
&format!("Delete {file_name:?}?"), &format!("Delete {file_name:?}?"),
&["Delete", "Cancel"], &["Delete", "Cancel"],
); );
Some(cx.spawn(|this, mut cx| async move {
cx.spawn(|this, mut cx| async move {
if answer.await != Ok(0) { if answer.await != Ok(0) {
return Ok(()); return Ok(());
} }
@ -820,7 +793,10 @@ impl ProjectPanel {
.ok_or_else(|| anyhow!("no such entry")) .ok_or_else(|| anyhow!("no such entry"))
})?? })??
.await .await
})) })
.detach_and_log_err(cx);
Some(())
});
} }
fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) { fn select_next(&mut self, _: &SelectNext, cx: &mut ViewContext<Self>) {
@ -897,8 +873,9 @@ impl ProjectPanel {
} }
} }
fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) -> Option<()> { fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
if let Some((worktree, entry)) = self.selected_entry(cx) { maybe!({
let (worktree, entry) = self.selected_entry(cx)?;
let clipboard_entry = self.clipboard_entry?; let clipboard_entry = self.clipboard_entry?;
if clipboard_entry.worktree_id() != worktree.id() { if clipboard_entry.worktree_id() != worktree.id() {
return None; return None;
@ -942,15 +919,16 @@ impl ProjectPanel {
if let Some(task) = self.project.update(cx, |project, cx| { if let Some(task) = self.project.update(cx, |project, cx| {
project.rename_entry(clipboard_entry.entry_id(), new_path, cx) project.rename_entry(clipboard_entry.entry_id(), new_path, cx)
}) { }) {
task.detach_and_log_err(cx) task.detach_and_log_err(cx);
} }
} else if let Some(task) = self.project.update(cx, |project, cx| { } else if let Some(task) = self.project.update(cx, |project, cx| {
project.copy_entry(clipboard_entry.entry_id(), new_path, cx) project.copy_entry(clipboard_entry.entry_id(), new_path, cx)
}) { }) {
task.detach_and_log_err(cx) task.detach_and_log_err(cx);
} }
}
None Some(())
});
} }
fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) { fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
@ -977,7 +955,7 @@ impl ProjectPanel {
} }
} }
fn open_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) { fn open_in_terminal(&mut self, _: &OpenInTerminal, _cx: &mut ViewContext<Self>) {
todo!() todo!()
// if let Some((worktree, entry)) = self.selected_entry(cx) { // if let Some((worktree, entry)) = self.selected_entry(cx) {
// let window = cx.window(); // let window = cx.window();
@ -1012,36 +990,37 @@ impl ProjectPanel {
} }
} }
fn move_entry( // todo!()
&mut self, // fn move_entry(
entry_to_move: ProjectEntryId, // &mut self,
destination: ProjectEntryId, // entry_to_move: ProjectEntryId,
destination_is_file: bool, // destination: ProjectEntryId,
cx: &mut ViewContext<Self>, // destination_is_file: bool,
) { // cx: &mut ViewContext<Self>,
let destination_worktree = self.project.update(cx, |project, cx| { // ) {
let entry_path = project.path_for_entry(entry_to_move, cx)?; // let destination_worktree = self.project.update(cx, |project, cx| {
let destination_entry_path = project.path_for_entry(destination, cx)?.path.clone(); // let entry_path = project.path_for_entry(entry_to_move, cx)?;
// let destination_entry_path = project.path_for_entry(destination, cx)?.path.clone();
let mut destination_path = destination_entry_path.as_ref(); // let mut destination_path = destination_entry_path.as_ref();
if destination_is_file { // if destination_is_file {
destination_path = destination_path.parent()?; // destination_path = destination_path.parent()?;
} // }
let mut new_path = destination_path.to_path_buf(); // let mut new_path = destination_path.to_path_buf();
new_path.push(entry_path.path.file_name()?); // new_path.push(entry_path.path.file_name()?);
if new_path != entry_path.path.as_ref() { // if new_path != entry_path.path.as_ref() {
let task = project.rename_entry(entry_to_move, new_path, cx)?; // let task = project.rename_entry(entry_to_move, new_path, cx)?;
cx.foreground_executor().spawn(task).detach_and_log_err(cx); // cx.foreground_executor().spawn(task).detach_and_log_err(cx);
} // }
Some(project.worktree_id_for_entry(destination, cx)?) // Some(project.worktree_id_for_entry(destination, cx)?)
}); // });
if let Some(destination_worktree) = destination_worktree { // if let Some(destination_worktree) = destination_worktree {
self.expand_entry(destination_worktree, destination, cx); // self.expand_entry(destination_worktree, destination, cx);
} // }
} // }
fn index_for_selection(&self, selection: Selection) -> Option<(usize, usize, usize)> { fn index_for_selection(&self, selection: Selection) -> Option<(usize, usize, usize)> {
let mut entry_index = 0; let mut entry_index = 0;
@ -1366,23 +1345,32 @@ impl ProjectPanel {
.git_status .git_status
.as_ref() .as_ref()
.map(|status| match status { .map(|status| match status {
GitFileStatus::Added => theme.styles.status.created, GitFileStatus::Added => theme.status().created,
GitFileStatus::Modified => theme.styles.status.modified, GitFileStatus::Modified => theme.status().modified,
GitFileStatus::Conflict => theme.styles.status.conflict, GitFileStatus::Conflict => theme.status().conflict,
}) })
.unwrap_or(theme.styles.status.info); .unwrap_or(theme.status().info);
h_stack() h_stack()
.child(if let Some(icon) = &details.icon { .child(if let Some(icon) = &details.icon {
div().child(svg().path(icon.to_string())) div().child(
// todo!() Marshall: Can we use our `IconElement` component here?
svg()
.size(rems(0.9375))
.flex_none()
.path(icon.to_string())
.text_color(cx.theme().colors().icon),
)
} else { } else {
div() div()
}) })
.child( .child(
if let (Some(editor), true) = (editor, show_editor) { if let (Some(editor), true) = (editor, show_editor) {
div().child(editor.clone()) div().w_full().child(editor.clone())
} else { } else {
div().child(details.filename.clone()) div()
.text_color(filename_text_color)
.child(Label::new(details.filename.clone()))
} }
.ml_1(), .ml_1(),
) )
@ -1390,11 +1378,10 @@ impl ProjectPanel {
} }
fn render_entry( fn render_entry(
&self,
entry_id: ProjectEntryId, entry_id: ProjectEntryId,
details: EntryDetails, details: EntryDetails,
editor: &View<Editor>,
// dragged_entry_destination: &mut Option<Arc<Path>>, // dragged_entry_destination: &mut Option<Arc<Path>>,
// theme: &theme::ProjectPanel,
cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
) -> Div<Self, StatefulInteractivity<Self>> { ) -> Div<Self, StatefulInteractivity<Self>> {
let kind = details.kind; let kind = details.kind;
@ -1402,9 +1389,18 @@ impl ProjectPanel {
const INDENT_SIZE: Pixels = px(16.0); const INDENT_SIZE: Pixels = px(16.0);
let padding = INDENT_SIZE + details.depth as f32 * px(settings.indent_size); let padding = INDENT_SIZE + details.depth as f32 * px(settings.indent_size);
let show_editor = details.is_editing && !details.is_processing; let show_editor = details.is_editing && !details.is_processing;
let is_selected = self
.selection
.map_or(false, |selection| selection.entry_id == entry_id);
Self::render_entry_visual_element(&details, Some(editor), padding, cx) Self::render_entry_visual_element(&details, Some(&self.filename_editor), padding, cx)
.id(entry_id.to_proto() as usize) .id(entry_id.to_proto() as usize)
.w_full()
.cursor_pointer()
.when(is_selected, |this| {
this.bg(cx.theme().colors().element_selected)
})
.hover(|style| style.bg(cx.theme().colors().element_hover))
.on_click(move |this, event, cx| { .on_click(move |this, event, cx| {
if !show_editor { if !show_editor {
if kind.is_dir() { if kind.is_dir() {
@ -1418,38 +1414,51 @@ impl ProjectPanel {
} }
} }
}) })
// .on_down(MouseButton::Right, move |event, this, cx| { .on_mouse_down(MouseButton::Right, move |this, event, cx| {
// this.deploy_context_menu(event.position, entry_id, cx); this.deploy_context_menu(event.position, entry_id, cx);
// }) })
// .on_up(MouseButton::Left, move |_, this, cx| { // .on_drop::<ProjectEntryId>(|this, event, cx| {
// if let Some((_, dragged_entry)) = cx
// .global::<DragAndDrop<Workspace>>()
// .currently_dragged::<ProjectEntryId>(cx.window())
// {
// this.move_entry( // this.move_entry(
// *dragged_entry, // *dragged_entry,
// entry_id, // entry_id,
// matches!(details.kind, EntryKind::File(_)), // matches!(details.kind, EntryKind::File(_)),
// cx, // cx,
// ); // );
// }
// }) // })
} }
} }
impl Render for ProjectPanel { impl Render for ProjectPanel {
type Element = Div<Self, StatefulInteractivity<Self>, FocusEnabled<Self>>; type Element = Div<Self, StatefulInteractivity<Self>, FocusableKeyDispatch<Self>>;
fn render(&mut self, cx: &mut gpui::ViewContext<Self>) -> Self::Element {
enum ProjectPanel {}
let theme = cx.theme();
let last_worktree_root_id = self.last_worktree_root_id;
fn render(&mut self, _cx: &mut gpui::ViewContext<Self>) -> Self::Element {
let has_worktree = self.visible_entries.len() != 0; let has_worktree = self.visible_entries.len() != 0;
if has_worktree { if has_worktree {
div() div()
.id("project-panel") .id("project-panel")
.size_full()
.context("ProjectPanel")
.on_action(Self::select_next)
.on_action(Self::select_prev)
.on_action(Self::expand_selected_entry)
.on_action(Self::collapse_selected_entry)
.on_action(Self::collapse_all_entries)
.on_action(Self::new_file)
.on_action(Self::new_directory)
.on_action(Self::rename)
.on_action(Self::delete)
.on_action(Self::confirm)
.on_action(Self::open_file)
.on_action(Self::cancel)
.on_action(Self::cut)
.on_action(Self::copy)
.on_action(Self::copy_path)
.on_action(Self::copy_relative_path)
.on_action(Self::paste)
.on_action(Self::reveal_in_finder)
.on_action(Self::open_in_terminal)
.on_action(Self::new_search_in_directory)
.track_focus(&self.focus_handle) .track_focus(&self.focus_handle)
.child( .child(
uniform_list( uniform_list(
@ -1461,17 +1470,12 @@ impl Render for ProjectPanel {
|this: &mut Self, range, cx| { |this: &mut Self, range, cx| {
let mut items = SmallVec::new(); let mut items = SmallVec::new();
this.for_each_visible_entry(range, cx, |id, details, cx| { this.for_each_visible_entry(range, cx, |id, details, cx| {
items.push(Self::render_entry( items.push(this.render_entry(id, details, cx));
id,
details,
&this.filename_editor,
// &mut dragged_entry_destination,
cx,
));
}); });
items items
}, },
) )
.size_full()
.track_scroll(self.list.clone()), .track_scroll(self.list.clone()),
) )
} else { } else {

View file

@ -0,0 +1,45 @@
use anyhow;
use schemars::JsonSchema;
use serde_derive::{Deserialize, Serialize};
use settings::Settings;
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProjectPanelDockPosition {
Left,
Right,
}
#[derive(Deserialize, Debug)]
pub struct ProjectPanelSettings {
pub default_width: f32,
pub dock: ProjectPanelDockPosition,
pub file_icons: bool,
pub folder_icons: bool,
pub git_status: bool,
pub indent_size: f32,
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema, Debug)]
pub struct ProjectPanelSettingsContent {
pub default_width: Option<f32>,
pub dock: Option<ProjectPanelDockPosition>,
pub file_icons: Option<bool>,
pub folder_icons: Option<bool>,
pub git_status: Option<bool>,
pub indent_size: Option<f32>,
}
impl Settings for ProjectPanelSettings {
const KEY: Option<&'static str> = Some("project_panel");
type FileContent = ProjectPanelSettingsContent;
fn load(
default_value: &Self::FileContent,
user_values: &[&Self::FileContent],
_: &mut gpui::AppContext,
) -> anyhow::Result<Self> {
Self::load_via_json_merge(default_value, user_values)
}
}

View file

@ -9,7 +9,7 @@ use schemars::{
}; };
use serde::Deserialize; use serde::Deserialize;
use serde_json::Value; use serde_json::Value;
use util::{asset_str, ResultExt}; use util::asset_str;
#[derive(Debug, Deserialize, Default, Clone, JsonSchema)] #[derive(Debug, Deserialize, Default, Clone, JsonSchema)]
#[serde(transparent)] #[serde(transparent)]
@ -86,7 +86,9 @@ impl KeymapFile {
"invalid binding value for keystroke {keystroke}, context {context:?}" "invalid binding value for keystroke {keystroke}, context {context:?}"
) )
}) })
.log_err() // todo!()
.ok()
// .log_err()
.map(|action| KeyBinding::load(&keystroke, action, context.as_deref())) .map(|action| KeyBinding::load(&keystroke, action, context.as_deref()))
}) })
.collect::<Result<Vec<_>>>()?; .collect::<Result<Vec<_>>>()?;

View file

@ -2,10 +2,8 @@ use std::sync::Arc;
use gpui::{div, DefiniteLength, Hsla, MouseButton, WindowContext}; use gpui::{div, DefiniteLength, Hsla, MouseButton, WindowContext};
use crate::{ use crate::prelude::*;
h_stack, prelude::*, Icon, IconButton, IconColor, IconElement, Label, LabelColor, use crate::{h_stack, Icon, IconButton, IconElement, Label, LineHeightStyle, TextColor};
LineHeightStyle,
};
/// Provides the flexibility to use either a standard /// Provides the flexibility to use either a standard
/// button or an icon button in a given context. /// button or an icon button in a given context.
@ -87,7 +85,7 @@ pub struct Button<V: 'static> {
label: SharedString, label: SharedString,
variant: ButtonVariant, variant: ButtonVariant,
width: Option<DefiniteLength>, width: Option<DefiniteLength>,
color: Option<LabelColor>, color: Option<TextColor>,
} }
impl<V: 'static> Button<V> { impl<V: 'static> Button<V> {
@ -141,14 +139,14 @@ impl<V: 'static> Button<V> {
self self
} }
pub fn color(mut self, color: Option<LabelColor>) -> Self { pub fn color(mut self, color: Option<TextColor>) -> Self {
self.color = color; self.color = color;
self self
} }
pub fn label_color(&self, color: Option<LabelColor>) -> LabelColor { pub fn label_color(&self, color: Option<TextColor>) -> TextColor {
if self.disabled { if self.disabled {
LabelColor::Disabled TextColor::Disabled
} else if let Some(color) = color { } else if let Some(color) = color {
color color
} else { } else {
@ -156,21 +154,21 @@ impl<V: 'static> Button<V> {
} }
} }
fn render_label(&self, color: LabelColor) -> Label { fn render_label(&self, color: TextColor) -> Label {
Label::new(self.label.clone()) Label::new(self.label.clone())
.color(color) .color(color)
.line_height_style(LineHeightStyle::UILabel) .line_height_style(LineHeightStyle::UILabel)
} }
fn render_icon(&self, icon_color: IconColor) -> Option<IconElement> { fn render_icon(&self, icon_color: TextColor) -> Option<IconElement> {
self.icon.map(|i| IconElement::new(i).color(icon_color)) self.icon.map(|i| IconElement::new(i).color(icon_color))
} }
pub fn render(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> { pub fn render(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
let (icon_color, label_color) = match (self.disabled, self.color) { let (icon_color, label_color) = match (self.disabled, self.color) {
(true, _) => (IconColor::Disabled, LabelColor::Disabled), (true, _) => (TextColor::Disabled, TextColor::Disabled),
(_, None) => (IconColor::Default, LabelColor::Default), (_, None) => (TextColor::Default, TextColor::Default),
(_, Some(color)) => (IconColor::from(color), color), (_, Some(color)) => (TextColor::from(color), color),
}; };
let mut button = h_stack() let mut button = h_stack()
@ -240,7 +238,7 @@ pub use stories::*;
#[cfg(feature = "stories")] #[cfg(feature = "stories")]
mod stories { mod stories {
use super::*; use super::*;
use crate::{h_stack, v_stack, LabelColor, Story}; use crate::{h_stack, v_stack, Story, TextColor};
use gpui::{rems, Div, Render}; use gpui::{rems, Div, Render};
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
@ -265,7 +263,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label").variant(ButtonVariant::Ghost), // .state(state), Button::new("Label").variant(ButtonVariant::Ghost), // .state(state),
@ -276,7 +274,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")
@ -290,7 +288,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")
@ -307,7 +305,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label").variant(ButtonVariant::Filled), // .state(state), Button::new("Label").variant(ButtonVariant::Filled), // .state(state),
@ -318,7 +316,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")
@ -332,7 +330,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")
@ -349,7 +347,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")
@ -363,7 +361,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")
@ -379,7 +377,7 @@ mod stories {
v_stack() v_stack()
.gap_1() .gap_1()
.child( .child(
Label::new(state.to_string()).color(LabelColor::Muted), Label::new(state.to_string()).color(TextColor::Muted),
) )
.child( .child(
Button::new("Label") Button::new("Label")

View file

@ -6,7 +6,7 @@ use gpui::{
}; };
use theme2::ActiveTheme; use theme2::ActiveTheme;
use crate::{Icon, IconColor, IconElement, Selection}; use crate::{Icon, IconElement, Selection, TextColor};
pub type CheckHandler<V> = Arc<dyn Fn(Selection, &mut V, &mut ViewContext<V>) + Send + Sync>; pub type CheckHandler<V> = Arc<dyn Fn(Selection, &mut V, &mut ViewContext<V>) + Send + Sync>;
@ -58,9 +58,9 @@ impl<V: 'static> Checkbox<V> {
.color( .color(
// If the checkbox is disabled we change the color of the icon. // If the checkbox is disabled we change the color of the icon.
if self.disabled { if self.disabled {
IconColor::Disabled TextColor::Disabled
} else { } else {
IconColor::Selected TextColor::Selected
}, },
), ),
) )
@ -73,9 +73,9 @@ impl<V: 'static> Checkbox<V> {
.color( .color(
// If the checkbox is disabled we change the color of the icon. // If the checkbox is disabled we change the color of the icon.
if self.disabled { if self.disabled {
IconColor::Disabled TextColor::Disabled
} else { } else {
IconColor::Selected TextColor::Selected
}, },
), ),
) )

View file

@ -1,7 +1,7 @@
use gpui::{rems, svg, Hsla}; use gpui::{rems, svg};
use strum::EnumIter; use strum::EnumIter;
use crate::{prelude::*, LabelColor}; use crate::prelude::*;
#[derive(Default, PartialEq, Copy, Clone)] #[derive(Default, PartialEq, Copy, Clone)]
pub enum IconSize { pub enum IconSize {
@ -10,70 +10,6 @@ pub enum IconSize {
Medium, Medium,
} }
#[derive(Default, PartialEq, Copy, Clone)]
pub enum IconColor {
#[default]
Default,
Accent,
Created,
Deleted,
Disabled,
Error,
Hidden,
Info,
Modified,
Muted,
Placeholder,
Player(u32),
Selected,
Success,
Warning,
}
impl IconColor {
pub fn color(self, cx: &WindowContext) -> Hsla {
match self {
IconColor::Default => cx.theme().colors().icon,
IconColor::Muted => cx.theme().colors().icon_muted,
IconColor::Disabled => cx.theme().colors().icon_disabled,
IconColor::Placeholder => cx.theme().colors().icon_placeholder,
IconColor::Accent => cx.theme().colors().icon_accent,
IconColor::Error => cx.theme().status().error,
IconColor::Warning => cx.theme().status().warning,
IconColor::Success => cx.theme().status().success,
IconColor::Info => cx.theme().status().info,
IconColor::Selected => cx.theme().colors().icon_accent,
IconColor::Player(i) => cx.theme().styles.player.0[i.clone() as usize].cursor,
IconColor::Created => cx.theme().status().created,
IconColor::Modified => cx.theme().status().modified,
IconColor::Deleted => cx.theme().status().deleted,
IconColor::Hidden => cx.theme().status().hidden,
}
}
}
impl From<LabelColor> for IconColor {
fn from(label: LabelColor) -> Self {
match label {
LabelColor::Default => IconColor::Default,
LabelColor::Muted => IconColor::Muted,
LabelColor::Disabled => IconColor::Disabled,
LabelColor::Placeholder => IconColor::Placeholder,
LabelColor::Accent => IconColor::Accent,
LabelColor::Error => IconColor::Error,
LabelColor::Warning => IconColor::Warning,
LabelColor::Success => IconColor::Success,
LabelColor::Info => IconColor::Info,
LabelColor::Selected => IconColor::Selected,
LabelColor::Player(i) => IconColor::Player(i),
LabelColor::Created => IconColor::Created,
LabelColor::Modified => IconColor::Modified,
LabelColor::Deleted => IconColor::Deleted,
LabelColor::Hidden => IconColor::Hidden,
}
}
}
#[derive(Debug, PartialEq, Copy, Clone, EnumIter)] #[derive(Debug, PartialEq, Copy, Clone, EnumIter)]
pub enum Icon { pub enum Icon {
Ai, Ai,
@ -194,7 +130,7 @@ impl Icon {
#[derive(Component)] #[derive(Component)]
pub struct IconElement { pub struct IconElement {
icon: Icon, icon: Icon,
color: IconColor, color: TextColor,
size: IconSize, size: IconSize,
} }
@ -202,12 +138,12 @@ impl IconElement {
pub fn new(icon: Icon) -> Self { pub fn new(icon: Icon) -> Self {
Self { Self {
icon, icon,
color: IconColor::default(), color: TextColor::default(),
size: IconSize::default(), size: IconSize::default(),
} }
} }
pub fn color(mut self, color: IconColor) -> Self { pub fn color(mut self, color: TextColor) -> Self {
self.color = color; self.color = color;
self self
} }

View file

@ -1,10 +1,7 @@
use crate::{h_stack, prelude::*, ClickHandler, Icon, IconElement, TextColor, TextTooltip};
use gpui::{MouseButton, VisualContext};
use std::sync::Arc; use std::sync::Arc;
use gpui::MouseButton;
use crate::{h_stack, prelude::*};
use crate::{ClickHandler, Icon, IconColor, IconElement};
struct IconButtonHandlers<V: 'static> { struct IconButtonHandlers<V: 'static> {
click: Option<ClickHandler<V>>, click: Option<ClickHandler<V>>,
} }
@ -19,9 +16,10 @@ impl<V: 'static> Default for IconButtonHandlers<V> {
pub struct IconButton<V: 'static> { pub struct IconButton<V: 'static> {
id: ElementId, id: ElementId,
icon: Icon, icon: Icon,
color: IconColor, color: TextColor,
variant: ButtonVariant, variant: ButtonVariant,
state: InteractionState, state: InteractionState,
tooltip: Option<SharedString>,
handlers: IconButtonHandlers<V>, handlers: IconButtonHandlers<V>,
} }
@ -30,9 +28,10 @@ impl<V: 'static> IconButton<V> {
Self { Self {
id: id.into(), id: id.into(),
icon, icon,
color: IconColor::default(), color: TextColor::default(),
variant: ButtonVariant::default(), variant: ButtonVariant::default(),
state: InteractionState::default(), state: InteractionState::default(),
tooltip: None,
handlers: IconButtonHandlers::default(), handlers: IconButtonHandlers::default(),
} }
} }
@ -42,7 +41,7 @@ impl<V: 'static> IconButton<V> {
self self
} }
pub fn color(mut self, color: IconColor) -> Self { pub fn color(mut self, color: TextColor) -> Self {
self.color = color; self.color = color;
self self
} }
@ -57,6 +56,11 @@ impl<V: 'static> IconButton<V> {
self self
} }
pub fn tooltip(mut self, tooltip: impl Into<SharedString>) -> Self {
self.tooltip = Some(tooltip.into());
self
}
pub fn on_click( pub fn on_click(
mut self, mut self,
handler: impl 'static + Fn(&mut V, &mut ViewContext<V>) + Send + Sync, handler: impl 'static + Fn(&mut V, &mut ViewContext<V>) + Send + Sync,
@ -67,7 +71,7 @@ impl<V: 'static> IconButton<V> {
fn render(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> { fn render(self, _view: &mut V, cx: &mut ViewContext<V>) -> impl Component<V> {
let icon_color = match (self.state, self.color) { let icon_color = match (self.state, self.color) {
(InteractionState::Disabled, _) => IconColor::Disabled, (InteractionState::Disabled, _) => TextColor::Disabled,
_ => self.color, _ => self.color,
}; };
@ -101,6 +105,11 @@ impl<V: 'static> IconButton<V> {
}); });
} }
if let Some(tooltip) = self.tooltip.clone() {
button =
button.tooltip(move |_, cx| cx.build_view(|cx| TextTooltip::new(tooltip.clone())));
}
button button
} }
} }

View file

@ -1,6 +1,6 @@
use crate::prelude::*; use crate::prelude::*;
use crate::Label; use crate::Label;
use crate::LabelColor; use crate::TextColor;
#[derive(Default, PartialEq)] #[derive(Default, PartialEq)]
pub enum InputVariant { pub enum InputVariant {
@ -71,15 +71,15 @@ impl Input {
}; };
let placeholder_label = Label::new(self.placeholder.clone()).color(if self.disabled { let placeholder_label = Label::new(self.placeholder.clone()).color(if self.disabled {
LabelColor::Disabled TextColor::Disabled
} else { } else {
LabelColor::Placeholder TextColor::Placeholder
}); });
let label = Label::new(self.value.clone()).color(if self.disabled { let label = Label::new(self.value.clone()).color(if self.disabled {
LabelColor::Disabled TextColor::Disabled
} else { } else {
LabelColor::Default TextColor::Default
}); });
div() div()

View file

@ -3,7 +3,7 @@ use strum::EnumIter;
use crate::prelude::*; use crate::prelude::*;
#[derive(Component)] #[derive(Component, Clone)]
pub struct KeyBinding { pub struct KeyBinding {
/// A keybinding consists of a key and a set of modifier keys. /// A keybinding consists of a key and a set of modifier keys.
/// More then one keybinding produces a chord. /// More then one keybinding produces a chord.

View file

@ -3,8 +3,15 @@ use gpui::{relative, Hsla, Text, TextRun, WindowContext};
use crate::prelude::*; use crate::prelude::*;
use crate::styled_ext::StyledExt; use crate::styled_ext::StyledExt;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Default)]
pub enum LabelSize {
#[default]
Default,
Small,
}
#[derive(Default, PartialEq, Copy, Clone)] #[derive(Default, PartialEq, Copy, Clone)]
pub enum LabelColor { pub enum TextColor {
#[default] #[default]
Default, Default,
Accent, Accent,
@ -23,24 +30,24 @@ pub enum LabelColor {
Warning, Warning,
} }
impl LabelColor { impl TextColor {
pub fn hsla(&self, cx: &WindowContext) -> Hsla { pub fn color(&self, cx: &WindowContext) -> Hsla {
match self { match self {
LabelColor::Default => cx.theme().colors().text, TextColor::Default => cx.theme().colors().text,
LabelColor::Muted => cx.theme().colors().text_muted, TextColor::Muted => cx.theme().colors().text_muted,
LabelColor::Created => cx.theme().status().created, TextColor::Created => cx.theme().status().created,
LabelColor::Modified => cx.theme().status().modified, TextColor::Modified => cx.theme().status().modified,
LabelColor::Deleted => cx.theme().status().deleted, TextColor::Deleted => cx.theme().status().deleted,
LabelColor::Disabled => cx.theme().colors().text_disabled, TextColor::Disabled => cx.theme().colors().text_disabled,
LabelColor::Hidden => cx.theme().status().hidden, TextColor::Hidden => cx.theme().status().hidden,
LabelColor::Info => cx.theme().status().info, TextColor::Info => cx.theme().status().info,
LabelColor::Placeholder => cx.theme().colors().text_placeholder, TextColor::Placeholder => cx.theme().colors().text_placeholder,
LabelColor::Accent => cx.theme().colors().text_accent, TextColor::Accent => cx.theme().colors().text_accent,
LabelColor::Player(i) => cx.theme().styles.player.0[i.clone() as usize].cursor, TextColor::Player(i) => cx.theme().styles.player.0[i.clone() as usize].cursor,
LabelColor::Error => cx.theme().status().error, TextColor::Error => cx.theme().status().error,
LabelColor::Selected => cx.theme().colors().text_accent, TextColor::Selected => cx.theme().colors().text_accent,
LabelColor::Success => cx.theme().status().success, TextColor::Success => cx.theme().status().success,
LabelColor::Warning => cx.theme().status().warning, TextColor::Warning => cx.theme().status().warning,
} }
} }
} }
@ -56,8 +63,9 @@ pub enum LineHeightStyle {
#[derive(Component)] #[derive(Component)]
pub struct Label { pub struct Label {
label: SharedString, label: SharedString,
size: LabelSize,
line_height_style: LineHeightStyle, line_height_style: LineHeightStyle,
color: LabelColor, color: TextColor,
strikethrough: bool, strikethrough: bool,
} }
@ -65,13 +73,19 @@ impl Label {
pub fn new(label: impl Into<SharedString>) -> Self { pub fn new(label: impl Into<SharedString>) -> Self {
Self { Self {
label: label.into(), label: label.into(),
size: LabelSize::Default,
line_height_style: LineHeightStyle::default(), line_height_style: LineHeightStyle::default(),
color: LabelColor::Default, color: TextColor::Default,
strikethrough: false, strikethrough: false,
} }
} }
pub fn color(mut self, color: LabelColor) -> Self { pub fn size(mut self, size: LabelSize) -> Self {
self.size = size;
self
}
pub fn color(mut self, color: TextColor) -> Self {
self.color = color; self.color = color;
self self
} }
@ -95,14 +109,17 @@ impl Label {
.top_1_2() .top_1_2()
.w_full() .w_full()
.h_px() .h_px()
.bg(LabelColor::Hidden.hsla(cx)), .bg(TextColor::Hidden.color(cx)),
) )
}) })
.text_ui() .map(|this| match self.size {
LabelSize::Default => this.text_ui(),
LabelSize::Small => this.text_ui_sm(),
})
.when(self.line_height_style == LineHeightStyle::UILabel, |this| { .when(self.line_height_style == LineHeightStyle::UILabel, |this| {
this.line_height(relative(1.)) this.line_height(relative(1.))
}) })
.text_color(self.color.hsla(cx)) .text_color(self.color.color(cx))
.child(self.label.clone()) .child(self.label.clone())
} }
} }
@ -110,7 +127,8 @@ impl Label {
#[derive(Component)] #[derive(Component)]
pub struct HighlightedLabel { pub struct HighlightedLabel {
label: SharedString, label: SharedString,
color: LabelColor, size: LabelSize,
color: TextColor,
highlight_indices: Vec<usize>, highlight_indices: Vec<usize>,
strikethrough: bool, strikethrough: bool,
} }
@ -121,13 +139,19 @@ impl HighlightedLabel {
pub fn new(label: impl Into<SharedString>, highlight_indices: Vec<usize>) -> Self { pub fn new(label: impl Into<SharedString>, highlight_indices: Vec<usize>) -> Self {
Self { Self {
label: label.into(), label: label.into(),
color: LabelColor::Default, size: LabelSize::Default,
color: TextColor::Default,
highlight_indices, highlight_indices,
strikethrough: false, strikethrough: false,
} }
} }
pub fn color(mut self, color: LabelColor) -> Self { pub fn size(mut self, size: LabelSize) -> Self {
self.size = size;
self
}
pub fn color(mut self, color: TextColor) -> Self {
self.color = color; self.color = color;
self self
} }
@ -146,7 +170,7 @@ impl HighlightedLabel {
let mut runs: Vec<TextRun> = Vec::new(); let mut runs: Vec<TextRun> = Vec::new();
for (char_ix, char) in self.label.char_indices() { for (char_ix, char) in self.label.char_indices() {
let mut color = self.color.hsla(cx); let mut color = self.color.color(cx);
if let Some(highlight_ix) = highlight_indices.peek() { if let Some(highlight_ix) = highlight_indices.peek() {
if char_ix == *highlight_ix { if char_ix == *highlight_ix {
@ -183,9 +207,13 @@ impl HighlightedLabel {
.my_auto() .my_auto()
.w_full() .w_full()
.h_px() .h_px()
.bg(LabelColor::Hidden.hsla(cx)), .bg(TextColor::Hidden.color(cx)),
) )
}) })
.map(|this| match self.size {
LabelSize::Default => this.text_ui(),
LabelSize::Small => this.text_ui_sm(),
})
.child(Text::styled(self.label, runs)) .child(Text::styled(self.label, runs))
} }
} }

View file

@ -1,11 +1,11 @@
use gpui::div; use gpui::div;
use crate::prelude::*;
use crate::settings::user_settings; use crate::settings::user_settings;
use crate::{ use crate::{
disclosure_control, h_stack, v_stack, Avatar, Icon, IconColor, IconElement, IconSize, Label, disclosure_control, h_stack, v_stack, Avatar, GraphicSlot, Icon, IconElement, IconSize, Label,
LabelColor, Toggle, TextColor, Toggle,
}; };
use crate::{prelude::*, GraphicSlot};
#[derive(Clone, Copy, Default, Debug, PartialEq)] #[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum ListItemVariant { pub enum ListItemVariant {
@ -68,7 +68,7 @@ impl ListHeader {
.items_center() .items_center()
.children(icons.into_iter().map(|i| { .children(icons.into_iter().map(|i| {
IconElement::new(i) IconElement::new(i)
.color(IconColor::Muted) .color(TextColor::Muted)
.size(IconSize::Small) .size(IconSize::Small)
})), })),
), ),
@ -106,10 +106,10 @@ impl ListHeader {
.items_center() .items_center()
.children(self.left_icon.map(|i| { .children(self.left_icon.map(|i| {
IconElement::new(i) IconElement::new(i)
.color(IconColor::Muted) .color(TextColor::Muted)
.size(IconSize::Small) .size(IconSize::Small)
})) }))
.child(Label::new(self.label.clone()).color(LabelColor::Muted)), .child(Label::new(self.label.clone()).color(TextColor::Muted)),
) )
.child(disclosure_control), .child(disclosure_control),
) )
@ -157,10 +157,10 @@ impl ListSubHeader {
.items_center() .items_center()
.children(self.left_icon.map(|i| { .children(self.left_icon.map(|i| {
IconElement::new(i) IconElement::new(i)
.color(IconColor::Muted) .color(TextColor::Muted)
.size(IconSize::Small) .size(IconSize::Small)
})) }))
.child(Label::new(self.label.clone()).color(LabelColor::Muted)), .child(Label::new(self.label.clone()).color(TextColor::Muted)),
), ),
) )
} }
@ -291,7 +291,7 @@ impl ListEntry {
h_stack().child( h_stack().child(
IconElement::new(i) IconElement::new(i)
.size(IconSize::Small) .size(IconSize::Small)
.color(IconColor::Muted), .color(TextColor::Muted),
), ),
), ),
Some(GraphicSlot::Avatar(src)) => Some(h_stack().child(Avatar::new(src))), Some(GraphicSlot::Avatar(src)) => Some(h_stack().child(Avatar::new(src))),
@ -394,7 +394,7 @@ impl List {
(false, _) => div().children(self.items), (false, _) => div().children(self.items),
(true, Toggle::Toggled(false)) => div(), (true, Toggle::Toggled(false)) => div(),
(true, _) => { (true, _) => {
div().child(Label::new(self.empty_message.clone()).color(LabelColor::Muted)) div().child(Label::new(self.empty_message.clone()).color(TextColor::Muted))
} }
}; };

View file

@ -1,5 +1,5 @@
use crate::prelude::*; use crate::prelude::*;
use crate::{h_stack, v_stack, KeyBinding, Label, LabelColor}; use crate::{h_stack, v_stack, KeyBinding, Label, TextColor};
#[derive(Component)] #[derive(Component)]
pub struct Palette { pub struct Palette {
@ -54,7 +54,7 @@ impl Palette {
v_stack() v_stack()
.gap_px() .gap_px()
.child(v_stack().py_0p5().px_1().child(div().px_2().py_0p5().child( .child(v_stack().py_0p5().px_1().child(div().px_2().py_0p5().child(
Label::new(self.input_placeholder.clone()).color(LabelColor::Placeholder), Label::new(self.input_placeholder.clone()).color(TextColor::Placeholder),
))) )))
.child( .child(
div() div()
@ -75,7 +75,7 @@ impl Palette {
Some( Some(
h_stack().justify_between().px_2().py_1().child( h_stack().justify_between().px_2().py_1().child(
Label::new(self.empty_string.clone()) Label::new(self.empty_string.clone())
.color(LabelColor::Muted), .color(TextColor::Muted),
), ),
) )
} else { } else {
@ -108,7 +108,7 @@ impl Palette {
pub struct PaletteItem { pub struct PaletteItem {
pub label: SharedString, pub label: SharedString,
pub sublabel: Option<SharedString>, pub sublabel: Option<SharedString>,
pub keybinding: Option<KeyBinding>, pub key_binding: Option<KeyBinding>,
} }
impl PaletteItem { impl PaletteItem {
@ -116,7 +116,7 @@ impl PaletteItem {
Self { Self {
label: label.into(), label: label.into(),
sublabel: None, sublabel: None,
keybinding: None, key_binding: None,
} }
} }
@ -130,11 +130,8 @@ impl PaletteItem {
self self
} }
pub fn keybinding<K>(mut self, keybinding: K) -> Self pub fn key_binding(mut self, key_binding: impl Into<Option<KeyBinding>>) -> Self {
where self.key_binding = key_binding.into();
K: Into<Option<KeyBinding>>,
{
self.keybinding = keybinding.into();
self self
} }
@ -149,7 +146,7 @@ impl PaletteItem {
.child(Label::new(self.label.clone())) .child(Label::new(self.label.clone()))
.children(self.sublabel.clone().map(|sublabel| Label::new(sublabel))), .children(self.sublabel.clone().map(|sublabel| Label::new(sublabel))),
) )
.children(self.keybinding) .children(self.key_binding)
} }
} }
@ -182,23 +179,23 @@ mod stories {
.placeholder("Execute a command...") .placeholder("Execute a command...")
.items(vec![ .items(vec![
PaletteItem::new("theme selector: toggle") PaletteItem::new("theme selector: toggle")
.keybinding(KeyBinding::new(binding("cmd-k cmd-t"))), .key_binding(KeyBinding::new(binding("cmd-k cmd-t"))),
PaletteItem::new("assistant: inline assist") PaletteItem::new("assistant: inline assist")
.keybinding(KeyBinding::new(binding("cmd-enter"))), .key_binding(KeyBinding::new(binding("cmd-enter"))),
PaletteItem::new("assistant: quote selection") PaletteItem::new("assistant: quote selection")
.keybinding(KeyBinding::new(binding("cmd-<"))), .key_binding(KeyBinding::new(binding("cmd-<"))),
PaletteItem::new("assistant: toggle focus") PaletteItem::new("assistant: toggle focus")
.keybinding(KeyBinding::new(binding("cmd-?"))), .key_binding(KeyBinding::new(binding("cmd-?"))),
PaletteItem::new("auto update: check"), PaletteItem::new("auto update: check"),
PaletteItem::new("auto update: view release notes"), PaletteItem::new("auto update: view release notes"),
PaletteItem::new("branches: open recent") PaletteItem::new("branches: open recent")
.keybinding(KeyBinding::new(binding("cmd-alt-b"))), .key_binding(KeyBinding::new(binding("cmd-alt-b"))),
PaletteItem::new("chat panel: toggle focus"), PaletteItem::new("chat panel: toggle focus"),
PaletteItem::new("cli: install"), PaletteItem::new("cli: install"),
PaletteItem::new("client: sign in"), PaletteItem::new("client: sign in"),
PaletteItem::new("client: sign out"), PaletteItem::new("client: sign out"),
PaletteItem::new("editor: cancel") PaletteItem::new("editor: cancel")
.keybinding(KeyBinding::new(binding("escape"))), .key_binding(KeyBinding::new(binding("escape"))),
]), ]),
) )
} }

View file

@ -1,5 +1,5 @@
use crate::prelude::*; use crate::prelude::*;
use crate::{Icon, IconColor, IconElement, Label, LabelColor}; use crate::{Icon, IconElement, Label, TextColor};
use gpui::{red, Div, ElementId, Render, View, VisualContext}; use gpui::{red, Div, ElementId, Render, View, VisualContext};
#[derive(Component, Clone)] #[derive(Component, Clone)]
@ -92,20 +92,18 @@ impl Tab {
let label = match (self.git_status, is_deleted) { let label = match (self.git_status, is_deleted) {
(_, true) | (GitStatus::Deleted, false) => Label::new(self.title.clone()) (_, true) | (GitStatus::Deleted, false) => Label::new(self.title.clone())
.color(LabelColor::Hidden) .color(TextColor::Hidden)
.set_strikethrough(true), .set_strikethrough(true),
(GitStatus::None, false) => Label::new(self.title.clone()), (GitStatus::None, false) => Label::new(self.title.clone()),
(GitStatus::Created, false) => { (GitStatus::Created, false) => Label::new(self.title.clone()).color(TextColor::Created),
Label::new(self.title.clone()).color(LabelColor::Created)
}
(GitStatus::Modified, false) => { (GitStatus::Modified, false) => {
Label::new(self.title.clone()).color(LabelColor::Modified) Label::new(self.title.clone()).color(TextColor::Modified)
} }
(GitStatus::Renamed, false) => Label::new(self.title.clone()).color(LabelColor::Accent), (GitStatus::Renamed, false) => Label::new(self.title.clone()).color(TextColor::Accent),
(GitStatus::Conflict, false) => Label::new(self.title.clone()), (GitStatus::Conflict, false) => Label::new(self.title.clone()),
}; };
let close_icon = || IconElement::new(Icon::Close).color(IconColor::Muted); let close_icon = || IconElement::new(Icon::Close).color(TextColor::Muted);
let (tab_bg, tab_hover_bg, tab_active_bg) = match self.current { let (tab_bg, tab_hover_bg, tab_active_bg) = match self.current {
false => ( false => (
@ -148,7 +146,7 @@ impl Tab {
.children(has_fs_conflict.then(|| { .children(has_fs_conflict.then(|| {
IconElement::new(Icon::ExclamationTriangle) IconElement::new(Icon::ExclamationTriangle)
.size(crate::IconSize::Small) .size(crate::IconSize::Small)
.color(IconColor::Warning) .color(TextColor::Warning)
})) }))
.children(self.icon.map(IconElement::new)) .children(self.icon.map(IconElement::new))
.children(if self.close_side == IconSide::Left { .children(if self.close_side == IconSide::Left {

View file

@ -1,6 +1,6 @@
use gpui::{div, Component, ParentElement}; use gpui::{div, Component, ParentElement};
use crate::{Icon, IconColor, IconElement, IconSize}; use crate::{Icon, IconElement, IconSize, TextColor};
/// Whether the entry is toggleable, and if so, whether it is currently toggled. /// Whether the entry is toggleable, and if so, whether it is currently toggled.
/// ///
@ -49,12 +49,12 @@ pub fn disclosure_control<V: 'static>(toggle: Toggle) -> impl Component<V> {
(false, _) => div(), (false, _) => div(),
(_, true) => div().child( (_, true) => div().child(
IconElement::new(Icon::ChevronDown) IconElement::new(Icon::ChevronDown)
.color(IconColor::Muted) .color(TextColor::Muted)
.size(IconSize::Small), .size(IconSize::Small),
), ),
(_, false) => div().child( (_, false) => div().child(
IconElement::new(Icon::ChevronRight) IconElement::new(Icon::ChevronRight)
.color(IconColor::Muted) .color(TextColor::Muted)
.size(IconSize::Small), .size(IconSize::Small),
), ),
} }

View file

@ -1,16 +1,32 @@
use gpui::{div, Div, ParentElement, Render, SharedString, Styled, ViewContext}; use gpui::{Div, Render};
use theme2::ActiveTheme; use theme2::ActiveTheme;
use crate::StyledExt; use crate::prelude::*;
use crate::{h_stack, v_stack, KeyBinding, Label, LabelSize, StyledExt, TextColor};
#[derive(Clone, Debug)]
pub struct TextTooltip { pub struct TextTooltip {
title: SharedString, title: SharedString,
meta: Option<SharedString>,
key_binding: Option<KeyBinding>,
} }
impl TextTooltip { impl TextTooltip {
pub fn new(str: SharedString) -> Self { pub fn new(title: impl Into<SharedString>) -> Self {
Self { title: str } Self {
title: title.into(),
meta: None,
key_binding: None,
}
}
pub fn meta(mut self, meta: impl Into<SharedString>) -> Self {
self.meta = Some(meta.into());
self
}
pub fn key_binding(mut self, key_binding: impl Into<Option<KeyBinding>>) -> Self {
self.key_binding = key_binding.into();
self
} }
} }
@ -18,13 +34,26 @@ impl Render for TextTooltip {
type Element = Div<Self>; type Element = Div<Self>;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
div() v_stack()
.elevation_2(cx) .elevation_2(cx)
.font("Zed Sans") .font("Zed Sans")
.text_ui() .text_ui_sm()
.text_color(cx.theme().colors().text) .text_color(cx.theme().colors().text)
.py_1() .py_1()
.px_2() .px_2()
.child(
h_stack()
.child(self.title.clone()) .child(self.title.clone())
.when_some(self.key_binding.clone(), |this, key_binding| {
this.justify_between().child(key_binding)
}),
)
.when_some(self.meta.clone(), |this, meta| {
this.child(
Label::new(meta)
.size(LabelSize::Small)
.color(TextColor::Muted),
)
})
} }
} }

View file

@ -6,8 +6,8 @@ pub use gpui::{
}; };
pub use crate::elevation::*; pub use crate::elevation::*;
pub use crate::ButtonVariant;
pub use crate::StyledExt; pub use crate::StyledExt;
pub use crate::{ButtonVariant, TextColor};
pub use theme2::ActiveTheme; pub use theme2::ActiveTheme;
use gpui::Hsla; use gpui::Hsla;

View file

@ -10,9 +10,9 @@ use theme2::ActiveTheme;
use crate::{binding, HighlightedText}; use crate::{binding, HighlightedText};
use crate::{ use crate::{
Buffer, BufferRow, BufferRows, Button, EditorPane, FileSystemStatus, GitStatus, Buffer, BufferRow, BufferRows, Button, EditorPane, FileSystemStatus, GitStatus,
HighlightedLine, Icon, KeyBinding, Label, LabelColor, ListEntry, ListEntrySize, Livestream, HighlightedLine, Icon, KeyBinding, Label, ListEntry, ListEntrySize, Livestream, MicStatus,
MicStatus, Notification, PaletteItem, Player, PlayerCallStatus, PlayerWithCallStatus, Notification, PaletteItem, Player, PlayerCallStatus, PlayerWithCallStatus, PublicPlayer,
PublicPlayer, ScreenShareStatus, Symbol, Tab, Toggle, VideoStatus, ScreenShareStatus, Symbol, Tab, TextColor, Toggle, VideoStatus,
}; };
use crate::{ListItem, NotificationAction}; use crate::{ListItem, NotificationAction};
@ -490,20 +490,20 @@ pub fn static_project_panel_project_items() -> Vec<ListItem> {
ListEntry::new(Label::new(".config")) ListEntry::new(Label::new(".config"))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new(".git").color(LabelColor::Hidden)) ListEntry::new(Label::new(".git").color(TextColor::Hidden))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new(".cargo")) ListEntry::new(Label::new(".cargo"))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new(".idea").color(LabelColor::Hidden)) ListEntry::new(Label::new(".idea").color(TextColor::Hidden))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new("assets")) ListEntry::new(Label::new("assets"))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1) .indent_level(1)
.toggle(Toggle::Toggled(true)), .toggle(Toggle::Toggled(true)),
ListEntry::new(Label::new("cargo-target").color(LabelColor::Hidden)) ListEntry::new(Label::new("cargo-target").color(TextColor::Hidden))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new("crates")) ListEntry::new(Label::new("crates"))
@ -528,7 +528,7 @@ pub fn static_project_panel_project_items() -> Vec<ListItem> {
ListEntry::new(Label::new("call")) ListEntry::new(Label::new("call"))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(2), .indent_level(2),
ListEntry::new(Label::new("sqlez").color(LabelColor::Modified)) ListEntry::new(Label::new("sqlez").color(TextColor::Modified))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(2) .indent_level(2)
.toggle(Toggle::Toggled(false)), .toggle(Toggle::Toggled(false)),
@ -543,45 +543,45 @@ pub fn static_project_panel_project_items() -> Vec<ListItem> {
ListEntry::new(Label::new("derive_element.rs")) ListEntry::new(Label::new("derive_element.rs"))
.left_icon(Icon::FileRust.into()) .left_icon(Icon::FileRust.into())
.indent_level(4), .indent_level(4),
ListEntry::new(Label::new("storybook").color(LabelColor::Modified)) ListEntry::new(Label::new("storybook").color(TextColor::Modified))
.left_icon(Icon::FolderOpen.into()) .left_icon(Icon::FolderOpen.into())
.indent_level(1) .indent_level(1)
.toggle(Toggle::Toggled(true)), .toggle(Toggle::Toggled(true)),
ListEntry::new(Label::new("docs").color(LabelColor::Default)) ListEntry::new(Label::new("docs").color(TextColor::Default))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(2) .indent_level(2)
.toggle(Toggle::Toggled(true)), .toggle(Toggle::Toggled(true)),
ListEntry::new(Label::new("src").color(LabelColor::Modified)) ListEntry::new(Label::new("src").color(TextColor::Modified))
.left_icon(Icon::FolderOpen.into()) .left_icon(Icon::FolderOpen.into())
.indent_level(3) .indent_level(3)
.toggle(Toggle::Toggled(true)), .toggle(Toggle::Toggled(true)),
ListEntry::new(Label::new("ui").color(LabelColor::Modified)) ListEntry::new(Label::new("ui").color(TextColor::Modified))
.left_icon(Icon::FolderOpen.into()) .left_icon(Icon::FolderOpen.into())
.indent_level(4) .indent_level(4)
.toggle(Toggle::Toggled(true)), .toggle(Toggle::Toggled(true)),
ListEntry::new(Label::new("component").color(LabelColor::Created)) ListEntry::new(Label::new("component").color(TextColor::Created))
.left_icon(Icon::FolderOpen.into()) .left_icon(Icon::FolderOpen.into())
.indent_level(5) .indent_level(5)
.toggle(Toggle::Toggled(true)), .toggle(Toggle::Toggled(true)),
ListEntry::new(Label::new("facepile.rs").color(LabelColor::Default)) ListEntry::new(Label::new("facepile.rs").color(TextColor::Default))
.left_icon(Icon::FileRust.into()) .left_icon(Icon::FileRust.into())
.indent_level(6), .indent_level(6),
ListEntry::new(Label::new("follow_group.rs").color(LabelColor::Default)) ListEntry::new(Label::new("follow_group.rs").color(TextColor::Default))
.left_icon(Icon::FileRust.into()) .left_icon(Icon::FileRust.into())
.indent_level(6), .indent_level(6),
ListEntry::new(Label::new("list_item.rs").color(LabelColor::Created)) ListEntry::new(Label::new("list_item.rs").color(TextColor::Created))
.left_icon(Icon::FileRust.into()) .left_icon(Icon::FileRust.into())
.indent_level(6), .indent_level(6),
ListEntry::new(Label::new("tab.rs").color(LabelColor::Default)) ListEntry::new(Label::new("tab.rs").color(TextColor::Default))
.left_icon(Icon::FileRust.into()) .left_icon(Icon::FileRust.into())
.indent_level(6), .indent_level(6),
ListEntry::new(Label::new("target").color(LabelColor::Hidden)) ListEntry::new(Label::new("target").color(TextColor::Hidden))
.left_icon(Icon::Folder.into()) .left_icon(Icon::Folder.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new(".dockerignore")) ListEntry::new(Label::new(".dockerignore"))
.left_icon(Icon::FileGeneric.into()) .left_icon(Icon::FileGeneric.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new(".DS_Store").color(LabelColor::Hidden)) ListEntry::new(Label::new(".DS_Store").color(TextColor::Hidden))
.left_icon(Icon::FileGeneric.into()) .left_icon(Icon::FileGeneric.into())
.indent_level(1), .indent_level(1),
ListEntry::new(Label::new("Cargo.lock")) ListEntry::new(Label::new("Cargo.lock"))
@ -701,16 +701,16 @@ pub fn static_collab_panel_channels() -> Vec<ListItem> {
pub fn example_editor_actions() -> Vec<PaletteItem> { pub fn example_editor_actions() -> Vec<PaletteItem> {
vec![ vec![
PaletteItem::new("New File").keybinding(KeyBinding::new(binding("cmd-n"))), PaletteItem::new("New File").key_binding(KeyBinding::new(binding("cmd-n"))),
PaletteItem::new("Open File").keybinding(KeyBinding::new(binding("cmd-o"))), PaletteItem::new("Open File").key_binding(KeyBinding::new(binding("cmd-o"))),
PaletteItem::new("Save File").keybinding(KeyBinding::new(binding("cmd-s"))), PaletteItem::new("Save File").key_binding(KeyBinding::new(binding("cmd-s"))),
PaletteItem::new("Cut").keybinding(KeyBinding::new(binding("cmd-x"))), PaletteItem::new("Cut").key_binding(KeyBinding::new(binding("cmd-x"))),
PaletteItem::new("Copy").keybinding(KeyBinding::new(binding("cmd-c"))), PaletteItem::new("Copy").key_binding(KeyBinding::new(binding("cmd-c"))),
PaletteItem::new("Paste").keybinding(KeyBinding::new(binding("cmd-v"))), PaletteItem::new("Paste").key_binding(KeyBinding::new(binding("cmd-v"))),
PaletteItem::new("Undo").keybinding(KeyBinding::new(binding("cmd-z"))), PaletteItem::new("Undo").key_binding(KeyBinding::new(binding("cmd-z"))),
PaletteItem::new("Redo").keybinding(KeyBinding::new(binding("cmd-shift-z"))), PaletteItem::new("Redo").key_binding(KeyBinding::new(binding("cmd-shift-z"))),
PaletteItem::new("Find").keybinding(KeyBinding::new(binding("cmd-f"))), PaletteItem::new("Find").key_binding(KeyBinding::new(binding("cmd-f"))),
PaletteItem::new("Replace").keybinding(KeyBinding::new(binding("cmd-r"))), PaletteItem::new("Replace").key_binding(KeyBinding::new(binding("cmd-r"))),
PaletteItem::new("Jump to Line"), PaletteItem::new("Jump to Line"),
PaletteItem::new("Select All"), PaletteItem::new("Select All"),
PaletteItem::new("Deselect All"), PaletteItem::new("Deselect All"),

View file

@ -1,7 +1,7 @@
use gpui::{Div, Render, View, VisualContext}; use gpui::{Div, Render, View, VisualContext};
use crate::prelude::*; use crate::prelude::*;
use crate::{h_stack, Icon, IconButton, IconColor, Input}; use crate::{h_stack, Icon, IconButton, Input, TextColor};
#[derive(Clone)] #[derive(Clone)]
pub struct BufferSearch { pub struct BufferSearch {
@ -36,7 +36,7 @@ impl Render for BufferSearch {
.child( .child(
h_stack().child(Input::new("Search")).child( h_stack().child(Input::new("Search")).child(
IconButton::<Self>::new("replace", Icon::Replace) IconButton::<Self>::new("replace", Icon::Replace)
.when(self.is_replace_open, |this| this.color(IconColor::Accent)) .when(self.is_replace_open, |this| this.color(TextColor::Accent))
.on_click(|buffer_search, cx| { .on_click(|buffer_search, cx| {
buffer_search.toggle_replace(cx); buffer_search.toggle_replace(cx);
}), }),

View file

@ -1,7 +1,7 @@
use chrono::NaiveDateTime; use chrono::NaiveDateTime;
use crate::prelude::*; use crate::prelude::*;
use crate::{Icon, IconButton, Input, Label, LabelColor}; use crate::{Icon, IconButton, Input, Label, TextColor};
#[derive(Component)] #[derive(Component)]
pub struct ChatPanel { pub struct ChatPanel {
@ -95,7 +95,7 @@ impl ChatMessage {
.child(Label::new(self.author.clone())) .child(Label::new(self.author.clone()))
.child( .child(
Label::new(self.sent_at.format("%m/%d/%Y").to_string()) Label::new(self.sent_at.format("%m/%d/%Y").to_string())
.color(LabelColor::Muted), .color(TextColor::Muted),
), ),
) )
.child(div().child(Label::new(self.text.clone()))) .child(div().child(Label::new(self.text.clone())))

View file

@ -1,4 +1,4 @@
use crate::{prelude::*, Button, Label, LabelColor, Modal}; use crate::{prelude::*, Button, Label, Modal, TextColor};
#[derive(Component)] #[derive(Component)]
pub struct CopilotModal { pub struct CopilotModal {
@ -14,7 +14,7 @@ impl CopilotModal {
div().id(self.id.clone()).child( div().id(self.id.clone()).child(
Modal::new("some-id") Modal::new("some-id")
.title("Connect Copilot to Zed") .title("Connect Copilot to Zed")
.child(Label::new("You can update your settings or sign out from the Copilot menu in the status bar.").color(LabelColor::Muted)) .child(Label::new("You can update your settings or sign out from the Copilot menu in the status bar.").color(TextColor::Muted))
.primary_action(Button::new("Connect to Github").variant(ButtonVariant::Filled)), .primary_action(Button::new("Connect to Github").variant(ButtonVariant::Filled)),
) )
} }

View file

@ -5,7 +5,7 @@ use gpui::{Div, Render, View, VisualContext};
use crate::prelude::*; use crate::prelude::*;
use crate::{ use crate::{
hello_world_rust_editor_with_status_example, v_stack, Breadcrumb, Buffer, BufferSearch, Icon, hello_world_rust_editor_with_status_example, v_stack, Breadcrumb, Buffer, BufferSearch, Icon,
IconButton, IconColor, Symbol, Tab, TabBar, Toolbar, IconButton, Symbol, Tab, TabBar, TextColor, Toolbar,
}; };
#[derive(Clone)] #[derive(Clone)]
@ -63,7 +63,7 @@ impl Render for EditorPane {
IconButton::new("toggle_inlay_hints", Icon::InlayHint), IconButton::new("toggle_inlay_hints", Icon::InlayHint),
IconButton::<Self>::new("buffer_search", Icon::MagnifyingGlass) IconButton::<Self>::new("buffer_search", Icon::MagnifyingGlass)
.when(self.is_buffer_search_open, |this| { .when(self.is_buffer_search_open, |this| {
this.color(IconColor::Accent) this.color(TextColor::Accent)
}) })
.on_click(|editor, cx| { .on_click(|editor, cx| {
editor.toggle_buffer_search(cx); editor.toggle_buffer_search(cx);

View file

@ -1,8 +1,8 @@
use crate::utils::naive_format_distance_from_now; use crate::utils::naive_format_distance_from_now;
use crate::{ use crate::{
h_stack, prelude::*, static_new_notification_items_2, v_stack, Avatar, ButtonOrIconButton, h_stack, prelude::*, static_new_notification_items_2, v_stack, Avatar, ButtonOrIconButton,
Icon, IconElement, Label, LabelColor, LineHeightStyle, ListHeaderMeta, ListSeparator, Icon, IconElement, Label, LineHeightStyle, ListHeaderMeta, ListSeparator, PublicPlayer,
PublicPlayer, UnreadIndicator, TextColor, UnreadIndicator,
}; };
use crate::{ClickHandler, ListHeader}; use crate::{ClickHandler, ListHeader};
@ -48,7 +48,7 @@ impl NotificationsPanel {
.border_color(cx.theme().colors().border_variant) .border_color(cx.theme().colors().border_variant)
.child( .child(
Label::new("Search...") Label::new("Search...")
.color(LabelColor::Placeholder) .color(TextColor::Placeholder)
.line_height_style(LineHeightStyle::UILabel), .line_height_style(LineHeightStyle::UILabel),
), ),
) )
@ -252,7 +252,7 @@ impl<V> Notification<V> {
if let Some(icon) = icon { if let Some(icon) = icon {
meta_el = meta_el.child(IconElement::new(icon.clone())); meta_el = meta_el.child(IconElement::new(icon.clone()));
} }
meta_el.child(Label::new(text.clone()).color(LabelColor::Muted)) meta_el.child(Label::new(text.clone()).color(TextColor::Muted))
}) })
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
) )
@ -311,7 +311,7 @@ impl<V> Notification<V> {
true, true,
true, true,
)) ))
.color(LabelColor::Muted), .color(TextColor::Muted),
) )
.child(self.render_meta_items(cx)), .child(self.render_meta_items(cx)),
) )
@ -321,11 +321,11 @@ impl<V> Notification<V> {
// Show the taken_message // Show the taken_message
(Some(_), Some(action_taken)) => h_stack() (Some(_), Some(action_taken)) => h_stack()
.children(action_taken.taken_message.0.map(|icon| { .children(action_taken.taken_message.0.map(|icon| {
IconElement::new(icon).color(crate::IconColor::Muted) IconElement::new(icon).color(crate::TextColor::Muted)
})) }))
.child( .child(
Label::new(action_taken.taken_message.1.clone()) Label::new(action_taken.taken_message.1.clone())
.color(LabelColor::Muted), .color(TextColor::Muted),
), ),
// Show the actions // Show the actions
(Some(actions), None) => { (Some(actions), None) => {

View file

@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use crate::prelude::*; use crate::prelude::*;
use crate::{Button, Icon, IconButton, IconColor, ToolDivider, Workspace}; use crate::{Button, Icon, IconButton, TextColor, ToolDivider, Workspace};
#[derive(Default, PartialEq)] #[derive(Default, PartialEq)]
pub enum Tool { pub enum Tool {
@ -110,7 +110,7 @@ impl StatusBar {
.child( .child(
IconButton::<Workspace>::new("project_panel", Icon::FileTree) IconButton::<Workspace>::new("project_panel", Icon::FileTree)
.when(workspace.is_project_panel_open(), |this| { .when(workspace.is_project_panel_open(), |this| {
this.color(IconColor::Accent) this.color(TextColor::Accent)
}) })
.on_click(|workspace, cx| { .on_click(|workspace, cx| {
workspace.toggle_project_panel(cx); workspace.toggle_project_panel(cx);
@ -119,7 +119,7 @@ impl StatusBar {
.child( .child(
IconButton::<Workspace>::new("collab_panel", Icon::Hash) IconButton::<Workspace>::new("collab_panel", Icon::Hash)
.when(workspace.is_collab_panel_open(), |this| { .when(workspace.is_collab_panel_open(), |this| {
this.color(IconColor::Accent) this.color(TextColor::Accent)
}) })
.on_click(|workspace, cx| { .on_click(|workspace, cx| {
workspace.toggle_collab_panel(); workspace.toggle_collab_panel();
@ -174,7 +174,7 @@ impl StatusBar {
.child( .child(
IconButton::<Workspace>::new("terminal", Icon::Terminal) IconButton::<Workspace>::new("terminal", Icon::Terminal)
.when(workspace.is_terminal_open(), |this| { .when(workspace.is_terminal_open(), |this| {
this.color(IconColor::Accent) this.color(TextColor::Accent)
}) })
.on_click(|workspace, cx| { .on_click(|workspace, cx| {
workspace.toggle_terminal(cx); workspace.toggle_terminal(cx);
@ -183,7 +183,7 @@ impl StatusBar {
.child( .child(
IconButton::<Workspace>::new("chat_panel", Icon::MessageBubbles) IconButton::<Workspace>::new("chat_panel", Icon::MessageBubbles)
.when(workspace.is_chat_panel_open(), |this| { .when(workspace.is_chat_panel_open(), |this| {
this.color(IconColor::Accent) this.color(TextColor::Accent)
}) })
.on_click(|workspace, cx| { .on_click(|workspace, cx| {
workspace.toggle_chat_panel(cx); workspace.toggle_chat_panel(cx);
@ -192,7 +192,7 @@ impl StatusBar {
.child( .child(
IconButton::<Workspace>::new("assistant_panel", Icon::Ai) IconButton::<Workspace>::new("assistant_panel", Icon::Ai)
.when(workspace.is_assistant_panel_open(), |this| { .when(workspace.is_assistant_panel_open(), |this| {
this.color(IconColor::Accent) this.color(TextColor::Accent)
}) })
.on_click(|workspace, cx| { .on_click(|workspace, cx| {
workspace.toggle_assistant_panel(cx); workspace.toggle_assistant_panel(cx);

View file

@ -6,8 +6,8 @@ use gpui::{Div, Render, View, VisualContext};
use crate::prelude::*; use crate::prelude::*;
use crate::settings::user_settings; use crate::settings::user_settings;
use crate::{ use crate::{
Avatar, Button, Icon, IconButton, IconColor, MicStatus, PlayerStack, PlayerWithCallStatus, Avatar, Button, Icon, IconButton, MicStatus, PlayerStack, PlayerWithCallStatus,
ScreenShareStatus, ToolDivider, TrafficLights, ScreenShareStatus, TextColor, ToolDivider, TrafficLights,
}; };
#[derive(Clone)] #[derive(Clone)]
@ -152,19 +152,19 @@ impl Render for TitleBar {
.gap_1() .gap_1()
.child( .child(
IconButton::<TitleBar>::new("toggle_mic_status", Icon::Mic) IconButton::<TitleBar>::new("toggle_mic_status", Icon::Mic)
.when(self.is_mic_muted(), |this| this.color(IconColor::Error)) .when(self.is_mic_muted(), |this| this.color(TextColor::Error))
.on_click(|title_bar, cx| title_bar.toggle_mic_status(cx)), .on_click(|title_bar, cx| title_bar.toggle_mic_status(cx)),
) )
.child( .child(
IconButton::<TitleBar>::new("toggle_deafened", Icon::AudioOn) IconButton::<TitleBar>::new("toggle_deafened", Icon::AudioOn)
.when(self.is_deafened, |this| this.color(IconColor::Error)) .when(self.is_deafened, |this| this.color(TextColor::Error))
.on_click(|title_bar, cx| title_bar.toggle_deafened(cx)), .on_click(|title_bar, cx| title_bar.toggle_deafened(cx)),
) )
.child( .child(
IconButton::<TitleBar>::new("toggle_screen_share", Icon::Screen) IconButton::<TitleBar>::new("toggle_screen_share", Icon::Screen)
.when( .when(
self.screen_share_status == ScreenShareStatus::Shared, self.screen_share_status == ScreenShareStatus::Shared,
|this| this.color(IconColor::Accent), |this| this.color(TextColor::Accent),
) )
.on_click(|title_bar, cx| { .on_click(|title_bar, cx| {
title_bar.toggle_screen_share_status(cx) title_bar.toggle_screen_share_status(cx)

View file

@ -1,7 +1,7 @@
use crate::{status_bar::StatusItemView, Axis, Workspace}; use crate::{status_bar::StatusItemView, Axis, Workspace};
use gpui::{ use gpui::{
div, Action, AnyView, AppContext, Div, Entity, EntityId, EventEmitter, ParentElement, Render, div, Action, AnyView, AppContext, Div, Entity, EntityId, EventEmitter, FocusHandle,
Subscription, View, ViewContext, WeakView, WindowContext, ParentElement, Render, Styled, Subscription, View, ViewContext, WeakView, WindowContext,
}; };
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -34,6 +34,7 @@ pub trait Panel: Render + EventEmitter<PanelEvent> {
fn set_zoomed(&mut self, _zoomed: bool, _cx: &mut ViewContext<Self>) {} fn set_zoomed(&mut self, _zoomed: bool, _cx: &mut ViewContext<Self>) {}
fn set_active(&mut self, _active: bool, _cx: &mut ViewContext<Self>) {} fn set_active(&mut self, _active: bool, _cx: &mut ViewContext<Self>) {}
fn has_focus(&self, cx: &WindowContext) -> bool; fn has_focus(&self, cx: &WindowContext) -> bool;
fn focus_handle(&self, cx: &WindowContext) -> FocusHandle;
} }
pub trait PanelHandle: Send + Sync { pub trait PanelHandle: Send + Sync {
@ -51,6 +52,7 @@ pub trait PanelHandle: Send + Sync {
fn icon_tooltip(&self, cx: &WindowContext) -> (String, Option<Box<dyn Action>>); fn icon_tooltip(&self, cx: &WindowContext) -> (String, Option<Box<dyn Action>>);
fn icon_label(&self, cx: &WindowContext) -> Option<String>; fn icon_label(&self, cx: &WindowContext) -> Option<String>;
fn has_focus(&self, cx: &WindowContext) -> bool; fn has_focus(&self, cx: &WindowContext) -> bool;
fn focus_handle(&self, cx: &WindowContext) -> FocusHandle;
fn to_any(&self) -> AnyView; fn to_any(&self) -> AnyView;
} }
@ -117,6 +119,10 @@ where
fn to_any(&self) -> AnyView { fn to_any(&self) -> AnyView {
self.clone().into() self.clone().into()
} }
fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
self.read(cx).focus_handle(cx).clone()
}
} }
impl From<&dyn PanelHandle> for AnyView { impl From<&dyn PanelHandle> for AnyView {
@ -422,7 +428,11 @@ impl Render for Dock {
type Element = Div<Self>; type Element = Div<Self>;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
todo!() if let Some(entry) = self.visible_entry() {
div().size_full().child(entry.panel.to_any())
} else {
div()
}
} }
} }
@ -728,5 +738,9 @@ pub mod test {
fn has_focus(&self, _cx: &WindowContext) -> bool { fn has_focus(&self, _cx: &WindowContext) -> bool {
self.has_focus self.has_focus
} }
fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
unimplemented!()
}
} }
} }

View file

@ -27,7 +27,7 @@ use std::{
}, },
}; };
use ui::v_stack; use ui::v_stack;
use ui::{prelude::*, Icon, IconButton, IconColor, IconElement, TextTooltip}; use ui::{prelude::*, Icon, IconButton, IconElement, TextColor, TextTooltip};
use util::truncate_and_remove_front; use util::truncate_and_remove_front;
#[derive(PartialEq, Clone, Copy, Deserialize, Debug)] #[derive(PartialEq, Clone, Copy, Deserialize, Debug)]
@ -733,21 +733,21 @@ impl Pane {
// self.activate_item(index, activate_pane, activate_pane, cx); // self.activate_item(index, activate_pane, activate_pane, cx);
// } // }
// pub fn close_active_item( pub fn close_active_item(
// &mut self, &mut self,
// action: &CloseActiveItem, action: &CloseActiveItem,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// ) -> Option<Task<Result<()>>> { ) -> Option<Task<Result<()>>> {
// if self.items.is_empty() { if self.items.is_empty() {
// return None; return None;
// } }
// let active_item_id = self.items[self.active_item_index].id(); let active_item_id = self.items[self.active_item_index].id();
// Some(self.close_item_by_id( Some(self.close_item_by_id(
// active_item_id, active_item_id,
// action.save_intent.unwrap_or(SaveIntent::Close), action.save_intent.unwrap_or(SaveIntent::Close),
// cx, cx,
// )) ))
// } }
pub fn close_item_by_id( pub fn close_item_by_id(
&mut self, &mut self,
@ -1432,13 +1432,13 @@ impl Pane {
Some( Some(
IconElement::new(Icon::ExclamationTriangle) IconElement::new(Icon::ExclamationTriangle)
.size(ui::IconSize::Small) .size(ui::IconSize::Small)
.color(IconColor::Warning), .color(TextColor::Warning),
) )
} else if item.is_dirty(cx) { } else if item.is_dirty(cx) {
Some( Some(
IconElement::new(Icon::ExclamationTriangle) IconElement::new(Icon::ExclamationTriangle)
.size(ui::IconSize::Small) .size(ui::IconSize::Small)
.color(IconColor::Info), .color(TextColor::Info),
) )
} else { } else {
None None
@ -1919,7 +1919,12 @@ impl Render for Pane {
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element { fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element {
v_stack() v_stack()
.context("Pane")
.size_full() .size_full()
.on_action(|pane: &mut Self, action, cx| {
pane.close_active_item(action, cx)
.map(|task| task.detach_and_log_err(cx));
})
.child(self.render_tab_bar(cx)) .child(self.render_tab_bar(cx))
.child(div() /* todo!(toolbar) */) .child(div() /* todo!(toolbar) */)
.child(if let Some(item) = self.active_item() { .child(if let Some(item) = self.active_item() {

View file

@ -29,7 +29,7 @@ use client2::{
Client, TypedEnvelope, UserStore, Client, TypedEnvelope, UserStore,
}; };
use collections::{hash_map, HashMap, HashSet}; use collections::{hash_map, HashMap, HashSet};
use dock::{Dock, DockPosition, PanelButtons}; use dock::{Dock, DockPosition, Panel, PanelButtons, PanelHandle as _};
use futures::{ use futures::{
channel::{mpsc, oneshot}, channel::{mpsc, oneshot},
future::try_join_all, future::try_join_all,
@ -45,7 +45,7 @@ use gpui::{
}; };
use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, ProjectItem}; use item::{FollowableItem, FollowableItemHandle, Item, ItemHandle, ItemSettings, ProjectItem};
use itertools::Itertools; use itertools::Itertools;
use language2::LanguageRegistry; use language2::{LanguageRegistry, Rope};
use lazy_static::lazy_static; use lazy_static::lazy_static;
pub use modal_layer::*; pub use modal_layer::*;
use node_runtime::NodeRuntime; use node_runtime::NodeRuntime;
@ -69,10 +69,10 @@ use std::{
}; };
use theme2::ActiveTheme; use theme2::ActiveTheme;
pub use toolbar::{ToolbarItemLocation, ToolbarItemView}; pub use toolbar::{ToolbarItemLocation, ToolbarItemView};
use ui::{h_stack, Button, ButtonVariant, Label, LabelColor}; use ui::{h_stack, Button, ButtonVariant, KeyBinding, Label, TextColor, TextTooltip};
use util::ResultExt; use util::ResultExt;
use uuid::Uuid; use uuid::Uuid;
use workspace_settings::{AutosaveSetting, WorkspaceSettings}; pub use workspace_settings::{AutosaveSetting, WorkspaceSettings};
lazy_static! { lazy_static! {
static ref ZED_WINDOW_SIZE: Option<Size<GlobalPixels>> = env::var("ZED_WINDOW_SIZE") static ref ZED_WINDOW_SIZE: Option<Size<GlobalPixels>> = env::var("ZED_WINDOW_SIZE")
@ -248,102 +248,6 @@ pub fn init(app_state: Arc<AppState>, cx: &mut AppContext) {
// } // }
// } // }
// }); // });
// cx.add_async_action(Workspace::open);
// cx.add_async_action(Workspace::follow_next_collaborator);
// cx.add_async_action(Workspace::close);
// cx.add_async_action(Workspace::close_inactive_items_and_panes);
// cx.add_async_action(Workspace::close_all_items_and_panes);
// cx.add_global_action(Workspace::close_global);
// cx.add_global_action(restart);
// cx.add_async_action(Workspace::save_all);
// cx.add_action(Workspace::add_folder_to_project);
// cx.add_action(
// |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
// let pane = workspace.active_pane().clone();
// workspace.unfollow(&pane, cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace, action: &Save, cx: &mut ViewContext<Workspace>| {
// workspace
// .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), cx)
// .detach_and_log_err(cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
// workspace
// .save_active_item(SaveIntent::SaveAs, cx)
// .detach_and_log_err(cx);
// },
// );
// cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
// workspace.activate_previous_pane(cx)
// });
// cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
// workspace.activate_next_pane(cx)
// });
// cx.add_action(
// |workspace: &mut Workspace, action: &ActivatePaneInDirection, cx| {
// workspace.activate_pane_in_direction(action.0, cx)
// },
// );
// cx.add_action(
// |workspace: &mut Workspace, action: &SwapPaneInDirection, cx| {
// workspace.swap_pane_in_direction(action.0, cx)
// },
// );
// cx.add_action(|workspace: &mut Workspace, _: &ToggleLeftDock, cx| {
// workspace.toggle_dock(DockPosition::Left, cx);
// });
// cx.add_action(|workspace: &mut Workspace, _: &ToggleRightDock, cx| {
// workspace.toggle_dock(DockPosition::Right, cx);
// });
// cx.add_action(|workspace: &mut Workspace, _: &ToggleBottomDock, cx| {
// workspace.toggle_dock(DockPosition::Bottom, cx);
// });
// cx.add_action(|workspace: &mut Workspace, _: &CloseAllDocks, cx| {
// workspace.close_all_docks(cx);
// });
// cx.add_action(Workspace::activate_pane_at_index);
// cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
// workspace.reopen_closed_item(cx).detach();
// });
// cx.add_action(|workspace: &mut Workspace, _: &GoBack, cx| {
// workspace
// .go_back(workspace.active_pane().downgrade(), cx)
// .detach();
// });
// cx.add_action(|workspace: &mut Workspace, _: &GoForward, cx| {
// workspace
// .go_forward(workspace.active_pane().downgrade(), cx)
// .detach();
// });
// cx.add_action(|_: &mut Workspace, _: &install_cli::Install, cx| {
// cx.spawn(|workspace, mut cx| async move {
// let err = install_cli::install_cli(&cx)
// .await
// .context("Failed to create CLI symlink");
// workspace.update(&mut cx, |workspace, cx| {
// if matches!(err, Err(_)) {
// err.notify_err(workspace, cx);
// } else {
// workspace.show_notification(1, cx, |cx| {
// cx.build_view(|_| {
// MessageNotification::new("Successfully installed the `zed` binary")
// })
// });
// }
// })
// })
// .detach();
// });
} }
type ProjectItemBuilders = type ProjectItemBuilders =
@ -942,108 +846,15 @@ impl Workspace {
&self.right_dock &self.right_dock
} }
// pub fn add_panel<T: Panel>(&mut self, panel: View<T>, cx: &mut ViewContext<Self>) pub fn add_panel<T: Panel>(&mut self, panel: View<T>, cx: &mut ViewContext<Self>) {
// where let dock = match panel.position(cx) {
// T::Event: std::fmt::Debug, DockPosition::Left => &self.left_dock,
// { DockPosition::Bottom => &self.bottom_dock,
// self.add_panel_with_extra_event_handler(panel, cx, |_, _, _, _| {}) DockPosition::Right => &self.right_dock,
// } };
// pub fn add_panel_with_extra_event_handler<T: Panel, F>( dock.update(cx, |dock, cx| dock.add_panel(panel, cx));
// &mut self, }
// panel: View<T>,
// cx: &mut ViewContext<Self>,
// handler: F,
// ) where
// T::Event: std::fmt::Debug,
// F: Fn(&mut Self, &View<T>, &T::Event, &mut ViewContext<Self>) + 'static,
// {
// let dock = match panel.position(cx) {
// DockPosition::Left => &self.left_dock,
// DockPosition::Bottom => &self.bottom_dock,
// DockPosition::Right => &self.right_dock,
// };
// self.subscriptions.push(cx.subscribe(&panel, {
// let mut dock = dock.clone();
// let mut prev_position = panel.position(cx);
// move |this, panel, event, cx| {
// if T::should_change_position_on_event(event) {
// THIS HAS BEEN MOVED TO NORMAL EVENT EMISSION
// See: Dock::add_panel
//
// let new_position = panel.read(cx).position(cx);
// let mut was_visible = false;
// dock.update(cx, |dock, cx| {
// prev_position = new_position;
// was_visible = dock.is_open()
// && dock
// .visible_panel()
// .map_or(false, |active_panel| active_panel.id() == panel.id());
// dock.remove_panel(&panel, cx);
// });
// if panel.is_zoomed(cx) {
// this.zoomed_position = Some(new_position);
// }
// dock = match panel.read(cx).position(cx) {
// DockPosition::Left => &this.left_dock,
// DockPosition::Bottom => &this.bottom_dock,
// DockPosition::Right => &this.right_dock,
// }
// .clone();
// dock.update(cx, |dock, cx| {
// dock.add_panel(panel.clone(), cx);
// if was_visible {
// dock.set_open(true, cx);
// dock.activate_panel(dock.panels_len() - 1, cx);
// }
// });
// } else if T::should_zoom_in_on_event(event) {
// THIS HAS BEEN MOVED TO NORMAL EVENT EMISSION
// See: Dock::add_panel
//
// dock.update(cx, |dock, cx| dock.set_panel_zoomed(&panel, true, cx));
// if !panel.has_focus(cx) {
// cx.focus(&panel);
// }
// this.zoomed = Some(panel.downgrade().into_any());
// this.zoomed_position = Some(panel.read(cx).position(cx));
// } else if T::should_zoom_out_on_event(event) {
// THIS HAS BEEN MOVED TO NORMAL EVENT EMISSION
// See: Dock::add_panel
//
// dock.update(cx, |dock, cx| dock.set_panel_zoomed(&panel, false, cx));
// if this.zoomed_position == Some(prev_position) {
// this.zoomed = None;
// this.zoomed_position = None;
// }
// cx.notify();
// } else if T::is_focus_event(event) {
// THIS HAS BEEN MOVED TO NORMAL EVENT EMISSION
// See: Dock::add_panel
//
// let position = panel.read(cx).position(cx);
// this.dismiss_zoomed_items_to_reveal(Some(position), cx);
// if panel.is_zoomed(cx) {
// this.zoomed = Some(panel.downgrade().into_any());
// this.zoomed_position = Some(position);
// } else {
// this.zoomed = None;
// this.zoomed_position = None;
// }
// this.update_active_view_for_followers(cx);
// cx.notify();
// } else {
// handler(this, &panel, event, cx)
// }
// }
// }));
// dock.update(cx, |dock, cx| dock.add_panel(panel, cx));
// }
pub fn status_bar(&self) -> &View<StatusBar> { pub fn status_bar(&self) -> &View<StatusBar> {
&self.status_bar &self.status_bar
@ -1241,29 +1052,29 @@ impl Workspace {
// self.titlebar_item.clone() // self.titlebar_item.clone()
// } // }
// /// Call the given callback with a workspace whose project is local. /// Call the given callback with a workspace whose project is local.
// /// ///
// /// If the given workspace has a local project, then it will be passed /// If the given workspace has a local project, then it will be passed
// /// to the callback. Otherwise, a new empty window will be created. /// to the callback. Otherwise, a new empty window will be created.
// pub fn with_local_workspace<T, F>( pub fn with_local_workspace<T, F>(
// &mut self, &mut self,
// cx: &mut ViewContext<Self>, cx: &mut ViewContext<Self>,
// callback: F, callback: F,
// ) -> Task<Result<T>> ) -> Task<Result<T>>
// where where
// T: 'static, T: 'static,
// F: 'static + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T, F: 'static + FnOnce(&mut Workspace, &mut ViewContext<Workspace>) -> T,
// { {
// if self.project.read(cx).is_local() { if self.project.read(cx).is_local() {
// Task::Ready(Some(Ok(callback(self, cx)))) Task::Ready(Some(Ok(callback(self, cx))))
// } else { } else {
// let task = Self::new_local(Vec::new(), self.app_state.clone(), None, cx); let task = Self::new_local(Vec::new(), self.app_state.clone(), None, cx);
// cx.spawn(|_vh, mut cx| async move { cx.spawn(|_vh, mut cx| async move {
// let (workspace, _) = task.await; let (workspace, _) = task.await?;
// workspace.update(&mut cx, callback) workspace.update(&mut cx, callback)
// }) })
// } }
// } }
pub fn worktrees<'a>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Model<Worktree>> { pub fn worktrees<'a>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Model<Worktree>> {
self.project.read(cx).worktrees() self.project.read(cx).worktrees()
@ -1735,42 +1546,43 @@ impl Workspace {
// } // }
// } // }
// pub fn toggle_dock(&mut self, dock_side: DockPosition, cx: &mut ViewContext<Self>) { pub fn toggle_dock(&mut self, dock_side: DockPosition, cx: &mut ViewContext<Self>) {
// let dock = match dock_side { let dock = match dock_side {
// DockPosition::Left => &self.left_dock, DockPosition::Left => &self.left_dock,
// DockPosition::Bottom => &self.bottom_dock, DockPosition::Bottom => &self.bottom_dock,
// DockPosition::Right => &self.right_dock, DockPosition::Right => &self.right_dock,
// }; };
// let mut focus_center = false; let mut focus_center = false;
// let mut reveal_dock = false; let mut reveal_dock = false;
// dock.update(cx, |dock, cx| { dock.update(cx, |dock, cx| {
// let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side); let other_is_zoomed = self.zoomed.is_some() && self.zoomed_position != Some(dock_side);
// let was_visible = dock.is_open() && !other_is_zoomed; let was_visible = dock.is_open() && !other_is_zoomed;
// dock.set_open(!was_visible, cx); dock.set_open(!was_visible, cx);
// if let Some(active_panel) = dock.active_panel() { if let Some(active_panel) = dock.active_panel() {
// if was_visible { if was_visible {
// if active_panel.has_focus(cx) { if active_panel.has_focus(cx) {
// focus_center = true; focus_center = true;
// } }
// } else { } else {
// cx.focus(active_panel.as_any()); let focus_handle = &active_panel.focus_handle(cx);
// reveal_dock = true; cx.focus(focus_handle);
// } reveal_dock = true;
// } }
// }); }
});
// if reveal_dock { if reveal_dock {
// self.dismiss_zoomed_items_to_reveal(Some(dock_side), cx); self.dismiss_zoomed_items_to_reveal(Some(dock_side), cx);
// } }
// if focus_center { if focus_center {
// cx.focus_self(); cx.focus(&self.focus_handle);
// } }
// cx.notify(); cx.notify();
// self.serialize_workspace(cx); self.serialize_workspace(cx);
// } }
pub fn close_all_docks(&mut self, cx: &mut ViewContext<Self>) { pub fn close_all_docks(&mut self, cx: &mut ViewContext<Self>) {
let docks = [&self.left_dock, &self.bottom_dock, &self.right_dock]; let docks = [&self.left_dock, &self.bottom_dock, &self.right_dock];
@ -2659,18 +2471,51 @@ impl Workspace {
.child( .child(
h_stack() h_stack()
// TODO - Add player menu // TODO - Add player menu
.child(
div()
.id("project_owner_indicator")
.child( .child(
Button::new("player") Button::new("player")
.variant(ButtonVariant::Ghost) .variant(ButtonVariant::Ghost)
.color(Some(LabelColor::Player(0))), .color(Some(TextColor::Player(0))),
)
.tooltip(move |_, cx| {
cx.build_view(|cx| TextTooltip::new("Toggle following"))
}),
) )
// TODO - Add project menu // TODO - Add project menu
.child(
div()
.id("titlebar_project_menu_button")
.child(Button::new("project_name").variant(ButtonVariant::Ghost)) .child(Button::new("project_name").variant(ButtonVariant::Ghost))
.tooltip(move |_, cx| {
cx.build_view(|cx| TextTooltip::new("Recent Projects"))
}),
)
// TODO - Add git menu // TODO - Add git menu
.child(
div()
.id("titlebar_git_menu_button")
.child( .child(
Button::new("branch_name") Button::new("branch_name")
.variant(ButtonVariant::Ghost) .variant(ButtonVariant::Ghost)
.color(Some(LabelColor::Muted)), .color(Some(TextColor::Muted)),
)
.tooltip(move |_, cx| {
// todo!() Replace with real action.
#[gpui::action]
struct NoAction {}
cx.build_view(|cx| {
TextTooltip::new("Recent Branches")
.key_binding(KeyBinding::new(gpui::KeyBinding::new(
"cmd-b",
NoAction {},
None,
)))
.meta("Only local branches shown")
})
}),
), ),
) // self.titlebar_item ) // self.titlebar_item
.child(h_stack().child(Label::new("Right side titlebar item"))) .child(h_stack().child(Label::new("Right side titlebar item")))
@ -3467,6 +3312,107 @@ impl Workspace {
}) })
} }
fn actions(div: Div<Self>) -> Div<Self> {
div
// cx.add_async_action(Workspace::open);
// cx.add_async_action(Workspace::follow_next_collaborator);
// cx.add_async_action(Workspace::close);
// cx.add_async_action(Workspace::close_inactive_items_and_panes);
// cx.add_async_action(Workspace::close_all_items_and_panes);
// cx.add_global_action(Workspace::close_global);
// cx.add_global_action(restart);
// cx.add_async_action(Workspace::save_all);
// cx.add_action(Workspace::add_folder_to_project);
// cx.add_action(
// |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
// let pane = workspace.active_pane().clone();
// workspace.unfollow(&pane, cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace, action: &Save, cx: &mut ViewContext<Workspace>| {
// workspace
// .save_active_item(action.save_intent.unwrap_or(SaveIntent::Save), cx)
// .detach_and_log_err(cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace, _: &SaveAs, cx: &mut ViewContext<Workspace>| {
// workspace
// .save_active_item(SaveIntent::SaveAs, cx)
// .detach_and_log_err(cx);
// },
// );
// cx.add_action(|workspace: &mut Workspace, _: &ActivatePreviousPane, cx| {
// workspace.activate_previous_pane(cx)
// });
// cx.add_action(|workspace: &mut Workspace, _: &ActivateNextPane, cx| {
// workspace.activate_next_pane(cx)
// });
// cx.add_action(
// |workspace: &mut Workspace, action: &ActivatePaneInDirection, cx| {
// workspace.activate_pane_in_direction(action.0, cx)
// },
// );
// cx.add_action(
// |workspace: &mut Workspace, action: &SwapPaneInDirection, cx| {
// workspace.swap_pane_in_direction(action.0, cx)
// },
// );
.on_action(|this, e: &ToggleLeftDock, cx| {
println!("TOGGLING DOCK");
this.toggle_dock(DockPosition::Left, cx);
})
// cx.add_action(|workspace: &mut Workspace, _: &ToggleRightDock, cx| {
// workspace.toggle_dock(DockPosition::Right, cx);
// });
// cx.add_action(|workspace: &mut Workspace, _: &ToggleBottomDock, cx| {
// workspace.toggle_dock(DockPosition::Bottom, cx);
// });
// cx.add_action(|workspace: &mut Workspace, _: &CloseAllDocks, cx| {
// workspace.close_all_docks(cx);
// });
// cx.add_action(Workspace::activate_pane_at_index);
// cx.add_action(|workspace: &mut Workspace, _: &ReopenClosedItem, cx| {
// workspace.reopen_closed_item(cx).detach();
// });
// cx.add_action(|workspace: &mut Workspace, _: &GoBack, cx| {
// workspace
// .go_back(workspace.active_pane().downgrade(), cx)
// .detach();
// });
// cx.add_action(|workspace: &mut Workspace, _: &GoForward, cx| {
// workspace
// .go_forward(workspace.active_pane().downgrade(), cx)
// .detach();
// });
// cx.add_action(|_: &mut Workspace, _: &install_cli::Install, cx| {
// cx.spawn(|workspace, mut cx| async move {
// let err = install_cli::install_cli(&cx)
// .await
// .context("Failed to create CLI symlink");
// workspace.update(&mut cx, |workspace, cx| {
// if matches!(err, Err(_)) {
// err.notify_err(workspace, cx);
// } else {
// workspace.show_notification(1, cx, |cx| {
// cx.build_view(|_| {
// MessageNotification::new("Successfully installed the `zed` binary")
// })
// });
// }
// })
// })
// .detach();
// });
}
// todo!()
// #[cfg(any(test, feature = "test-support"))]
// pub fn test_new(project: ModelHandle<Project>, cx: &mut ViewContext<Self>) -> Self {
// use node_runtime::FakeNodeRuntime;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub fn test_new(project: Model<Project>, cx: &mut ViewContext<Self>) -> Self { pub fn test_new(project: Model<Project>, cx: &mut ViewContext<Self>) -> Self {
use gpui::Context; use gpui::Context;
@ -3522,13 +3468,14 @@ impl Workspace {
pub fn register_action<A: Action>( pub fn register_action<A: Action>(
&mut self, &mut self,
callback: impl Fn(&mut Self, &A, &mut ViewContext<Self>) + 'static, callback: impl Fn(&mut Self, &A, &mut ViewContext<Self>) + 'static,
) { ) -> &mut Self {
let callback = Arc::new(callback); let callback = Arc::new(callback);
self.workspace_actions.push(Box::new(move |div| { self.workspace_actions.push(Box::new(move |div| {
let callback = callback.clone(); let callback = callback.clone();
div.on_action(move |workspace, event, cx| (callback.clone())(workspace, event, cx)) div.on_action(move |workspace, event, cx| (callback.clone())(workspace, event, cx))
})); }));
self
} }
fn add_workspace_actions_listeners( fn add_workspace_actions_listeners(
@ -3795,28 +3742,19 @@ impl Render for Workspace {
.border_b() .border_b()
.border_color(cx.theme().colors().border) .border_color(cx.theme().colors().border)
.child(self.modal_layer.clone()) .child(self.modal_layer.clone())
// .children(
// Some(
// Panel::new("project-panel-outer", cx)
// .side(PanelSide::Left)
// .child(ProjectPanel::new("project-panel-inner")),
// )
// .filter(|_| self.is_project_panel_open()),
// )
// .children(
// Some(
// Panel::new("collab-panel-outer", cx)
// .child(CollabPanel::new("collab-panel-inner"))
// .side(PanelSide::Left),
// )
// .filter(|_| self.is_collab_panel_open()),
// )
// .child(NotificationToast::new(
// "maxbrunsfeld has requested to add you as a contact.".into(),
// ))
.child( .child(
div().flex().flex_col().flex_1().h_full().child( div()
div().flex().flex_1().child(self.center.render( .flex()
.flex_row()
.flex_1()
.h_full()
.child(div().flex().flex_1().child(self.left_dock.clone()))
.child(
div()
.flex()
.flex_col()
.flex_1()
.child(self.center.render(
&self.project, &self.project,
&self.follower_states, &self.follower_states,
self.active_call(), self.active_call(),
@ -3824,54 +3762,11 @@ impl Render for Workspace {
self.zoomed.as_ref(), self.zoomed.as_ref(),
&self.app_state, &self.app_state,
cx, cx,
)), ))
), // .children( .child(div().flex().flex_1().child(self.bottom_dock.clone())),
// Some( )
// Panel::new("terminal-panel", cx) .child(div().flex().flex_1().child(self.right_dock.clone())),
// .child(Terminal::new()) ),
// .allowed_sides(PanelAllowedSides::BottomOnly)
// .side(PanelSide::Bottom),
// )
// .filter(|_| self.is_terminal_open()),
// ),
), // .children(
// Some(
// Panel::new("chat-panel-outer", cx)
// .side(PanelSide::Right)
// .child(ChatPanel::new("chat-panel-inner").messages(vec![
// ChatMessage::new(
// "osiewicz".to_string(),
// "is this thing on?".to_string(),
// DateTime::parse_from_rfc3339("2023-09-27T15:40:52.707Z")
// .unwrap()
// .naive_local(),
// ),
// ChatMessage::new(
// "maxdeviant".to_string(),
// "Reading you loud and clear!".to_string(),
// DateTime::parse_from_rfc3339("2023-09-28T15:40:52.707Z")
// .unwrap()
// .naive_local(),
// ),
// ])),
// )
// .filter(|_| self.is_chat_panel_open()),
// )
// .children(
// Some(
// Panel::new("notifications-panel-outer", cx)
// .side(PanelSide::Right)
// .child(NotificationsPanel::new("notifications-panel-inner")),
// )
// .filter(|_| self.is_notifications_panel_open()),
// )
// .children(
// Some(
// Panel::new("assistant-panel-outer", cx)
// .child(AssistantPanel::new("assistant-panel-inner")),
// )
// .filter(|_| self.is_assistant_panel_open()),
// ),
) )
.child(self.status_bar.clone()) .child(self.status_bar.clone())
// .when(self.debug.show_toast, |this| { // .when(self.debug.show_toast, |this| {
@ -4526,32 +4421,32 @@ pub fn open_new(
}) })
} }
// pub fn create_and_open_local_file( pub fn create_and_open_local_file(
// path: &'static Path, path: &'static Path,
// cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Workspace>,
// default_content: impl 'static + Send + FnOnce() -> Rope, default_content: impl 'static + Send + FnOnce() -> Rope,
// ) -> Task<Result<Box<dyn ItemHandle>>> { ) -> Task<Result<Box<dyn ItemHandle>>> {
// cx.spawn(|workspace, mut cx| async move { cx.spawn(|workspace, mut cx| async move {
// let fs = workspace.read_with(&cx, |workspace, _| workspace.app_state().fs.clone())?; let fs = workspace.update(&mut cx, |workspace, _| workspace.app_state().fs.clone())?;
// if !fs.is_file(path).await { if !fs.is_file(path).await {
// fs.create_file(path, Default::default()).await?; fs.create_file(path, Default::default()).await?;
// fs.save(path, &default_content(), Default::default()) fs.save(path, &default_content(), Default::default())
// .await?; .await?;
// } }
// let mut items = workspace let mut items = workspace
// .update(&mut cx, |workspace, cx| { .update(&mut cx, |workspace, cx| {
// workspace.with_local_workspace(cx, |workspace, cx| { workspace.with_local_workspace(cx, |workspace, cx| {
// workspace.open_paths(vec![path.to_path_buf()], false, cx) workspace.open_paths(vec![path.to_path_buf()], false, cx)
// }) })
// })? })?
// .await? .await?
// .await; .await;
// let item = items.pop().flatten(); let item = items.pop().flatten();
// item.ok_or_else(|| anyhow!("path {path:?} is not a file"))? item.ok_or_else(|| anyhow!("path {path:?} is not a file"))?
// }) })
// } }
// pub fn join_remote_project( // pub fn join_remote_project(
// project_id: u64, // project_id: u64,

View file

@ -43,7 +43,7 @@ fsevent = { path = "../fsevent" }
fuzzy = { path = "../fuzzy" } fuzzy = { path = "../fuzzy" }
go_to_line = { package = "go_to_line2", path = "../go_to_line2" } go_to_line = { package = "go_to_line2", path = "../go_to_line2" }
gpui = { package = "gpui2", path = "../gpui2" } gpui = { package = "gpui2", path = "../gpui2" }
install_cli = { path = "../install_cli" } install_cli = { package = "install_cli2", path = "../install_cli2" }
journal = { package = "journal2", path = "../journal2" } journal = { package = "journal2", path = "../journal2" }
language = { package = "language2", path = "../language2" } language = { package = "language2", path = "../language2" }
# language_selector = { path = "../language_selector" } # language_selector = { path = "../language_selector" }
@ -55,7 +55,7 @@ node_runtime = { path = "../node_runtime" }
# outline = { path = "../outline" } # outline = { path = "../outline" }
# plugin_runtime = { path = "../plugin_runtime",optional = true } # plugin_runtime = { path = "../plugin_runtime",optional = true }
project = { package = "project2", path = "../project2" } project = { package = "project2", path = "../project2" }
# project_panel = { path = "../project_panel" } project_panel = { package = "project_panel2", path = "../project_panel2" }
# project_symbols = { path = "../project_symbols" } # project_symbols = { path = "../project_symbols" }
# quick_action_bar = { path = "../quick_action_bar" } # quick_action_bar = { path = "../quick_action_bar" }
# recent_projects = { path = "../recent_projects" } # recent_projects = { path = "../recent_projects" }

View file

@ -50,14 +50,16 @@ use util::{
use uuid::Uuid; use uuid::Uuid;
use workspace::{AppState, WorkspaceStore}; use workspace::{AppState, WorkspaceStore};
use zed2::{ use zed2::{
build_window_options, ensure_only_instance, handle_cli_connection, initialize_workspace, build_window_options, ensure_only_instance, handle_cli_connection, init_zed_actions,
languages, Assets, IsOnlyInstance, OpenListener, OpenRequest, initialize_workspace, languages, Assets, IsOnlyInstance, OpenListener, OpenRequest,
}; };
mod open_listener; mod open_listener;
fn main() { fn main() {
menu::init(); menu::init();
zed_actions::init();
let http = http::client(); let http = http::client();
init_paths(); init_paths();
init_logger(); init_logger();
@ -96,7 +98,7 @@ fn main() {
let (listener, mut open_rx) = OpenListener::new(); let (listener, mut open_rx) = OpenListener::new();
let listener = Arc::new(listener); let listener = Arc::new(listener);
let open_listener = listener.clone(); let open_listener = listener.clone();
app.on_open_urls(move |urls, _| open_listener.open_urls(urls)); app.on_open_urls(move |urls, _| open_listener.open_urls(&urls));
app.on_reopen(move |_cx| { app.on_reopen(move |_cx| {
// todo!("workspace") // todo!("workspace")
// if cx.has_global::<Weak<AppState>>() { // if cx.has_global::<Weak<AppState>>() {
@ -111,6 +113,8 @@ fn main() {
app.run(move |cx| { app.run(move |cx| {
cx.set_global(*RELEASE_CHANNEL); cx.set_global(*RELEASE_CHANNEL);
cx.set_global(listener.clone());
load_embedded_fonts(cx); load_embedded_fonts(cx);
let mut store = SettingsStore::default(); let mut store = SettingsStore::default();
@ -189,7 +193,7 @@ fn main() {
file_finder::init(cx); file_finder::init(cx);
// outline::init(cx); // outline::init(cx);
// project_symbols::init(cx); // project_symbols::init(cx);
// project_panel::init(Assets, cx); project_panel::init(Assets, cx);
// channel::init(&client, user_store.clone(), cx); // channel::init(&client, user_store.clone(), cx);
// diagnostics::init(cx); // diagnostics::init(cx);
// search::init(cx); // search::init(cx);
@ -209,12 +213,13 @@ fn main() {
// zed::init(&app_state, cx); // zed::init(&app_state, cx);
// cx.set_menus(menus::menus()); // cx.set_menus(menus::menus());
init_zed_actions(app_state.clone(), cx);
if stdout_is_a_pty() { if stdout_is_a_pty() {
cx.activate(true); cx.activate(true);
let urls = collect_url_args(); let urls = collect_url_args();
if !urls.is_empty() { if !urls.is_empty() {
listener.open_urls(urls) listener.open_urls(&urls)
} }
} else { } else {
upload_previous_panics(http.clone(), cx); upload_previous_panics(http.clone(), cx);
@ -224,7 +229,7 @@ fn main() {
if std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_some() if std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_some()
&& !listener.triggered.load(Ordering::Acquire) && !listener.triggered.load(Ordering::Acquire)
{ {
listener.open_urls(collect_url_args()) listener.open_urls(&collect_url_args())
} }
} }

View file

@ -54,7 +54,7 @@ impl OpenListener {
) )
} }
pub fn open_urls(&self, urls: Vec<String>) { pub fn open_urls(&self, urls: &[String]) {
self.triggered.store(true, Ordering::Release); self.triggered.store(true, Ordering::Release);
let request = if let Some(server_name) = let request = if let Some(server_name) =
urls.first().and_then(|url| url.strip_prefix("zed-cli://")) urls.first().and_then(|url| url.strip_prefix("zed-cli://"))
@ -101,7 +101,7 @@ impl OpenListener {
None None
} }
fn handle_file_urls(&self, urls: Vec<String>) -> Option<OpenRequest> { fn handle_file_urls(&self, urls: &[String]) -> Option<OpenRequest> {
let paths: Vec<_> = urls let paths: Vec<_> = urls
.iter() .iter()
.flat_map(|url| url.strip_prefix("file://")) .flat_map(|url| url.strip_prefix("file://"))

View file

@ -1,5 +1,5 @@
#![allow(unused_variables, dead_code, unused_mut)] #![allow(unused_variables, unused_mut)]
// todo!() this is to make transition easier. //todo!()
mod assets; mod assets;
pub mod languages; pub mod languages;
@ -7,17 +7,56 @@ mod only_instance;
mod open_listener; mod open_listener;
pub use assets::*; pub use assets::*;
use collections::VecDeque;
use editor::{Editor, MultiBuffer};
use gpui::{ use gpui::{
point, px, AppContext, AsyncWindowContext, Task, TitlebarOptions, WeakView, WindowBounds, actions, point, px, AppContext, AsyncWindowContext, Context, PromptLevel, Task,
WindowKind, WindowOptions, TitlebarOptions, ViewContext, VisualContext, WeakView, WindowBounds, WindowKind, WindowOptions,
}; };
pub use only_instance::*; pub use only_instance::*;
pub use open_listener::*; pub use open_listener::*;
use anyhow::Result; use anyhow::{anyhow, Context as _, Result};
use std::sync::Arc; use project_panel::ProjectPanel;
use settings::{initial_local_settings_content, Settings};
use std::{borrow::Cow, ops::Deref, sync::Arc};
use util::{
asset_str,
channel::ReleaseChannel,
paths::{self, LOCAL_SETTINGS_RELATIVE_PATH},
ResultExt,
};
use uuid::Uuid; use uuid::Uuid;
use workspace::{AppState, Workspace}; use workspace::{
create_and_open_local_file, dock::PanelHandle,
notifications::simple_message_notification::MessageNotification, open_new, AppState, NewFile,
NewWindow, Workspace, WorkspaceSettings,
};
use zed_actions::{OpenBrowser, OpenZedURL};
actions!(
About,
DebugElements,
DecreaseBufferFontSize,
Hide,
HideOthers,
IncreaseBufferFontSize,
Minimize,
OpenDefaultKeymap,
OpenDefaultSettings,
OpenKeymap,
OpenLicenses,
OpenLocalSettings,
OpenLog,
OpenSettings,
OpenTelemetryLog,
Quit,
ResetBufferFontSize,
ResetDatabase,
ShowAll,
ToggleFullScreen,
Zoom,
);
pub fn build_window_options( pub fn build_window_options(
bounds: Option<WindowBounds>, bounds: Option<WindowBounds>,
@ -47,6 +86,211 @@ pub fn build_window_options(
} }
} }
pub fn init_zed_actions(app_state: Arc<AppState>, cx: &mut AppContext) {
cx.observe_new_views(move |workspace: &mut Workspace, _cx| {
workspace
.register_action(about)
.register_action(|_, _: &Hide, cx| {
cx.hide();
})
.register_action(|_, _: &HideOthers, cx| {
cx.hide_other_apps();
})
.register_action(|_, _: &ShowAll, cx| {
cx.unhide_other_apps();
})
.register_action(|_, _: &Minimize, cx| {
cx.minimize_window();
})
.register_action(|_, _: &Zoom, cx| {
cx.zoom_window();
})
.register_action(|_, _: &ToggleFullScreen, cx| {
cx.toggle_full_screen();
})
.register_action(quit)
.register_action(|_, action: &OpenZedURL, cx| {
cx.global::<Arc<OpenListener>>()
.open_urls(&[action.url.clone()])
})
.register_action(|_, action: &OpenBrowser, cx| cx.open_url(&action.url))
//todo!(buffer font size)
// cx.add_global_action(move |_: &IncreaseBufferFontSize, cx| {
// theme::adjust_font_size(cx, |size| *size += 1.0)
// });
// cx.add_global_action(move |_: &DecreaseBufferFontSize, cx| {
// theme::adjust_font_size(cx, |size| *size -= 1.0)
// });
// cx.add_global_action(move |_: &ResetBufferFontSize, cx| theme::reset_font_size(cx));
.register_action(|_, _: &install_cli::Install, cx| {
cx.spawn(|_, cx| async move {
install_cli::install_cli(cx.deref())
.await
.context("error creating CLI symlink")
})
.detach_and_log_err(cx);
})
.register_action(|workspace, _: &OpenLog, cx| {
open_log_file(workspace, cx);
})
.register_action(|workspace, _: &OpenLicenses, cx| {
open_bundled_file(
workspace,
asset_str::<Assets>("licenses.md"),
"Open Source License Attribution",
"Markdown",
cx,
);
})
.register_action(
move |workspace: &mut Workspace,
_: &OpenTelemetryLog,
cx: &mut ViewContext<Workspace>| {
open_telemetry_log_file(workspace, cx);
},
)
.register_action(
move |_: &mut Workspace, _: &OpenKeymap, cx: &mut ViewContext<Workspace>| {
create_and_open_local_file(&paths::KEYMAP, cx, Default::default)
.detach_and_log_err(cx);
},
)
.register_action(
move |_: &mut Workspace, _: &OpenSettings, cx: &mut ViewContext<Workspace>| {
create_and_open_local_file(&paths::SETTINGS, cx, || {
settings::initial_user_settings_content().as_ref().into()
})
.detach_and_log_err(cx);
},
)
.register_action(open_local_settings_file)
.register_action(
move |workspace: &mut Workspace,
_: &OpenDefaultKeymap,
cx: &mut ViewContext<Workspace>| {
open_bundled_file(
workspace,
settings::default_keymap(),
"Default Key Bindings",
"JSON",
cx,
);
},
)
.register_action(
move |workspace: &mut Workspace,
_: &OpenDefaultSettings,
cx: &mut ViewContext<Workspace>| {
open_bundled_file(
workspace,
settings::default_settings(),
"Default Settings",
"JSON",
cx,
);
},
)
//todo!()
// cx.add_action({
// move |workspace: &mut Workspace, _: &DebugElements, cx: &mut ViewContext<Workspace>| {
// let app_state = workspace.app_state().clone();
// let markdown = app_state.languages.language_for_name("JSON");
// let window = cx.window();
// cx.spawn(|workspace, mut cx| async move {
// let markdown = markdown.await.log_err();
// let content = to_string_pretty(&window.debug_elements(&cx).ok_or_else(|| {
// anyhow!("could not debug elements for window {}", window.id())
// })?)
// .unwrap();
// workspace
// .update(&mut cx, |workspace, cx| {
// workspace.with_local_workspace(cx, move |workspace, cx| {
// let project = workspace.project().clone();
// let buffer = project
// .update(cx, |project, cx| {
// project.create_buffer(&content, markdown, cx)
// })
// .expect("creating buffers on a local workspace always succeeds");
// let buffer = cx.add_model(|cx| {
// MultiBuffer::singleton(buffer, cx)
// .with_title("Debug Elements".into())
// });
// workspace.add_item(
// Box::new(cx.add_view(|cx| {
// Editor::for_multibuffer(buffer, Some(project.clone()), cx)
// })),
// cx,
// );
// })
// })?
// .await
// })
// .detach_and_log_err(cx);
// }
// });
// .register_action(
// |workspace: &mut Workspace,
// _: &project_panel::ToggleFocus,
// cx: &mut ViewContext<Workspace>| {
// workspace.toggle_panel_focus::<ProjectPanel>(cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace,
// _: &collab_ui::collab_panel::ToggleFocus,
// cx: &mut ViewContext<Workspace>| {
// workspace.toggle_panel_focus::<collab_ui::collab_panel::CollabPanel>(cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace,
// _: &collab_ui::chat_panel::ToggleFocus,
// cx: &mut ViewContext<Workspace>| {
// workspace.toggle_panel_focus::<collab_ui::chat_panel::ChatPanel>(cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace,
// _: &collab_ui::notification_panel::ToggleFocus,
// cx: &mut ViewContext<Workspace>| {
// workspace.toggle_panel_focus::<collab_ui::notification_panel::NotificationPanel>(cx);
// },
// );
// cx.add_action(
// |workspace: &mut Workspace,
// _: &terminal_panel::ToggleFocus,
// cx: &mut ViewContext<Workspace>| {
// workspace.toggle_panel_focus::<TerminalPanel>(cx);
// },
// );
.register_action({
let app_state = Arc::downgrade(&app_state);
move |_, _: &NewWindow, cx| {
if let Some(app_state) = app_state.upgrade() {
open_new(&app_state, cx, |workspace, cx| {
Editor::new_file(workspace, &Default::default(), cx)
})
.detach();
}
}
})
.register_action({
let app_state = Arc::downgrade(&app_state);
move |_, _: &NewFile, cx| {
if let Some(app_state) = app_state.upgrade() {
open_new(&app_state, cx, |workspace, cx| {
Editor::new_file(workspace, &Default::default(), cx)
})
.detach();
}
}
});
//todo!()
// load_default_keymap(cx);
})
.detach();
}
pub fn initialize_workspace( pub fn initialize_workspace(
workspace_handle: WeakView<Workspace>, workspace_handle: WeakView<Workspace>,
was_deserialized: bool, was_deserialized: bool,
@ -138,9 +382,9 @@ pub fn initialize_workspace(
// } // }
// false // false
// }); // });
// })?; })?;
// let project_panel = ProjectPanel::load(workspace_handle.clone(), cx.clone()); let project_panel = ProjectPanel::load(workspace_handle.clone(), cx.clone());
// let terminal_panel = TerminalPanel::load(workspace_handle.clone(), cx.clone()); // let terminal_panel = TerminalPanel::load(workspace_handle.clone(), cx.clone());
// let assistant_panel = AssistantPanel::load(workspace_handle.clone(), cx.clone()); // let assistant_panel = AssistantPanel::load(workspace_handle.clone(), cx.clone());
// let channels_panel = // let channels_panel =
@ -151,36 +395,25 @@ pub fn initialize_workspace(
// workspace_handle.clone(), // workspace_handle.clone(),
// cx.clone(), // cx.clone(),
// ); // );
// let ( let (
// project_panel, project_panel,
// terminal_panel, // terminal_panel,
// assistant_panel, // assistant_panel,
// channels_panel, // channels_panel,
// chat_panel, // chat_panel,
// notification_panel, // notification_panel,
// ) = futures::try_join!( ) = futures::try_join!(
// project_panel, project_panel,
// terminal_panel, // terminal_panel,
// assistant_panel, // assistant_panel,
// channels_panel, // channels_panel,
// chat_panel, // chat_panel,
// notification_panel, // notification_panel,
// )?; )?;
// workspace_handle.update(&mut cx, |workspace, cx| {
// let project_panel_position = project_panel.position(cx); workspace_handle.update(&mut cx, |workspace, cx| {
// workspace.add_panel_with_extra_event_handler( let project_panel_position = project_panel.position(cx);
// project_panel, workspace.add_panel(project_panel, cx);
// cx,
// |workspace, _, event, cx| match event {
// project_panel::Event::NewSearchInDirectory { dir_entry } => {
// search::ProjectSearchView::new_search_in_directory(workspace, dir_entry, cx)
// }
// project_panel::Event::ActivatePanel => {
// workspace.focus_panel::<ProjectPanel>(cx);
// }
// _ => {}
// },
// );
// workspace.add_panel(terminal_panel, cx); // workspace.add_panel(terminal_panel, cx);
// workspace.add_panel(assistant_panel, cx); // workspace.add_panel(assistant_panel, cx);
// workspace.add_panel(channels_panel, cx); // workspace.add_panel(channels_panel, cx);
@ -198,10 +431,287 @@ pub fn initialize_workspace(
// .map_or(false, |entry| entry.is_dir()) // .map_or(false, |entry| entry.is_dir())
// }) // })
// { // {
// workspace.toggle_dock(project_panel_position, cx); workspace.toggle_dock(project_panel_position, cx);
// } // }
// cx.focus_self(); // cx.focus_self();
})?; })?;
Ok(()) Ok(())
}) })
} }
fn about(_: &mut Workspace, _: &About, cx: &mut gpui::ViewContext<Workspace>) {
let app_name = cx.global::<ReleaseChannel>().display_name();
let version = env!("CARGO_PKG_VERSION");
let prompt = cx.prompt(PromptLevel::Info, &format!("{app_name} {version}"), &["OK"]);
cx.foreground_executor()
.spawn(async {
prompt.await.ok();
})
.detach();
}
fn quit(_: &mut Workspace, _: &Quit, cx: &mut gpui::ViewContext<Workspace>) {
let should_confirm = WorkspaceSettings::get_global(cx).confirm_quit;
cx.spawn(|_, mut cx| async move {
let mut workspace_windows = cx.update(|_, cx| {
cx.windows()
.into_iter()
.filter_map(|window| window.downcast::<Workspace>())
.collect::<Vec<_>>()
})?;
// If multiple windows have unsaved changes, and need a save prompt,
// prompt in the active window before switching to a different window.
cx.update(|_, cx| {
workspace_windows.sort_by_key(|window| window.is_active(&cx) == Some(false));
})
.log_err();
if let (true, Some(window)) = (should_confirm, workspace_windows.first().copied()) {
let answer = cx
.update(|_, cx| {
cx.prompt(
PromptLevel::Info,
"Are you sure you want to quit?",
&["Quit", "Cancel"],
)
})
.log_err();
if let Some(mut answer) = answer {
let answer = answer.await.ok();
if answer != Some(0) {
return Ok(());
}
}
}
// If the user cancels any save prompt, then keep the app open.
for window in workspace_windows {
if let Some(should_close) = window
.update(&mut cx, |workspace, cx| {
workspace.prepare_to_close(true, cx)
})
.log_err()
{
if !should_close.await? {
return Ok(());
}
}
}
cx.update(|_, cx| {
cx.quit();
})?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
}
fn open_log_file(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
const MAX_LINES: usize = 1000;
workspace
.with_local_workspace(cx, move |workspace, cx| {
let fs = workspace.app_state().fs.clone();
cx.spawn(|workspace, mut cx| async move {
let (old_log, new_log) =
futures::join!(fs.load(&paths::OLD_LOG), fs.load(&paths::LOG));
let mut lines = VecDeque::with_capacity(MAX_LINES);
for line in old_log
.iter()
.flat_map(|log| log.lines())
.chain(new_log.iter().flat_map(|log| log.lines()))
{
if lines.len() == MAX_LINES {
lines.pop_front();
}
lines.push_back(line);
}
let log = lines
.into_iter()
.flat_map(|line| [line, "\n"])
.collect::<String>();
workspace
.update(&mut cx, |workspace, cx| {
let project = workspace.project().clone();
let buffer = project
.update(cx, |project, cx| project.create_buffer("", None, cx))
.expect("creating buffers on a local workspace always succeeds");
buffer.update(cx, |buffer, cx| buffer.edit([(0..0, log)], None, cx));
let buffer = cx.build_model(|cx| {
MultiBuffer::singleton(buffer, cx).with_title("Log".into())
});
workspace.add_item(
Box::new(cx.build_view(|cx| {
Editor::for_multibuffer(buffer, Some(project), cx)
})),
cx,
);
})
.log_err();
})
.detach();
})
.detach();
}
fn open_local_settings_file(
workspace: &mut Workspace,
_: &OpenLocalSettings,
cx: &mut ViewContext<Workspace>,
) {
let project = workspace.project().clone();
let worktree = project
.read(cx)
.visible_worktrees(cx)
.find_map(|tree| tree.read(cx).root_entry()?.is_dir().then_some(tree));
if let Some(worktree) = worktree {
let tree_id = worktree.read(cx).id();
cx.spawn(|workspace, mut cx| async move {
let file_path = &*LOCAL_SETTINGS_RELATIVE_PATH;
if let Some(dir_path) = file_path.parent() {
if worktree.update(&mut cx, |tree, _| tree.entry_for_path(dir_path).is_none())? {
project
.update(&mut cx, |project, cx| {
project.create_entry((tree_id, dir_path), true, cx)
})?
.ok_or_else(|| anyhow!("worktree was removed"))?
.await?;
}
}
if worktree.update(&mut cx, |tree, _| tree.entry_for_path(file_path).is_none())? {
project
.update(&mut cx, |project, cx| {
project.create_entry((tree_id, file_path), false, cx)
})?
.ok_or_else(|| anyhow!("worktree was removed"))?
.await?;
}
let editor = workspace
.update(&mut cx, |workspace, cx| {
workspace.open_path((tree_id, file_path), None, true, cx)
})?
.await?
.downcast::<Editor>()
.ok_or_else(|| anyhow!("unexpected item type"))?;
editor
.downgrade()
.update(&mut cx, |editor, cx| {
if let Some(buffer) = editor.buffer().read(cx).as_singleton() {
if buffer.read(cx).is_empty() {
buffer.update(cx, |buffer, cx| {
buffer.edit([(0..0, initial_local_settings_content())], None, cx)
});
}
}
})
.ok();
anyhow::Ok(())
})
.detach();
} else {
workspace.show_notification(0, cx, |cx| {
cx.build_view(|_| MessageNotification::new("This project has no folders open."))
})
}
}
fn open_telemetry_log_file(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
workspace.with_local_workspace(cx, move |workspace, cx| {
let app_state = workspace.app_state().clone();
cx.spawn(|workspace, mut cx| async move {
async fn fetch_log_string(app_state: &Arc<AppState>) -> Option<String> {
let path = app_state.client.telemetry().log_file_path()?;
app_state.fs.load(&path).await.log_err()
}
let log = fetch_log_string(&app_state).await.unwrap_or_else(|| "// No data has been collected yet".to_string());
const MAX_TELEMETRY_LOG_LEN: usize = 5 * 1024 * 1024;
let mut start_offset = log.len().saturating_sub(MAX_TELEMETRY_LOG_LEN);
if let Some(newline_offset) = log[start_offset..].find('\n') {
start_offset += newline_offset + 1;
}
let log_suffix = &log[start_offset..];
let json = app_state.languages.language_for_name("JSON").await.log_err();
workspace.update(&mut cx, |workspace, cx| {
let project = workspace.project().clone();
let buffer = project
.update(cx, |project, cx| project.create_buffer("", None, cx))
.expect("creating buffers on a local workspace always succeeds");
buffer.update(cx, |buffer, cx| {
buffer.set_language(json, cx);
buffer.edit(
[(
0..0,
concat!(
"// Zed collects anonymous usage data to help us understand how people are using the app.\n",
"// Telemetry can be disabled via the `settings.json` file.\n",
"// Here is the data that has been reported for the current session:\n",
"\n"
),
)],
None,
cx,
);
buffer.edit([(buffer.len()..buffer.len(), log_suffix)], None, cx);
});
let buffer = cx.build_model(|cx| {
MultiBuffer::singleton(buffer, cx).with_title("Telemetry Log".into())
});
workspace.add_item(
Box::new(cx.build_view(|cx| Editor::for_multibuffer(buffer, Some(project), cx))),
cx,
);
}).log_err()?;
Some(())
})
.detach();
}).detach();
}
fn open_bundled_file(
workspace: &mut Workspace,
text: Cow<'static, str>,
title: &'static str,
language: &'static str,
cx: &mut ViewContext<Workspace>,
) {
let language = workspace.app_state().languages.language_for_name(language);
cx.spawn(|workspace, mut cx| async move {
let language = language.await.log_err();
workspace
.update(&mut cx, |workspace, cx| {
workspace.with_local_workspace(cx, |workspace, cx| {
let project = workspace.project();
let buffer = project.update(cx, move |project, cx| {
project
.create_buffer(text.as_ref(), language, cx)
.expect("creating buffers on a local workspace always succeeds")
});
let buffer = cx.build_model(|cx| {
MultiBuffer::singleton(buffer, cx).with_title(title.into())
});
workspace.add_item(
Box::new(cx.build_view(|cx| {
Editor::for_multibuffer(buffer, Some(project.clone()), cx)
})),
cx,
);
})
})?
.await
})
.detach_and_log_err(cx);
}

View file

@ -1,33 +1,19 @@
use gpui::{action, actions}; use gpui::action;
actions!( // If the zed binary doesn't use anything in this crate, it will be optimized away
About, // and the actions won't initialize. So we just provide an empty initialization function
DebugElements, // to be called from main.
DecreaseBufferFontSize, //
Hide, // These may provide relevant context:
HideOthers, // https://github.com/rust-lang/rust/issues/47384
IncreaseBufferFontSize, // https://github.com/mmastrac/rust-ctor/issues/280
Minimize, pub fn init() {}
OpenDefaultKeymap,
OpenDefaultSettings,
OpenKeymap,
OpenLicenses,
OpenLocalSettings,
OpenLog,
OpenSettings,
OpenTelemetryLog,
Quit,
ResetBufferFontSize,
ResetDatabase,
ShowAll,
ToggleFullScreen,
Zoom,
);
#[action] #[action]
pub struct OpenBrowser { pub struct OpenBrowser {
pub url: String, pub url: String,
} }
#[action] #[action]
pub struct OpenZedURL { pub struct OpenZedURL {
pub url: String, pub url: String,