Merge branch 'main' into Z-1292/show_search_results_in_scrollbar

This commit is contained in:
Piotr Osiewicz
2023-07-06 11:43:44 +02:00
700 changed files with 30718 additions and 10511 deletions
@@ -207,16 +207,11 @@ impl ActivityIndicator {
let mut checking_for_update = SmallVec::<[_; 3]>::new();
let mut failed = SmallVec::<[_; 3]>::new();
for status in &self.statuses {
let name = status.name.clone();
match status.status {
LanguageServerBinaryStatus::CheckingForUpdate => {
checking_for_update.push(status.name.clone());
}
LanguageServerBinaryStatus::Downloading => {
downloading.push(status.name.clone());
}
LanguageServerBinaryStatus::Failed { .. } => {
failed.push(status.name.clone());
}
LanguageServerBinaryStatus::CheckingForUpdate => checking_for_update.push(name),
LanguageServerBinaryStatus::Downloading => downloading.push(name),
LanguageServerBinaryStatus::Failed { .. } => failed.push(name),
LanguageServerBinaryStatus::Downloaded | LanguageServerBinaryStatus::Cached => {}
}
}
@@ -326,7 +321,7 @@ impl View for ActivityIndicator {
let mut element = MouseEventHandler::<Self, _>::new(0, cx, |state, cx| {
let theme = &theme::current(cx).workspace.status_bar.lsp_status;
let style = if state.hovered() && on_click.is_some() {
theme.hover.as_ref().unwrap_or(&theme.default)
theme.hovered.as_ref().unwrap_or(&theme.default)
} else {
&theme.default
};
+4 -1
View File
@@ -22,13 +22,16 @@ util = { path = "../util" }
workspace = { path = "../workspace" }
anyhow.workspace = true
chrono = "0.4"
chrono = { version = "0.4", features = ["serde"] }
futures.workspace = true
isahc.workspace = true
regex.workspace = true
schemars.workspace = true
serde.workspace = true
serde_json.workspace = true
smol.workspace = true
tiktoken-rs = "0.4"
[dev-dependencies]
editor = { path = "../editor", features = ["test-support"] }
project = { path = "../project", features = ["test-support"] }
+92 -2
View File
@@ -1,19 +1,109 @@
pub mod assistant;
mod assistant_settings;
use anyhow::Result;
pub use assistant::AssistantPanel;
use chrono::{DateTime, Local};
use collections::HashMap;
use fs::Fs;
use futures::StreamExt;
use gpui::AppContext;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display};
use std::{
cmp::Reverse,
fmt::{self, Display},
path::PathBuf,
sync::Arc,
};
use util::paths::CONVERSATIONS_DIR;
// Data types for chat completion requests
#[derive(Serialize)]
#[derive(Debug, Serialize)]
struct OpenAIRequest {
model: String,
messages: Vec<RequestMessage>,
stream: bool,
}
#[derive(
Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
struct MessageId(usize);
#[derive(Clone, Debug, Serialize, Deserialize)]
struct MessageMetadata {
role: Role,
sent_at: DateTime<Local>,
status: MessageStatus,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
enum MessageStatus {
Pending,
Done,
Error(Arc<str>),
}
#[derive(Serialize, Deserialize)]
struct SavedMessage {
id: MessageId,
start: usize,
}
#[derive(Serialize, Deserialize)]
struct SavedConversation {
zed: String,
version: String,
text: String,
messages: Vec<SavedMessage>,
message_metadata: HashMap<MessageId, MessageMetadata>,
summary: String,
model: String,
}
impl SavedConversation {
const VERSION: &'static str = "0.1.0";
}
struct SavedConversationMetadata {
title: String,
path: PathBuf,
mtime: chrono::DateTime<chrono::Local>,
}
impl SavedConversationMetadata {
pub async fn list(fs: Arc<dyn Fs>) -> Result<Vec<Self>> {
fs.create_dir(&CONVERSATIONS_DIR).await?;
let mut paths = fs.read_dir(&CONVERSATIONS_DIR).await?;
let mut conversations = Vec::<SavedConversationMetadata>::new();
while let Some(path) = paths.next().await {
let path = path?;
let pattern = r" - \d+.zed.json$";
let re = Regex::new(pattern).unwrap();
let metadata = fs.metadata(&path).await?;
if let Some((file_name, metadata)) = path
.file_name()
.and_then(|name| name.to_str())
.zip(metadata)
{
let title = re.replace(file_name, "");
conversations.push(Self {
title: title.into_owned(),
path,
mtime: metadata.mtime.into(),
});
}
}
conversations.sort_unstable_by_key(|conversation| Reverse(conversation.mtime));
Ok(conversations)
}
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
struct RequestMessage {
role: Role,
+1540 -464
View File
File diff suppressed because it is too large Load Diff
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "audio"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/audio.rs"
doctest = false
[dependencies]
gpui = { path = "../gpui" }
collections = { path = "../collections" }
util = { path = "../util" }
rodio = "0.17.1"
log.workspace = true
anyhow.workspace = true
parking_lot.workspace = true
[dev-dependencies]
+44
View File
@@ -0,0 +1,44 @@
use std::{io::Cursor, sync::Arc};
use anyhow::Result;
use collections::HashMap;
use gpui::{AppContext, AssetSource};
use rodio::{
source::{Buffered, SamplesConverter},
Decoder, Source,
};
type Sound = Buffered<SamplesConverter<Decoder<Cursor<Vec<u8>>>, f32>>;
pub struct SoundRegistry {
cache: Arc<parking_lot::Mutex<HashMap<String, Sound>>>,
assets: Box<dyn AssetSource>,
}
impl SoundRegistry {
pub fn new(source: impl AssetSource) -> Arc<Self> {
Arc::new(Self {
cache: Default::default(),
assets: Box::new(source),
})
}
pub fn global(cx: &AppContext) -> Arc<Self> {
cx.global::<Arc<Self>>().clone()
}
pub fn get(&self, name: &str) -> Result<impl Source<Item = f32>> {
if let Some(wav) = self.cache.lock().get(name) {
return Ok(wav.clone());
}
let path = format!("sounds/{}.wav", name);
let bytes = self.assets.load(&path)?.into_owned();
let cursor = Cursor::new(bytes);
let source = Decoder::new(cursor)?.convert_samples::<f32>().buffered();
self.cache.lock().insert(name.to_string(), source.clone());
Ok(source)
}
}
+67
View File
@@ -0,0 +1,67 @@
use assets::SoundRegistry;
use gpui::{AppContext, AssetSource};
use rodio::{OutputStream, OutputStreamHandle};
use util::ResultExt;
mod assets;
pub fn init(source: impl AssetSource, cx: &mut AppContext) {
cx.set_global(SoundRegistry::new(source));
cx.set_global(Audio::new());
}
pub enum Sound {
Joined,
Leave,
Mute,
Unmute,
StartScreenshare,
StopScreenshare,
}
impl Sound {
fn file(&self) -> &'static str {
match self {
Self::Joined => "joined_call",
Self::Leave => "leave_call",
Self::Mute => "mute",
Self::Unmute => "unmute",
Self::StartScreenshare => "start_screenshare",
Self::StopScreenshare => "stop_screenshare",
}
}
}
pub struct Audio {
_output_stream: Option<OutputStream>,
output_handle: Option<OutputStreamHandle>,
}
impl Audio {
pub fn new() -> Self {
let (_output_stream, output_handle) = OutputStream::try_default().log_err().unzip();
Self {
_output_stream,
output_handle,
}
}
pub fn play_sound(sound: Sound, cx: &AppContext) {
if !cx.has_global::<Self>() {
return;
}
let this = cx.global::<Self>();
let Some(output_handle) = this.output_handle.as_ref() else {
return;
};
let Some(source) = SoundRegistry::global(cx).get(sound.file()).log_err() else {
return;
};
output_handle.play_raw(source).log_err();
}
}
@@ -49,7 +49,7 @@ impl View for UpdateNotification {
)
.with_child(
MouseEventHandler::<Cancel, _>::new(0, cx, |state, _| {
let style = theme.dismiss_button.style_for(state, false);
let style = theme.dismiss_button.style_for(state);
Svg::new("icons/x_mark_8.svg")
.with_color(style.color)
.constrained()
@@ -74,7 +74,7 @@ impl View for UpdateNotification {
),
)
.with_child({
let style = theme.action_message.style_for(state, false);
let style = theme.action_message.style_for(state);
Text::new("View the release notes", style.text.clone())
.contained()
.with_style(style.container)
+1 -1
View File
@@ -83,7 +83,7 @@ impl View for Breadcrumbs {
}
MouseEventHandler::<Breadcrumbs, Breadcrumbs>::new(0, cx, |state, _| {
let style = style.style_for(state, false);
let style = style.style_for(state);
crumbs.with_style(style.container)
})
.on_click(MouseButton::Left, |_, this, cx| {
+1
View File
@@ -19,6 +19,7 @@ test-support = [
]
[dependencies]
audio = { path = "../audio" }
client = { path = "../client" }
collections = { path = "../collections" }
gpui = { path = "../gpui" }
+5 -1
View File
@@ -3,6 +3,7 @@ use client::{proto, User};
use collections::HashMap;
use gpui::WeakModelHandle;
pub use live_kit_client::Frame;
use live_kit_client::RemoteAudioTrack;
use project::Project;
use std::{fmt, sync::Arc};
@@ -42,7 +43,10 @@ pub struct RemoteParticipant {
pub peer_id: proto::PeerId,
pub projects: Vec<proto::ParticipantProject>,
pub location: ParticipantLocation,
pub tracks: HashMap<live_kit_client::Sid, Arc<RemoteVideoTrack>>,
pub muted: bool,
pub speaking: bool,
pub video_tracks: HashMap<live_kit_client::Sid, Arc<RemoteVideoTrack>>,
pub audio_tracks: HashMap<live_kit_client::Sid, Arc<RemoteAudioTrack>>,
}
#[derive(Clone)]
+397 -31
View File
@@ -3,6 +3,7 @@ use crate::{
IncomingCall,
};
use anyhow::{anyhow, Result};
use audio::{Audio, Sound};
use client::{
proto::{self, PeerId},
Client, TypedEnvelope, User, UserStore,
@@ -12,7 +13,10 @@ use fs::Fs;
use futures::{FutureExt, StreamExt};
use gpui::{AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task, WeakModelHandle};
use language::LanguageRegistry;
use live_kit_client::{LocalTrackPublication, LocalVideoTrack, RemoteVideoTrackUpdate};
use live_kit_client::{
LocalAudioTrack, LocalTrackPublication, LocalVideoTrack, RemoteAudioTrackUpdate,
RemoteVideoTrackUpdate,
};
use postage::stream::Stream;
use project::Project;
use std::{future::Future, mem, pin::Pin, sync::Arc, time::Duration};
@@ -28,6 +32,9 @@ pub enum Event {
RemoteVideoTracksChanged {
participant_id: proto::PeerId,
},
RemoteAudioTracksChanged {
participant_id: proto::PeerId,
},
RemoteProjectShared {
owner: Arc<User>,
project_id: u64,
@@ -112,9 +119,9 @@ impl Room {
}
});
let mut track_changes = room.remote_video_track_updates();
let _maintain_tracks = cx.spawn_weak(|this, mut cx| async move {
while let Some(track_change) = track_changes.next().await {
let mut track_video_changes = room.remote_video_track_updates();
let _maintain_video_tracks = cx.spawn_weak(|this, mut cx| async move {
while let Some(track_change) = track_video_changes.next().await {
let this = if let Some(this) = this.upgrade(&cx) {
this
} else {
@@ -127,16 +134,42 @@ impl Room {
}
});
cx.foreground()
.spawn(room.connect(&connection_info.server_url, &connection_info.token))
.detach_and_log_err(cx);
let mut track_audio_changes = room.remote_audio_track_updates();
let _maintain_audio_tracks = cx.spawn_weak(|this, mut cx| async move {
while let Some(track_change) = track_audio_changes.next().await {
let this = if let Some(this) = this.upgrade(&cx) {
this
} else {
break;
};
this.update(&mut cx, |this, cx| {
this.remote_audio_track_updated(track_change, cx).log_err()
});
}
});
let connect = room.connect(&connection_info.server_url, &connection_info.token);
cx.spawn(|this, mut cx| async move {
connect.await?;
this.update(&mut cx, |this, cx| this.share_microphone(cx))
.await?;
anyhow::Ok(())
})
.detach_and_log_err(cx);
Some(LiveKitRoom {
room,
screen_track: ScreenTrack::None,
screen_track: LocalTrack::None,
microphone_track: LocalTrack::None,
next_publish_id: 0,
muted_by_user: false,
deafened: false,
speaking: false,
_maintain_room,
_maintain_tracks,
_maintain_tracks: [_maintain_video_tracks, _maintain_audio_tracks],
})
} else {
None
@@ -145,6 +178,8 @@ impl Room {
let maintain_connection =
cx.spawn_weak(|this, cx| Self::maintain_connection(this, client.clone(), cx).log_err());
Audio::play_sound(Sound::Joined, cx);
Self {
id,
live_kit: live_kit_room,
@@ -234,6 +269,7 @@ impl Room {
room.apply_room_update(room_proto, cx)?;
anyhow::Ok(())
})?;
Ok(room)
})
}
@@ -275,6 +311,8 @@ impl Room {
}
}
Audio::play_sound(Sound::Leave, cx);
self.status = RoomStatus::Offline;
self.remote_participants.clear();
self.pending_participants.clear();
@@ -618,20 +656,34 @@ impl Room {
peer_id,
projects: participant.projects,
location,
tracks: Default::default(),
muted: false,
speaking: false,
video_tracks: Default::default(),
audio_tracks: Default::default(),
},
);
Audio::play_sound(Sound::Joined, cx);
if let Some(live_kit) = this.live_kit.as_ref() {
let tracks =
let video_tracks =
live_kit.room.remote_video_tracks(&user.id.to_string());
for track in tracks {
let audio_tracks =
live_kit.room.remote_audio_tracks(&user.id.to_string());
for track in video_tracks {
this.remote_video_track_updated(
RemoteVideoTrackUpdate::Subscribed(track),
cx,
)
.log_err();
}
for track in audio_tracks {
this.remote_audio_track_updated(
RemoteAudioTrackUpdate::Subscribed(track),
cx,
)
.log_err();
}
}
}
}
@@ -706,7 +758,7 @@ impl Room {
.remote_participants
.get_mut(&user_id)
.ok_or_else(|| anyhow!("subscribed to track by unknown participant"))?;
participant.tracks.insert(
participant.video_tracks.insert(
track_id.clone(),
Arc::new(RemoteVideoTrack {
live_kit_track: track,
@@ -725,7 +777,7 @@ impl Room {
.remote_participants
.get_mut(&user_id)
.ok_or_else(|| anyhow!("unsubscribed from track by unknown participant"))?;
participant.tracks.remove(&track_id);
participant.video_tracks.remove(&track_id);
cx.emit(Event::RemoteVideoTracksChanged {
participant_id: participant.peer_id,
});
@@ -736,6 +788,84 @@ impl Room {
Ok(())
}
fn remote_audio_track_updated(
&mut self,
change: RemoteAudioTrackUpdate,
cx: &mut ModelContext<Self>,
) -> Result<()> {
match change {
RemoteAudioTrackUpdate::ActiveSpeakersChanged { speakers } => {
let mut speaker_ids = speakers
.into_iter()
.filter_map(|speaker_sid| speaker_sid.parse().ok())
.collect::<Vec<u64>>();
speaker_ids.sort_unstable();
for (sid, participant) in &mut self.remote_participants {
if let Ok(_) = speaker_ids.binary_search(sid) {
participant.speaking = true;
} else {
participant.speaking = false;
}
}
if let Some(id) = self.client.user_id() {
if let Some(room) = &mut self.live_kit {
if let Ok(_) = speaker_ids.binary_search(&id) {
room.speaking = true;
} else {
room.speaking = false;
}
}
}
cx.notify();
}
RemoteAudioTrackUpdate::MuteChanged { track_id, muted } => {
for participant in &mut self.remote_participants.values_mut() {
let mut found = false;
for track in participant.audio_tracks.values() {
if track.sid() == track_id {
found = true;
break;
}
}
if found {
participant.muted = muted;
break;
}
}
cx.notify();
}
RemoteAudioTrackUpdate::Subscribed(track) => {
let user_id = track.publisher_id().parse()?;
let track_id = track.sid().to_string();
let participant = self
.remote_participants
.get_mut(&user_id)
.ok_or_else(|| anyhow!("subscribed to track by unknown participant"))?;
participant.audio_tracks.insert(track_id.clone(), track);
cx.emit(Event::RemoteAudioTracksChanged {
participant_id: participant.peer_id,
});
}
RemoteAudioTrackUpdate::Unsubscribed {
publisher_id,
track_id,
} => {
let user_id = publisher_id.parse()?;
let participant = self
.remote_participants
.get_mut(&user_id)
.ok_or_else(|| anyhow!("unsubscribed from track by unknown participant"))?;
participant.audio_tracks.remove(&track_id);
cx.emit(Event::RemoteAudioTracksChanged {
participant_id: participant.peer_id,
});
}
}
cx.notify();
Ok(())
}
fn check_invariants(&self) {
#[cfg(any(test, feature = "test-support"))]
{
@@ -801,6 +931,7 @@ impl Room {
cx.spawn(|this, mut cx| async move {
let project =
Project::remote(id, client, user_store, language_registry, fs, cx.clone()).await?;
this.update(&mut cx, |this, cx| {
this.joined_projects.retain(|project| {
if let Some(project) = project.upgrade(cx) {
@@ -908,7 +1039,116 @@ impl Room {
pub fn is_screen_sharing(&self) -> bool {
self.live_kit.as_ref().map_or(false, |live_kit| {
!matches!(live_kit.screen_track, ScreenTrack::None)
!matches!(live_kit.screen_track, LocalTrack::None)
})
}
pub fn is_sharing_mic(&self) -> bool {
self.live_kit.as_ref().map_or(false, |live_kit| {
!matches!(live_kit.microphone_track, LocalTrack::None)
})
}
pub fn is_muted(&self) -> bool {
self.live_kit
.as_ref()
.and_then(|live_kit| match &live_kit.microphone_track {
LocalTrack::None => None,
LocalTrack::Pending { muted, .. } => Some(*muted),
LocalTrack::Published { muted, .. } => Some(*muted),
})
.unwrap_or(false)
}
pub fn is_speaking(&self) -> bool {
self.live_kit
.as_ref()
.map_or(false, |live_kit| live_kit.speaking)
}
pub fn is_deafened(&self) -> Option<bool> {
self.live_kit.as_ref().map(|live_kit| live_kit.deafened)
}
pub fn share_microphone(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
if self.status.is_offline() {
return Task::ready(Err(anyhow!("room is offline")));
} else if self.is_sharing_mic() {
return Task::ready(Err(anyhow!("microphone was already shared")));
}
let publish_id = if let Some(live_kit) = self.live_kit.as_mut() {
let publish_id = post_inc(&mut live_kit.next_publish_id);
live_kit.microphone_track = LocalTrack::Pending {
publish_id,
muted: false,
};
cx.notify();
publish_id
} else {
return Task::ready(Err(anyhow!("live-kit was not initialized")));
};
cx.spawn_weak(|this, mut cx| async move {
let publish_track = async {
let track = LocalAudioTrack::create();
this.upgrade(&cx)
.ok_or_else(|| anyhow!("room was dropped"))?
.read_with(&cx, |this, _| {
this.live_kit
.as_ref()
.map(|live_kit| live_kit.room.publish_audio_track(&track))
})
.ok_or_else(|| anyhow!("live-kit was not initialized"))?
.await
};
let publication = publish_track.await;
this.upgrade(&cx)
.ok_or_else(|| anyhow!("room was dropped"))?
.update(&mut cx, |this, cx| {
let live_kit = this
.live_kit
.as_mut()
.ok_or_else(|| anyhow!("live-kit was not initialized"))?;
let (canceled, muted) = if let LocalTrack::Pending {
publish_id: cur_publish_id,
muted,
} = &live_kit.microphone_track
{
(*cur_publish_id != publish_id, *muted)
} else {
(true, false)
};
match publication {
Ok(publication) => {
if canceled {
live_kit.room.unpublish_track(publication);
} else {
if muted {
cx.background().spawn(publication.set_mute(muted)).detach();
}
live_kit.microphone_track = LocalTrack::Published {
track_publication: publication,
muted,
};
cx.notify();
}
Ok(())
}
Err(error) => {
if canceled {
Ok(())
} else {
live_kit.microphone_track = LocalTrack::None;
cx.notify();
Err(error)
}
}
}
})
})
}
@@ -921,7 +1161,10 @@ impl Room {
let (displays, publish_id) = if let Some(live_kit) = self.live_kit.as_mut() {
let publish_id = post_inc(&mut live_kit.next_publish_id);
live_kit.screen_track = ScreenTrack::Pending { publish_id };
live_kit.screen_track = LocalTrack::Pending {
publish_id,
muted: false,
};
cx.notify();
(live_kit.room.display_sources(), publish_id)
} else {
@@ -955,13 +1198,14 @@ impl Room {
.as_mut()
.ok_or_else(|| anyhow!("live-kit was not initialized"))?;
let canceled = if let ScreenTrack::Pending {
let (canceled, muted) = if let LocalTrack::Pending {
publish_id: cur_publish_id,
muted,
} = &live_kit.screen_track
{
*cur_publish_id != publish_id
(*cur_publish_id != publish_id, *muted)
} else {
true
(true, false)
};
match publication {
@@ -969,16 +1213,25 @@ impl Room {
if canceled {
live_kit.room.unpublish_track(publication);
} else {
live_kit.screen_track = ScreenTrack::Published(publication);
if muted {
cx.background().spawn(publication.set_mute(muted)).detach();
}
live_kit.screen_track = LocalTrack::Published {
track_publication: publication,
muted,
};
cx.notify();
}
Audio::play_sound(Sound::StartScreenshare, cx);
Ok(())
}
Err(error) => {
if canceled {
Ok(())
} else {
live_kit.screen_track = ScreenTrack::None;
live_kit.screen_track = LocalTrack::None;
cx.notify();
Err(error)
}
@@ -988,6 +1241,59 @@ impl Room {
})
}
pub fn toggle_mute(&mut self, cx: &mut ModelContext<Self>) -> Result<Task<Result<()>>> {
let should_mute = !self.is_muted();
if let Some(live_kit) = self.live_kit.as_mut() {
let (ret_task, old_muted) = live_kit.set_mute(should_mute, cx)?;
live_kit.muted_by_user = should_mute;
if old_muted == true && live_kit.deafened == true {
if let Some(task) = self.toggle_deafen(cx).ok() {
task.detach();
}
}
Ok(ret_task)
} else {
Err(anyhow!("LiveKit not started"))
}
}
pub fn toggle_deafen(&mut self, cx: &mut ModelContext<Self>) -> Result<Task<Result<()>>> {
if let Some(live_kit) = self.live_kit.as_mut() {
(*live_kit).deafened = !live_kit.deafened;
let mut tasks = Vec::with_capacity(self.remote_participants.len());
// Context notification is sent within set_mute itself.
let mut mute_task = None;
// When deafening, mute user's mic as well.
// When undeafening, unmute user's mic unless it was manually muted prior to deafening.
if live_kit.deafened || !live_kit.muted_by_user {
mute_task = Some(live_kit.set_mute(live_kit.deafened, cx)?.0);
};
for participant in self.remote_participants.values() {
for track in live_kit
.room
.remote_audio_track_publications(&participant.user.id.to_string())
{
tasks.push(cx.foreground().spawn(track.set_enabled(!live_kit.deafened)));
}
}
Ok(cx.foreground().spawn(async move {
if let Some(mute_task) = mute_task {
mute_task.await?;
}
for task in tasks {
task.await?;
}
Ok(())
}))
} else {
Err(anyhow!("LiveKit not started"))
}
}
pub fn unshare_screen(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
if self.status.is_offline() {
return Err(anyhow!("room is offline"));
@@ -998,14 +1304,18 @@ impl Room {
.as_mut()
.ok_or_else(|| anyhow!("live-kit was not initialized"))?;
match mem::take(&mut live_kit.screen_track) {
ScreenTrack::None => Err(anyhow!("screen was not shared")),
ScreenTrack::Pending { .. } => {
LocalTrack::None => Err(anyhow!("screen was not shared")),
LocalTrack::Pending { .. } => {
cx.notify();
Ok(())
}
ScreenTrack::Published(track) => {
live_kit.room.unpublish_track(track);
LocalTrack::Published {
track_publication, ..
} => {
live_kit.room.unpublish_track(track_publication);
cx.notify();
Audio::play_sound(Sound::StopScreenshare, cx);
Ok(())
}
}
@@ -1023,19 +1333,75 @@ impl Room {
struct LiveKitRoom {
room: Arc<live_kit_client::Room>,
screen_track: ScreenTrack,
screen_track: LocalTrack,
microphone_track: LocalTrack,
/// Tracks whether we're currently in a muted state due to auto-mute from deafening or manual mute performed by user.
muted_by_user: bool,
deafened: bool,
speaking: bool,
next_publish_id: usize,
_maintain_room: Task<()>,
_maintain_tracks: Task<()>,
_maintain_tracks: [Task<()>; 2],
}
enum ScreenTrack {
impl LiveKitRoom {
fn set_mute(
self: &mut LiveKitRoom,
should_mute: bool,
cx: &mut ModelContext<Room>,
) -> Result<(Task<Result<()>>, bool)> {
if !should_mute {
// clear user muting state.
self.muted_by_user = false;
}
let (result, old_muted) = match &mut self.microphone_track {
LocalTrack::None => Err(anyhow!("microphone was not shared")),
LocalTrack::Pending { muted, .. } => {
let old_muted = *muted;
*muted = should_mute;
cx.notify();
Ok((Task::Ready(Some(Ok(()))), old_muted))
}
LocalTrack::Published {
track_publication,
muted,
} => {
let old_muted = *muted;
*muted = should_mute;
cx.notify();
Ok((
cx.background().spawn(track_publication.set_mute(*muted)),
old_muted,
))
}
}?;
if old_muted != should_mute {
if should_mute {
Audio::play_sound(Sound::Mute, cx);
} else {
Audio::play_sound(Sound::Unmute, cx);
}
}
Ok((result, old_muted))
}
}
enum LocalTrack {
None,
Pending { publish_id: usize },
Published(LocalTrackPublication),
Pending {
publish_id: usize,
muted: bool,
},
Published {
track_publication: LocalTrackPublication,
muted: bool,
},
}
impl Default for ScreenTrack {
impl Default for LocalTrack {
fn default() -> Self {
Self::None
}
+8 -34
View File
@@ -1,5 +1,4 @@
use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
use db::kvp::KEY_VALUE_STORE;
use gpui::{executor::Background, serde_json, AppContext, Task};
use lazy_static::lazy_static;
use parking_lot::Mutex;
@@ -8,7 +7,6 @@ use std::{env, io::Write, mem, path::PathBuf, sync::Arc, time::Duration};
use tempfile::NamedTempFile;
use util::http::HttpClient;
use util::{channel::ReleaseChannel, TryFutureExt};
use uuid::Uuid;
pub struct Telemetry {
http_client: Arc<dyn HttpClient>,
@@ -120,39 +118,15 @@ impl Telemetry {
Some(self.state.lock().log_file.as_ref()?.path().to_path_buf())
}
pub fn start(self: &Arc<Self>) {
let this = self.clone();
self.executor
.spawn(
async move {
let installation_id =
if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp("device_id") {
installation_id
} else {
let installation_id = Uuid::new_v4().to_string();
KEY_VALUE_STORE
.write_kvp("device_id".to_string(), installation_id.clone())
.await?;
installation_id
};
pub fn start(self: &Arc<Self>, installation_id: Option<String>) {
let mut state = self.state.lock();
state.installation_id = installation_id.map(|id| id.into());
let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
drop(state);
let installation_id: Arc<str> = installation_id.into();
let mut state = this.state.lock();
state.installation_id = Some(installation_id.clone());
let has_clickhouse_events = !state.clickhouse_events_queue.is_empty();
drop(state);
if has_clickhouse_events {
this.flush_clickhouse_events();
}
anyhow::Ok(())
}
.log_err(),
)
.detach();
if has_clickhouse_events {
self.flush_clickhouse_events();
}
}
/// This method takes the entire TelemetrySettings struct in order to force client code
+3 -2
View File
@@ -3,7 +3,7 @@ authors = ["Nathan Sobo <nathan@zed.dev>"]
default-run = "collab"
edition = "2021"
name = "collab"
version = "0.14.2"
version = "0.16.0"
publish = false
[[bin]]
@@ -57,6 +57,7 @@ tracing-log = "0.1.3"
tracing-subscriber = { version = "0.3.11", features = ["env-filter", "json"] }
[dev-dependencies]
audio = { path = "../audio" }
collections = { path = "../collections", features = ["test-support"] }
gpui = { path = "../gpui", features = ["test-support"] }
call = { path = "../call", features = ["test-support"] }
@@ -67,7 +68,7 @@ fs = { path = "../fs", features = ["test-support"] }
git = { path = "../git", features = ["test-support"] }
live_kit_client = { path = "../live_kit_client", features = ["test-support"] }
lsp = { path = "../lsp", features = ["test-support"] }
pretty_assertions = "1.3.0"
pretty_assertions.workspace = true
project = { path = "../project", features = ["test-support"] }
rpc = { path = "../rpc", features = ["test-support"] }
settings = { path = "../settings", features = ["test-support"] }
@@ -74,6 +74,7 @@ CREATE TABLE "worktree_entries" (
"mtime_seconds" INTEGER NOT NULL,
"mtime_nanos" INTEGER NOT NULL,
"is_symlink" BOOL NOT NULL,
"is_external" BOOL NOT NULL,
"is_ignored" BOOL NOT NULL,
"is_deleted" BOOL NOT NULL,
"git_status" INTEGER,
@@ -0,0 +1,2 @@
ALTER TABLE "worktree_entries"
ADD "is_external" BOOL NOT NULL DEFAULT FALSE;
+3
View File
@@ -1539,6 +1539,7 @@ impl Database {
}),
is_symlink: db_entry.is_symlink,
is_ignored: db_entry.is_ignored,
is_external: db_entry.is_external,
git_status: db_entry.git_status.map(|status| status as i32),
});
}
@@ -2349,6 +2350,7 @@ impl Database {
mtime_nanos: ActiveValue::set(mtime.nanos as i32),
is_symlink: ActiveValue::set(entry.is_symlink),
is_ignored: ActiveValue::set(entry.is_ignored),
is_external: ActiveValue::set(entry.is_external),
git_status: ActiveValue::set(entry.git_status.map(|status| status as i64)),
is_deleted: ActiveValue::set(false),
scan_id: ActiveValue::set(update.scan_id as i64),
@@ -2705,6 +2707,7 @@ impl Database {
}),
is_symlink: db_entry.is_symlink,
is_ignored: db_entry.is_ignored,
is_external: db_entry.is_external,
git_status: db_entry.git_status.map(|status| status as i32),
});
}
+1
View File
@@ -18,6 +18,7 @@ pub struct Model {
pub git_status: Option<i64>,
pub is_symlink: bool,
pub is_ignored: bool,
pub is_external: bool,
pub is_deleted: bool,
pub scan_id: i64,
}
+16 -1
View File
@@ -201,6 +201,7 @@ impl Server {
.add_message_handler(update_language_server)
.add_message_handler(update_diagnostic_summary)
.add_message_handler(update_worktree_settings)
.add_message_handler(refresh_inlay_hints)
.add_request_handler(forward_project_request::<proto::GetHover>)
.add_request_handler(forward_project_request::<proto::GetDefinition>)
.add_request_handler(forward_project_request::<proto::GetTypeDefinition>)
@@ -224,7 +225,9 @@ impl Server {
.add_request_handler(forward_project_request::<proto::RenameProjectEntry>)
.add_request_handler(forward_project_request::<proto::CopyProjectEntry>)
.add_request_handler(forward_project_request::<proto::DeleteProjectEntry>)
.add_request_handler(forward_project_request::<proto::ExpandProjectEntry>)
.add_request_handler(forward_project_request::<proto::OnTypeFormatting>)
.add_request_handler(forward_project_request::<proto::InlayHints>)
.add_message_handler(create_buffer_for_peer)
.add_request_handler(update_buffer)
.add_message_handler(update_buffer_file)
@@ -1573,6 +1576,10 @@ async fn update_worktree_settings(
Ok(())
}
async fn refresh_inlay_hints(request: proto::RefreshInlayHints, session: Session) -> Result<()> {
broadcast_project_message(request.project_id, request, session).await
}
async fn start_language_server(
request: proto::StartLanguageServer,
session: Session,
@@ -1749,7 +1756,15 @@ async fn buffer_reloaded(request: proto::BufferReloaded, session: Session) -> Re
}
async fn buffer_saved(request: proto::BufferSaved, session: Session) -> Result<()> {
let project_id = ProjectId::from_proto(request.project_id);
broadcast_project_message(request.project_id, request, session).await
}
async fn broadcast_project_message<T: EnvelopedMessage>(
project_id: u64,
request: T,
session: Session,
) -> Result<()> {
let project_id = ProjectId::from_proto(project_id);
let project_connection_ids = session
.db()
.await
+1
View File
@@ -203,6 +203,7 @@ impl TestServer {
language::init(cx);
editor::init_settings(cx);
workspace::init(app_state.clone(), cx);
audio::init((), cx);
call::init(client.clone(), user_store.clone(), cx);
});
+649 -12
View File
@@ -18,7 +18,7 @@ use gpui::{
};
use indoc::indoc;
use language::{
language_settings::{AllLanguageSettings, Formatter},
language_settings::{AllLanguageSettings, Formatter, InlayHintKind, InlayHintSettings},
tree_sitter_rust, Anchor, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language,
LanguageConfig, OffsetRangeExt, Point, Rope,
};
@@ -34,12 +34,17 @@ use std::{
path::{Path, PathBuf},
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering::SeqCst},
atomic::{AtomicBool, AtomicU32, Ordering::SeqCst},
Arc,
},
};
use unindent::Unindent as _;
use workspace::{item::ItemHandle as _, shared_screen::SharedScreen, SplitDirection, Workspace};
use workspace::{
dock::{test::TestPanel, DockPosition},
item::{test::TestItem, ItemHandle as _},
shared_screen::SharedScreen,
SplitDirection, Workspace,
};
#[ctor::ctor]
fn init_logger() {
@@ -252,7 +257,7 @@ async fn test_basic_calls(
room_b.read_with(cx_b, |room, _| {
assert_eq!(
room.remote_participants()[&client_a.user_id().unwrap()]
.tracks
.video_tracks
.len(),
1
);
@@ -269,7 +274,7 @@ async fn test_basic_calls(
room_c.read_with(cx_c, |room, _| {
assert_eq!(
room.remote_participants()[&client_a.user_id().unwrap()]
.tracks
.video_tracks
.len(),
1
);
@@ -1261,6 +1266,27 @@ async fn test_share_project(
let client_b_collaborator = project.collaborators().get(&client_b_peer_id).unwrap();
assert_eq!(client_b_collaborator.replica_id, replica_id_b);
});
project_b.read_with(cx_b, |project, cx| {
let worktree = project.worktrees(cx).next().unwrap().read(cx);
assert_eq!(
worktree.paths().map(AsRef::as_ref).collect::<Vec<_>>(),
[
Path::new(".gitignore"),
Path::new("a.txt"),
Path::new("b.txt"),
Path::new("ignored-dir"),
]
);
});
project_b
.update(cx_b, |project, cx| {
let worktree = project.worktrees(cx).next().unwrap();
let entry = worktree.read(cx).entry_for_path("ignored-dir").unwrap();
project.expand_entry(worktree_id, entry.id, cx).unwrap()
})
.await
.unwrap();
project_b.read_with(cx_b, |project, cx| {
let worktree = project.worktrees(cx).next().unwrap().read(cx);
assert_eq!(
@@ -6847,12 +6873,43 @@ async fn test_basic_following(
)
});
// Client B activates an external window again, and the previously-opened screen-sharing item
// gets activated.
active_call_b
.update(cx_b, |call, cx| call.set_location(None, cx))
.await
.unwrap();
// Client B activates a panel, and the previously-opened screen-sharing item gets activated.
let panel = cx_b.add_view(workspace_b.window_id(), |_| {
TestPanel::new(DockPosition::Left)
});
workspace_b.update(cx_b, |workspace, cx| {
workspace.add_panel(panel, cx);
workspace.toggle_panel_focus::<TestPanel>(cx);
});
deterministic.run_until_parked();
assert_eq!(
workspace_a.read_with(cx_a, |workspace, cx| workspace
.active_item(cx)
.unwrap()
.id()),
shared_screen.id()
);
// Toggling the focus back to the pane causes client A to return to the multibuffer.
workspace_b.update(cx_b, |workspace, cx| {
workspace.toggle_panel_focus::<TestPanel>(cx);
});
deterministic.run_until_parked();
workspace_a.read_with(cx_a, |workspace, cx| {
assert_eq!(
workspace.active_item(cx).unwrap().id(),
multibuffer_editor_a.id()
)
});
// Client B activates an item that doesn't implement following,
// so the previously-opened screen-sharing item gets activated.
let unfollowable_item = cx_b.add_view(workspace_b.window_id(), |_| TestItem::new());
workspace_b.update(cx_b, |workspace, cx| {
workspace.active_pane().update(cx, |pane, cx| {
pane.add_item(Box::new(unfollowable_item), true, true, None, cx)
})
});
deterministic.run_until_parked();
assert_eq!(
workspace_a.read_with(cx_a, |workspace, cx| workspace
@@ -6957,7 +7014,7 @@ async fn test_join_call_after_screen_was_shared(
room.remote_participants()
.get(&client_a.user_id().unwrap())
.unwrap()
.tracks
.video_tracks
.len(),
1
);
@@ -7743,6 +7800,572 @@ async fn test_on_input_format_from_guest_to_host(
});
}
#[gpui::test]
async fn test_mutual_editor_inlay_hint_cache_update(
deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
) {
deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
server
.create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
.await;
let active_call_a = cx_a.read(ActiveCall::global);
let active_call_b = cx_b.read(ActiveCall::global);
cx_a.update(editor::init);
cx_b.update(editor::init);
cx_a.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<AllLanguageSettings>(cx, |settings| {
settings.defaults.inlay_hints = Some(InlayHintSettings {
enabled: true,
show_type_hints: true,
show_parameter_hints: false,
show_other_hints: true,
})
});
});
});
cx_b.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<AllLanguageSettings>(cx, |settings| {
settings.defaults.inlay_hints = Some(InlayHintSettings {
enabled: true,
show_type_hints: true,
show_parameter_hints: false,
show_other_hints: true,
})
});
});
});
let allowed_hint_kinds = HashSet::from_iter([None, Some(InlayHintKind::Type)]);
let mut language = Language::new(
LanguageConfig {
name: "Rust".into(),
path_suffixes: vec!["rs".to_string()],
..Default::default()
},
Some(tree_sitter_rust::language()),
);
let mut fake_language_servers = language
.set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
inlay_hint_provider: Some(lsp::OneOf::Left(true)),
..Default::default()
},
..Default::default()
}))
.await;
let language = Arc::new(language);
client_a.language_registry.add(Arc::clone(&language));
client_b.language_registry.add(language);
client_a
.fs
.insert_tree(
"/a",
json!({
"main.rs": "fn main() { a } // and some long comment to ensure inlays are not trimmed out",
"other.rs": "// Test file",
}),
)
.await;
let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
active_call_a
.update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
.await
.unwrap();
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
.unwrap();
let workspace_a = client_a.build_workspace(&project_a, cx_a);
cx_a.foreground().start_waiting();
let _buffer_a = project_a
.update(cx_a, |project, cx| {
project.open_local_buffer("/a/main.rs", cx)
})
.await
.unwrap();
let fake_language_server = fake_language_servers.next().await.unwrap();
let next_call_id = Arc::new(AtomicU32::new(0));
let editor_a = workspace_a
.update(cx_a, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
fake_language_server
.handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
let task_next_call_id = Arc::clone(&next_call_id);
async move {
assert_eq!(
params.text_document.uri,
lsp::Url::from_file_path("/a/main.rs").unwrap(),
);
let mut current_call_id = Arc::clone(&task_next_call_id).fetch_add(1, SeqCst);
let mut new_hints = Vec::with_capacity(current_call_id as usize);
loop {
new_hints.push(lsp::InlayHint {
position: lsp::Position::new(0, current_call_id),
label: lsp::InlayHintLabel::String(current_call_id.to_string()),
kind: None,
text_edits: None,
tooltip: None,
padding_left: None,
padding_right: None,
data: None,
});
if current_call_id == 0 {
break;
}
current_call_id -= 1;
}
Ok(Some(new_hints))
}
})
.next()
.await
.unwrap();
cx_a.foreground().finish_waiting();
cx_a.foreground().run_until_parked();
let mut edits_made = 1;
editor_a.update(cx_a, |editor, _| {
assert_eq!(
vec!["0".to_string()],
extract_hint_labels(editor),
"Host should get its first hints when opens an editor"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Cache should use editor settings to get the allowed hint kinds"
);
assert_eq!(
inlay_cache.version, edits_made,
"Host editor update the cache version after every cache/view change",
);
});
let workspace_b = client_b.build_workspace(&project_b, cx_b);
let editor_b = workspace_b
.update(cx_b, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
cx_b.foreground().run_until_parked();
editor_b.update(cx_b, |editor, _| {
assert_eq!(
vec!["0".to_string(), "1".to_string()],
extract_hint_labels(editor),
"Client should get its first hints when opens an editor"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Cache should use editor settings to get the allowed hint kinds"
);
assert_eq!(
inlay_cache.version, edits_made,
"Guest editor update the cache version after every cache/view change"
);
});
editor_b.update(cx_b, |editor, cx| {
editor.change_selections(None, cx, |s| s.select_ranges([13..13].clone()));
editor.handle_input(":", cx);
cx.focus(&editor_b);
edits_made += 1;
});
cx_a.foreground().run_until_parked();
cx_b.foreground().run_until_parked();
editor_a.update(cx_a, |editor, _| {
assert_eq!(
vec!["0".to_string(), "1".to_string(), "2".to_string()],
extract_hint_labels(editor),
"Host should get hints from the 1st edit and 1st LSP query"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(inlay_cache.version, edits_made);
});
editor_b.update(cx_b, |editor, _| {
assert_eq!(
vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string()
],
extract_hint_labels(editor),
"Guest should get hints the 1st edit and 2nd LSP query"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(inlay_cache.version, edits_made);
});
editor_a.update(cx_a, |editor, cx| {
editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
editor.handle_input("a change to increment both buffers' versions", cx);
cx.focus(&editor_a);
edits_made += 1;
});
cx_a.foreground().run_until_parked();
cx_b.foreground().run_until_parked();
editor_a.update(cx_a, |editor, _| {
assert_eq!(
vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string()
],
extract_hint_labels(editor),
"Host should get hints from 3rd edit, 5th LSP query: \
4th query was made by guest (but not applied) due to cache invalidation logic"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(inlay_cache.version, edits_made);
});
editor_b.update(cx_b, |editor, _| {
assert_eq!(
vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
"5".to_string(),
],
extract_hint_labels(editor),
"Guest should get hints from 3rd edit, 6th LSP query"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(inlay_cache.version, edits_made);
});
fake_language_server
.request::<lsp::request::InlayHintRefreshRequest>(())
.await
.expect("inlay refresh request failed");
edits_made += 1;
cx_a.foreground().run_until_parked();
cx_b.foreground().run_until_parked();
editor_a.update(cx_a, |editor, _| {
assert_eq!(
vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
"5".to_string(),
"6".to_string(),
],
extract_hint_labels(editor),
"Host should react to /refresh LSP request and get new hints from 7th LSP query"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(
inlay_cache.version, edits_made,
"Host should accepted all edits and bump its cache version every time"
);
});
editor_b.update(cx_b, |editor, _| {
assert_eq!(
vec![
"0".to_string(),
"1".to_string(),
"2".to_string(),
"3".to_string(),
"4".to_string(),
"5".to_string(),
"6".to_string(),
"7".to_string(),
],
extract_hint_labels(editor),
"Guest should get a /refresh LSP request propagated by host and get new hints from 8th LSP query"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(
inlay_cache.version,
edits_made,
"Guest should accepted all edits and bump its cache version every time"
);
});
}
#[gpui::test]
async fn test_inlay_hint_refresh_is_forwarded(
deterministic: Arc<Deterministic>,
cx_a: &mut TestAppContext,
cx_b: &mut TestAppContext,
) {
deterministic.forbid_parking();
let mut server = TestServer::start(&deterministic).await;
let client_a = server.create_client(cx_a, "user_a").await;
let client_b = server.create_client(cx_b, "user_b").await;
server
.create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
.await;
let active_call_a = cx_a.read(ActiveCall::global);
let active_call_b = cx_b.read(ActiveCall::global);
cx_a.update(editor::init);
cx_b.update(editor::init);
cx_a.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<AllLanguageSettings>(cx, |settings| {
settings.defaults.inlay_hints = Some(InlayHintSettings {
enabled: false,
show_type_hints: true,
show_parameter_hints: false,
show_other_hints: true,
})
});
});
});
cx_b.update(|cx| {
cx.update_global(|store: &mut SettingsStore, cx| {
store.update_user_settings::<AllLanguageSettings>(cx, |settings| {
settings.defaults.inlay_hints = Some(InlayHintSettings {
enabled: true,
show_type_hints: true,
show_parameter_hints: false,
show_other_hints: true,
})
});
});
});
let allowed_hint_kinds = HashSet::from_iter([None, Some(InlayHintKind::Type)]);
let mut language = Language::new(
LanguageConfig {
name: "Rust".into(),
path_suffixes: vec!["rs".to_string()],
..Default::default()
},
Some(tree_sitter_rust::language()),
);
let mut fake_language_servers = language
.set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
inlay_hint_provider: Some(lsp::OneOf::Left(true)),
..Default::default()
},
..Default::default()
}))
.await;
let language = Arc::new(language);
client_a.language_registry.add(Arc::clone(&language));
client_b.language_registry.add(language);
client_a
.fs
.insert_tree(
"/a",
json!({
"main.rs": "fn main() { a } // and some long comment to ensure inlays are not trimmed out",
"other.rs": "// Test file",
}),
)
.await;
let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
active_call_a
.update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
.await
.unwrap();
let project_id = active_call_a
.update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
.await
.unwrap();
let project_b = client_b.build_remote_project(project_id, cx_b).await;
active_call_b
.update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
.await
.unwrap();
let workspace_a = client_a.build_workspace(&project_a, cx_a);
let workspace_b = client_b.build_workspace(&project_b, cx_b);
cx_a.foreground().start_waiting();
cx_b.foreground().start_waiting();
let editor_a = workspace_a
.update(cx_a, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
let editor_b = workspace_b
.update(cx_b, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
let fake_language_server = fake_language_servers.next().await.unwrap();
let next_call_id = Arc::new(AtomicU32::new(0));
fake_language_server
.handle_request::<lsp::request::InlayHintRequest, _, _>(move |params, _| {
let task_next_call_id = Arc::clone(&next_call_id);
async move {
assert_eq!(
params.text_document.uri,
lsp::Url::from_file_path("/a/main.rs").unwrap(),
);
let mut current_call_id = Arc::clone(&task_next_call_id).fetch_add(1, SeqCst);
let mut new_hints = Vec::with_capacity(current_call_id as usize);
loop {
new_hints.push(lsp::InlayHint {
position: lsp::Position::new(0, current_call_id),
label: lsp::InlayHintLabel::String(current_call_id.to_string()),
kind: None,
text_edits: None,
tooltip: None,
padding_left: None,
padding_right: None,
data: None,
});
if current_call_id == 0 {
break;
}
current_call_id -= 1;
}
Ok(Some(new_hints))
}
})
.next()
.await
.unwrap();
cx_a.foreground().finish_waiting();
cx_b.foreground().finish_waiting();
cx_a.foreground().run_until_parked();
editor_a.update(cx_a, |editor, _| {
assert!(
extract_hint_labels(editor).is_empty(),
"Host should get no hints due to them turned off"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Host should have allowed hint kinds set despite hints are off"
);
assert_eq!(
inlay_cache.version, 0,
"Host should not increment its cache version due to no changes",
);
});
let mut edits_made = 1;
cx_b.foreground().run_until_parked();
editor_b.update(cx_b, |editor, _| {
assert_eq!(
vec!["0".to_string()],
extract_hint_labels(editor),
"Client should get its first hints when opens an editor"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Cache should use editor settings to get the allowed hint kinds"
);
assert_eq!(
inlay_cache.version, edits_made,
"Guest editor update the cache version after every cache/view change"
);
});
fake_language_server
.request::<lsp::request::InlayHintRefreshRequest>(())
.await
.expect("inlay refresh request failed");
cx_a.foreground().run_until_parked();
editor_a.update(cx_a, |editor, _| {
assert!(
extract_hint_labels(editor).is_empty(),
"Host should get nop hints due to them turned off, even after the /refresh"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(inlay_cache.allowed_hint_kinds, allowed_hint_kinds);
assert_eq!(
inlay_cache.version, 0,
"Host should not increment its cache version due to no changes",
);
});
edits_made += 1;
cx_b.foreground().run_until_parked();
editor_b.update(cx_b, |editor, _| {
assert_eq!(
vec!["0".to_string(), "1".to_string(),],
extract_hint_labels(editor),
"Guest should get a /refresh LSP request propagated by host despite host hints are off"
);
let inlay_cache = editor.inlay_hint_cache();
assert_eq!(
inlay_cache.allowed_hint_kinds, allowed_hint_kinds,
"Inlay kinds settings never change during the test"
);
assert_eq!(
inlay_cache.version, edits_made,
"Guest should accepted all edits and bump its cache version every time"
);
});
}
#[derive(Debug, Eq, PartialEq)]
struct RoomParticipants {
remote: Vec<String>,
@@ -7766,3 +8389,17 @@ fn room_participants(room: &ModelHandle<Room>, cx: &mut TestAppContext) -> RoomP
RoomParticipants { remote, pending }
})
}
fn extract_hint_labels(editor: &Editor) -> Vec<String> {
let mut labels = Vec::new();
for (_, excerpt_hints) in &editor.inlay_hint_cache().hints {
let excerpt_hints = excerpt_hints.read();
for (_, inlay) in excerpt_hints.hints.iter() {
match &inlay.label {
project::InlayHintLabel::String(s) => labels.push(s.to_string()),
_ => unreachable!(),
}
}
}
labels
}
+4
View File
@@ -35,10 +35,14 @@ gpui = { path = "../gpui" }
menu = { path = "../menu" }
picker = { path = "../picker" }
project = { path = "../project" }
recent_projects = {path = "../recent_projects"}
settings = { path = "../settings" }
theme = { path = "../theme" }
theme_selector = { path = "../theme_selector" }
util = { path = "../util" }
workspace = { path = "../workspace" }
zed-actions = {path = "../zed-actions"}
anyhow.workspace = true
futures.workspace = true
+238
View File
@@ -0,0 +1,238 @@
use anyhow::{anyhow, bail};
use fuzzy::{StringMatch, StringMatchCandidate};
use gpui::{elements::*, AppContext, MouseState, Task, ViewContext, ViewHandle};
use picker::{Picker, PickerDelegate, PickerEvent};
use std::{ops::Not, sync::Arc};
use util::ResultExt;
use workspace::{Toast, Workspace};
pub fn init(cx: &mut AppContext) {
Picker::<BranchListDelegate>::init(cx);
}
pub type BranchList = Picker<BranchListDelegate>;
pub fn build_branch_list(
workspace: ViewHandle<Workspace>,
cx: &mut ViewContext<BranchList>,
) -> BranchList {
Picker::new(
BranchListDelegate {
matches: vec![],
workspace,
selected_index: 0,
last_query: String::default(),
},
cx,
)
.with_theme(|theme| theme.picker.clone())
}
pub struct BranchListDelegate {
matches: Vec<StringMatch>,
workspace: ViewHandle<Workspace>,
selected_index: usize,
last_query: String,
}
impl PickerDelegate for BranchListDelegate {
fn placeholder_text(&self) -> Arc<str> {
"Select branch...".into()
}
fn match_count(&self) -> usize {
self.matches.len()
}
fn selected_index(&self) -> usize {
self.selected_index
}
fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
self.selected_index = ix;
}
fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
cx.spawn(move |picker, mut cx| async move {
let Some(candidates) = picker
.read_with(&mut cx, |view, cx| {
let delegate = view.delegate();
let project = delegate.workspace.read(cx).project().read(&cx);
let mut cwd =
project
.visible_worktrees(cx)
.next()
.unwrap()
.read(cx)
.abs_path()
.to_path_buf();
cwd.push(".git");
let Some(repo) = project.fs().open_repo(&cwd) else {bail!("Project does not have associated git repository.")};
let mut branches = repo
.lock()
.branches()?;
const RECENT_BRANCHES_COUNT: usize = 10;
if query.is_empty() && branches.len() > RECENT_BRANCHES_COUNT {
// Truncate list of recent branches
// Do a partial sort to show recent-ish branches first.
branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
rhs.unix_timestamp.cmp(&lhs.unix_timestamp)
});
branches.truncate(RECENT_BRANCHES_COUNT);
branches.sort_unstable_by(|lhs, rhs| lhs.name.cmp(&rhs.name));
}
Ok(branches
.iter()
.cloned()
.enumerate()
.map(|(ix, command)| StringMatchCandidate {
id: ix,
char_bag: command.name.chars().collect(),
string: command.name.into(),
})
.collect::<Vec<_>>())
})
.log_err() else { return; };
let Some(candidates) = candidates.log_err() else {return;};
let matches = if query.is_empty() {
candidates
.into_iter()
.enumerate()
.map(|(index, candidate)| StringMatch {
candidate_id: index,
string: candidate.string,
positions: Vec::new(),
score: 0.0,
})
.collect()
} else {
fuzzy::match_strings(
&candidates,
&query,
true,
10000,
&Default::default(),
cx.background(),
)
.await
};
picker
.update(&mut cx, |picker, _| {
let delegate = picker.delegate_mut();
delegate.matches = matches;
if delegate.matches.is_empty() {
delegate.selected_index = 0;
} else {
delegate.selected_index =
core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
}
delegate.last_query = query;
})
.log_err();
})
}
fn confirm(&mut self, cx: &mut ViewContext<Picker<Self>>) {
let current_pick = self.selected_index();
let current_pick = self.matches[current_pick].string.clone();
cx.spawn(|picker, mut cx| async move {
picker.update(&mut cx, |this, cx| {
let project = this.delegate().workspace.read(cx).project().read(cx);
let mut cwd = project
.visible_worktrees(cx)
.next()
.ok_or_else(|| anyhow!("There are no visisible worktrees."))?
.read(cx)
.abs_path()
.to_path_buf();
cwd.push(".git");
let status = project
.fs()
.open_repo(&cwd)
.ok_or_else(|| anyhow!("Could not open repository at path `{}`", cwd.as_os_str().to_string_lossy()))?
.lock()
.change_branch(&current_pick);
if status.is_err() {
const GIT_CHECKOUT_FAILURE_ID: usize = 2048;
this.delegate().workspace.update(cx, |model, ctx| {
model.show_toast(
Toast::new(
GIT_CHECKOUT_FAILURE_ID,
format!("Failed to checkout branch '{current_pick}', check for conflicts or unstashed files"),
),
ctx,
)
});
status?;
}
cx.emit(PickerEvent::Dismiss);
Ok::<(), anyhow::Error>(())
}).log_err();
}).detach();
}
fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
cx.emit(PickerEvent::Dismiss);
}
fn render_match(
&self,
ix: usize,
mouse_state: &mut MouseState,
selected: bool,
cx: &gpui::AppContext,
) -> AnyElement<Picker<Self>> {
const DISPLAYED_MATCH_LEN: usize = 29;
let theme = &theme::current(cx);
let hit = &self.matches[ix];
let shortened_branch_name = util::truncate_and_trailoff(&hit.string, DISPLAYED_MATCH_LEN);
let highlights = hit
.positions
.iter()
.copied()
.filter(|index| index < &DISPLAYED_MATCH_LEN)
.collect();
let style = theme.picker.item.in_state(selected).style_for(mouse_state);
Flex::row()
.with_child(
Label::new(shortened_branch_name.clone(), style.label.clone())
.with_highlights(highlights)
.contained()
.aligned()
.left(),
)
.contained()
.with_style(style.container)
.constrained()
.with_height(theme.contact_finder.row_height)
.into_any()
}
fn render_header(
&self,
cx: &mut ViewContext<Picker<Self>>,
) -> Option<AnyElement<Picker<Self>>> {
let theme = &theme::current(cx);
let style = theme.picker.header.clone();
let label = if self.last_query.is_empty() {
Flex::row()
.with_child(Label::new("Recent branches", style.label.clone()))
.contained()
.with_style(style.container)
} else {
Flex::row()
.with_child(Label::new("Branches", style.label.clone()))
.with_children(self.matches.is_empty().not().then(|| {
let suffix = if self.matches.len() == 1 { "" } else { "es" };
Label::new(
format!("{} match{}", self.matches.len(), suffix),
style.label,
)
.flex_float()
}))
.contained()
.with_style(style.container)
};
Some(label.into_any())
}
}
+500 -134
View File
@@ -1,6 +1,10 @@
use crate::{
contact_notification::ContactNotification, contacts_popover, face_pile::FacePile,
toggle_screen_sharing, ToggleScreenSharing,
branch_list::{build_branch_list, BranchList},
contact_notification::ContactNotification,
contacts_popover,
face_pile::FacePile,
toggle_deafen, toggle_mute, toggle_screen_sharing, LeaveCall, ToggleDeafen, ToggleMute,
ToggleScreenSharing,
};
use call::{ActiveCall, ParticipantLocation, Room};
use client::{proto::PeerId, Client, ContactEventKind, SignIn, SignOut, User, UserStore};
@@ -17,19 +21,25 @@ use gpui::{
AppContext, Entity, ImageData, LayoutContext, ModelHandle, SceneBuilder, Subscription, View,
ViewContext, ViewHandle, WeakViewHandle,
};
use project::Project;
use picker::PickerEvent;
use project::{Project, RepositoryEntry};
use recent_projects::{build_recent_projects, RecentProjects};
use std::{ops::Range, sync::Arc};
use theme::{AvatarStyle, Theme};
use util::ResultExt;
use workspace::{FollowNextCollaborator, Workspace};
use workspace::{FollowNextCollaborator, Workspace, WORKSPACE_DB};
const MAX_TITLE_LENGTH: usize = 75;
const MAX_PROJECT_NAME_LENGTH: usize = 40;
const MAX_BRANCH_NAME_LENGTH: usize = 40;
actions!(
collab,
[
ToggleContactsMenu,
ToggleUserMenu,
ToggleVcsMenu,
ToggleProjectMenu,
SwitchBranch,
ShareProject,
UnshareProject,
]
@@ -40,6 +50,8 @@ pub fn init(cx: &mut AppContext) {
cx.add_action(CollabTitlebarItem::share_project);
cx.add_action(CollabTitlebarItem::unshare_project);
cx.add_action(CollabTitlebarItem::toggle_user_menu);
cx.add_action(CollabTitlebarItem::toggle_vcs_menu);
cx.add_action(CollabTitlebarItem::toggle_project_menu);
}
pub struct CollabTitlebarItem {
@@ -48,6 +60,8 @@ pub struct CollabTitlebarItem {
client: Arc<Client>,
workspace: WeakViewHandle<Workspace>,
contacts_popover: Option<ViewHandle<ContactsPopover>>,
branch_popover: Option<ViewHandle<BranchList>>,
project_popover: Option<ViewHandle<recent_projects::RecentProjects>>,
user_menu: ViewHandle<ContextMenu>,
_subscriptions: Vec<Subscription>,
}
@@ -68,37 +82,43 @@ impl View for CollabTitlebarItem {
return Empty::new().into_any();
};
let project = self.project.read(cx);
let theme = theme::current(cx).clone();
let mut left_container = Flex::row();
let mut right_container = Flex::row().align_children_center();
left_container.add_child(self.collect_title_root_names(&project, theme.clone(), cx));
left_container.add_child(self.collect_title_root_names(theme.clone(), cx));
let user = self.user_store.read(cx).current_user();
let peer_id = self.client.peer_id();
if let Some(((user, peer_id), room)) = user
.as_ref()
.zip(peer_id)
.zip(ActiveCall::global(cx).read(cx).room().cloned())
{
left_container
.add_children(self.render_in_call_share_unshare_button(&workspace, &theme, cx));
right_container.add_children(self.render_collaborators(&workspace, &theme, &room, cx));
right_container
.add_child(self.render_current_user(&workspace, &theme, &user, peer_id, cx));
.add_children(self.render_in_call_share_unshare_button(&workspace, &theme, cx));
right_container.add_child(self.render_leave_call(&theme, cx));
let muted = room.read(cx).is_muted();
let speaking = room.read(cx).is_speaking();
left_container.add_child(
self.render_current_user(&workspace, &theme, &user, peer_id, muted, speaking, cx),
);
left_container.add_children(self.render_collaborators(&workspace, &theme, &room, cx));
right_container.add_child(self.render_toggle_mute(&theme, &room, cx));
right_container.add_child(self.render_toggle_deafen(&theme, &room, cx));
right_container.add_child(self.render_toggle_screen_sharing_button(&theme, &room, cx));
}
let status = workspace.read(cx).client().status();
let status = &*status.borrow();
if matches!(status, client::Status::Connected { .. }) {
right_container.add_child(self.render_toggle_contacts_button(&theme, cx));
right_container.add_child(self.render_user_menu_button(&theme, cx));
let avatar = user.as_ref().and_then(|user| user.avatar.clone());
right_container.add_child(self.render_user_menu_button(&theme, avatar, cx));
} else {
right_container.add_children(self.render_connection_status(status, cx));
right_container.add_child(self.render_sign_in_button(&theme, cx));
right_container.add_child(self.render_user_menu_button(&theme, None, cx));
}
Stack::new()
@@ -108,7 +128,6 @@ impl View for CollabTitlebarItem {
.with_child(
right_container.contained().with_background_color(
theme
.workspace
.titlebar
.container
.background_color
@@ -163,7 +182,6 @@ impl CollabTitlebarItem {
}),
);
let view_id = cx.view_id();
Self {
workspace: workspace.weak_handle(),
project,
@@ -171,69 +189,105 @@ impl CollabTitlebarItem {
client,
contacts_popover: None,
user_menu: cx.add_view(|cx| {
let view_id = cx.view_id();
let mut menu = ContextMenu::new(view_id, cx);
menu.set_position_mode(OverlayPositionMode::Local);
menu
}),
branch_popover: None,
project_popover: None,
_subscriptions: subscriptions,
}
}
fn collect_title_root_names(
&self,
project: &Project,
theme: Arc<Theme>,
cx: &ViewContext<Self>,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let names_and_branches = project.visible_worktrees(cx).map(|worktree| {
let worktree = worktree.read(cx);
(worktree.root_name(), worktree.root_git_entry())
});
let project = self.project.read(cx);
fn push_str(buffer: &mut String, index: &mut usize, str: &str) {
buffer.push_str(str);
*index += str.chars().count();
}
let (name, entry) = {
let mut names_and_branches = project.visible_worktrees(cx).map(|worktree| {
let worktree = worktree.read(cx);
(worktree.root_name(), worktree.root_git_entry())
});
let mut indices = Vec::new();
let mut index = 0;
let mut title = String::new();
let mut names_and_branches = names_and_branches.peekable();
while let Some((name, entry)) = names_and_branches.next() {
let pre_index = index;
push_str(&mut title, &mut index, name);
indices.extend((pre_index..index).into_iter());
if let Some(branch) = entry.and_then(|entry| entry.branch()) {
push_str(&mut title, &mut index, "/");
push_str(&mut title, &mut index, &branch);
}
if names_and_branches.peek().is_some() {
push_str(&mut title, &mut index, ", ");
if index >= MAX_TITLE_LENGTH {
title.push_str("");
break;
}
}
}
let text_style = theme.workspace.titlebar.title.clone();
let item_spacing = theme.workspace.titlebar.item_spacing;
let mut highlight = text_style.clone();
highlight.color = theme.workspace.titlebar.highlight_color;
let style = LabelStyle {
text: text_style,
highlight_text: Some(highlight),
names_and_branches.next().unwrap_or(("", None))
};
Label::new(title, style)
.with_highlights(indices)
.contained()
.with_margin_right(item_spacing)
.aligned()
.left()
.into_any_named("title-with-git-information")
let name = util::truncate_and_trailoff(name, MAX_PROJECT_NAME_LENGTH);
let branch_prepended = entry
.as_ref()
.and_then(RepositoryEntry::branch)
.map(|branch| util::truncate_and_trailoff(&branch, MAX_BRANCH_NAME_LENGTH));
let project_style = theme.titlebar.project_menu_button.clone();
let git_style = theme.titlebar.git_menu_button.clone();
let divider_style = theme.titlebar.project_name_divider.clone();
let item_spacing = theme.titlebar.item_spacing;
let mut ret = Flex::row().with_child(
Stack::new()
.with_child(
MouseEventHandler::<ToggleProjectMenu, Self>::new(0, cx, |mouse_state, _| {
let style = project_style
.in_state(self.project_popover.is_some())
.style_for(mouse_state);
Label::new(name, style.text.clone())
.contained()
.with_style(style.container)
.aligned()
.left()
.into_any_named("title-project-name")
})
.with_cursor_style(CursorStyle::PointingHand)
.on_down(MouseButton::Left, move |_, this, cx| {
this.toggle_project_menu(&Default::default(), cx)
})
.on_click(MouseButton::Left, move |_, _, _| {}),
)
.with_children(self.render_project_popover_host(&theme.titlebar, cx)),
);
if let Some(git_branch) = branch_prepended {
ret = ret.with_child(
Flex::row()
.with_child(
Label::new("/", divider_style.text)
.contained()
.with_style(divider_style.container)
.aligned()
.left(),
)
.with_child(
Stack::new()
.with_child(
MouseEventHandler::<ToggleVcsMenu, Self>::new(
0,
cx,
|mouse_state, _| {
let style = git_style
.in_state(self.branch_popover.is_some())
.style_for(mouse_state);
Label::new(git_branch, style.text.clone())
.contained()
.with_style(style.container.clone())
.with_margin_right(item_spacing)
.aligned()
.left()
.into_any_named("title-project-branch")
},
)
.with_cursor_style(CursorStyle::PointingHand)
.on_down(MouseButton::Left, move |_, this, cx| {
this.toggle_vcs_menu(&Default::default(), cx)
})
.on_click(MouseButton::Left, move |_, _, _| {}),
)
.with_children(self.render_branches_popover_host(&theme.titlebar, cx)),
),
)
}
ret.into_any()
}
fn window_activation_changed(&mut self, active: bool, cx: &mut ViewContext<Self>) {
@@ -297,55 +351,167 @@ impl CollabTitlebarItem {
}
pub fn toggle_user_menu(&mut self, _: &ToggleUserMenu, cx: &mut ViewContext<Self>) {
let theme = theme::current(cx).clone();
let avatar_style = theme.workspace.titlebar.leader_avatar.clone();
let item_style = theme.context_menu.item.disabled_style().clone();
self.user_menu.update(cx, |user_menu, cx| {
let items = if let Some(user) = self.user_store.read(cx).current_user() {
let items = if let Some(_) = self.user_store.read(cx).current_user() {
vec![
ContextMenuItem::Static(Box::new(move |_| {
Flex::row()
.with_children(user.avatar.clone().map(|avatar| {
Self::render_face(
avatar,
avatar_style.clone(),
Color::transparent_black(),
)
}))
.with_child(Label::new(
user.github_login.clone(),
item_style.label.clone(),
))
.contained()
.with_style(item_style.container)
.into_any()
})),
ContextMenuItem::action("Sign out", SignOut),
ContextMenuItem::action("Settings", zed_actions::OpenSettings),
ContextMenuItem::action("Theme", theme_selector::Toggle),
ContextMenuItem::separator(),
ContextMenuItem::action(
"Send Feedback",
"Share Feedback",
feedback::feedback_editor::GiveFeedback,
),
ContextMenuItem::action("Sign out", SignOut),
]
} else {
vec![
ContextMenuItem::action("Sign in", SignIn),
ContextMenuItem::action("Settings", zed_actions::OpenSettings),
ContextMenuItem::action("Theme", theme_selector::Toggle),
ContextMenuItem::separator(),
ContextMenuItem::action(
"Send Feedback",
"Share Feedback",
feedback::feedback_editor::GiveFeedback,
),
]
};
user_menu.show(Default::default(), AnchorCorner::TopRight, items, cx);
user_menu.toggle(Default::default(), AnchorCorner::TopRight, items, cx);
});
}
fn render_branches_popover_host<'a>(
&'a self,
_theme: &'a theme::Titlebar,
cx: &'a mut ViewContext<Self>,
) -> Option<AnyElement<Self>> {
self.branch_popover.as_ref().map(|child| {
let theme = theme::current(cx).clone();
let child = ChildView::new(child, cx);
let child = MouseEventHandler::<BranchList, Self>::new(0, cx, |_, _| {
child
.flex(1., true)
.contained()
.constrained()
.with_width(theme.contacts_popover.width)
.with_height(theme.contacts_popover.height)
})
.on_click(MouseButton::Left, |_, _, _| {})
.on_down_out(MouseButton::Left, move |_, this, cx| {
this.branch_popover.take();
cx.emit(());
cx.notify();
})
.contained()
.into_any();
Overlay::new(child)
.with_fit_mode(OverlayFitMode::SwitchAnchor)
.with_anchor_corner(AnchorCorner::TopLeft)
.with_z_index(999)
.aligned()
.bottom()
.left()
.into_any()
})
}
fn render_project_popover_host<'a>(
&'a self,
_theme: &'a theme::Titlebar,
cx: &'a mut ViewContext<Self>,
) -> Option<AnyElement<Self>> {
self.project_popover.as_ref().map(|child| {
let theme = theme::current(cx).clone();
let child = ChildView::new(child, cx);
let child = MouseEventHandler::<RecentProjects, Self>::new(0, cx, |_, _| {
child
.flex(1., true)
.contained()
.constrained()
.with_width(theme.contacts_popover.width)
.with_height(theme.contacts_popover.height)
})
.on_click(MouseButton::Left, |_, _, _| {})
.on_down_out(MouseButton::Left, move |_, this, cx| {
this.project_popover.take();
cx.emit(());
cx.notify();
})
.into_any();
Overlay::new(child)
.with_fit_mode(OverlayFitMode::SwitchAnchor)
.with_anchor_corner(AnchorCorner::TopLeft)
.with_z_index(999)
.aligned()
.bottom()
.left()
.into_any()
})
}
pub fn toggle_vcs_menu(&mut self, _: &ToggleVcsMenu, cx: &mut ViewContext<Self>) {
if self.branch_popover.take().is_none() {
if let Some(workspace) = self.workspace.upgrade(cx) {
let view = cx.add_view(|cx| build_branch_list(workspace, cx));
cx.subscribe(&view, |this, _, event, cx| {
match event {
PickerEvent::Dismiss => {
this.branch_popover = None;
}
}
cx.notify();
})
.detach();
self.project_popover.take();
cx.focus(&view);
self.branch_popover = Some(view);
}
}
cx.notify();
}
pub fn toggle_project_menu(&mut self, _: &ToggleProjectMenu, cx: &mut ViewContext<Self>) {
let workspace = self.workspace.clone();
if self.project_popover.take().is_none() {
cx.spawn(|this, mut cx| async move {
let workspaces = WORKSPACE_DB
.recent_workspaces_on_disk()
.await
.unwrap_or_default()
.into_iter()
.map(|(_, location)| location)
.collect();
let workspace = workspace.clone();
this.update(&mut cx, move |this, cx| {
let view = cx.add_view(|cx| build_recent_projects(workspace, workspaces, cx));
cx.subscribe(&view, |this, _, event, cx| {
match event {
PickerEvent::Dismiss => {
this.project_popover = None;
}
}
cx.notify();
})
.detach();
cx.focus(&view);
this.branch_popover.take();
this.project_popover = Some(view);
cx.notify();
})
.log_err();
})
.detach();
}
cx.notify();
}
fn render_toggle_contacts_button(
&self,
theme: &Theme,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let titlebar = &theme.workspace.titlebar;
let titlebar = &theme.titlebar;
let badge = if self
.user_store
@@ -361,8 +527,20 @@ impl CollabTitlebarItem {
.contained()
.with_style(titlebar.toggle_contacts_badge)
.contained()
.with_margin_left(titlebar.toggle_contacts_button.default.icon_width)
.with_margin_top(titlebar.toggle_contacts_button.default.icon_width)
.with_margin_left(
titlebar
.toggle_contacts_button
.inactive_state()
.default
.icon_width,
)
.with_margin_top(
titlebar
.toggle_contacts_button
.inactive_state()
.default
.icon_width,
)
.aligned(),
)
};
@@ -372,8 +550,9 @@ impl CollabTitlebarItem {
MouseEventHandler::<ToggleContactsMenu, Self>::new(0, cx, |state, _| {
let style = titlebar
.toggle_contacts_button
.style_for(state, self.contacts_popover.is_some());
Svg::new("icons/user_plus_16.svg")
.in_state(self.contacts_popover.is_some())
.style_for(state);
Svg::new("icons/radix/person.svg")
.with_color(style.color)
.constrained()
.with_width(style.icon_width)
@@ -400,7 +579,6 @@ impl CollabTitlebarItem {
.with_children(self.render_contacts_popover_host(titlebar, cx))
.into_any()
}
fn render_toggle_screen_sharing_button(
&self,
theme: &Theme,
@@ -410,16 +588,21 @@ impl CollabTitlebarItem {
let icon;
let tooltip;
if room.read(cx).is_screen_sharing() {
icon = "icons/enable_screen_sharing_12.svg";
icon = "icons/radix/desktop.svg";
tooltip = "Stop Sharing Screen"
} else {
icon = "icons/disable_screen_sharing_12.svg";
icon = "icons/radix/desktop.svg";
tooltip = "Share Screen";
}
let titlebar = &theme.workspace.titlebar;
let active = room.read(cx).is_screen_sharing();
let titlebar = &theme.titlebar;
MouseEventHandler::<ToggleScreenSharing, Self>::new(0, cx, |state, _| {
let style = titlebar.call_control.style_for(state, false);
let style = titlebar
.screen_share_button
.in_state(active)
.style_for(state);
Svg::new(icon)
.with_color(style.color)
.constrained()
@@ -445,7 +628,141 @@ impl CollabTitlebarItem {
.aligned()
.into_any()
}
fn render_toggle_mute(
&self,
theme: &Theme,
room: &ModelHandle<Room>,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let icon;
let tooltip;
let is_muted = room.read(cx).is_muted();
if is_muted {
icon = "icons/radix/mic-mute.svg";
tooltip = "Unmute microphone\nRight click for options";
} else {
icon = "icons/radix/mic.svg";
tooltip = "Mute microphone\nRight click for options";
}
let titlebar = &theme.titlebar;
MouseEventHandler::<ToggleMute, Self>::new(0, cx, |state, _| {
let style = titlebar
.toggle_microphone_button
.in_state(is_muted)
.style_for(state);
let image = Svg::new(icon)
.with_color(style.color)
.constrained()
.with_width(style.icon_width)
.aligned()
.constrained()
.with_width(style.button_width)
.with_height(style.button_width)
.contained()
.with_style(style.container);
if let Some(color) = style.container.background_color {
image.with_background_color(color)
} else {
image
}
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, _, cx| {
toggle_mute(&Default::default(), cx)
})
.with_tooltip::<ToggleMute>(
0,
tooltip.into(),
Some(Box::new(ToggleMute)),
theme.tooltip.clone(),
cx,
)
.aligned()
.into_any()
}
fn render_toggle_deafen(
&self,
theme: &Theme,
room: &ModelHandle<Room>,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let icon;
let tooltip;
let is_deafened = room.read(cx).is_deafened().unwrap_or(false);
if is_deafened {
icon = "icons/radix/speaker-off.svg";
tooltip = "Unmute speakers\nRight click for options";
} else {
icon = "icons/radix/speaker-loud.svg";
tooltip = "Mute speakers\nRight click for options";
}
let titlebar = &theme.titlebar;
MouseEventHandler::<ToggleDeafen, Self>::new(0, cx, |state, _| {
let style = titlebar
.toggle_speakers_button
.in_state(is_deafened)
.style_for(state);
Svg::new(icon)
.with_color(style.color)
.constrained()
.with_width(style.icon_width)
.aligned()
.constrained()
.with_width(style.button_width)
.with_height(style.button_width)
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, _, cx| {
toggle_deafen(&Default::default(), cx)
})
.with_tooltip::<ToggleDeafen>(
0,
tooltip.into(),
Some(Box::new(ToggleDeafen)),
theme.tooltip.clone(),
cx,
)
.aligned()
.into_any()
}
fn render_leave_call(&self, theme: &Theme, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let icon = "icons/radix/exit.svg";
let tooltip = "Leave call";
let titlebar = &theme.titlebar;
MouseEventHandler::<LeaveCall, Self>::new(0, cx, |state, _| {
let style = titlebar.leave_call_button.style_for(state);
Svg::new(icon)
.with_color(style.color)
.constrained()
.with_width(style.icon_width)
.aligned()
.constrained()
.with_width(style.button_width)
.with_height(style.button_width)
.contained()
.with_style(style.container)
})
.with_cursor_style(CursorStyle::PointingHand)
.on_click(MouseButton::Left, move |_, _, cx| {
ActiveCall::global(cx)
.update(cx, |call, cx| call.hang_up(cx))
.detach_and_log_err(cx);
})
.with_tooltip::<LeaveCall>(
0,
tooltip.into(),
Some(Box::new(LeaveCall)),
theme.tooltip.clone(),
cx,
)
.aligned()
.into_any()
}
fn render_in_call_share_unshare_button(
&self,
workspace: &ViewHandle<Workspace>,
@@ -458,14 +775,14 @@ impl CollabTitlebarItem {
}
let is_shared = project.read(cx).is_shared();
let label = if is_shared { "Unshare" } else { "Share" };
let label = if is_shared { "Stop Sharing" } else { "Share" };
let tooltip = if is_shared {
"Unshare project from call participants"
"Stop sharing project with call participants"
} else {
"Share project with call participants"
};
let titlebar = &theme.workspace.titlebar;
let titlebar = &theme.titlebar;
enum ShareUnshare {}
Some(
@@ -473,7 +790,7 @@ impl CollabTitlebarItem {
.with_child(
MouseEventHandler::<ShareUnshare, Self>::new(0, cx, |state, _| {
//TODO: Ensure this button has consistent width for both text variations
let style = titlebar.share_button.style_for(state, false);
let style = titlebar.share_button.inactive_state().style_for(state);
Label::new(label, style.text.clone())
.contained()
.with_style(style.container)
@@ -496,7 +813,7 @@ impl CollabTitlebarItem {
)
.aligned()
.contained()
.with_margin_left(theme.workspace.titlebar.item_spacing)
.with_margin_left(theme.titlebar.item_spacing)
.into_any(),
)
}
@@ -504,26 +821,56 @@ impl CollabTitlebarItem {
fn render_user_menu_button(
&self,
theme: &Theme,
avatar: Option<Arc<ImageData>>,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let titlebar = &theme.workspace.titlebar;
let tooltip = theme.tooltip.clone();
let user_menu_button_style = if avatar.is_some() {
&theme.titlebar.user_menu.user_menu_button_online
} else {
&theme.titlebar.user_menu.user_menu_button_offline
};
let avatar_style = &user_menu_button_style.avatar;
Stack::new()
.with_child(
MouseEventHandler::<ToggleUserMenu, Self>::new(0, cx, |state, _| {
let style = titlebar.call_control.style_for(state, false);
Svg::new("icons/ellipsis_14.svg")
.with_color(style.color)
.constrained()
.with_width(style.icon_width)
let style = user_menu_button_style
.user_menu
.inactive_state()
.style_for(state);
let mut dropdown = Flex::row().align_children_center();
if let Some(avatar_img) = avatar {
dropdown = dropdown.with_child(Self::render_face(
avatar_img,
*avatar_style,
Color::transparent_black(),
None,
));
};
dropdown
.with_child(
Svg::new("icons/caret_down_8.svg")
.with_color(user_menu_button_style.icon.color)
.constrained()
.with_width(user_menu_button_style.icon.width)
.contained()
.into_any(),
)
.aligned()
.constrained()
.with_width(style.button_width)
.with_height(style.button_width)
.with_height(style.width)
.contained()
.with_style(style.container)
.into_any()
})
.with_cursor_style(CursorStyle::PointingHand)
.on_down(MouseButton::Left, move |_, this, cx| {
this.user_menu.update(cx, |menu, _| menu.delay_cancel());
})
.on_click(MouseButton::Left, move |_, this, cx| {
this.toggle_user_menu(&Default::default(), cx)
})
@@ -531,11 +878,10 @@ impl CollabTitlebarItem {
0,
"Toggle user menu".to_owned(),
Some(Box::new(ToggleUserMenu)),
theme.tooltip.clone(),
tooltip,
cx,
)
.contained()
.with_margin_left(theme.workspace.titlebar.item_spacing),
.contained(),
)
.with_child(
ChildView::new(&self.user_menu, cx)
@@ -547,9 +893,9 @@ impl CollabTitlebarItem {
}
fn render_sign_in_button(&self, theme: &Theme, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
let titlebar = &theme.workspace.titlebar;
let titlebar = &theme.titlebar;
MouseEventHandler::<SignIn, Self>::new(0, cx, |state, _| {
let style = titlebar.sign_in_prompt.style_for(state, false);
let style = titlebar.sign_in_button.inactive_state().style_for(state);
Label::new("Sign In", style.text.clone())
.contained()
.with_style(style.container)
@@ -572,7 +918,7 @@ impl CollabTitlebarItem {
self.contacts_popover.as_ref().map(|popover| {
Overlay::new(ChildView::new(popover, cx))
.with_fit_mode(OverlayFitMode::SwitchAnchor)
.with_anchor_corner(AnchorCorner::TopRight)
.with_anchor_corner(AnchorCorner::TopLeft)
.with_z_index(999)
.aligned()
.bottom()
@@ -611,11 +957,13 @@ impl CollabTitlebarItem {
replica_id,
participant.peer_id,
Some(participant.location),
participant.muted,
participant.speaking,
workspace,
theme,
cx,
))
.with_margin_right(theme.workspace.titlebar.face_pile_spacing),
.with_margin_right(theme.titlebar.face_pile_spacing),
)
})
.collect()
@@ -627,19 +975,24 @@ impl CollabTitlebarItem {
theme: &Theme,
user: &Arc<User>,
peer_id: PeerId,
muted: bool,
speaking: bool,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let replica_id = workspace.read(cx).project().read(cx).replica_id();
Container::new(self.render_face_pile(
user,
Some(replica_id),
peer_id,
None,
muted,
speaking,
workspace,
theme,
cx,
))
.with_margin_right(theme.workspace.titlebar.item_spacing)
.with_margin_right(theme.titlebar.item_spacing)
.into_any()
}
@@ -649,6 +1002,8 @@ impl CollabTitlebarItem {
replica_id: Option<ReplicaId>,
peer_id: PeerId,
location: Option<ParticipantLocation>,
muted: bool,
speaking: bool,
workspace: &ViewHandle<Workspace>,
theme: &Theme,
cx: &mut ViewContext<Self>,
@@ -671,15 +1026,23 @@ impl CollabTitlebarItem {
})
.unwrap_or(false);
let leader_style = theme.workspace.titlebar.leader_avatar;
let follower_style = theme.workspace.titlebar.follower_avatar;
let leader_style = theme.titlebar.leader_avatar;
let follower_style = theme.titlebar.follower_avatar;
let microphone_state = if muted {
Some(theme.titlebar.muted)
} else if speaking {
Some(theme.titlebar.speaking)
} else {
None
};
let mut background_color = theme
.workspace
.titlebar
.container
.background_color
.unwrap_or_default();
if let Some(replica_id) = replica_id {
if followed_by_self {
let selection = theme.editor.replica_selection_style(replica_id).selection;
@@ -690,11 +1053,12 @@ impl CollabTitlebarItem {
let mut content = Stack::new()
.with_children(user.avatar.as_ref().map(|avatar| {
let face_pile = FacePile::new(theme.workspace.titlebar.follower_avatar_overlap)
let face_pile = FacePile::new(theme.titlebar.follower_avatar_overlap)
.with_child(Self::render_face(
avatar.clone(),
Self::location_style(workspace, location, leader_style, cx),
background_color,
microphone_state,
))
.with_children(
(|| {
@@ -726,6 +1090,7 @@ impl CollabTitlebarItem {
avatar.clone(),
follower_style,
background_color,
None,
))
}))
})()
@@ -735,7 +1100,7 @@ impl CollabTitlebarItem {
let mut container = face_pile
.contained()
.with_style(theme.workspace.titlebar.leader_selection);
.with_style(theme.titlebar.leader_selection);
if let Some(replica_id) = replica_id {
if followed_by_self {
@@ -752,8 +1117,8 @@ impl CollabTitlebarItem {
Some(
AvatarRibbon::new(color)
.constrained()
.with_width(theme.workspace.titlebar.avatar_ribbon.width)
.with_height(theme.workspace.titlebar.avatar_ribbon.height)
.with_width(theme.titlebar.avatar_ribbon.width)
.with_height(theme.titlebar.avatar_ribbon.height)
.aligned()
.bottom(),
)
@@ -844,12 +1209,13 @@ impl CollabTitlebarItem {
avatar: Arc<ImageData>,
avatar_style: AvatarStyle,
background_color: Color,
microphone_state: Option<Color>,
) -> AnyElement<V> {
Image::from_data(avatar)
.with_style(avatar_style.image)
.aligned()
.contained()
.with_background_color(background_color)
.with_background_color(microphone_state.unwrap_or(background_color))
.with_corner_radius(avatar_style.outer_corner_radius)
.constrained()
.with_width(avatar_style.outer_width)
@@ -873,22 +1239,22 @@ impl CollabTitlebarItem {
| client::Status::Reconnecting { .. }
| client::Status::ReconnectionError { .. } => Some(
Svg::new("icons/cloud_slash_12.svg")
.with_color(theme.workspace.titlebar.offline_icon.color)
.with_color(theme.titlebar.offline_icon.color)
.constrained()
.with_width(theme.workspace.titlebar.offline_icon.width)
.with_width(theme.titlebar.offline_icon.width)
.aligned()
.contained()
.with_style(theme.workspace.titlebar.offline_icon.container)
.with_style(theme.titlebar.offline_icon.container)
.into_any(),
),
client::Status::UpgradeRequired => Some(
MouseEventHandler::<ConnectionStatusButton, Self>::new(0, cx, |_, _| {
Label::new(
"Please update Zed to collaborate",
theme.workspace.titlebar.outdated_warning.text.clone(),
theme.titlebar.outdated_warning.text.clone(),
)
.contained()
.with_style(theme.workspace.titlebar.outdated_warning.container)
.with_style(theme.titlebar.outdated_warning.container)
.aligned()
})
.with_cursor_style(CursorStyle::PointingHand)
+40 -2
View File
@@ -1,3 +1,4 @@
mod branch_list;
mod collab_titlebar_item;
mod contact_finder;
mod contact_list;
@@ -9,15 +10,26 @@ mod notifications;
mod project_shared_notification;
mod sharing_status_indicator;
use call::ActiveCall;
use call::{ActiveCall, Room};
pub use collab_titlebar_item::{CollabTitlebarItem, ToggleContactsMenu};
use gpui::{actions, AppContext, Task};
use std::sync::Arc;
use util::ResultExt;
use workspace::AppState;
actions!(collab, [ToggleScreenSharing]);
actions!(
collab,
[
ToggleScreenSharing,
ToggleMute,
ToggleDeafen,
LeaveCall,
ShareMicrophone
]
);
pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
branch_list::init(cx);
collab_titlebar_item::init(cx);
contact_list::init(cx);
contact_finder::init(cx);
@@ -27,6 +39,9 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut AppContext) {
sharing_status_indicator::init(cx);
cx.add_global_action(toggle_screen_sharing);
cx.add_global_action(toggle_mute);
cx.add_global_action(toggle_deafen);
cx.add_global_action(share_microphone);
}
pub fn toggle_screen_sharing(_: &ToggleScreenSharing, cx: &mut AppContext) {
@@ -41,3 +56,26 @@ pub fn toggle_screen_sharing(_: &ToggleScreenSharing, cx: &mut AppContext) {
toggle_screen_sharing.detach_and_log_err(cx);
}
}
pub fn toggle_mute(_: &ToggleMute, cx: &mut AppContext) {
if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
room.update(cx, Room::toggle_mute)
.map(|task| task.detach_and_log_err(cx))
.log_err();
}
}
pub fn toggle_deafen(_: &ToggleDeafen, cx: &mut AppContext) {
if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
room.update(cx, Room::toggle_deafen)
.map(|task| task.detach_and_log_err(cx))
.log_err();
}
}
pub fn share_microphone(_: &ShareMicrophone, cx: &mut AppContext) {
if let Some(room) = ActiveCall::global(cx).read(cx).room().cloned() {
room.update(cx, Room::share_microphone)
.detach_and_log_err(cx)
}
}
+2 -1
View File
@@ -117,7 +117,8 @@ impl PickerDelegate for ContactFinderDelegate {
.contact_finder
.picker
.item
.style_for(mouse_state, selected);
.in_state(selected)
.style_for(mouse_state);
Flex::row()
.with_children(user.avatar.clone().map(|avatar| {
Image::from_data(avatar)
+27 -18
View File
@@ -514,10 +514,10 @@ impl ContactList {
project_id: project.id,
worktree_root_names: project.worktree_root_names.clone(),
host_user_id: participant.user.id,
is_last: projects.peek().is_none() && participant.tracks.is_empty(),
is_last: projects.peek().is_none() && participant.video_tracks.is_empty(),
});
}
if !participant.tracks.is_empty() {
if !participant.video_tracks.is_empty() {
participant_entries.push(ContactEntry::ParticipantScreen {
peer_id: participant.peer_id,
is_last: true,
@@ -774,7 +774,8 @@ impl ContactList {
.with_style(
*theme
.contact_row
.style_for(&mut Default::default(), is_selected),
.in_state(is_selected)
.style_for(&mut Default::default()),
)
.into_any()
}
@@ -797,7 +798,7 @@ impl ContactList {
.width
.or(theme.contact_avatar.height)
.unwrap_or(0.);
let row = &theme.project_row.default;
let row = &theme.project_row.inactive_state().default;
let tree_branch = theme.tree_branch;
let line_height = row.name.text.line_height(font_cache);
let cap_height = row.name.text.cap_height(font_cache);
@@ -810,8 +811,11 @@ impl ContactList {
};
MouseEventHandler::<JoinProject, Self>::new(project_id as usize, cx, |mouse_state, _| {
let tree_branch = *tree_branch.style_for(mouse_state, is_selected);
let row = theme.project_row.style_for(mouse_state, is_selected);
let tree_branch = *tree_branch.in_state(is_selected).style_for(mouse_state);
let row = theme
.project_row
.in_state(is_selected)
.style_for(mouse_state);
Flex::row()
.with_child(
@@ -893,7 +897,7 @@ impl ContactList {
.width
.or(theme.contact_avatar.height)
.unwrap_or(0.);
let row = &theme.project_row.default;
let row = &theme.project_row.inactive_state().default;
let tree_branch = theme.tree_branch;
let line_height = row.name.text.line_height(font_cache);
let cap_height = row.name.text.cap_height(font_cache);
@@ -904,8 +908,11 @@ impl ContactList {
peer_id.as_u64() as usize,
cx,
|mouse_state, _| {
let tree_branch = *tree_branch.style_for(mouse_state, is_selected);
let row = theme.project_row.style_for(mouse_state, is_selected);
let tree_branch = *tree_branch.in_state(is_selected).style_for(mouse_state);
let row = theme
.project_row
.in_state(is_selected)
.style_for(mouse_state);
Flex::row()
.with_child(
@@ -989,7 +996,8 @@ impl ContactList {
let header_style = theme
.header_row
.style_for(&mut Default::default(), is_selected);
.in_state(is_selected)
.style_for(&mut Default::default());
let text = match section {
Section::ActiveCall => "Collaborators",
Section::Requests => "Contact Requests",
@@ -999,7 +1007,7 @@ impl ContactList {
let leave_call = if section == Section::ActiveCall {
Some(
MouseEventHandler::<LeaveCallContactList, Self>::new(0, cx, |state, _| {
let style = theme.leave_call.style_for(state, false);
let style = theme.leave_call.style_for(state);
Label::new("Leave Call", style.text.clone())
.contained()
.with_style(style.container)
@@ -1110,8 +1118,7 @@ impl ContactList {
contact.user.id as usize,
cx,
|mouse_state, _| {
let button_style =
theme.contact_button.style_for(mouse_state, false);
let button_style = theme.contact_button.style_for(mouse_state);
render_icon_button(button_style, "icons/x_mark_8.svg")
.aligned()
.flex_float()
@@ -1146,7 +1153,8 @@ impl ContactList {
.with_style(
*theme
.contact_row
.style_for(&mut Default::default(), is_selected),
.in_state(is_selected)
.style_for(&mut Default::default()),
)
})
.on_click(MouseButton::Left, move |_, this, cx| {
@@ -1204,7 +1212,7 @@ impl ContactList {
let button_style = if is_contact_request_pending {
&theme.disabled_button
} else {
theme.contact_button.style_for(mouse_state, false)
theme.contact_button.style_for(mouse_state)
};
render_icon_button(button_style, "icons/x_mark_8.svg").aligned()
})
@@ -1227,7 +1235,7 @@ impl ContactList {
let button_style = if is_contact_request_pending {
&theme.disabled_button
} else {
theme.contact_button.style_for(mouse_state, false)
theme.contact_button.style_for(mouse_state)
};
render_icon_button(button_style, "icons/check_8.svg")
.aligned()
@@ -1250,7 +1258,7 @@ impl ContactList {
let button_style = if is_contact_request_pending {
&theme.disabled_button
} else {
theme.contact_button.style_for(mouse_state, false)
theme.contact_button.style_for(mouse_state)
};
render_icon_button(button_style, "icons/x_mark_8.svg")
.aligned()
@@ -1277,7 +1285,8 @@ impl ContactList {
.with_style(
*theme
.contact_row
.style_for(&mut Default::default(), is_selected),
.in_state(is_selected)
.style_for(&mut Default::default()),
)
.into_any()
}
+2 -2
View File
@@ -53,7 +53,7 @@ where
)
.with_child(
MouseEventHandler::<Dismiss, V>::new(user.id as usize, cx, |state, _| {
let style = theme.dismiss_button.style_for(state, false);
let style = theme.dismiss_button.style_for(state);
Svg::new("icons/x_mark_8.svg")
.with_color(style.color)
.constrained()
@@ -93,7 +93,7 @@ where
.with_children(buttons.into_iter().enumerate().map(
|(ix, (message, handler))| {
MouseEventHandler::<Button, V>::new(ix, cx, |state, _| {
let button = theme.button.style_for(state, false);
let button = theme.button.style_for(state);
Label::new(message, button.text.clone())
.contained()
.with_style(button.container)
@@ -185,8 +185,8 @@ impl PickerDelegate for CommandPaletteDelegate {
let mat = &self.matches[ix];
let command = &self.actions[mat.candidate_id];
let theme = theme::current(cx);
let style = theme.picker.item.style_for(mouse_state, selected);
let key_style = &theme.command_palette.key.style_for(mouse_state, selected);
let style = theme.picker.item.in_state(selected).style_for(mouse_state);
let key_style = &theme.command_palette.key.in_state(selected);
let keystroke_spacing = theme.command_palette.keystroke_spacing;
Flex::row()
+51 -18
View File
@@ -124,6 +124,7 @@ pub struct ContextMenu {
items: Vec<ContextMenuItem>,
selected_index: Option<usize>,
visible: bool,
delay_cancel: bool,
previously_focused_view_id: Option<usize>,
parent_view_id: usize,
_actions_observation: Subscription,
@@ -178,6 +179,7 @@ impl ContextMenu {
pub fn new(parent_view_id: usize, cx: &mut ViewContext<Self>) -> Self {
Self {
show_count: 0,
delay_cancel: false,
anchor_position: Default::default(),
anchor_corner: AnchorCorner::TopLeft,
position_mode: OverlayPositionMode::Window,
@@ -232,15 +234,22 @@ impl ContextMenu {
}
}
pub fn delay_cancel(&mut self) {
self.delay_cancel = true;
}
fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
self.reset(cx);
let show_count = self.show_count;
cx.defer(move |this, cx| {
if cx.handle().is_focused(cx) && this.show_count == show_count {
let window_id = cx.window_id();
(**cx).focus(window_id, this.previously_focused_view_id.take());
}
});
if !self.delay_cancel {
self.reset(cx);
let show_count = self.show_count;
cx.defer(move |this, cx| {
if cx.handle().is_focused(cx) && this.show_count == show_count {
(**cx).focus(this.previously_focused_view_id.take());
}
});
} else {
self.delay_cancel = false;
}
}
fn reset(&mut self, cx: &mut ViewContext<Self>) {
@@ -293,6 +302,34 @@ impl ContextMenu {
}
}
pub fn toggle(
&mut self,
anchor_position: Vector2F,
anchor_corner: AnchorCorner,
items: Vec<ContextMenuItem>,
cx: &mut ViewContext<Self>,
) {
if self.visible() {
self.cancel(&Cancel, cx);
} else {
let mut items = items.into_iter().peekable();
if items.peek().is_some() {
self.items = items.collect();
self.anchor_position = anchor_position;
self.anchor_corner = anchor_corner;
self.visible = true;
self.show_count += 1;
if !cx.is_self_focused() {
self.previously_focused_view_id = cx.focused_view_id();
}
cx.focus_self();
} else {
self.visible = false;
}
}
cx.notify();
}
pub fn show(
&mut self,
anchor_position: Vector2F,
@@ -328,10 +365,8 @@ impl ContextMenu {
Flex::column().with_children(self.items.iter().enumerate().map(|(ix, item)| {
match item {
ContextMenuItem::Item { label, .. } => {
let style = style.item.style_for(
&mut Default::default(),
Some(ix) == self.selected_index,
);
let style = style.item.in_state(self.selected_index == Some(ix));
let style = style.style_for(&mut Default::default());
match label {
ContextMenuItemLabel::String(label) => {
@@ -363,10 +398,8 @@ impl ContextMenu {
.with_children(self.items.iter().enumerate().map(|(ix, item)| {
match item {
ContextMenuItem::Item { action, .. } => {
let style = style.item.style_for(
&mut Default::default(),
Some(ix) == self.selected_index,
);
let style = style.item.in_state(self.selected_index == Some(ix));
let style = style.style_for(&mut Default::default());
match action {
ContextMenuItemAction::Action(action) => KeystrokeLabel::new(
@@ -412,8 +445,8 @@ impl ContextMenu {
let action = action.clone();
let view_id = self.parent_view_id;
MouseEventHandler::<MenuItem, ContextMenu>::new(ix, cx, |state, _| {
let style =
style.item.style_for(state, Some(ix) == self.selected_index);
let style = style.item.in_state(self.selected_index == Some(ix));
let style = style.style_for(state);
let keystroke = match &action {
ContextMenuItemAction::Action(action) => Some(
KeystrokeLabel::new(
+8 -5
View File
@@ -15,7 +15,7 @@ use language::{
ToPointUtf16,
};
use log::{debug, error};
use lsp::{LanguageServer, LanguageServerId};
use lsp::{LanguageServer, LanguageServerBinary, LanguageServerId};
use node_runtime::NodeRuntime;
use request::{LogMessage, StatusNotification};
use settings::SettingsStore;
@@ -340,7 +340,7 @@ impl Copilot {
let http = util::http::FakeHttpClient::create(|_| async { unreachable!() });
let this = cx.add_model(|cx| Self {
http: http.clone(),
node_runtime: NodeRuntime::new(http, cx.background().clone()),
node_runtime: NodeRuntime::instance(http, cx.background().clone()),
server: CopilotServer::Running(RunningCopilotServer {
lsp: Arc::new(server),
sign_in_status: SignInStatus::Authorized,
@@ -361,11 +361,14 @@ impl Copilot {
let start_language_server = async {
let server_path = get_copilot_lsp(http).await?;
let node_path = node_runtime.binary_path().await?;
let arguments: &[OsString] = &[server_path.into(), "--stdio".into()];
let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
let binary = LanguageServerBinary {
path: node_path,
arguments,
};
let server = LanguageServer::new(
LanguageServerId(0),
&node_path,
arguments,
binary,
Path::new("/"),
None,
cx.clone(),
+3 -3
View File
@@ -127,16 +127,16 @@ impl CopilotCodeVerification {
.with_child(
Label::new(
if copied { "Copied!" } else { "Copy" },
device_code_style.cta.style_for(state, false).text.clone(),
device_code_style.cta.style_for(state).text.clone(),
)
.aligned()
.contained()
.with_style(*device_code_style.right_container.style_for(state, false))
.with_style(*device_code_style.right_container.style_for(state))
.constrained()
.with_width(device_code_style.right),
)
.contained()
.with_style(device_code_style.cta.style_for(state, false).container)
.with_style(device_code_style.cta.style_for(state).container)
})
.on_click(gpui::platform::MouseButton::Left, {
let user_code = data.user_code.clone();
+8 -4
View File
@@ -71,7 +71,8 @@ impl View for CopilotButton {
.status_bar
.panel_buttons
.button
.style_for(state, active);
.in_state(active)
.style_for(state);
Flex::row()
.with_child(
@@ -101,6 +102,9 @@ impl View for CopilotButton {
}
})
.with_cursor_style(CursorStyle::PointingHand)
.on_down(MouseButton::Left, |_, this, cx| {
this.popup_menu.update(cx, |menu, _| menu.delay_cancel());
})
.on_click(MouseButton::Left, {
let status = status.clone();
move |_, this, cx| match status {
@@ -185,7 +189,7 @@ impl CopilotButton {
}));
self.popup_menu.update(cx, |menu, cx| {
menu.show(
menu.toggle(
Default::default(),
AnchorCorner::BottomRight,
menu_options,
@@ -255,7 +259,7 @@ impl CopilotButton {
move |state: &mut MouseState, style: &theme::ContextMenuItem| {
Flex::row()
.with_child(Label::new("Copilot Settings", style.label.clone()))
.with_child(theme::ui::icon(icon_style.style_for(state, false)))
.with_child(theme::ui::icon(icon_style.style_for(state)))
.align_children_center()
.into_any()
},
@@ -265,7 +269,7 @@ impl CopilotButton {
menu_options.push(ContextMenuItem::action("Sign Out", SignOut));
self.popup_menu.update(cx, |menu, cx| {
menu.show(
menu.toggle(
Default::default(),
AnchorCorner::BottomRight,
menu_options,
+3 -1
View File
@@ -1509,7 +1509,8 @@ mod tests {
let snapshot = editor.snapshot(cx);
snapshot
.blocks_in_range(0..snapshot.max_point().row())
.filter_map(|(row, block)| {
.enumerate()
.filter_map(|(ix, (row, block))| {
let name = match block {
TransformBlock::Custom(block) => block
.render(&mut BlockContext {
@@ -1520,6 +1521,7 @@ mod tests {
gutter_width: 0.,
line_height: 0.,
em_width: 0.,
block_id: ix,
})
.name()?
.to_string(),
+2 -2
View File
@@ -100,7 +100,7 @@ impl View for DiagnosticIndicator {
.workspace
.status_bar
.diagnostic_summary
.style_for(state, false);
.style_for(state);
let mut summary_row = Flex::row();
if self.summary.error_count > 0 {
@@ -198,7 +198,7 @@ impl View for DiagnosticIndicator {
MouseEventHandler::<Message, _>::new(1, cx, |state, _| {
Label::new(
diagnostic.message.split('\n').next().unwrap().to_string(),
message_style.style_for(state, false).text.clone(),
message_style.style_for(state).text.clone(),
)
.aligned()
.contained()
+86 -70
View File
@@ -1,24 +1,23 @@
mod block_map;
mod fold_map;
mod suggestion_map;
mod inlay_map;
mod tab_map;
mod wrap_map;
use crate::{Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint};
use crate::{Anchor, AnchorRangeExt, InlayId, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint};
pub use block_map::{BlockMap, BlockPoint};
use collections::{HashMap, HashSet};
use fold_map::{FoldMap, FoldOffset};
use fold_map::FoldMap;
use gpui::{
color::Color,
fonts::{FontId, HighlightStyle},
Entity, ModelContext, ModelHandle,
};
use inlay_map::InlayMap;
use language::{
language_settings::language_settings, OffsetUtf16, Point, Subscription as BufferSubscription,
};
use std::{any::TypeId, fmt::Debug, num::NonZeroU32, ops::Range, sync::Arc};
pub use suggestion_map::Suggestion;
use suggestion_map::SuggestionMap;
use sum_tree::{Bias, TreeMap};
use tab_map::TabMap;
use wrap_map::WrapMap;
@@ -28,6 +27,8 @@ pub use block_map::{
BlockDisposition, BlockId, BlockProperties, BlockStyle, RenderBlock, TransformBlock,
};
pub use self::inlay_map::Inlay;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum FoldStatus {
Folded,
@@ -44,7 +45,7 @@ pub struct DisplayMap {
buffer: ModelHandle<MultiBuffer>,
buffer_subscription: BufferSubscription,
fold_map: FoldMap,
suggestion_map: SuggestionMap,
inlay_map: InlayMap,
tab_map: TabMap,
wrap_map: ModelHandle<WrapMap>,
block_map: BlockMap,
@@ -69,8 +70,8 @@ impl DisplayMap {
let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
let tab_size = Self::tab_size(&buffer, cx);
let (fold_map, snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
let (suggestion_map, snapshot) = SuggestionMap::new(snapshot);
let (inlay_map, snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
let (fold_map, snapshot) = FoldMap::new(snapshot);
let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
let (wrap_map, snapshot) = WrapMap::new(snapshot, font_id, font_size, wrap_width, cx);
let block_map = BlockMap::new(snapshot, buffer_header_height, excerpt_header_height);
@@ -79,7 +80,7 @@ impl DisplayMap {
buffer,
buffer_subscription,
fold_map,
suggestion_map,
inlay_map,
tab_map,
wrap_map,
block_map,
@@ -88,16 +89,13 @@ impl DisplayMap {
}
}
pub fn snapshot(&self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
pub fn snapshot(&mut self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let (fold_snapshot, edits) = self.fold_map.read(buffer_snapshot, edits);
let (suggestion_snapshot, edits) = self.suggestion_map.sync(fold_snapshot.clone(), edits);
let (inlay_snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
let (fold_snapshot, edits) = self.fold_map.read(inlay_snapshot.clone(), edits);
let tab_size = Self::tab_size(&self.buffer, cx);
let (tab_snapshot, edits) = self
.tab_map
.sync(suggestion_snapshot.clone(), edits, tab_size);
let (tab_snapshot, edits) = self.tab_map.sync(fold_snapshot.clone(), edits, tab_size);
let (wrap_snapshot, edits) = self
.wrap_map
.update(cx, |map, cx| map.sync(tab_snapshot.clone(), edits, cx));
@@ -106,7 +104,7 @@ impl DisplayMap {
DisplaySnapshot {
buffer_snapshot: self.buffer.read(cx).snapshot(cx),
fold_snapshot,
suggestion_snapshot,
inlay_snapshot,
tab_snapshot,
wrap_snapshot,
block_snapshot,
@@ -132,15 +130,14 @@ impl DisplayMap {
let snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let tab_size = Self::tab_size(&self.buffer, cx);
let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
.update(cx, |map, cx| map.sync(snapshot, edits, cx));
self.block_map.read(snapshot, edits);
let (snapshot, edits) = fold_map.fold(ranges);
let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
@@ -157,15 +154,14 @@ impl DisplayMap {
let snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let tab_size = Self::tab_size(&self.buffer, cx);
let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
.update(cx, |map, cx| map.sync(snapshot, edits, cx));
self.block_map.read(snapshot, edits);
let (snapshot, edits) = fold_map.unfold(ranges, inclusive);
let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
@@ -181,8 +177,8 @@ impl DisplayMap {
let snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let tab_size = Self::tab_size(&self.buffer, cx);
let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
let (snapshot, edits) = self.fold_map.read(snapshot, edits);
let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
@@ -199,8 +195,8 @@ impl DisplayMap {
let snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let tab_size = Self::tab_size(&self.buffer, cx);
let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
let (snapshot, edits) = self.fold_map.read(snapshot, edits);
let (snapshot, edits) = self.suggestion_map.sync(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
@@ -231,32 +227,6 @@ impl DisplayMap {
self.text_highlights.remove(&Some(type_id))
}
pub fn has_suggestion(&self) -> bool {
self.suggestion_map.has_suggestion()
}
pub fn replace_suggestion<T>(
&self,
new_suggestion: Option<Suggestion<T>>,
cx: &mut ModelContext<Self>,
) -> Option<Suggestion<FoldOffset>>
where
T: ToPoint,
{
let snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let tab_size = Self::tab_size(&self.buffer, cx);
let (snapshot, edits) = self.fold_map.read(snapshot, edits);
let (snapshot, edits, old_suggestion) =
self.suggestion_map.replace(new_suggestion, snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
.update(cx, |map, cx| map.sync(snapshot, edits, cx));
self.block_map.read(snapshot, edits);
old_suggestion
}
pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) -> bool {
self.wrap_map
.update(cx, |map, cx| map.set_font(font_id, font_size, cx))
@@ -271,6 +241,39 @@ impl DisplayMap {
.update(cx, |map, cx| map.set_wrap_width(width, cx))
}
pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
self.inlay_map.current_inlays()
}
pub fn splice_inlays(
&mut self,
to_remove: Vec<InlayId>,
to_insert: Vec<Inlay>,
cx: &mut ModelContext<Self>,
) {
if to_remove.is_empty() && to_insert.is_empty() {
return;
}
let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
let edits = self.buffer_subscription.consume().into_inner();
let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
let (snapshot, edits) = self.fold_map.read(snapshot, edits);
let tab_size = Self::tab_size(&self.buffer, cx);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
.update(cx, |map, cx| map.sync(snapshot, edits, cx));
self.block_map.read(snapshot, edits);
let (snapshot, edits) = self.inlay_map.splice(to_remove, to_insert);
let (snapshot, edits) = self.fold_map.read(snapshot, edits);
let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
let (snapshot, edits) = self
.wrap_map
.update(cx, |map, cx| map.sync(snapshot, edits, cx));
self.block_map.read(snapshot, edits);
}
fn tab_size(buffer: &ModelHandle<MultiBuffer>, cx: &mut ModelContext<Self>) -> NonZeroU32 {
let language = buffer
.read(cx)
@@ -288,7 +291,7 @@ impl DisplayMap {
pub struct DisplaySnapshot {
pub buffer_snapshot: MultiBufferSnapshot,
fold_snapshot: fold_map::FoldSnapshot,
suggestion_snapshot: suggestion_map::SuggestionSnapshot,
inlay_snapshot: inlay_map::InlaySnapshot,
tab_snapshot: tab_map::TabSnapshot,
wrap_snapshot: wrap_map::WrapSnapshot,
block_snapshot: block_map::BlockSnapshot,
@@ -316,9 +319,11 @@ impl DisplaySnapshot {
pub fn prev_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
loop {
let mut fold_point = self.fold_snapshot.to_fold_point(point, Bias::Left);
*fold_point.column_mut() = 0;
point = fold_point.to_buffer_point(&self.fold_snapshot);
let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Left);
fold_point.0.column = 0;
inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
point = self.inlay_snapshot.to_buffer_point(inlay_point);
let mut display_point = self.point_to_display_point(point, Bias::Left);
*display_point.column_mut() = 0;
@@ -332,9 +337,11 @@ impl DisplaySnapshot {
pub fn next_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
loop {
let mut fold_point = self.fold_snapshot.to_fold_point(point, Bias::Right);
*fold_point.column_mut() = self.fold_snapshot.line_len(fold_point.row());
point = fold_point.to_buffer_point(&self.fold_snapshot);
let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Right);
fold_point.0.column = self.fold_snapshot.line_len(fold_point.row());
inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
point = self.inlay_snapshot.to_buffer_point(inlay_point);
let mut display_point = self.point_to_display_point(point, Bias::Right);
*display_point.column_mut() = self.line_len(display_point.row());
@@ -364,9 +371,9 @@ impl DisplaySnapshot {
}
fn point_to_display_point(&self, point: Point, bias: Bias) -> DisplayPoint {
let fold_point = self.fold_snapshot.to_fold_point(point, bias);
let suggestion_point = self.suggestion_snapshot.to_suggestion_point(fold_point);
let tab_point = self.tab_snapshot.to_tab_point(suggestion_point);
let inlay_point = self.inlay_snapshot.to_inlay_point(point);
let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
let tab_point = self.tab_snapshot.to_tab_point(fold_point);
let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
let block_point = self.block_snapshot.to_block_point(wrap_point);
DisplayPoint(block_point)
@@ -376,9 +383,9 @@ impl DisplaySnapshot {
let block_point = point.0;
let wrap_point = self.block_snapshot.to_wrap_point(block_point);
let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
let suggestion_point = self.tab_snapshot.to_suggestion_point(tab_point, bias).0;
let fold_point = self.suggestion_snapshot.to_fold_point(suggestion_point);
fold_point.to_buffer_point(&self.fold_snapshot)
let fold_point = self.tab_snapshot.to_fold_point(tab_point, bias).0;
let inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
self.inlay_snapshot.to_buffer_point(inlay_point)
}
pub fn max_point(&self) -> DisplayPoint {
@@ -388,7 +395,13 @@ impl DisplaySnapshot {
/// Returns text chunks starting at the given display row until the end of the file
pub fn text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
self.block_snapshot
.chunks(display_row..self.max_point().row() + 1, false, None, None)
.chunks(
display_row..self.max_point().row() + 1,
false,
None,
None,
None,
)
.map(|h| h.text)
}
@@ -396,7 +409,7 @@ impl DisplaySnapshot {
pub fn reverse_text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
(0..=display_row).into_iter().rev().flat_map(|row| {
self.block_snapshot
.chunks(row..row + 1, false, None, None)
.chunks(row..row + 1, false, None, None, None)
.map(|h| h.text)
.collect::<Vec<_>>()
.into_iter()
@@ -408,13 +421,15 @@ impl DisplaySnapshot {
&self,
display_rows: Range<u32>,
language_aware: bool,
suggestion_highlight: Option<HighlightStyle>,
hint_highlights: Option<HighlightStyle>,
suggestion_highlights: Option<HighlightStyle>,
) -> DisplayChunks<'_> {
self.block_snapshot.chunks(
display_rows,
language_aware,
Some(&self.text_highlights),
suggestion_highlight,
hint_highlights,
suggestion_highlights,
)
}
@@ -790,9 +805,10 @@ impl DisplayPoint {
pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
let wrap_point = map.block_snapshot.to_wrap_point(self.0);
let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
let suggestion_point = map.tab_snapshot.to_suggestion_point(tab_point, bias).0;
let fold_point = map.suggestion_snapshot.to_fold_point(suggestion_point);
fold_point.to_buffer_offset(&map.fold_snapshot)
let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
map.inlay_snapshot
.to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
}
}
@@ -1706,7 +1722,7 @@ pub mod tests {
) -> Vec<(String, Option<Color>, Option<Color>)> {
let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
for chunk in snapshot.chunks(rows, true, None) {
for chunk in snapshot.chunks(rows, true, None, None) {
let syntax_color = chunk
.syntax_highlight_id
.and_then(|id| id.style(theme)?.color);
+43 -37
View File
@@ -88,6 +88,7 @@ pub struct BlockContext<'a, 'b, 'c> {
pub gutter_padding: f32,
pub em_width: f32,
pub line_height: f32,
pub block_id: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
@@ -243,7 +244,7 @@ impl BlockMap {
// Preserve any old transforms that precede this edit.
let old_start = WrapRow(edit.old.start);
let new_start = WrapRow(edit.new.start);
new_transforms.push_tree(cursor.slice(&old_start, Bias::Left, &()), &());
new_transforms.append(cursor.slice(&old_start, Bias::Left, &()), &());
if let Some(transform) = cursor.item() {
if transform.is_isomorphic() && old_start == cursor.end(&()) {
new_transforms.push(transform.clone(), &());
@@ -425,7 +426,7 @@ impl BlockMap {
push_isomorphic(&mut new_transforms, extent_after_edit);
}
new_transforms.push_tree(cursor.suffix(&()), &());
new_transforms.append(cursor.suffix(&()), &());
debug_assert_eq!(
new_transforms.summary().input_rows,
wrap_snapshot.max_point().row() + 1
@@ -572,9 +573,15 @@ impl<'a> BlockMapWriter<'a> {
impl BlockSnapshot {
#[cfg(test)]
pub fn text(&self) -> String {
self.chunks(0..self.transforms.summary().output_rows, false, None, None)
.map(|chunk| chunk.text)
.collect()
self.chunks(
0..self.transforms.summary().output_rows,
false,
None,
None,
None,
)
.map(|chunk| chunk.text)
.collect()
}
pub fn chunks<'a>(
@@ -582,7 +589,8 @@ impl BlockSnapshot {
rows: Range<u32>,
language_aware: bool,
text_highlights: Option<&'a TextHighlights>,
suggestion_highlight: Option<HighlightStyle>,
hint_highlights: Option<HighlightStyle>,
suggestion_highlights: Option<HighlightStyle>,
) -> BlockChunks<'a> {
let max_output_row = cmp::min(rows.end, self.transforms.summary().output_rows);
let mut cursor = self.transforms.cursor::<(BlockRow, WrapRow)>();
@@ -615,7 +623,8 @@ impl BlockSnapshot {
input_start..input_end,
language_aware,
text_highlights,
suggestion_highlight,
hint_highlights,
suggestion_highlights,
),
input_chunk: Default::default(),
transforms: cursor,
@@ -988,7 +997,7 @@ fn offset_for_row(s: &str, target: u32) -> (u32, usize) {
#[cfg(test)]
mod tests {
use super::*;
use crate::display_map::suggestion_map::SuggestionMap;
use crate::display_map::inlay_map::InlayMap;
use crate::display_map::{fold_map::FoldMap, tab_map::TabMap, wrap_map::WrapMap};
use crate::multi_buffer::MultiBuffer;
use gpui::{elements::Empty, Element};
@@ -1029,9 +1038,9 @@ mod tests {
let buffer = MultiBuffer::build_simple(text, cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
let (fold_map, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (suggestion_map, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (tab_map, tab_snapshot) = TabMap::new(suggestion_snapshot, 1.try_into().unwrap());
let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (mut tab_map, tab_snapshot) = TabMap::new(fold_snapshot, 1.try_into().unwrap());
let (wrap_map, wraps_snapshot) = WrapMap::new(tab_snapshot, font_id, 14.0, None, cx);
let mut block_map = BlockMap::new(wraps_snapshot.clone(), 1, 1);
@@ -1174,12 +1183,11 @@ mod tests {
buffer.snapshot(cx)
});
let (fold_snapshot, fold_edits) =
fold_map.read(buffer_snapshot, subscription.consume().into_inner());
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.sync(fold_snapshot, fold_edits);
let (inlay_snapshot, inlay_edits) =
inlay_map.sync(buffer_snapshot, subscription.consume().into_inner());
let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
let (tab_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, 4.try_into().unwrap());
tab_map.sync(fold_snapshot, fold_edits, 4.try_into().unwrap());
let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
wrap_map.sync(tab_snapshot, tab_edits, cx)
});
@@ -1204,9 +1212,9 @@ mod tests {
let buffer = MultiBuffer::build_simple(text, cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let (_, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (_, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (_, tab_snapshot) = TabMap::new(suggestion_snapshot, 1.try_into().unwrap());
let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (_, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
let (_, wraps_snapshot) = WrapMap::new(tab_snapshot, font_id, 14.0, Some(60.), cx);
let mut block_map = BlockMap::new(wraps_snapshot.clone(), 1, 1);
@@ -1276,9 +1284,9 @@ mod tests {
};
let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
let (fold_map, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (suggestion_map, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (tab_map, tab_snapshot) = TabMap::new(suggestion_snapshot, tab_size);
let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (mut tab_map, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
let (wrap_map, wraps_snapshot) =
WrapMap::new(tab_snapshot, font_id, font_size, wrap_width, cx);
let mut block_map = BlockMap::new(
@@ -1331,12 +1339,11 @@ mod tests {
})
.collect::<Vec<_>>();
let (fold_snapshot, fold_edits) =
fold_map.read(buffer_snapshot.clone(), vec![]);
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.sync(fold_snapshot, fold_edits);
let (inlay_snapshot, inlay_edits) =
inlay_map.sync(buffer_snapshot.clone(), vec![]);
let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
let (tab_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, tab_size);
tab_map.sync(fold_snapshot, fold_edits, tab_size);
let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
wrap_map.sync(tab_snapshot, tab_edits, cx)
});
@@ -1356,12 +1363,11 @@ mod tests {
})
.collect();
let (fold_snapshot, fold_edits) =
fold_map.read(buffer_snapshot.clone(), vec![]);
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.sync(fold_snapshot, fold_edits);
let (inlay_snapshot, inlay_edits) =
inlay_map.sync(buffer_snapshot.clone(), vec![]);
let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
let (tab_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, tab_size);
tab_map.sync(fold_snapshot, fold_edits, tab_size);
let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
wrap_map.sync(tab_snapshot, tab_edits, cx)
});
@@ -1380,11 +1386,10 @@ mod tests {
}
}
let (fold_snapshot, fold_edits) = fold_map.read(buffer_snapshot.clone(), buffer_edits);
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.sync(fold_snapshot, fold_edits);
let (tab_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, tab_size);
let (inlay_snapshot, inlay_edits) =
inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
let (tab_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
let (wraps_snapshot, wrap_edits) = wrap_map.update(cx, |wrap_map, cx| {
wrap_map.sync(tab_snapshot, tab_edits, cx)
});
@@ -1498,6 +1503,7 @@ mod tests {
false,
None,
None,
None,
)
.map(|chunk| chunk.text)
.collect::<String>();
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,871 +0,0 @@
use super::{
fold_map::{FoldBufferRows, FoldChunks, FoldEdit, FoldOffset, FoldPoint, FoldSnapshot},
TextHighlights,
};
use crate::{MultiBufferSnapshot, ToPoint};
use gpui::fonts::HighlightStyle;
use language::{Bias, Chunk, Edit, Patch, Point, Rope, TextSummary};
use parking_lot::Mutex;
use std::{
cmp,
ops::{Add, AddAssign, Range, Sub},
};
use util::post_inc;
pub type SuggestionEdit = Edit<SuggestionOffset>;
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
pub struct SuggestionOffset(pub usize);
impl Add for SuggestionOffset {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
impl Sub for SuggestionOffset {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self(self.0 - rhs.0)
}
}
impl AddAssign for SuggestionOffset {
fn add_assign(&mut self, rhs: Self) {
self.0 += rhs.0;
}
}
#[derive(Copy, Clone, Debug, Default, Eq, Ord, PartialOrd, PartialEq)]
pub struct SuggestionPoint(pub Point);
impl SuggestionPoint {
pub fn new(row: u32, column: u32) -> Self {
Self(Point::new(row, column))
}
pub fn row(self) -> u32 {
self.0.row
}
pub fn column(self) -> u32 {
self.0.column
}
}
#[derive(Clone, Debug)]
pub struct Suggestion<T> {
pub position: T,
pub text: Rope,
}
pub struct SuggestionMap(Mutex<SuggestionSnapshot>);
impl SuggestionMap {
pub fn new(fold_snapshot: FoldSnapshot) -> (Self, SuggestionSnapshot) {
let snapshot = SuggestionSnapshot {
fold_snapshot,
suggestion: None,
version: 0,
};
(Self(Mutex::new(snapshot.clone())), snapshot)
}
pub fn replace<T>(
&self,
new_suggestion: Option<Suggestion<T>>,
fold_snapshot: FoldSnapshot,
fold_edits: Vec<FoldEdit>,
) -> (
SuggestionSnapshot,
Vec<SuggestionEdit>,
Option<Suggestion<FoldOffset>>,
)
where
T: ToPoint,
{
let new_suggestion = new_suggestion.map(|new_suggestion| {
let buffer_point = new_suggestion
.position
.to_point(fold_snapshot.buffer_snapshot());
let fold_point = fold_snapshot.to_fold_point(buffer_point, Bias::Left);
let fold_offset = fold_point.to_offset(&fold_snapshot);
Suggestion {
position: fold_offset,
text: new_suggestion.text,
}
});
let (_, edits) = self.sync(fold_snapshot, fold_edits);
let mut snapshot = self.0.lock();
let mut patch = Patch::new(edits);
let old_suggestion = snapshot.suggestion.take();
if let Some(suggestion) = &old_suggestion {
patch = patch.compose([SuggestionEdit {
old: SuggestionOffset(suggestion.position.0)
..SuggestionOffset(suggestion.position.0 + suggestion.text.len()),
new: SuggestionOffset(suggestion.position.0)
..SuggestionOffset(suggestion.position.0),
}]);
}
if let Some(suggestion) = new_suggestion.as_ref() {
patch = patch.compose([SuggestionEdit {
old: SuggestionOffset(suggestion.position.0)
..SuggestionOffset(suggestion.position.0),
new: SuggestionOffset(suggestion.position.0)
..SuggestionOffset(suggestion.position.0 + suggestion.text.len()),
}]);
}
snapshot.suggestion = new_suggestion;
snapshot.version += 1;
(snapshot.clone(), patch.into_inner(), old_suggestion)
}
pub fn sync(
&self,
fold_snapshot: FoldSnapshot,
fold_edits: Vec<FoldEdit>,
) -> (SuggestionSnapshot, Vec<SuggestionEdit>) {
let mut snapshot = self.0.lock();
if snapshot.fold_snapshot.version != fold_snapshot.version {
snapshot.version += 1;
}
let mut suggestion_edits = Vec::new();
let mut suggestion_old_len = 0;
let mut suggestion_new_len = 0;
for fold_edit in fold_edits {
let start = fold_edit.new.start;
let end = FoldOffset(start.0 + fold_edit.old_len().0);
if let Some(suggestion) = snapshot.suggestion.as_mut() {
if end <= suggestion.position {
suggestion.position.0 += fold_edit.new_len().0;
suggestion.position.0 -= fold_edit.old_len().0;
} else if start > suggestion.position {
suggestion_old_len = suggestion.text.len();
suggestion_new_len = suggestion_old_len;
} else {
suggestion_old_len = suggestion.text.len();
snapshot.suggestion.take();
suggestion_edits.push(SuggestionEdit {
old: SuggestionOffset(fold_edit.old.start.0)
..SuggestionOffset(fold_edit.old.end.0 + suggestion_old_len),
new: SuggestionOffset(fold_edit.new.start.0)
..SuggestionOffset(fold_edit.new.end.0),
});
continue;
}
}
suggestion_edits.push(SuggestionEdit {
old: SuggestionOffset(fold_edit.old.start.0 + suggestion_old_len)
..SuggestionOffset(fold_edit.old.end.0 + suggestion_old_len),
new: SuggestionOffset(fold_edit.new.start.0 + suggestion_new_len)
..SuggestionOffset(fold_edit.new.end.0 + suggestion_new_len),
});
}
snapshot.fold_snapshot = fold_snapshot;
(snapshot.clone(), suggestion_edits)
}
pub fn has_suggestion(&self) -> bool {
let snapshot = self.0.lock();
snapshot.suggestion.is_some()
}
}
#[derive(Clone)]
pub struct SuggestionSnapshot {
pub fold_snapshot: FoldSnapshot,
pub suggestion: Option<Suggestion<FoldOffset>>,
pub version: usize,
}
impl SuggestionSnapshot {
pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
self.fold_snapshot.buffer_snapshot()
}
pub fn max_point(&self) -> SuggestionPoint {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_point = suggestion.position.to_point(&self.fold_snapshot);
let mut max_point = suggestion_point.0;
max_point += suggestion.text.max_point();
max_point += self.fold_snapshot.max_point().0 - suggestion_point.0;
SuggestionPoint(max_point)
} else {
SuggestionPoint(self.fold_snapshot.max_point().0)
}
}
pub fn len(&self) -> SuggestionOffset {
if let Some(suggestion) = self.suggestion.as_ref() {
let mut len = suggestion.position.0;
len += suggestion.text.len();
len += self.fold_snapshot.len().0 - suggestion.position.0;
SuggestionOffset(len)
} else {
SuggestionOffset(self.fold_snapshot.len().0)
}
}
pub fn line_len(&self, row: u32) -> u32 {
if let Some(suggestion) = &self.suggestion {
let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
if row < suggestion_start.row {
self.fold_snapshot.line_len(row)
} else if row > suggestion_end.row {
self.fold_snapshot
.line_len(suggestion_start.row + (row - suggestion_end.row))
} else {
let mut result = suggestion.text.line_len(row - suggestion_start.row);
if row == suggestion_start.row {
result += suggestion_start.column;
}
if row == suggestion_end.row {
result +=
self.fold_snapshot.line_len(suggestion_start.row) - suggestion_start.column;
}
result
}
} else {
self.fold_snapshot.line_len(row)
}
}
pub fn clip_point(&self, point: SuggestionPoint, bias: Bias) -> SuggestionPoint {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
if point.0 <= suggestion_start {
SuggestionPoint(self.fold_snapshot.clip_point(FoldPoint(point.0), bias).0)
} else if point.0 > suggestion_end {
let fold_point = self.fold_snapshot.clip_point(
FoldPoint(suggestion_start + (point.0 - suggestion_end)),
bias,
);
let suggestion_point = suggestion_end + (fold_point.0 - suggestion_start);
if bias == Bias::Left && suggestion_point == suggestion_end {
SuggestionPoint(suggestion_start)
} else {
SuggestionPoint(suggestion_point)
}
} else if bias == Bias::Left || suggestion_start == self.fold_snapshot.max_point().0 {
SuggestionPoint(suggestion_start)
} else {
let fold_point = if self.fold_snapshot.line_len(suggestion_start.row)
> suggestion_start.column
{
FoldPoint(suggestion_start + Point::new(0, 1))
} else {
FoldPoint(suggestion_start + Point::new(1, 0))
};
let clipped_fold_point = self.fold_snapshot.clip_point(fold_point, bias);
SuggestionPoint(suggestion_end + (clipped_fold_point.0 - suggestion_start))
}
} else {
SuggestionPoint(self.fold_snapshot.clip_point(FoldPoint(point.0), bias).0)
}
}
pub fn to_offset(&self, point: SuggestionPoint) -> SuggestionOffset {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
if point.0 <= suggestion_start {
SuggestionOffset(FoldPoint(point.0).to_offset(&self.fold_snapshot).0)
} else if point.0 > suggestion_end {
let fold_offset = FoldPoint(suggestion_start + (point.0 - suggestion_end))
.to_offset(&self.fold_snapshot);
SuggestionOffset(fold_offset.0 + suggestion.text.len())
} else {
let offset_in_suggestion =
suggestion.text.point_to_offset(point.0 - suggestion_start);
SuggestionOffset(suggestion.position.0 + offset_in_suggestion)
}
} else {
SuggestionOffset(FoldPoint(point.0).to_offset(&self.fold_snapshot).0)
}
}
pub fn to_point(&self, offset: SuggestionOffset) -> SuggestionPoint {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_point_start = suggestion.position.to_point(&self.fold_snapshot).0;
if offset.0 <= suggestion.position.0 {
SuggestionPoint(FoldOffset(offset.0).to_point(&self.fold_snapshot).0)
} else if offset.0 > (suggestion.position.0 + suggestion.text.len()) {
let fold_point = FoldOffset(offset.0 - suggestion.text.len())
.to_point(&self.fold_snapshot)
.0;
SuggestionPoint(
suggestion_point_start
+ suggestion.text.max_point()
+ (fold_point - suggestion_point_start),
)
} else {
let point_in_suggestion = suggestion
.text
.offset_to_point(offset.0 - suggestion.position.0);
SuggestionPoint(suggestion_point_start + point_in_suggestion)
}
} else {
SuggestionPoint(FoldOffset(offset.0).to_point(&self.fold_snapshot).0)
}
}
pub fn to_fold_point(&self, point: SuggestionPoint) -> FoldPoint {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
if point.0 <= suggestion_start {
FoldPoint(point.0)
} else if point.0 > suggestion_end {
FoldPoint(suggestion_start + (point.0 - suggestion_end))
} else {
FoldPoint(suggestion_start)
}
} else {
FoldPoint(point.0)
}
}
pub fn to_suggestion_point(&self, point: FoldPoint) -> SuggestionPoint {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
if point.0 <= suggestion_start {
SuggestionPoint(point.0)
} else {
let suggestion_end = suggestion_start + suggestion.text.max_point();
SuggestionPoint(suggestion_end + (point.0 - suggestion_start))
}
} else {
SuggestionPoint(point.0)
}
}
pub fn text_summary_for_range(&self, range: Range<SuggestionPoint>) -> TextSummary {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_start = suggestion.position.to_point(&self.fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
let mut summary = TextSummary::default();
let prefix_range =
cmp::min(range.start.0, suggestion_start)..cmp::min(range.end.0, suggestion_start);
if prefix_range.start < prefix_range.end {
summary += self.fold_snapshot.text_summary_for_range(
FoldPoint(prefix_range.start)..FoldPoint(prefix_range.end),
);
}
let suggestion_range =
cmp::max(range.start.0, suggestion_start)..cmp::min(range.end.0, suggestion_end);
if suggestion_range.start < suggestion_range.end {
let point_range = suggestion_range.start - suggestion_start
..suggestion_range.end - suggestion_start;
let offset_range = suggestion.text.point_to_offset(point_range.start)
..suggestion.text.point_to_offset(point_range.end);
summary += suggestion
.text
.cursor(offset_range.start)
.summary::<TextSummary>(offset_range.end);
}
let suffix_range = cmp::max(range.start.0, suggestion_end)..range.end.0;
if suffix_range.start < suffix_range.end {
let start = suggestion_start + (suffix_range.start - suggestion_end);
let end = suggestion_start + (suffix_range.end - suggestion_end);
summary += self
.fold_snapshot
.text_summary_for_range(FoldPoint(start)..FoldPoint(end));
}
summary
} else {
self.fold_snapshot
.text_summary_for_range(FoldPoint(range.start.0)..FoldPoint(range.end.0))
}
}
pub fn chars_at(&self, start: SuggestionPoint) -> impl '_ + Iterator<Item = char> {
let start = self.to_offset(start);
self.chunks(start..self.len(), false, None, None)
.flat_map(|chunk| chunk.text.chars())
}
pub fn chunks<'a>(
&'a self,
range: Range<SuggestionOffset>,
language_aware: bool,
text_highlights: Option<&'a TextHighlights>,
suggestion_highlight: Option<HighlightStyle>,
) -> SuggestionChunks<'a> {
if let Some(suggestion) = self.suggestion.as_ref() {
let suggestion_range =
suggestion.position.0..suggestion.position.0 + suggestion.text.len();
let prefix_chunks = if range.start.0 < suggestion_range.start {
Some(self.fold_snapshot.chunks(
FoldOffset(range.start.0)
..cmp::min(FoldOffset(suggestion_range.start), FoldOffset(range.end.0)),
language_aware,
text_highlights,
))
} else {
None
};
let clipped_suggestion_range = cmp::max(range.start.0, suggestion_range.start)
..cmp::min(range.end.0, suggestion_range.end);
let suggestion_chunks = if clipped_suggestion_range.start < clipped_suggestion_range.end
{
let start = clipped_suggestion_range.start - suggestion_range.start;
let end = clipped_suggestion_range.end - suggestion_range.start;
Some(suggestion.text.chunks_in_range(start..end))
} else {
None
};
let suffix_chunks = if range.end.0 > suggestion_range.end {
let start = cmp::max(suggestion_range.end, range.start.0) - suggestion_range.len();
let end = range.end.0 - suggestion_range.len();
Some(self.fold_snapshot.chunks(
FoldOffset(start)..FoldOffset(end),
language_aware,
text_highlights,
))
} else {
None
};
SuggestionChunks {
prefix_chunks,
suggestion_chunks,
suffix_chunks,
highlight_style: suggestion_highlight,
}
} else {
SuggestionChunks {
prefix_chunks: Some(self.fold_snapshot.chunks(
FoldOffset(range.start.0)..FoldOffset(range.end.0),
language_aware,
text_highlights,
)),
suggestion_chunks: None,
suffix_chunks: None,
highlight_style: None,
}
}
}
pub fn buffer_rows<'a>(&'a self, row: u32) -> SuggestionBufferRows<'a> {
let suggestion_range = if let Some(suggestion) = self.suggestion.as_ref() {
let start = suggestion.position.to_point(&self.fold_snapshot).0;
let end = start + suggestion.text.max_point();
start.row..end.row
} else {
u32::MAX..u32::MAX
};
let fold_buffer_rows = if row <= suggestion_range.start {
self.fold_snapshot.buffer_rows(row)
} else if row > suggestion_range.end {
self.fold_snapshot
.buffer_rows(row - (suggestion_range.end - suggestion_range.start))
} else {
let mut rows = self.fold_snapshot.buffer_rows(suggestion_range.start);
rows.next();
rows
};
SuggestionBufferRows {
current_row: row,
suggestion_row_start: suggestion_range.start,
suggestion_row_end: suggestion_range.end,
fold_buffer_rows,
}
}
#[cfg(test)]
pub fn text(&self) -> String {
self.chunks(Default::default()..self.len(), false, None, None)
.map(|chunk| chunk.text)
.collect()
}
}
pub struct SuggestionChunks<'a> {
prefix_chunks: Option<FoldChunks<'a>>,
suggestion_chunks: Option<text::Chunks<'a>>,
suffix_chunks: Option<FoldChunks<'a>>,
highlight_style: Option<HighlightStyle>,
}
impl<'a> Iterator for SuggestionChunks<'a> {
type Item = Chunk<'a>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(chunks) = self.prefix_chunks.as_mut() {
if let Some(chunk) = chunks.next() {
return Some(chunk);
} else {
self.prefix_chunks = None;
}
}
if let Some(chunks) = self.suggestion_chunks.as_mut() {
if let Some(chunk) = chunks.next() {
return Some(Chunk {
text: chunk,
highlight_style: self.highlight_style,
..Default::default()
});
} else {
self.suggestion_chunks = None;
}
}
if let Some(chunks) = self.suffix_chunks.as_mut() {
if let Some(chunk) = chunks.next() {
return Some(chunk);
} else {
self.suffix_chunks = None;
}
}
None
}
}
#[derive(Clone)]
pub struct SuggestionBufferRows<'a> {
current_row: u32,
suggestion_row_start: u32,
suggestion_row_end: u32,
fold_buffer_rows: FoldBufferRows<'a>,
}
impl<'a> Iterator for SuggestionBufferRows<'a> {
type Item = Option<u32>;
fn next(&mut self) -> Option<Self::Item> {
let row = post_inc(&mut self.current_row);
if row <= self.suggestion_row_start || row > self.suggestion_row_end {
self.fold_buffer_rows.next()
} else {
Some(None)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{display_map::fold_map::FoldMap, MultiBuffer};
use gpui::AppContext;
use rand::{prelude::StdRng, Rng};
use settings::SettingsStore;
use std::{
env,
ops::{Bound, RangeBounds},
};
#[gpui::test]
fn test_basic(cx: &mut AppContext) {
let buffer = MultiBuffer::build_simple("abcdefghi", cx);
let buffer_edits = buffer.update(cx, |buffer, _| buffer.subscribe());
let (mut fold_map, fold_snapshot) = FoldMap::new(buffer.read(cx).snapshot(cx));
let (suggestion_map, suggestion_snapshot) = SuggestionMap::new(fold_snapshot.clone());
assert_eq!(suggestion_snapshot.text(), "abcdefghi");
let (suggestion_snapshot, _, _) = suggestion_map.replace(
Some(Suggestion {
position: 3,
text: "123\n456".into(),
}),
fold_snapshot,
Default::default(),
);
assert_eq!(suggestion_snapshot.text(), "abc123\n456defghi");
buffer.update(cx, |buffer, cx| {
buffer.edit(
[(0..0, "ABC"), (3..3, "DEF"), (4..4, "GHI"), (9..9, "JKL")],
None,
cx,
)
});
let (fold_snapshot, fold_edits) = fold_map.read(
buffer.read(cx).snapshot(cx),
buffer_edits.consume().into_inner(),
);
let (suggestion_snapshot, _) = suggestion_map.sync(fold_snapshot.clone(), fold_edits);
assert_eq!(suggestion_snapshot.text(), "ABCabcDEF123\n456dGHIefghiJKL");
let (mut fold_map_writer, _, _) =
fold_map.write(buffer.read(cx).snapshot(cx), Default::default());
let (fold_snapshot, fold_edits) = fold_map_writer.fold([0..3]);
let (suggestion_snapshot, _) = suggestion_map.sync(fold_snapshot, fold_edits);
assert_eq!(suggestion_snapshot.text(), "⋯abcDEF123\n456dGHIefghiJKL");
let (mut fold_map_writer, _, _) =
fold_map.write(buffer.read(cx).snapshot(cx), Default::default());
let (fold_snapshot, fold_edits) = fold_map_writer.fold([6..10]);
let (suggestion_snapshot, _) = suggestion_map.sync(fold_snapshot, fold_edits);
assert_eq!(suggestion_snapshot.text(), "⋯abc⋯GHIefghiJKL");
}
#[gpui::test(iterations = 100)]
fn test_random_suggestions(cx: &mut AppContext, mut rng: StdRng) {
init_test(cx);
let operations = env::var("OPERATIONS")
.map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
.unwrap_or(10);
let len = rng.gen_range(0..30);
let buffer = if rng.gen() {
let text = util::RandomCharIter::new(&mut rng)
.take(len)
.collect::<String>();
MultiBuffer::build_simple(&text, cx)
} else {
MultiBuffer::build_random(&mut rng, cx)
};
let mut buffer_snapshot = buffer.read(cx).snapshot(cx);
log::info!("buffer text: {:?}", buffer_snapshot.text());
let (mut fold_map, mut fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (suggestion_map, mut suggestion_snapshot) = SuggestionMap::new(fold_snapshot.clone());
for _ in 0..operations {
let mut suggestion_edits = Patch::default();
let mut prev_suggestion_text = suggestion_snapshot.text();
let mut buffer_edits = Vec::new();
match rng.gen_range(0..=100) {
0..=29 => {
let (_, edits) = suggestion_map.randomly_mutate(&mut rng);
suggestion_edits = suggestion_edits.compose(edits);
}
30..=59 => {
for (new_fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
fold_snapshot = new_fold_snapshot;
let (_, edits) = suggestion_map.sync(fold_snapshot.clone(), fold_edits);
suggestion_edits = suggestion_edits.compose(edits);
}
}
_ => buffer.update(cx, |buffer, cx| {
let subscription = buffer.subscribe();
let edit_count = rng.gen_range(1..=5);
buffer.randomly_mutate(&mut rng, edit_count, cx);
buffer_snapshot = buffer.snapshot(cx);
let edits = subscription.consume().into_inner();
log::info!("editing {:?}", edits);
buffer_edits.extend(edits);
}),
};
let (new_fold_snapshot, fold_edits) =
fold_map.read(buffer_snapshot.clone(), buffer_edits);
fold_snapshot = new_fold_snapshot;
let (new_suggestion_snapshot, edits) =
suggestion_map.sync(fold_snapshot.clone(), fold_edits);
suggestion_snapshot = new_suggestion_snapshot;
suggestion_edits = suggestion_edits.compose(edits);
log::info!("buffer text: {:?}", buffer_snapshot.text());
log::info!("folds text: {:?}", fold_snapshot.text());
log::info!("suggestions text: {:?}", suggestion_snapshot.text());
let mut expected_text = Rope::from(fold_snapshot.text().as_str());
let mut expected_buffer_rows = fold_snapshot.buffer_rows(0).collect::<Vec<_>>();
if let Some(suggestion) = suggestion_snapshot.suggestion.as_ref() {
expected_text.replace(
suggestion.position.0..suggestion.position.0,
&suggestion.text.to_string(),
);
let suggestion_start = suggestion.position.to_point(&fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
expected_buffer_rows.splice(
(suggestion_start.row + 1) as usize..(suggestion_start.row + 1) as usize,
(0..suggestion_end.row - suggestion_start.row).map(|_| None),
);
}
assert_eq!(suggestion_snapshot.text(), expected_text.to_string());
for row_start in 0..expected_buffer_rows.len() {
assert_eq!(
suggestion_snapshot
.buffer_rows(row_start as u32)
.collect::<Vec<_>>(),
&expected_buffer_rows[row_start..],
"incorrect buffer rows starting at {}",
row_start
);
}
for _ in 0..5 {
let mut end = rng.gen_range(0..=suggestion_snapshot.len().0);
end = expected_text.clip_offset(end, Bias::Right);
let mut start = rng.gen_range(0..=end);
start = expected_text.clip_offset(start, Bias::Right);
let actual_text = suggestion_snapshot
.chunks(
SuggestionOffset(start)..SuggestionOffset(end),
false,
None,
None,
)
.map(|chunk| chunk.text)
.collect::<String>();
assert_eq!(
actual_text,
expected_text.slice(start..end).to_string(),
"incorrect text in range {:?}",
start..end
);
let start_point = SuggestionPoint(expected_text.offset_to_point(start));
let end_point = SuggestionPoint(expected_text.offset_to_point(end));
assert_eq!(
suggestion_snapshot.text_summary_for_range(start_point..end_point),
expected_text.slice(start..end).summary()
);
}
for edit in suggestion_edits.into_inner() {
prev_suggestion_text.replace_range(
edit.new.start.0..edit.new.start.0 + edit.old_len().0,
&suggestion_snapshot.text()[edit.new.start.0..edit.new.end.0],
);
}
assert_eq!(prev_suggestion_text, suggestion_snapshot.text());
assert_eq!(expected_text.max_point(), suggestion_snapshot.max_point().0);
assert_eq!(expected_text.len(), suggestion_snapshot.len().0);
let mut suggestion_point = SuggestionPoint::default();
let mut suggestion_offset = SuggestionOffset::default();
for ch in expected_text.chars() {
assert_eq!(
suggestion_snapshot.to_offset(suggestion_point),
suggestion_offset,
"invalid to_offset({:?})",
suggestion_point
);
assert_eq!(
suggestion_snapshot.to_point(suggestion_offset),
suggestion_point,
"invalid to_point({:?})",
suggestion_offset
);
assert_eq!(
suggestion_snapshot
.to_suggestion_point(suggestion_snapshot.to_fold_point(suggestion_point)),
suggestion_snapshot.clip_point(suggestion_point, Bias::Left),
);
let mut bytes = [0; 4];
for byte in ch.encode_utf8(&mut bytes).as_bytes() {
suggestion_offset.0 += 1;
if *byte == b'\n' {
suggestion_point.0 += Point::new(1, 0);
} else {
suggestion_point.0 += Point::new(0, 1);
}
let clipped_left_point =
suggestion_snapshot.clip_point(suggestion_point, Bias::Left);
let clipped_right_point =
suggestion_snapshot.clip_point(suggestion_point, Bias::Right);
assert!(
clipped_left_point <= clipped_right_point,
"clipped left point {:?} is greater than clipped right point {:?}",
clipped_left_point,
clipped_right_point
);
assert_eq!(
clipped_left_point.0,
expected_text.clip_point(clipped_left_point.0, Bias::Left)
);
assert_eq!(
clipped_right_point.0,
expected_text.clip_point(clipped_right_point.0, Bias::Right)
);
assert!(clipped_left_point <= suggestion_snapshot.max_point());
assert!(clipped_right_point <= suggestion_snapshot.max_point());
if let Some(suggestion) = suggestion_snapshot.suggestion.as_ref() {
let suggestion_start = suggestion.position.to_point(&fold_snapshot).0;
let suggestion_end = suggestion_start + suggestion.text.max_point();
let invalid_range = (
Bound::Excluded(suggestion_start),
Bound::Included(suggestion_end),
);
assert!(
!invalid_range.contains(&clipped_left_point.0),
"clipped left point {:?} is inside invalid suggestion range {:?}",
clipped_left_point,
invalid_range
);
assert!(
!invalid_range.contains(&clipped_right_point.0),
"clipped right point {:?} is inside invalid suggestion range {:?}",
clipped_right_point,
invalid_range
);
}
}
}
}
}
fn init_test(cx: &mut AppContext) {
cx.set_global(SettingsStore::test(cx));
theme::init((), cx);
}
impl SuggestionMap {
pub fn randomly_mutate(
&self,
rng: &mut impl Rng,
) -> (SuggestionSnapshot, Vec<SuggestionEdit>) {
let fold_snapshot = self.0.lock().fold_snapshot.clone();
let new_suggestion = if rng.gen_bool(0.3) {
None
} else {
let index = rng.gen_range(0..=fold_snapshot.buffer_snapshot().len());
let len = rng.gen_range(0..30);
Some(Suggestion {
position: index,
text: util::RandomCharIter::new(rng)
.take(len)
.filter(|ch| *ch != '\r')
.collect::<String>()
.as_str()
.into(),
})
};
log::info!("replacing suggestion with {:?}", new_suggestion);
let (snapshot, edits, _) =
self.replace(new_suggestion, fold_snapshot, Default::default());
(snapshot, edits)
}
}
}
+105 -119
View File
@@ -1,80 +1,76 @@
use super::{
suggestion_map::{self, SuggestionChunks, SuggestionEdit, SuggestionPoint, SuggestionSnapshot},
fold_map::{self, FoldChunks, FoldEdit, FoldPoint, FoldSnapshot},
TextHighlights,
};
use crate::MultiBufferSnapshot;
use gpui::fonts::HighlightStyle;
use language::{Chunk, Point};
use parking_lot::Mutex;
use std::{cmp, mem, num::NonZeroU32, ops::Range};
use sum_tree::Bias;
const MAX_EXPANSION_COLUMN: u32 = 256;
pub struct TabMap(Mutex<TabSnapshot>);
pub struct TabMap(TabSnapshot);
impl TabMap {
pub fn new(input: SuggestionSnapshot, tab_size: NonZeroU32) -> (Self, TabSnapshot) {
pub fn new(fold_snapshot: FoldSnapshot, tab_size: NonZeroU32) -> (Self, TabSnapshot) {
let snapshot = TabSnapshot {
suggestion_snapshot: input,
fold_snapshot,
tab_size,
max_expansion_column: MAX_EXPANSION_COLUMN,
version: 0,
};
(Self(Mutex::new(snapshot.clone())), snapshot)
(Self(snapshot.clone()), snapshot)
}
#[cfg(test)]
pub fn set_max_expansion_column(&self, column: u32) -> TabSnapshot {
self.0.lock().max_expansion_column = column;
self.0.lock().clone()
pub fn set_max_expansion_column(&mut self, column: u32) -> TabSnapshot {
self.0.max_expansion_column = column;
self.0.clone()
}
pub fn sync(
&self,
suggestion_snapshot: SuggestionSnapshot,
mut suggestion_edits: Vec<SuggestionEdit>,
&mut self,
fold_snapshot: FoldSnapshot,
mut fold_edits: Vec<FoldEdit>,
tab_size: NonZeroU32,
) -> (TabSnapshot, Vec<TabEdit>) {
let mut old_snapshot = self.0.lock();
let old_snapshot = &mut self.0;
let mut new_snapshot = TabSnapshot {
suggestion_snapshot,
fold_snapshot,
tab_size,
max_expansion_column: old_snapshot.max_expansion_column,
version: old_snapshot.version,
};
if old_snapshot.suggestion_snapshot.version != new_snapshot.suggestion_snapshot.version {
if old_snapshot.fold_snapshot.version != new_snapshot.fold_snapshot.version {
new_snapshot.version += 1;
}
let mut tab_edits = Vec::with_capacity(suggestion_edits.len());
let mut tab_edits = Vec::with_capacity(fold_edits.len());
if old_snapshot.tab_size == new_snapshot.tab_size {
// Expand each edit to include the next tab on the same line as the edit,
// and any subsequent tabs on that line that moved across the tab expansion
// boundary.
for suggestion_edit in &mut suggestion_edits {
let old_end = old_snapshot
.suggestion_snapshot
.to_point(suggestion_edit.old.end);
let old_end_row_successor_offset =
old_snapshot.suggestion_snapshot.to_offset(cmp::min(
SuggestionPoint::new(old_end.row() + 1, 0),
old_snapshot.suggestion_snapshot.max_point(),
));
let new_end = new_snapshot
.suggestion_snapshot
.to_point(suggestion_edit.new.end);
for fold_edit in &mut fold_edits {
let old_end = fold_edit.old.end.to_point(&old_snapshot.fold_snapshot);
let old_end_row_successor_offset = cmp::min(
FoldPoint::new(old_end.row() + 1, 0),
old_snapshot.fold_snapshot.max_point(),
)
.to_offset(&old_snapshot.fold_snapshot);
let new_end = fold_edit.new.end.to_point(&new_snapshot.fold_snapshot);
let mut offset_from_edit = 0;
let mut first_tab_offset = None;
let mut last_tab_with_changed_expansion_offset = None;
'outer: for chunk in old_snapshot.suggestion_snapshot.chunks(
suggestion_edit.old.end..old_end_row_successor_offset,
'outer: for chunk in old_snapshot.fold_snapshot.chunks(
fold_edit.old.end..old_end_row_successor_offset,
false,
None,
None,
None,
) {
for (ix, _) in chunk.text.match_indices('\t') {
let offset_from_edit = offset_from_edit + (ix as u32);
@@ -102,39 +98,31 @@ impl TabMap {
}
if let Some(offset) = last_tab_with_changed_expansion_offset.or(first_tab_offset) {
suggestion_edit.old.end.0 += offset as usize + 1;
suggestion_edit.new.end.0 += offset as usize + 1;
fold_edit.old.end.0 += offset as usize + 1;
fold_edit.new.end.0 += offset as usize + 1;
}
}
// Combine any edits that overlap due to the expansion.
let mut ix = 1;
while ix < suggestion_edits.len() {
let (prev_edits, next_edits) = suggestion_edits.split_at_mut(ix);
while ix < fold_edits.len() {
let (prev_edits, next_edits) = fold_edits.split_at_mut(ix);
let prev_edit = prev_edits.last_mut().unwrap();
let edit = &next_edits[0];
if prev_edit.old.end >= edit.old.start {
prev_edit.old.end = edit.old.end;
prev_edit.new.end = edit.new.end;
suggestion_edits.remove(ix);
fold_edits.remove(ix);
} else {
ix += 1;
}
}
for suggestion_edit in suggestion_edits {
let old_start = old_snapshot
.suggestion_snapshot
.to_point(suggestion_edit.old.start);
let old_end = old_snapshot
.suggestion_snapshot
.to_point(suggestion_edit.old.end);
let new_start = new_snapshot
.suggestion_snapshot
.to_point(suggestion_edit.new.start);
let new_end = new_snapshot
.suggestion_snapshot
.to_point(suggestion_edit.new.end);
for fold_edit in fold_edits {
let old_start = fold_edit.old.start.to_point(&old_snapshot.fold_snapshot);
let old_end = fold_edit.old.end.to_point(&old_snapshot.fold_snapshot);
let new_start = fold_edit.new.start.to_point(&new_snapshot.fold_snapshot);
let new_end = fold_edit.new.end.to_point(&new_snapshot.fold_snapshot);
tab_edits.push(TabEdit {
old: old_snapshot.to_tab_point(old_start)..old_snapshot.to_tab_point(old_end),
new: new_snapshot.to_tab_point(new_start)..new_snapshot.to_tab_point(new_end),
@@ -155,7 +143,7 @@ impl TabMap {
#[derive(Clone)]
pub struct TabSnapshot {
pub suggestion_snapshot: SuggestionSnapshot,
pub fold_snapshot: FoldSnapshot,
pub tab_size: NonZeroU32,
pub max_expansion_column: u32,
pub version: usize,
@@ -163,18 +151,15 @@ pub struct TabSnapshot {
impl TabSnapshot {
pub fn buffer_snapshot(&self) -> &MultiBufferSnapshot {
self.suggestion_snapshot.buffer_snapshot()
&self.fold_snapshot.inlay_snapshot.buffer
}
pub fn line_len(&self, row: u32) -> u32 {
let max_point = self.max_point();
if row < max_point.row() {
self.to_tab_point(SuggestionPoint::new(
row,
self.suggestion_snapshot.line_len(row),
))
.0
.column
self.to_tab_point(FoldPoint::new(row, self.fold_snapshot.line_len(row)))
.0
.column
} else {
max_point.column()
}
@@ -185,10 +170,10 @@ impl TabSnapshot {
}
pub fn text_summary_for_range(&self, range: Range<TabPoint>) -> TextSummary {
let input_start = self.to_suggestion_point(range.start, Bias::Left).0;
let input_end = self.to_suggestion_point(range.end, Bias::Right).0;
let input_start = self.to_fold_point(range.start, Bias::Left).0;
let input_end = self.to_fold_point(range.end, Bias::Right).0;
let input_summary = self
.suggestion_snapshot
.fold_snapshot
.text_summary_for_range(input_start..input_end);
let mut first_line_chars = 0;
@@ -198,7 +183,7 @@ impl TabSnapshot {
self.max_point()
};
for c in self
.chunks(range.start..line_end, false, None, None)
.chunks(range.start..line_end, false, None, None, None)
.flat_map(|chunk| chunk.text.chars())
{
if c == '\n' {
@@ -217,6 +202,7 @@ impl TabSnapshot {
false,
None,
None,
None,
)
.flat_map(|chunk| chunk.text.chars())
{
@@ -238,15 +224,17 @@ impl TabSnapshot {
range: Range<TabPoint>,
language_aware: bool,
text_highlights: Option<&'a TextHighlights>,
suggestion_highlight: Option<HighlightStyle>,
hint_highlights: Option<HighlightStyle>,
suggestion_highlights: Option<HighlightStyle>,
) -> TabChunks<'a> {
let (input_start, expanded_char_column, to_next_stop) =
self.to_suggestion_point(range.start, Bias::Left);
self.to_fold_point(range.start, Bias::Left);
let input_column = input_start.column();
let input_start = self.suggestion_snapshot.to_offset(input_start);
let input_start = input_start.to_offset(&self.fold_snapshot);
let input_end = self
.suggestion_snapshot
.to_offset(self.to_suggestion_point(range.end, Bias::Right).0);
.to_fold_point(range.end, Bias::Right)
.0
.to_offset(&self.fold_snapshot);
let to_next_stop = if range.start.0 + Point::new(0, to_next_stop) > range.end.0 {
range.end.column() - range.start.column()
} else {
@@ -254,11 +242,12 @@ impl TabSnapshot {
};
TabChunks {
suggestion_chunks: self.suggestion_snapshot.chunks(
fold_chunks: self.fold_snapshot.chunks(
input_start..input_end,
language_aware,
text_highlights,
suggestion_highlight,
hint_highlights,
suggestion_highlights,
),
input_column,
column: expanded_char_column,
@@ -275,63 +264,58 @@ impl TabSnapshot {
}
}
pub fn buffer_rows(&self, row: u32) -> suggestion_map::SuggestionBufferRows {
self.suggestion_snapshot.buffer_rows(row)
pub fn buffer_rows(&self, row: u32) -> fold_map::FoldBufferRows<'_> {
self.fold_snapshot.buffer_rows(row)
}
#[cfg(test)]
pub fn text(&self) -> String {
self.chunks(TabPoint::zero()..self.max_point(), false, None, None)
self.chunks(TabPoint::zero()..self.max_point(), false, None, None, None)
.map(|chunk| chunk.text)
.collect()
}
pub fn max_point(&self) -> TabPoint {
self.to_tab_point(self.suggestion_snapshot.max_point())
self.to_tab_point(self.fold_snapshot.max_point())
}
pub fn clip_point(&self, point: TabPoint, bias: Bias) -> TabPoint {
self.to_tab_point(
self.suggestion_snapshot
.clip_point(self.to_suggestion_point(point, bias).0, bias),
self.fold_snapshot
.clip_point(self.to_fold_point(point, bias).0, bias),
)
}
pub fn to_tab_point(&self, input: SuggestionPoint) -> TabPoint {
let chars = self
.suggestion_snapshot
.chars_at(SuggestionPoint::new(input.row(), 0));
pub fn to_tab_point(&self, input: FoldPoint) -> TabPoint {
let chars = self.fold_snapshot.chars_at(FoldPoint::new(input.row(), 0));
let expanded = self.expand_tabs(chars, input.column());
TabPoint::new(input.row(), expanded)
}
pub fn to_suggestion_point(&self, output: TabPoint, bias: Bias) -> (SuggestionPoint, u32, u32) {
let chars = self
.suggestion_snapshot
.chars_at(SuggestionPoint::new(output.row(), 0));
pub fn to_fold_point(&self, output: TabPoint, bias: Bias) -> (FoldPoint, u32, u32) {
let chars = self.fold_snapshot.chars_at(FoldPoint::new(output.row(), 0));
let expanded = output.column();
let (collapsed, expanded_char_column, to_next_stop) =
self.collapse_tabs(chars, expanded, bias);
(
SuggestionPoint::new(output.row(), collapsed as u32),
FoldPoint::new(output.row(), collapsed as u32),
expanded_char_column,
to_next_stop,
)
}
pub fn make_tab_point(&self, point: Point, bias: Bias) -> TabPoint {
let fold_point = self
.suggestion_snapshot
.fold_snapshot
.to_fold_point(point, bias);
let suggestion_point = self.suggestion_snapshot.to_suggestion_point(fold_point);
self.to_tab_point(suggestion_point)
let inlay_point = self.fold_snapshot.inlay_snapshot.to_inlay_point(point);
let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
self.to_tab_point(fold_point)
}
pub fn to_point(&self, point: TabPoint, bias: Bias) -> Point {
let suggestion_point = self.to_suggestion_point(point, bias).0;
let fold_point = self.suggestion_snapshot.to_fold_point(suggestion_point);
fold_point.to_buffer_point(&self.suggestion_snapshot.fold_snapshot)
let fold_point = self.to_fold_point(point, bias).0;
let inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
self.fold_snapshot
.inlay_snapshot
.to_buffer_point(inlay_point)
}
fn expand_tabs(&self, chars: impl Iterator<Item = char>, column: u32) -> u32 {
@@ -490,7 +474,7 @@ impl<'a> std::ops::AddAssign<&'a Self> for TextSummary {
const SPACES: &str = " ";
pub struct TabChunks<'a> {
suggestion_chunks: SuggestionChunks<'a>,
fold_chunks: FoldChunks<'a>,
chunk: Chunk<'a>,
column: u32,
max_expansion_column: u32,
@@ -506,7 +490,7 @@ impl<'a> Iterator for TabChunks<'a> {
fn next(&mut self) -> Option<Self::Item> {
if self.chunk.text.is_empty() {
if let Some(chunk) = self.suggestion_chunks.next() {
if let Some(chunk) = self.fold_chunks.next() {
self.chunk = chunk;
if self.inside_leading_tab {
self.chunk.text = &self.chunk.text[1..];
@@ -574,7 +558,7 @@ impl<'a> Iterator for TabChunks<'a> {
mod tests {
use super::*;
use crate::{
display_map::{fold_map::FoldMap, suggestion_map::SuggestionMap},
display_map::{fold_map::FoldMap, inlay_map::InlayMap},
MultiBuffer,
};
use rand::{prelude::StdRng, Rng};
@@ -583,9 +567,9 @@ mod tests {
fn test_expand_tabs(cx: &mut gpui::AppContext) {
let buffer = MultiBuffer::build_simple("", cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let (_, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (_, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (_, tab_snapshot) = TabMap::new(suggestion_snapshot, 4.try_into().unwrap());
let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (_, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
assert_eq!(tab_snapshot.expand_tabs("\t".chars(), 0), 0);
assert_eq!(tab_snapshot.expand_tabs("\t".chars(), 1), 4);
@@ -600,9 +584,9 @@ mod tests {
let buffer = MultiBuffer::build_simple(input, cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let (_, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (_, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (_, mut tab_snapshot) = TabMap::new(suggestion_snapshot, 4.try_into().unwrap());
let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (_, mut tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
tab_snapshot.max_expansion_column = max_expansion_column;
assert_eq!(tab_snapshot.text(), output);
@@ -615,6 +599,7 @@ mod tests {
false,
None,
None,
None,
)
.map(|c| c.text)
.collect::<String>(),
@@ -626,16 +611,16 @@ mod tests {
let input_point = Point::new(0, ix as u32);
let output_point = Point::new(0, output.find(c).unwrap() as u32);
assert_eq!(
tab_snapshot.to_tab_point(SuggestionPoint(input_point)),
tab_snapshot.to_tab_point(FoldPoint(input_point)),
TabPoint(output_point),
"to_tab_point({input_point:?})"
);
assert_eq!(
tab_snapshot
.to_suggestion_point(TabPoint(output_point), Bias::Left)
.to_fold_point(TabPoint(output_point), Bias::Left)
.0,
SuggestionPoint(input_point),
"to_suggestion_point({output_point:?})"
FoldPoint(input_point),
"to_fold_point({output_point:?})"
);
}
}
@@ -648,9 +633,9 @@ mod tests {
let buffer = MultiBuffer::build_simple(input, cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let (_, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (_, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (_, mut tab_snapshot) = TabMap::new(suggestion_snapshot, 4.try_into().unwrap());
let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (_, mut tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
tab_snapshot.max_expansion_column = max_expansion_column;
assert_eq!(tab_snapshot.text(), input);
@@ -662,9 +647,9 @@ mod tests {
let buffer = MultiBuffer::build_simple(&input, cx);
let buffer_snapshot = buffer.read(cx).snapshot(cx);
let (_, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (_, suggestion_snapshot) = SuggestionMap::new(fold_snapshot);
let (_, tab_snapshot) = TabMap::new(suggestion_snapshot, 4.try_into().unwrap());
let (_, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
let (_, fold_snapshot) = FoldMap::new(inlay_snapshot);
let (_, tab_snapshot) = TabMap::new(fold_snapshot, 4.try_into().unwrap());
assert_eq!(
chunks(&tab_snapshot, TabPoint::zero()),
@@ -689,7 +674,7 @@ mod tests {
let mut chunks = Vec::new();
let mut was_tab = false;
let mut text = String::new();
for chunk in snapshot.chunks(start..snapshot.max_point(), false, None, None) {
for chunk in snapshot.chunks(start..snapshot.max_point(), false, None, None, None) {
if chunk.is_tab != was_tab {
if !text.is_empty() {
chunks.push((mem::take(&mut text), was_tab));
@@ -721,15 +706,16 @@ mod tests {
let buffer_snapshot = buffer.read(cx).snapshot(cx);
log::info!("Buffer text: {:?}", buffer_snapshot.text());
let (mut fold_map, _) = FoldMap::new(buffer_snapshot.clone());
let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
log::info!("InlayMap text: {:?}", inlay_snapshot.text());
let (mut fold_map, _) = FoldMap::new(inlay_snapshot.clone());
fold_map.randomly_mutate(&mut rng);
let (fold_snapshot, _) = fold_map.read(buffer_snapshot, vec![]);
let (fold_snapshot, _) = fold_map.read(inlay_snapshot, vec![]);
log::info!("FoldMap text: {:?}", fold_snapshot.text());
let (suggestion_map, _) = SuggestionMap::new(fold_snapshot);
let (suggestion_snapshot, _) = suggestion_map.randomly_mutate(&mut rng);
log::info!("SuggestionMap text: {:?}", suggestion_snapshot.text());
let (inlay_snapshot, _) = inlay_map.randomly_mutate(&mut 0, &mut rng);
log::info!("InlayMap text: {:?}", inlay_snapshot.text());
let (tab_map, _) = TabMap::new(suggestion_snapshot.clone(), tab_size);
let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
let tabs_snapshot = tab_map.set_max_expansion_column(32);
let text = text::Rope::from(tabs_snapshot.text().as_str());
@@ -757,7 +743,7 @@ mod tests {
let expected_summary = TextSummary::from(expected_text.as_str());
assert_eq!(
tabs_snapshot
.chunks(start..end, false, None, None)
.chunks(start..end, false, None, None, None)
.map(|c| c.text)
.collect::<String>(),
expected_text,
@@ -767,7 +753,7 @@ mod tests {
);
let mut actual_summary = tabs_snapshot.text_summary_for_range(start..end);
if tab_size.get() > 1 && suggestion_snapshot.text().contains('\t') {
if tab_size.get() > 1 && inlay_snapshot.text().contains('\t') {
actual_summary.longest_row = expected_summary.longest_row;
actual_summary.longest_row_chars = expected_summary.longest_row_chars;
}
+42 -44
View File
@@ -1,5 +1,5 @@
use super::{
suggestion_map::SuggestionBufferRows,
fold_map::FoldBufferRows,
tab_map::{self, TabEdit, TabPoint, TabSnapshot},
TextHighlights,
};
@@ -65,7 +65,7 @@ pub struct WrapChunks<'a> {
#[derive(Clone)]
pub struct WrapBufferRows<'a> {
input_buffer_rows: SuggestionBufferRows<'a>,
input_buffer_rows: FoldBufferRows<'a>,
input_buffer_row: Option<u32>,
output_row: u32,
soft_wrapped: bool,
@@ -353,7 +353,7 @@ impl WrapSnapshot {
}
old_cursor.next(&());
new_transforms.push_tree(
new_transforms.append(
old_cursor.slice(&next_edit.old.start, Bias::Right, &()),
&(),
);
@@ -366,7 +366,7 @@ impl WrapSnapshot {
new_transforms.push_or_extend(Transform::isomorphic(summary));
}
old_cursor.next(&());
new_transforms.push_tree(old_cursor.suffix(&()), &());
new_transforms.append(old_cursor.suffix(&()), &());
}
}
}
@@ -446,6 +446,7 @@ impl WrapSnapshot {
false,
None,
None,
None,
);
let mut edit_transforms = Vec::<Transform>::new();
for _ in edit.new_rows.start..edit.new_rows.end {
@@ -500,7 +501,7 @@ impl WrapSnapshot {
new_transforms.push_or_extend(Transform::isomorphic(summary));
}
old_cursor.next(&());
new_transforms.push_tree(
new_transforms.append(
old_cursor.slice(
&TabPoint::new(next_edit.old_rows.start, 0),
Bias::Right,
@@ -517,7 +518,7 @@ impl WrapSnapshot {
new_transforms.push_or_extend(Transform::isomorphic(summary));
}
old_cursor.next(&());
new_transforms.push_tree(old_cursor.suffix(&()), &());
new_transforms.append(old_cursor.suffix(&()), &());
}
}
}
@@ -575,7 +576,8 @@ impl WrapSnapshot {
rows: Range<u32>,
language_aware: bool,
text_highlights: Option<&'a TextHighlights>,
suggestion_highlight: Option<HighlightStyle>,
hint_highlights: Option<HighlightStyle>,
suggestion_highlights: Option<HighlightStyle>,
) -> WrapChunks<'a> {
let output_start = WrapPoint::new(rows.start, 0);
let output_end = WrapPoint::new(rows.end, 0);
@@ -593,7 +595,8 @@ impl WrapSnapshot {
input_start..input_end,
language_aware,
text_highlights,
suggestion_highlight,
hint_highlights,
suggestion_highlights,
),
input_chunk: Default::default(),
output_position: output_start,
@@ -757,28 +760,18 @@ impl WrapSnapshot {
}
let text = language::Rope::from(self.text().as_str());
let input_buffer_rows = self.buffer_snapshot().buffer_rows(0).collect::<Vec<_>>();
let mut input_buffer_rows = self.tab_snapshot.buffer_rows(0);
let mut expected_buffer_rows = Vec::new();
let mut prev_fold_row = 0;
let mut prev_tab_row = 0;
for display_row in 0..=self.max_point().row() {
let tab_point = self.to_tab_point(WrapPoint::new(display_row, 0));
let suggestion_point = self
.tab_snapshot
.to_suggestion_point(tab_point, Bias::Left)
.0;
let fold_point = self
.tab_snapshot
.suggestion_snapshot
.to_fold_point(suggestion_point);
if fold_point.row() == prev_fold_row && display_row != 0 {
if tab_point.row() == prev_tab_row && display_row != 0 {
expected_buffer_rows.push(None);
} else {
let buffer_point = fold_point
.to_buffer_point(&self.tab_snapshot.suggestion_snapshot.fold_snapshot);
expected_buffer_rows.push(input_buffer_rows[buffer_point.row as usize]);
prev_fold_row = fold_point.row();
expected_buffer_rows.push(input_buffer_rows.next().unwrap());
}
prev_tab_row = tab_point.row();
assert_eq!(self.line_len(display_row), text.line_len(display_row));
}
@@ -1038,7 +1031,7 @@ fn consolidate_wrap_edits(edits: &mut Vec<WrapEdit>) {
mod tests {
use super::*;
use crate::{
display_map::{fold_map::FoldMap, suggestion_map::SuggestionMap, tab_map::TabMap},
display_map::{fold_map::FoldMap, inlay_map::InlayMap, tab_map::TabMap},
MultiBuffer,
};
use gpui::test::observe;
@@ -1089,11 +1082,11 @@ mod tests {
});
let mut buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
log::info!("Buffer text: {:?}", buffer_snapshot.text());
let (mut fold_map, fold_snapshot) = FoldMap::new(buffer_snapshot.clone());
let (mut inlay_map, inlay_snapshot) = InlayMap::new(buffer_snapshot.clone());
log::info!("InlayMap text: {:?}", inlay_snapshot.text());
let (mut fold_map, fold_snapshot) = FoldMap::new(inlay_snapshot.clone());
log::info!("FoldMap text: {:?}", fold_snapshot.text());
let (suggestion_map, suggestion_snapshot) = SuggestionMap::new(fold_snapshot.clone());
log::info!("SuggestionMap text: {:?}", suggestion_snapshot.text());
let (tab_map, _) = TabMap::new(suggestion_snapshot.clone(), tab_size);
let (mut tab_map, _) = TabMap::new(fold_snapshot.clone(), tab_size);
let tabs_snapshot = tab_map.set_max_expansion_column(32);
log::info!("TabMap text: {:?}", tabs_snapshot.text());
@@ -1122,6 +1115,7 @@ mod tests {
);
log::info!("Wrapped text: {:?}", actual_text);
let mut next_inlay_id = 0;
let mut edits = Vec::new();
for _i in 0..operations {
log::info!("{} ==============================================", _i);
@@ -1139,10 +1133,8 @@ mod tests {
}
20..=39 => {
for (fold_snapshot, fold_edits) in fold_map.randomly_mutate(&mut rng) {
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.sync(fold_snapshot, fold_edits);
let (tabs_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, tab_size);
tab_map.sync(fold_snapshot, fold_edits, tab_size);
let (mut snapshot, wrap_edits) =
wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
snapshot.check_invariants();
@@ -1151,10 +1143,11 @@ mod tests {
}
}
40..=59 => {
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.randomly_mutate(&mut rng);
let (inlay_snapshot, inlay_edits) =
inlay_map.randomly_mutate(&mut next_inlay_id, &mut rng);
let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
let (tabs_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, tab_size);
tab_map.sync(fold_snapshot, fold_edits, tab_size);
let (mut snapshot, wrap_edits) =
wrap_map.update(cx, |map, cx| map.sync(tabs_snapshot, tab_edits, cx));
snapshot.check_invariants();
@@ -1173,13 +1166,12 @@ mod tests {
}
log::info!("Buffer text: {:?}", buffer_snapshot.text());
let (fold_snapshot, fold_edits) = fold_map.read(buffer_snapshot.clone(), buffer_edits);
let (inlay_snapshot, inlay_edits) =
inlay_map.sync(buffer_snapshot.clone(), buffer_edits);
log::info!("InlayMap text: {:?}", inlay_snapshot.text());
let (fold_snapshot, fold_edits) = fold_map.read(inlay_snapshot, inlay_edits);
log::info!("FoldMap text: {:?}", fold_snapshot.text());
let (suggestion_snapshot, suggestion_edits) =
suggestion_map.sync(fold_snapshot, fold_edits);
log::info!("SuggestionMap text: {:?}", suggestion_snapshot.text());
let (tabs_snapshot, tab_edits) =
tab_map.sync(suggestion_snapshot, suggestion_edits, tab_size);
let (tabs_snapshot, tab_edits) = tab_map.sync(fold_snapshot, fold_edits, tab_size);
log::info!("TabMap text: {:?}", tabs_snapshot.text());
let unwrapped_text = tabs_snapshot.text();
@@ -1227,7 +1219,7 @@ mod tests {
if tab_size.get() == 1
|| !wrapped_snapshot
.tab_snapshot
.suggestion_snapshot
.fold_snapshot
.text()
.contains('\t')
{
@@ -1328,8 +1320,14 @@ mod tests {
}
pub fn text_chunks(&self, wrap_row: u32) -> impl Iterator<Item = &str> {
self.chunks(wrap_row..self.max_point().row() + 1, false, None, None)
.map(|h| h.text)
self.chunks(
wrap_row..self.max_point().row() + 1,
false,
None,
None,
None,
)
.map(|h| h.text)
}
fn verify_chunks(&mut self, rng: &mut impl Rng) {
@@ -1352,7 +1350,7 @@ mod tests {
}
let actual_text = self
.chunks(start_row..end_row, true, None, None)
.chunks(start_row..end_row, true, None, None, None)
.map(|c| c.text)
.collect::<String>();
assert_eq!(
+362 -56
View File
@@ -2,6 +2,7 @@ mod blink_manager;
pub mod display_map;
mod editor_settings;
mod element;
mod inlay_hint_cache;
mod git;
mod highlight_matching_bracket;
@@ -25,7 +26,7 @@ use aho_corasick::AhoCorasick;
use anyhow::{anyhow, Result};
use blink_manager::BlinkManager;
use client::{ClickhouseEvent, TelemetrySettings};
use clock::ReplicaId;
use clock::{Global, ReplicaId};
use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
use copilot::Copilot;
pub use display_map::DisplayPoint;
@@ -52,11 +53,12 @@ use gpui::{
};
use highlight_matching_bracket::refresh_matching_bracket_highlights;
use hover_popover::{hide_hover, HoverState};
use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
pub use items::MAX_TAB_TITLE_LEN;
use itertools::Itertools;
pub use language::{char_kind, CharKind};
use language::{
language_settings::{self, all_language_settings},
language_settings::{self, all_language_settings, InlayHintSettings},
AutoindentMode, BracketPair, Buffer, CodeAction, CodeLabel, Completion, CursorShape,
Diagnostic, DiagnosticSeverity, File, IndentKind, IndentSize, Language, OffsetRangeExt,
OffsetUtf16, Point, Selection, SelectionGoal, TransactionId,
@@ -64,11 +66,12 @@ use language::{
use link_go_to_definition::{
hide_link_definition, show_link_definition, LinkDefinitionKind, LinkGoToDefinitionState,
};
use log::error;
use multi_buffer::ToOffsetUtf16;
pub use multi_buffer::{
Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
ToPoint,
};
use multi_buffer::{MultiBufferChunks, ToOffsetUtf16};
use ordered_float::OrderedFloat;
use project::{FormatTrigger, Location, LocationLink, Project, ProjectPath, ProjectTransaction};
use scroll::{
@@ -85,12 +88,13 @@ use std::{
cmp::{self, Ordering, Reverse},
mem,
num::NonZeroU32,
ops::{Deref, DerefMut, Range},
ops::{ControlFlow, Deref, DerefMut, Range},
path::Path,
sync::Arc,
time::{Duration, Instant},
};
pub use sum_tree::Bias;
use text::Rope;
use theme::{DiagnosticStyle, Theme, ThemeSettings};
use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
use workspace::{ItemNavHistory, ViewId, Workspace};
@@ -180,6 +184,21 @@ pub struct GutterHover {
pub hovered: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum InlayId {
Suggestion(usize),
Hint(usize),
}
impl InlayId {
fn id(&self) -> usize {
match self {
Self::Suggestion(id) => *id,
Self::Hint(id) => *id,
}
}
}
actions!(
editor,
[
@@ -206,6 +225,7 @@ actions!(
DuplicateLine,
MoveLineUp,
MoveLineDown,
JoinLines,
Transpose,
Cut,
Copy,
@@ -321,6 +341,7 @@ pub fn init(cx: &mut AppContext) {
cx.add_action(Editor::indent);
cx.add_action(Editor::outdent);
cx.add_action(Editor::delete_line);
cx.add_action(Editor::join_lines);
cx.add_action(Editor::delete_to_previous_word_start);
cx.add_action(Editor::delete_to_previous_subword_start);
cx.add_action(Editor::delete_to_next_word_end);
@@ -533,6 +554,8 @@ pub struct Editor {
gutter_hovered: bool,
link_go_to_definition_state: LinkGoToDefinitionState,
copilot_state: CopilotState,
inlay_hint_cache: InlayHintCache,
next_inlay_id: usize,
_subscriptions: Vec<Subscription>,
}
@@ -1054,6 +1077,7 @@ pub struct CopilotState {
cycled: bool,
completions: Vec<copilot::Completion>,
active_completion_index: usize,
suggestion: Option<Inlay>,
}
impl Default for CopilotState {
@@ -1065,6 +1089,7 @@ impl Default for CopilotState {
completions: Default::default(),
active_completion_index: 0,
cycled: false,
suggestion: None,
}
}
}
@@ -1179,6 +1204,14 @@ enum GotoDefinitionKind {
Type,
}
#[derive(Debug, Clone)]
enum InlayRefreshReason {
SettingsChange(InlayHintSettings),
NewLinesShown,
BufferEdited(HashSet<Arc<Language>>),
RefreshRequested,
}
impl Editor {
pub fn single_line(
field_editor_style: Option<Arc<GetFieldEditorTheme>>,
@@ -1280,15 +1313,28 @@ impl Editor {
let soft_wrap_mode_override =
(mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
let mut project_subscription = None;
if mode == EditorMode::Full && buffer.read(cx).is_singleton() {
let mut project_subscriptions = Vec::new();
if mode == EditorMode::Full {
if let Some(project) = project.as_ref() {
project_subscription = Some(cx.observe(project, |_, _, cx| {
cx.emit(Event::TitleChanged);
}))
if buffer.read(cx).is_singleton() {
project_subscriptions.push(cx.observe(project, |_, _, cx| {
cx.emit(Event::TitleChanged);
}));
}
project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
if let project::Event::RefreshInlays = event {
editor.refresh_inlays(InlayRefreshReason::RefreshRequested, cx);
};
}));
}
}
let inlay_hint_settings = inlay_hint_settings(
selections.newest_anchor().head(),
&buffer.read(cx).snapshot(cx),
cx,
);
let mut this = Self {
handle: cx.weak_handle(),
buffer: buffer.clone(),
@@ -1322,6 +1368,7 @@ impl Editor {
.add_view(|cx| context_menu::ContextMenu::new(editor_view_id, cx)),
completion_tasks: Default::default(),
next_completion_id: 0,
next_inlay_id: 0,
available_code_actions: Default::default(),
code_actions_task: Default::default(),
document_highlights_task: Default::default(),
@@ -1338,6 +1385,7 @@ impl Editor {
hover_state: Default::default(),
link_go_to_definition_state: Default::default(),
copilot_state: Default::default(),
inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
gutter_hovered: false,
_subscriptions: vec![
cx.observe(&buffer, Self::on_buffer_changed),
@@ -1348,9 +1396,7 @@ impl Editor {
],
};
if let Some(project_subscription) = project_subscription {
this._subscriptions.push(project_subscription);
}
this._subscriptions.extend(project_subscriptions);
this.end_selection(cx);
this.scroll_manager.show_scrollbar(cx);
@@ -1871,7 +1917,7 @@ impl Editor {
s.set_pending(pending, mode);
});
} else {
log::error!("update_selection dispatched with no pending selection");
error!("update_selection dispatched with no pending selection");
return;
}
@@ -1989,6 +2035,7 @@ impl Editor {
}
let selections = self.selections.all_adjusted(cx);
let mut brace_inserted = false;
let mut edits = Vec::new();
let mut new_selections = Vec::with_capacity(selections.len());
let mut new_autoclose_regions = Vec::new();
@@ -2047,6 +2094,7 @@ impl Editor {
selection.range(),
format!("{}{}", text, bracket_pair.end).into(),
));
brace_inserted = true;
continue;
}
}
@@ -2073,6 +2121,7 @@ impl Editor {
selection.end..selection.end,
bracket_pair.end.as_str().into(),
));
brace_inserted = true;
new_selections.push((
Selection {
id: selection.id,
@@ -2140,8 +2189,7 @@ impl Editor {
let had_active_copilot_suggestion = this.has_active_copilot_suggestion(cx);
this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
// When buffer contents is updated and caret is moved, try triggering on type formatting.
if settings::get::<EditorSettings>(cx).use_on_type_format {
if !brace_inserted && settings::get::<EditorSettings>(cx).use_on_type_format {
if let Some(on_type_format_task) =
this.trigger_on_type_formatting(text.to_string(), cx)
{
@@ -2575,6 +2623,108 @@ impl Editor {
}
}
fn refresh_inlays(&mut self, reason: InlayRefreshReason, cx: &mut ViewContext<Self>) {
if self.project.is_none() || self.mode != EditorMode::Full {
return;
}
let (invalidate_cache, required_languages) = match reason {
InlayRefreshReason::SettingsChange(new_settings) => {
match self.inlay_hint_cache.update_settings(
&self.buffer,
new_settings,
self.visible_inlay_hints(cx),
cx,
) {
ControlFlow::Break(Some(InlaySplice {
to_remove,
to_insert,
})) => {
self.splice_inlay_hints(to_remove, to_insert, cx);
return;
}
ControlFlow::Break(None) => return,
ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
}
}
InlayRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
InlayRefreshReason::BufferEdited(buffer_languages) => {
(InvalidationStrategy::BufferEdited, Some(buffer_languages))
}
InlayRefreshReason::RefreshRequested => (InvalidationStrategy::RefreshRequested, None),
};
self.inlay_hint_cache.refresh_inlay_hints(
self.excerpt_visible_offsets(required_languages.as_ref(), cx),
invalidate_cache,
cx,
)
}
fn visible_inlay_hints(&self, cx: &ViewContext<'_, '_, Editor>) -> Vec<Inlay> {
self.display_map
.read(cx)
.current_inlays()
.filter(move |inlay| {
Some(inlay.id) != self.copilot_state.suggestion.as_ref().map(|h| h.id)
})
.cloned()
.collect()
}
fn excerpt_visible_offsets(
&self,
restrict_to_languages: Option<&HashSet<Arc<Language>>>,
cx: &mut ViewContext<'_, '_, Editor>,
) -> HashMap<ExcerptId, (ModelHandle<Buffer>, Global, Range<usize>)> {
let multi_buffer = self.buffer().read(cx);
let multi_buffer_snapshot = multi_buffer.snapshot(cx);
let multi_buffer_visible_start = self
.scroll_manager
.anchor()
.anchor
.to_point(&multi_buffer_snapshot);
let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
multi_buffer_visible_start
+ Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
Bias::Left,
);
let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
multi_buffer
.range_to_buffer_ranges(multi_buffer_visible_range, cx)
.into_iter()
.filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
.filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
let buffer = buffer_handle.read(cx);
let language = buffer.language()?;
if let Some(restrict_to_languages) = restrict_to_languages {
if !restrict_to_languages.contains(language) {
return None;
}
}
Some((
excerpt_id,
(
buffer_handle,
buffer.version().clone(),
excerpt_visible_range,
),
))
})
.collect()
}
fn splice_inlay_hints(
&self,
to_remove: Vec<InlayId>,
to_insert: Vec<Inlay>,
cx: &mut ViewContext<Self>,
) {
self.display_map.update(cx, |display_map, cx| {
display_map.splice_inlays(to_remove, to_insert, cx);
});
}
fn trigger_on_type_formatting(
&self,
input: String,
@@ -3225,10 +3375,7 @@ impl Editor {
}
fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
if let Some(suggestion) = self
.display_map
.update(cx, |map, cx| map.replace_suggestion::<usize>(None, cx))
{
if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
if let Some((copilot, completion)) =
Copilot::global(cx).zip(self.copilot_state.active_completion())
{
@@ -3247,7 +3394,7 @@ impl Editor {
}
fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
if self.has_active_copilot_suggestion(cx) {
if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| {
@@ -3258,8 +3405,9 @@ impl Editor {
self.report_copilot_event(None, false, cx)
}
self.display_map
.update(cx, |map, cx| map.replace_suggestion::<usize>(None, cx));
self.display_map.update(cx, |map, cx| {
map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
});
cx.notify();
true
} else {
@@ -3280,7 +3428,26 @@ impl Editor {
}
fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
self.display_map.read(cx).has_suggestion()
if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
let buffer = self.buffer.read(cx).read(cx);
suggestion.position.is_valid(&buffer)
} else {
false
}
}
fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
let suggestion = self.copilot_state.suggestion.take()?;
self.display_map.update(cx, |map, cx| {
map.splice_inlays(vec![suggestion.id], Default::default(), cx);
});
let buffer = self.buffer.read(cx).read(cx);
if suggestion.position.is_valid(&buffer) {
Some(suggestion)
} else {
None
}
}
fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
@@ -3297,14 +3464,17 @@ impl Editor {
.copilot_state
.text_for_active_completion(cursor, &snapshot)
{
let text = Rope::from(text);
let mut to_remove = Vec::new();
if let Some(suggestion) = self.copilot_state.suggestion.take() {
to_remove.push(suggestion.id);
}
let suggestion_inlay =
Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
self.copilot_state.suggestion = Some(suggestion_inlay.clone());
self.display_map.update(cx, move |map, cx| {
map.replace_suggestion(
Some(Suggestion {
position: cursor,
text: text.trim_end().into(),
}),
cx,
)
map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
});
cx.notify();
} else {
@@ -3320,15 +3490,21 @@ impl Editor {
pub fn render_code_actions_indicator(
&self,
style: &EditorStyle,
active: bool,
is_active: bool,
cx: &mut ViewContext<Self>,
) -> Option<AnyElement<Self>> {
if self.available_code_actions.is_some() {
enum CodeActions {}
Some(
MouseEventHandler::<CodeActions, _>::new(0, cx, |state, _| {
Svg::new("icons/bolt_8.svg")
.with_color(style.code_actions.indicator.style_for(state, active).color)
Svg::new("icons/bolt_8.svg").with_color(
style
.code_actions
.indicator
.in_state(is_active)
.style_for(state)
.color,
)
})
.with_cursor_style(CursorStyle::PointingHand)
.with_padding(Padding::uniform(3.))
@@ -3378,10 +3554,8 @@ impl Editor {
.with_color(
style
.indicator
.style_for(
mouse_state,
fold_status == FoldStatus::Folded,
)
.in_state(fold_status == FoldStatus::Folded)
.style_for(mouse_state)
.color,
)
.constrained()
@@ -3952,6 +4126,60 @@ impl Editor {
});
}
pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
let mut row_ranges = Vec::<Range<u32>>::new();
for selection in self.selections.all::<Point>(cx) {
let start = selection.start.row;
let end = if selection.start.row == selection.end.row {
selection.start.row + 1
} else {
selection.end.row
};
if let Some(last_row_range) = row_ranges.last_mut() {
if start <= last_row_range.end {
last_row_range.end = end;
continue;
}
}
row_ranges.push(start..end);
}
let snapshot = self.buffer.read(cx).snapshot(cx);
let mut cursor_positions = Vec::new();
for row_range in &row_ranges {
let anchor = snapshot.anchor_before(Point::new(
row_range.end - 1,
snapshot.line_len(row_range.end - 1),
));
cursor_positions.push(anchor.clone()..anchor);
}
self.transact(cx, |this, cx| {
for row_range in row_ranges.into_iter().rev() {
for row in row_range.rev() {
let end_of_line = Point::new(row, snapshot.line_len(row));
let indent = snapshot.indent_size_for_line(row + 1);
let start_of_next_line = Point::new(row + 1, indent.len);
let replace = if snapshot.line_len(row + 1) > indent.len {
" "
} else {
""
};
this.buffer.update(cx, |buffer, cx| {
buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
});
}
}
this.change_selections(Some(Autoscroll::fit()), cx, |s| {
s.select_anchor_ranges(cursor_positions)
});
});
}
pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
let buffer = &display_map.buffer_snapshot;
@@ -6581,7 +6809,7 @@ impl Editor {
if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
*end_selections = Some(self.selections.disjoint_anchors());
} else {
log::error!("unexpectedly ended a transaction that wasn't started by this editor");
error!("unexpectedly ended a transaction that wasn't started by this editor");
}
cx.emit(Event::Edited);
@@ -7031,7 +7259,7 @@ impl Editor {
fn on_buffer_event(
&mut self,
_: ModelHandle<MultiBuffer>,
multibuffer: ModelHandle<MultiBuffer>,
event: &multi_buffer::Event,
cx: &mut ViewContext<Self>,
) {
@@ -7043,6 +7271,33 @@ impl Editor {
self.update_visible_copilot_suggestion(cx);
}
cx.emit(Event::BufferEdited);
if let Some(project) = &self.project {
let project = project.read(cx);
let languages_affected = multibuffer
.read(cx)
.all_buffers()
.into_iter()
.filter_map(|buffer| {
let buffer = buffer.read(cx);
let language = buffer.language()?;
if project.is_local()
&& project.language_servers_for_buffer(buffer, cx).count() == 0
{
None
} else {
Some(language)
}
})
.cloned()
.collect::<HashSet<_>>();
if !languages_affected.is_empty() {
self.refresh_inlays(
InlayRefreshReason::BufferEdited(languages_affected),
cx,
);
}
}
}
multi_buffer::Event::ExcerptsAdded {
buffer,
@@ -7067,7 +7322,7 @@ impl Editor {
self.refresh_active_diagnostics(cx);
}
_ => {}
}
};
}
fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
@@ -7076,6 +7331,14 @@ impl Editor {
fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
self.refresh_copilot_suggestions(true, cx);
self.refresh_inlays(
InlayRefreshReason::SettingsChange(inlay_hint_settings(
self.selections.newest_anchor().head(),
&self.buffer.read(cx).snapshot(cx),
cx,
)),
cx,
);
}
pub fn set_searchable(&mut self, searchable: bool) {
@@ -7365,6 +7628,23 @@ impl Editor {
let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else { return; };
cx.write_to_clipboard(ClipboardItem::new(lines));
}
pub fn inlay_hint_cache(&self) -> &InlayHintCache {
&self.inlay_hint_cache
}
}
fn inlay_hint_settings(
location: Anchor,
snapshot: &MultiBufferSnapshot,
cx: &mut ViewContext<'_, '_, Editor>,
) -> InlayHintSettings {
let file = snapshot.file_at(location);
let language = snapshot.language_at(location);
let settings = all_language_settings(file, cx);
settings
.language(language.map(|l| l.name()).as_deref())
.inlay_hints
}
fn consume_contiguous_rows(
@@ -7581,8 +7861,14 @@ impl View for Editor {
keymap.add_identifier("renaming");
}
match self.context_menu.as_ref() {
Some(ContextMenu::Completions(_)) => keymap.add_identifier("showing_completions"),
Some(ContextMenu::CodeActions(_)) => keymap.add_identifier("showing_code_actions"),
Some(ContextMenu::Completions(_)) => {
keymap.add_identifier("menu");
keymap.add_identifier("showing_completions")
}
Some(ContextMenu::CodeActions(_)) => {
keymap.add_identifier("menu");
keymap.add_identifier("showing_code_actions")
}
None => {}
}
for layer in self.keymap_context_layers.values() {
@@ -7949,6 +8235,7 @@ impl Deref for EditorStyle {
pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> RenderBlock {
let mut highlighted_lines = Vec::new();
for (index, line) in diagnostic.message.lines().enumerate() {
let line = match &diagnostic.source {
Some(source) if index == 0 => {
@@ -7960,25 +8247,44 @@ pub fn diagnostic_block_renderer(diagnostic: Diagnostic, is_valid: bool) -> Rend
};
highlighted_lines.push(line);
}
let message = diagnostic.message;
Arc::new(move |cx: &mut BlockContext| {
let message = message.clone();
let settings = settings::get::<ThemeSettings>(cx);
let tooltip_style = settings.theme.tooltip.clone();
let theme = &settings.theme.editor;
let style = diagnostic_style(diagnostic.severity, is_valid, theme);
let font_size = (style.text_scale_factor * settings.buffer_font_size(cx)).round();
Flex::column()
.with_children(highlighted_lines.iter().map(|(line, highlights)| {
Label::new(
line.clone(),
style.message.clone().with_font_size(font_size),
)
.with_highlights(highlights.clone())
.contained()
.with_margin_left(cx.anchor_x)
}))
.aligned()
.left()
.into_any()
let anchor_x = cx.anchor_x;
enum BlockContextToolip {}
MouseEventHandler::<BlockContext, _>::new(cx.block_id, cx, |_, _| {
Flex::column()
.with_children(highlighted_lines.iter().map(|(line, highlights)| {
Label::new(
line.clone(),
style.message.clone().with_font_size(font_size),
)
.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".to_string(),
None,
tooltip_style,
cx,
)
.into_any()
})
}
+280 -3
View File
@@ -1,7 +1,11 @@
use super::*;
use crate::test::{
assert_text_with_selections, build_editor, editor_lsp_test_context::EditorLspTestContext,
editor_test_context::EditorTestContext, select_ranges,
use crate::{
scroll::scroll_amount::ScrollAmount,
test::{
assert_text_with_selections, build_editor, editor_lsp_test_context::EditorLspTestContext,
editor_test_context::EditorTestContext, select_ranges,
},
JoinLines,
};
use drag_and_drop::DragAndDrop;
use futures::StreamExt;
@@ -1356,6 +1360,43 @@ async fn test_move_start_of_paragraph_end_of_paragraph(cx: &mut gpui::TestAppCon
);
}
#[gpui::test]
async fn test_scroll_page_up_page_down(cx: &mut gpui::TestAppContext) {
init_test(cx, |_| {});
let mut cx = EditorTestContext::new(cx).await;
let line_height = cx.editor(|editor, cx| editor.style(cx).text.line_height(cx.font_cache()));
cx.simulate_window_resize(cx.window_id, vec2f(1000., 4. * line_height + 0.5));
cx.set_state(
&r#"ˇone
two
three
four
five
six
seven
eight
nine
ten
"#,
);
cx.update_editor(|editor, cx| {
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 0.));
editor.scroll_screen(&ScrollAmount::Page(1.), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
editor.scroll_screen(&ScrollAmount::Page(1.), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 6.));
editor.scroll_screen(&ScrollAmount::Page(-1.), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
editor.scroll_screen(&ScrollAmount::Page(-0.5), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 2.));
editor.scroll_screen(&ScrollAmount::Page(0.5), cx);
assert_eq!(editor.snapshot(cx).scroll_position(), vec2f(0., 3.));
});
}
#[gpui::test]
async fn test_move_page_up_page_down(cx: &mut gpui::TestAppContext) {
init_test(cx, |_| {});
@@ -2325,6 +2366,137 @@ fn test_delete_line(cx: &mut TestAppContext) {
});
}
#[gpui::test]
fn test_join_lines_with_single_selection(cx: &mut TestAppContext) {
init_test(cx, |_| {});
cx.add_window(|cx| {
let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
let mut editor = build_editor(buffer.clone(), cx);
let buffer = buffer.read(cx).as_singleton().unwrap();
assert_eq!(
editor.selections.ranges::<Point>(cx),
&[Point::new(0, 0)..Point::new(0, 0)]
);
// When on single line, replace newline at end by space
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
assert_eq!(
editor.selections.ranges::<Point>(cx),
&[Point::new(0, 3)..Point::new(0, 3)]
);
// When multiple lines are selected, remove newlines that are spanned by the selection
editor.change_selections(None, cx, |s| {
s.select_ranges([Point::new(0, 5)..Point::new(2, 2)])
});
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb ccc ddd\n\n");
assert_eq!(
editor.selections.ranges::<Point>(cx),
&[Point::new(0, 11)..Point::new(0, 11)]
);
// Undo should be transactional
editor.undo(&Undo, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n\n");
assert_eq!(
editor.selections.ranges::<Point>(cx),
&[Point::new(0, 5)..Point::new(2, 2)]
);
// When joining an empty line don't insert a space
editor.change_selections(None, cx, |s| {
s.select_ranges([Point::new(2, 1)..Point::new(2, 2)])
});
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd\n");
assert_eq!(
editor.selections.ranges::<Point>(cx),
[Point::new(2, 3)..Point::new(2, 3)]
);
// We can remove trailing newlines
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
assert_eq!(
editor.selections.ranges::<Point>(cx),
[Point::new(2, 3)..Point::new(2, 3)]
);
// We don't blow up on the last line
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb\nccc\nddd");
assert_eq!(
editor.selections.ranges::<Point>(cx),
[Point::new(2, 3)..Point::new(2, 3)]
);
// reset to test indentation
editor.buffer.update(cx, |buffer, cx| {
buffer.edit(
[
(Point::new(1, 0)..Point::new(1, 2), " "),
(Point::new(2, 0)..Point::new(2, 3), " \n\td"),
],
None,
cx,
)
});
// We remove any leading spaces
assert_eq!(buffer.read(cx).text(), "aaa bbb\n c\n \n\td");
editor.change_selections(None, cx, |s| {
s.select_ranges([Point::new(0, 1)..Point::new(0, 1)])
});
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb c\n \n\td");
// We don't insert a space for a line containing only spaces
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb c\n\td");
// We ignore any leading tabs
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb c d");
editor
});
}
#[gpui::test]
fn test_join_lines_with_multi_selection(cx: &mut TestAppContext) {
init_test(cx, |_| {});
cx.add_window(|cx| {
let buffer = MultiBuffer::build_simple("aaa\nbbb\nccc\nddd\n\n", cx);
let mut editor = build_editor(buffer.clone(), cx);
let buffer = buffer.read(cx).as_singleton().unwrap();
editor.change_selections(None, cx, |s| {
s.select_ranges([
Point::new(0, 2)..Point::new(1, 1),
Point::new(1, 2)..Point::new(1, 2),
Point::new(3, 1)..Point::new(3, 2),
])
});
editor.join_lines(&JoinLines, cx);
assert_eq!(buffer.read(cx).text(), "aaa bbb ccc\nddd\n");
assert_eq!(
editor.selections.ranges::<Point>(cx),
[
Point::new(0, 7)..Point::new(0, 7),
Point::new(1, 3)..Point::new(1, 3)
]
);
editor
});
}
#[gpui::test]
fn test_duplicate_line(cx: &mut TestAppContext) {
init_test(cx, |_| {});
@@ -6807,6 +6979,111 @@ async fn test_copilot_disabled_globs(
assert!(copilot_requests.try_next().is_ok());
}
#[gpui::test]
async fn test_on_type_formatting_not_triggered(cx: &mut gpui::TestAppContext) {
init_test(cx, |_| {});
let mut language = Language::new(
LanguageConfig {
name: "Rust".into(),
path_suffixes: vec!["rs".to_string()],
brackets: BracketPairConfig {
pairs: vec![BracketPair {
start: "{".to_string(),
end: "}".to_string(),
close: true,
newline: true,
}],
disabled_scopes_by_bracket_ix: Vec::new(),
},
..Default::default()
},
Some(tree_sitter_rust::language()),
);
let mut fake_servers = language
.set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
capabilities: lsp::ServerCapabilities {
document_on_type_formatting_provider: Some(lsp::DocumentOnTypeFormattingOptions {
first_trigger_character: "{".to_string(),
more_trigger_character: None,
}),
..Default::default()
},
..Default::default()
}))
.await;
let fs = FakeFs::new(cx.background());
fs.insert_tree(
"/a",
json!({
"main.rs": "fn main() { let a = 5; }",
"other.rs": "// Test file",
}),
)
.await;
let project = Project::test(fs, ["/a".as_ref()], cx).await;
project.update(cx, |project, _| project.languages().add(Arc::new(language)));
let (_, workspace) = cx.add_window(|cx| Workspace::test_new(project.clone(), cx));
let worktree_id = workspace.update(cx, |workspace, cx| {
workspace.project().read_with(cx, |project, cx| {
project.worktrees(cx).next().unwrap().read(cx).id()
})
});
let buffer = project
.update(cx, |project, cx| {
project.open_local_buffer("/a/main.rs", cx)
})
.await
.unwrap();
cx.foreground().run_until_parked();
cx.foreground().start_waiting();
let fake_server = fake_servers.next().await.unwrap();
let editor_handle = workspace
.update(cx, |workspace, cx| {
workspace.open_path((worktree_id, "main.rs"), None, true, cx)
})
.await
.unwrap()
.downcast::<Editor>()
.unwrap();
fake_server.handle_request::<lsp::request::OnTypeFormatting, _, _>(|params, _| async move {
assert_eq!(
params.text_document_position.text_document.uri,
lsp::Url::from_file_path("/a/main.rs").unwrap(),
);
assert_eq!(
params.text_document_position.position,
lsp::Position::new(0, 21),
);
Ok(Some(vec![lsp::TextEdit {
new_text: "]".to_string(),
range: lsp::Range::new(lsp::Position::new(0, 22), lsp::Position::new(0, 22)),
}]))
});
editor_handle.update(cx, |editor, cx| {
cx.focus(&editor_handle);
editor.change_selections(None, cx, |s| {
s.select_ranges([Point::new(0, 21)..Point::new(0, 20)])
});
editor.handle_input("{", cx);
});
cx.foreground().run_until_parked();
buffer.read_with(cx, |buffer, _| {
assert_eq!(
buffer.text(),
"fn main() { let a = {5}; }",
"No extra braces from on type formatting should appear in the buffer"
)
});
}
fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
let point = DisplayPoint::new(row as u32, column as u32);
point..point
+16 -7
View File
@@ -1433,7 +1433,12 @@ impl EditorElement {
} else {
let style = &self.style;
let chunks = snapshot
.chunks(rows.clone(), true, Some(style.theme.suggestion))
.chunks(
rows.clone(),
true,
Some(style.theme.hint),
Some(style.theme.suggestion),
)
.map(|chunk| {
let mut highlight_style = chunk
.syntax_highlight_id
@@ -1508,6 +1513,7 @@ impl EditorElement {
editor: &mut Editor,
cx: &mut LayoutContext<Editor>,
) -> (f32, Vec<BlockLayout>) {
let mut block_id = 0;
let scroll_x = snapshot.scroll_anchor.offset.x();
let (fixed_blocks, non_fixed_blocks) = snapshot
.blocks_in_range(rows.clone())
@@ -1515,7 +1521,7 @@ impl EditorElement {
TransformBlock::ExcerptHeader { .. } => false,
TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
});
let mut render_block = |block: &TransformBlock, width: f32| {
let mut render_block = |block: &TransformBlock, width: f32, block_id: usize| {
let mut element = match block {
TransformBlock::Custom(block) => {
let align_to = block
@@ -1540,6 +1546,7 @@ impl EditorElement {
scroll_x,
gutter_width,
em_width,
block_id,
})
}
TransformBlock::ExcerptHeader {
@@ -1568,7 +1575,7 @@ impl EditorElement {
enum JumpIcon {}
MouseEventHandler::<JumpIcon, _>::new((*id).into(), cx, |state, _| {
let style = style.jump_icon.style_for(state, false);
let style = style.jump_icon.style_for(state);
Svg::new("icons/arrow_up_right_8.svg")
.with_color(style.color)
.constrained()
@@ -1675,7 +1682,8 @@ impl EditorElement {
let mut fixed_block_max_width = 0f32;
let mut blocks = Vec::new();
for (row, block) in fixed_blocks {
let element = render_block(block, f32::INFINITY);
let element = render_block(block, f32::INFINITY, block_id);
block_id += 1;
fixed_block_max_width = fixed_block_max_width.max(element.size().x() + em_width);
blocks.push(BlockLayout {
row,
@@ -1695,7 +1703,8 @@ impl EditorElement {
.max(gutter_width + scroll_width),
BlockStyle::Fixed => unreachable!(),
};
let element = render_block(block, width);
let element = render_block(block, width, block_id);
block_id += 1;
blocks.push(BlockLayout {
row,
element,
@@ -1958,7 +1967,7 @@ impl Element<Editor> for EditorElement {
let em_advance = style.text.em_advance(cx.font_cache());
let overscroll = vec2f(em_width, 0.);
let snapshot = {
editor.set_visible_line_count(size.y() / line_height);
editor.set_visible_line_count(size.y() / line_height, cx);
let editor_width = text_width - gutter_margin - overscroll.x() - em_width;
let wrap_width = match editor.soft_wrap_mode(cx) {
@@ -2131,7 +2140,7 @@ impl Element<Editor> for EditorElement {
.folds
.ellipses
.background
.style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize), false)
.style_for(&mut cx.mouse_state::<FoldMarkers>(id as usize))
.color;
(id, fold, color)
File diff suppressed because it is too large Load Diff
+5 -5
View File
@@ -1010,7 +1010,7 @@ impl MultiBuffer {
let suffix = cursor.suffix(&());
let changed_trailing_excerpt = suffix.is_empty();
new_excerpts.push_tree(suffix, &());
new_excerpts.append(suffix, &());
drop(cursor);
snapshot.excerpts = new_excerpts;
snapshot.excerpt_ids = new_excerpt_ids;
@@ -1193,7 +1193,7 @@ impl MultiBuffer {
while let Some(excerpt_id) = excerpt_ids.next() {
// Seek to the next excerpt to remove, preserving any preceding excerpts.
let locator = snapshot.excerpt_locator_for_id(excerpt_id);
new_excerpts.push_tree(cursor.slice(&Some(locator), Bias::Left, &()), &());
new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
if let Some(mut excerpt) = cursor.item() {
if excerpt.id != excerpt_id {
@@ -1245,7 +1245,7 @@ impl MultiBuffer {
}
let suffix = cursor.suffix(&());
let changed_trailing_excerpt = suffix.is_empty();
new_excerpts.push_tree(suffix, &());
new_excerpts.append(suffix, &());
drop(cursor);
snapshot.excerpts = new_excerpts;
@@ -1509,7 +1509,7 @@ impl MultiBuffer {
let mut cursor = snapshot.excerpts.cursor::<(Option<&Locator>, usize)>();
for (locator, buffer, buffer_edited) in excerpts_to_edit {
new_excerpts.push_tree(cursor.slice(&Some(locator), Bias::Left, &()), &());
new_excerpts.append(cursor.slice(&Some(locator), Bias::Left, &()), &());
let old_excerpt = cursor.item().unwrap();
let buffer = buffer.read(cx);
let buffer_id = buffer.remote_id();
@@ -1549,7 +1549,7 @@ impl MultiBuffer {
new_excerpts.push(new_excerpt, &());
cursor.next(&());
}
new_excerpts.push_tree(cursor.suffix(&()), &());
new_excerpts.append(cursor.suffix(&()), &());
drop(cursor);
snapshot.excerpts = new_excerpts;
+17
View File
@@ -49,6 +49,10 @@ impl Anchor {
}
}
pub fn bias(&self) -> Bias {
self.text_anchor.bias
}
pub fn bias_left(&self, snapshot: &MultiBufferSnapshot) -> Anchor {
if self.text_anchor.bias != Bias::Left {
if let Some(excerpt) = snapshot.excerpt(self.excerpt_id) {
@@ -81,6 +85,19 @@ impl Anchor {
{
snapshot.summary_for_anchor(self)
}
pub fn is_valid(&self, snapshot: &MultiBufferSnapshot) -> bool {
if *self == Anchor::min() || *self == Anchor::max() {
true
} else if let Some(excerpt) = snapshot.excerpt(self.excerpt_id) {
excerpt.contains(self)
&& (self.text_anchor == excerpt.range.context.start
|| self.text_anchor == excerpt.range.context.end
|| self.text_anchor.is_valid(&excerpt.buffer))
} else {
false
}
}
}
impl ToOffset for Anchor {
+21 -5
View File
@@ -13,13 +13,14 @@ use gpui::{
};
use language::{Bias, Point};
use util::ResultExt;
use workspace::WorkspaceId;
use workspace::{item::Item, WorkspaceId};
use crate::{
display_map::{DisplaySnapshot, ToDisplayPoint},
hover_popover::hide_hover,
persistence::DB,
Anchor, DisplayPoint, Editor, EditorMode, Event, MultiBufferSnapshot, ToPoint,
Anchor, DisplayPoint, Editor, EditorMode, Event, InlayRefreshReason, MultiBufferSnapshot,
ToPoint,
};
use self::{
@@ -293,8 +294,19 @@ impl Editor {
self.scroll_manager.visible_line_count
}
pub(crate) fn set_visible_line_count(&mut self, lines: f32) {
self.scroll_manager.visible_line_count = Some(lines)
pub(crate) fn set_visible_line_count(&mut self, lines: f32, cx: &mut ViewContext<Self>) {
let opened_first_time = self.scroll_manager.visible_line_count.is_none();
self.scroll_manager.visible_line_count = Some(lines);
if opened_first_time {
cx.spawn(|editor, mut cx| async move {
editor
.update(&mut cx, |editor, cx| {
editor.refresh_inlays(InlayRefreshReason::NewLinesShown, cx)
})
.ok()
})
.detach()
}
}
pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
@@ -320,6 +332,10 @@ impl Editor {
workspace_id,
cx,
);
if !self.is_singleton(cx) {
self.refresh_inlays(InlayRefreshReason::NewLinesShown, cx);
}
}
pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
@@ -368,7 +384,7 @@ impl Editor {
}
let cur_position = self.scroll_position(cx);
let new_pos = cur_position + vec2f(0., amount.lines(self) - 1.);
let new_pos = cur_position + vec2f(0., amount.lines(self));
self.set_scroll_position(new_pos, cx);
}
+6 -6
View File
@@ -27,22 +27,22 @@ pub fn init(cx: &mut AppContext) {
cx.add_action(Editor::scroll_cursor_center);
cx.add_action(Editor::scroll_cursor_bottom);
cx.add_action(|this: &mut Editor, _: &LineDown, cx| {
this.scroll_screen(&ScrollAmount::LineDown, cx)
this.scroll_screen(&ScrollAmount::Line(1.), cx)
});
cx.add_action(|this: &mut Editor, _: &LineUp, cx| {
this.scroll_screen(&ScrollAmount::LineUp, cx)
this.scroll_screen(&ScrollAmount::Line(-1.), cx)
});
cx.add_action(|this: &mut Editor, _: &HalfPageDown, cx| {
this.scroll_screen(&ScrollAmount::HalfPageDown, cx)
this.scroll_screen(&ScrollAmount::Page(0.5), cx)
});
cx.add_action(|this: &mut Editor, _: &HalfPageUp, cx| {
this.scroll_screen(&ScrollAmount::HalfPageUp, cx)
this.scroll_screen(&ScrollAmount::Page(-0.5), cx)
});
cx.add_action(|this: &mut Editor, _: &PageDown, cx| {
this.scroll_screen(&ScrollAmount::PageDown, cx)
this.scroll_screen(&ScrollAmount::Page(1.), cx)
});
cx.add_action(|this: &mut Editor, _: &PageUp, cx| {
this.scroll_screen(&ScrollAmount::PageUp, cx)
this.scroll_screen(&ScrollAmount::Page(-1.), cx)
});
}
+15 -17
View File
@@ -6,12 +6,10 @@ use crate::Editor;
#[derive(Clone, PartialEq, Deserialize)]
pub enum ScrollAmount {
LineUp,
LineDown,
HalfPageUp,
HalfPageDown,
PageUp,
PageDown,
// Scroll N lines (positive is towards the end of the document)
Line(f32),
// Scroll N pages (positive is towards the end of the document)
Page(f32),
}
impl ScrollAmount {
@@ -24,10 +22,10 @@ impl ScrollAmount {
let context_menu = editor.context_menu.as_mut()?;
match self {
Self::LineDown | Self::HalfPageDown => context_menu.select_next(cx),
Self::LineUp | Self::HalfPageUp => context_menu.select_prev(cx),
Self::PageDown => context_menu.select_last(cx),
Self::PageUp => context_menu.select_first(cx),
Self::Line(c) if *c > 0. => context_menu.select_next(cx),
Self::Line(_) => context_menu.select_prev(cx),
Self::Page(c) if *c > 0. => context_menu.select_last(cx),
Self::Page(_) => context_menu.select_first(cx),
}
.then_some(())
})
@@ -36,13 +34,13 @@ impl ScrollAmount {
pub fn lines(&self, editor: &mut Editor) -> f32 {
match self {
Self::LineDown => 1.,
Self::LineUp => -1.,
Self::HalfPageDown => editor.visible_line_count().map(|l| l / 2.).unwrap_or(1.),
Self::HalfPageUp => -editor.visible_line_count().map(|l| l / 2.).unwrap_or(1.),
// Minus 1. here so that there is a pivot line that stays on the screen
Self::PageDown => editor.visible_line_count().unwrap_or(1.) - 1.,
Self::PageUp => -editor.visible_line_count().unwrap_or(1.) - 1.,
Self::Line(count) => *count,
Self::Page(count) => editor
.visible_line_count()
// subtract one to leave an anchor line
// round towards zero (so page-up and page-down are symmetric)
.map(|l| ((l - 1.) * count).trunc())
.unwrap_or(0.),
}
}
}
@@ -41,7 +41,8 @@ impl View for DeployFeedbackButton {
.status_bar
.panel_buttons
.button
.style_for(state, active);
.in_state(active)
.style_for(state);
Svg::new("icons/feedback_16.svg")
.with_color(style.icon_color)
@@ -48,7 +48,7 @@ impl View for SubmitFeedbackButton {
let theme = theme::current(cx).clone();
enum SubmitFeedbackButton {}
MouseEventHandler::<SubmitFeedbackButton, Self>::new(0, cx, |state, _| {
let style = theme.feedback.submit_button.style_for(state, false);
let style = theme.feedback.submit_button.style_for(state);
Label::new("Submit as Markdown", style.text.clone())
.contained()
.with_style(style.container)
+1 -1
View File
@@ -546,7 +546,7 @@ impl PickerDelegate for FileFinderDelegate {
.get(ix)
.expect("Invalid matches state: no element for index {ix}");
let theme = theme::current(cx);
let style = theme.picker.item.style_for(mouse_state, selected);
let style = theme.picker.item.in_state(selected).style_for(mouse_state);
let (file_name, file_name_positions, full_path, full_path_positions) =
self.labels_for_match(path_match, cx, ix);
Flex::column()
+4
View File
@@ -31,6 +31,10 @@ serde_derive.workspace = true
serde_json.workspace = true
log.workspace = true
libc = "0.2"
time.workspace = true
[dev-dependencies]
gpui = { path = "../gpui", features = ["test-support"] }
[features]
test-support = []
+86 -26
View File
@@ -108,6 +108,7 @@ pub trait Fs: Send + Sync {
async fn canonicalize(&self, path: &Path) -> Result<PathBuf>;
async fn is_file(&self, path: &Path) -> bool;
async fn metadata(&self, path: &Path) -> Result<Option<Metadata>>;
async fn read_link(&self, path: &Path) -> Result<PathBuf>;
async fn read_dir(
&self,
path: &Path,
@@ -278,6 +279,9 @@ impl Fs for RealFs {
async fn save(&self, path: &Path, text: &Rope, line_ending: LineEnding) -> Result<()> {
let buffer_size = text.summary().len.min(10 * 1024);
if let Some(path) = path.parent() {
self.create_dir(path).await?;
}
let file = smol::fs::File::create(path).await?;
let mut writer = smol::io::BufWriter::with_capacity(buffer_size, file);
for chunk in chunks(text, line_ending) {
@@ -323,6 +327,11 @@ impl Fs for RealFs {
}))
}
async fn read_link(&self, path: &Path) -> Result<PathBuf> {
let path = smol::fs::read_link(path).await?;
Ok(path)
}
async fn read_dir(
&self,
path: &Path,
@@ -382,6 +391,8 @@ struct FakeFsState {
event_txs: Vec<smol::channel::Sender<Vec<fsevent::Event>>>,
events_paused: bool,
buffered_events: Vec<fsevent::Event>,
metadata_call_count: usize,
read_dir_call_count: usize,
}
#[cfg(any(test, feature = "test-support"))]
@@ -407,46 +418,51 @@ enum FakeFsEntry {
impl FakeFsState {
fn read_path<'a>(&'a self, target: &Path) -> Result<Arc<Mutex<FakeFsEntry>>> {
Ok(self
.try_read_path(target)
.try_read_path(target, true)
.ok_or_else(|| anyhow!("path does not exist: {}", target.display()))?
.0)
}
fn try_read_path<'a>(&'a self, target: &Path) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
fn try_read_path<'a>(
&'a self,
target: &Path,
follow_symlink: bool,
) -> Option<(Arc<Mutex<FakeFsEntry>>, PathBuf)> {
let mut path = target.to_path_buf();
let mut real_path = PathBuf::new();
let mut canonical_path = PathBuf::new();
let mut entry_stack = Vec::new();
'outer: loop {
let mut path_components = path.components().collect::<collections::VecDeque<_>>();
while let Some(component) = path_components.pop_front() {
let mut path_components = path.components().peekable();
while let Some(component) = path_components.next() {
match component {
Component::Prefix(_) => panic!("prefix paths aren't supported"),
Component::RootDir => {
entry_stack.clear();
entry_stack.push(self.root.clone());
real_path.clear();
real_path.push("/");
canonical_path.clear();
canonical_path.push("/");
}
Component::CurDir => {}
Component::ParentDir => {
entry_stack.pop()?;
real_path.pop();
canonical_path.pop();
}
Component::Normal(name) => {
let current_entry = entry_stack.last().cloned()?;
let current_entry = current_entry.lock();
if let FakeFsEntry::Dir { entries, .. } = &*current_entry {
let entry = entries.get(name.to_str().unwrap()).cloned()?;
let _entry = entry.lock();
if let FakeFsEntry::Symlink { target, .. } = &*_entry {
let mut target = target.clone();
target.extend(path_components);
path = target;
continue 'outer;
} else {
entry_stack.push(entry.clone());
real_path.push(name);
if path_components.peek().is_some() || follow_symlink {
let entry = entry.lock();
if let FakeFsEntry::Symlink { target, .. } = &*entry {
let mut target = target.clone();
target.extend(path_components);
path = target;
continue 'outer;
}
}
entry_stack.push(entry.clone());
canonical_path.push(name);
} else {
return None;
}
@@ -455,7 +471,7 @@ impl FakeFsState {
}
break;
}
entry_stack.pop().map(|entry| (entry, real_path))
Some((entry_stack.pop()?, canonical_path))
}
fn write_path<Fn, T>(&self, path: &Path, callback: Fn) -> Result<T>
@@ -525,6 +541,8 @@ impl FakeFs {
event_txs: Default::default(),
buffered_events: Vec::new(),
events_paused: false,
read_dir_call_count: 0,
metadata_call_count: 0,
}),
})
}
@@ -761,6 +779,16 @@ impl FakeFs {
result
}
/// How many `read_dir` calls have been issued.
pub fn read_dir_call_count(&self) -> usize {
self.state.lock().read_dir_call_count
}
/// How many `metadata` calls have been issued.
pub fn metadata_call_count(&self) -> usize {
self.state.lock().metadata_call_count
}
async fn simulate_random_delay(&self) {
self.executor
.upgrade()
@@ -776,6 +804,10 @@ impl FakeFsEntry {
matches!(self, Self::File { .. })
}
fn is_symlink(&self) -> bool {
matches!(self, Self::Symlink { .. })
}
fn file_content(&self, path: &Path) -> Result<&String> {
if let Self::File { content, .. } = self {
Ok(content)
@@ -1048,6 +1080,9 @@ impl Fs for FakeFs {
self.simulate_random_delay().await;
let path = normalize_path(path);
let content = chunks(text, line_ending).collect();
if let Some(path) = path.parent() {
self.create_dir(path).await?;
}
self.write_file_internal(path, content)?;
Ok(())
}
@@ -1056,8 +1091,8 @@ impl Fs for FakeFs {
let path = normalize_path(path);
self.simulate_random_delay().await;
let state = self.state.lock();
if let Some((_, real_path)) = state.try_read_path(&path) {
Ok(real_path)
if let Some((_, canonical_path)) = state.try_read_path(&path, true) {
Ok(canonical_path)
} else {
Err(anyhow!("path does not exist: {}", path.display()))
}
@@ -1067,7 +1102,7 @@ impl Fs for FakeFs {
let path = normalize_path(path);
self.simulate_random_delay().await;
let state = self.state.lock();
if let Some((entry, _)) = state.try_read_path(&path) {
if let Some((entry, _)) = state.try_read_path(&path, true) {
entry.lock().is_file()
} else {
false
@@ -1077,11 +1112,19 @@ impl Fs for FakeFs {
async fn metadata(&self, path: &Path) -> Result<Option<Metadata>> {
self.simulate_random_delay().await;
let path = normalize_path(path);
let state = self.state.lock();
if let Some((entry, real_path)) = state.try_read_path(&path) {
let entry = entry.lock();
let is_symlink = real_path != path;
let mut state = self.state.lock();
state.metadata_call_count += 1;
if let Some((mut entry, _)) = state.try_read_path(&path, false) {
let is_symlink = entry.lock().is_symlink();
if is_symlink {
if let Some(e) = state.try_read_path(&path, true).map(|e| e.0) {
entry = e;
} else {
return Ok(None);
}
}
let entry = entry.lock();
Ok(Some(match &*entry {
FakeFsEntry::File { inode, mtime, .. } => Metadata {
inode: *inode,
@@ -1102,13 +1145,30 @@ impl Fs for FakeFs {
}
}
async fn read_link(&self, path: &Path) -> Result<PathBuf> {
self.simulate_random_delay().await;
let path = normalize_path(path);
let state = self.state.lock();
if let Some((entry, _)) = state.try_read_path(&path, false) {
let entry = entry.lock();
if let FakeFsEntry::Symlink { target } = &*entry {
Ok(target.clone())
} else {
Err(anyhow!("not a symlink: {}", path.display()))
}
} else {
Err(anyhow!("path does not exist: {}", path.display()))
}
}
async fn read_dir(
&self,
path: &Path,
) -> Result<Pin<Box<dyn Send + Stream<Item = Result<PathBuf>>>>> {
self.simulate_random_delay().await;
let path = normalize_path(path);
let state = self.state.lock();
let mut state = self.state.lock();
state.read_dir_call_count += 1;
let entry = state.read_path(&path)?;
let mut entry = entry.lock();
let children = entry.dir_entries(&path)?;
+47 -1
View File
@@ -1,6 +1,6 @@
use anyhow::Result;
use collections::HashMap;
use git2::ErrorCode;
use git2::{BranchType, ErrorCode};
use parking_lot::Mutex;
use rpc::proto;
use serde_derive::{Deserialize, Serialize};
@@ -16,6 +16,12 @@ use util::ResultExt;
pub use git2::Repository as LibGitRepository;
#[derive(Clone, Debug, Hash, PartialEq)]
pub struct Branch {
pub name: Box<str>,
/// Timestamp of most recent commit, normalized to Unix Epoch format.
pub unix_timestamp: Option<i64>,
}
#[async_trait::async_trait]
pub trait GitRepository: Send {
fn reload_index(&self);
@@ -27,6 +33,12 @@ pub trait GitRepository: Send {
fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>>;
fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>>;
fn branches(&self) -> Result<Vec<Branch>> {
Ok(vec![])
}
fn change_branch(&self, _: &str) -> Result<()> {
Ok(())
}
}
impl std::fmt::Debug for dyn GitRepository {
@@ -106,6 +118,40 @@ impl GitRepository for LibGitRepository {
}
}
}
fn branches(&self) -> Result<Vec<Branch>> {
let local_branches = self.branches(Some(BranchType::Local))?;
let valid_branches = local_branches
.filter_map(|branch| {
branch.ok().and_then(|(branch, _)| {
let name = branch.name().ok().flatten().map(Box::from)?;
let timestamp = branch.get().peel_to_commit().ok()?.time();
let unix_timestamp = timestamp.seconds();
let timezone_offset = timestamp.offset_minutes();
let utc_offset =
time::UtcOffset::from_whole_seconds(timezone_offset * 60).ok()?;
let unix_timestamp =
time::OffsetDateTime::from_unix_timestamp(unix_timestamp).ok()?;
Some(Branch {
name,
unix_timestamp: Some(unix_timestamp.to_offset(utc_offset).unix_timestamp()),
})
})
})
.collect();
Ok(valid_branches)
}
fn change_branch(&self, name: &str) -> Result<()> {
let revision = self.find_branch(name, BranchType::Local)?;
let revision = revision.get();
let as_tree = revision.peel_to_tree()?;
self.checkout_tree(as_tree.as_object(), None)?;
self.set_head(
revision
.name()
.ok_or_else(|| anyhow::anyhow!("Branch name could not be retrieved"))?,
)?;
Ok(())
}
}
fn read_status(status: git2::Status) -> Option<GitFileStatus> {
+11
View File
@@ -24,6 +24,7 @@ pub struct GoToLine {
prev_scroll_position: Option<Vector2F>,
cursor_point: Point,
max_point: Point,
has_focus: bool,
}
pub enum Event {
@@ -57,6 +58,7 @@ impl GoToLine {
prev_scroll_position: scroll_position,
cursor_point,
max_point,
has_focus: false,
}
}
@@ -178,11 +180,20 @@ impl View for GoToLine {
}
fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
self.has_focus = true;
cx.focus(&self.line_editor);
}
fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
self.has_focus = false;
}
}
impl Modal for GoToLine {
fn has_focus(&self) -> bool {
self.has_focus
}
fn dismiss_on_event(event: &Self::Event) -> bool {
matches!(event, Event::Dismissed)
}
+39 -15
View File
@@ -152,6 +152,29 @@ impl App {
asset_source,
))));
foreground_platform.on_event(Box::new({
let cx = app.0.clone();
move |event| {
if let Event::KeyDown(KeyDownEvent { keystroke, .. }) = &event {
// Allow system menu "cmd-?" shortcut to be overridden
if keystroke.cmd
&& !keystroke.shift
&& !keystroke.alt
&& !keystroke.function
&& keystroke.key == "?"
{
if cx
.borrow_mut()
.update_active_window(|cx| cx.dispatch_keystroke(keystroke))
.unwrap_or(false)
{
return true;
}
}
}
false
}
}));
foreground_platform.on_quit(Box::new({
let cx = app.0.clone();
move || {
@@ -445,7 +468,7 @@ type WindowBoundsCallback = Box<dyn FnMut(WindowBounds, Uuid, &mut WindowContext
type KeystrokeCallback =
Box<dyn FnMut(&Keystroke, &MatchResult, Option<&Box<dyn Action>>, &mut WindowContext) -> bool>;
type ActiveLabeledTasksCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
type DeserializeActionCallback = fn(json: &str) -> anyhow::Result<Box<dyn Action>>;
type DeserializeActionCallback = fn(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>;
type WindowShouldCloseSubscriptionCallback = Box<dyn FnMut(&mut AppContext) -> bool>;
pub struct AppContext {
@@ -624,14 +647,14 @@ impl AppContext {
pub fn deserialize_action(
&self,
name: &str,
argument: Option<&str>,
argument: Option<serde_json::Value>,
) -> Result<Box<dyn Action>> {
let callback = self
.action_deserializers
.get(name)
.ok_or_else(|| anyhow!("unknown action {}", name))?
.1;
callback(argument.unwrap_or("{}"))
callback(argument.unwrap_or_else(|| serde_json::Value::Object(Default::default())))
.with_context(|| format!("invalid data for action {}", name))
}
@@ -2948,14 +2971,12 @@ impl<'a, 'b, V: View> ViewContext<'a, 'b, V> {
}
pub fn focus(&mut self, handle: &AnyViewHandle) {
self.window_context
.focus(handle.window_id, Some(handle.view_id));
self.window_context.focus(Some(handle.view_id));
}
pub fn focus_self(&mut self) {
let window_id = self.window_id;
let view_id = self.view_id;
self.window_context.focus(window_id, Some(view_id));
self.window_context.focus(Some(view_id));
}
pub fn is_self_focused(&self) -> bool {
@@ -2974,8 +2995,7 @@ impl<'a, 'b, V: View> ViewContext<'a, 'b, V> {
}
pub fn blur(&mut self) {
let window_id = self.window_id;
self.window_context.focus(window_id, None);
self.window_context.focus(None);
}
pub fn on_window_should_close<F>(&mut self, mut callback: F)
@@ -3281,11 +3301,15 @@ impl<'a, 'b, V: View> ViewContext<'a, 'b, V> {
let region_id = MouseRegionId::new::<Tag>(self.view_id, region_id);
MouseState {
hovered: self.window.hovered_region_ids.contains(&region_id),
clicked: self
.window
.clicked_region_ids
.get(&region_id)
.and_then(|_| self.window.clicked_button),
clicked: if let Some((clicked_region_id, button)) = self.window.clicked_region {
if region_id == clicked_region_id {
Some(button)
} else {
None
}
} else {
None
},
accessed_hovered: false,
accessed_clicked: false,
}
@@ -5573,7 +5597,7 @@ mod tests {
let action1 = cx
.deserialize_action(
"test::something::ComplexAction",
Some(r#"{"arg": "a", "count": 5}"#),
Some(serde_json::from_str(r#"{"arg": "a", "count": 5}"#).unwrap()),
)
.unwrap();
let action2 = cx
+4 -4
View File
@@ -11,7 +11,7 @@ pub trait Action: 'static {
fn qualified_name() -> &'static str
where
Self: Sized;
fn from_json_str(json: &str) -> anyhow::Result<Box<dyn Action>>
fn from_json_str(json: serde_json::Value) -> anyhow::Result<Box<dyn Action>>
where
Self: Sized;
}
@@ -38,7 +38,7 @@ macro_rules! actions {
$crate::__impl_action! {
$namespace,
$name,
fn from_json_str(_: &str) -> $crate::anyhow::Result<Box<dyn $crate::Action>> {
fn from_json_str(_: $crate::serde_json::Value) -> $crate::anyhow::Result<Box<dyn $crate::Action>> {
Ok(Box::new(Self))
}
}
@@ -58,8 +58,8 @@ macro_rules! impl_actions {
$crate::__impl_action! {
$namespace,
$name,
fn from_json_str(json: &str) -> $crate::anyhow::Result<Box<dyn $crate::Action>> {
Ok(Box::new($crate::serde_json::from_str::<Self>(json)?))
fn from_json_str(json: $crate::serde_json::Value) -> $crate::anyhow::Result<Box<dyn $crate::Action>> {
Ok(Box::new($crate::serde_json::from_value::<Self>(json)?))
}
}
)*
+40 -25
View File
@@ -8,14 +8,14 @@ use crate::{
MouseButton, MouseMovedEvent, PromptLevel, WindowBounds,
},
scene::{
CursorRegion, MouseClick, MouseDown, MouseDownOut, MouseDrag, MouseEvent, MouseHover,
MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut, Scene,
CursorRegion, MouseClick, MouseClickOut, MouseDown, MouseDownOut, MouseDrag, MouseEvent,
MouseHover, MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut, Scene,
},
text_layout::TextLayoutCache,
util::post_inc,
Action, AnyView, AnyViewHandle, AppContext, BorrowAppContext, BorrowWindowContext, Effect,
Element, Entity, Handle, LayoutContext, MouseRegion, MouseRegionId, SceneBuilder, Subscription,
View, ViewContext, ViewHandle, WindowInvalidation,
Element, Entity, Handle, LayoutContext, MouseRegion, MouseRegionId, NoAction, SceneBuilder,
Subscription, View, ViewContext, ViewHandle, WindowInvalidation,
};
use anyhow::{anyhow, bail, Result};
use collections::{HashMap, HashSet};
@@ -53,7 +53,7 @@ pub struct Window {
last_mouse_moved_event: Option<Event>,
pub(crate) hovered_region_ids: HashSet<MouseRegionId>,
pub(crate) clicked_region_ids: HashSet<MouseRegionId>,
pub(crate) clicked_button: Option<MouseButton>,
pub(crate) clicked_region: Option<(MouseRegionId, MouseButton)>,
mouse_position: Vector2F,
text_layout_cache: TextLayoutCache,
}
@@ -86,7 +86,7 @@ impl Window {
last_mouse_moved_event: None,
hovered_region_ids: Default::default(),
clicked_region_ids: Default::default(),
clicked_button: None,
clicked_region: None,
mouse_position: vec2f(0., 0.),
titlebar_height,
appearance,
@@ -394,7 +394,7 @@ impl<'a> WindowContext<'a> {
.iter()
.filter_map(move |(name, (type_id, deserialize))| {
if let Some(action_depth) = handler_depths_by_action_type.get(type_id).copied() {
let action = deserialize("{}").ok()?;
let action = deserialize(serde_json::Value::Object(Default::default())).ok()?;
let bindings = self
.keystroke_matcher
.bindings_for_action_type(*type_id)
@@ -434,7 +434,11 @@ impl<'a> WindowContext<'a> {
MatchResult::None => false,
MatchResult::Pending => true,
MatchResult::Matches(matches) => {
let no_action_id = (NoAction {}).id();
for (view_id, action) in matches {
if action.id() == no_action_id {
return false;
}
if self.dispatch_action(Some(*view_id), action.as_ref()) {
self.keystroke_matcher.clear_pending();
handled_by = Some(action.boxed_clone());
@@ -480,8 +484,8 @@ impl<'a> WindowContext<'a> {
// specific ancestor element that contained both [positions]'
// So we need to store the overlapping regions on mouse down.
// If there is already clicked_button stored, don't replace it.
if self.window.clicked_button.is_none() {
// If there is already region being clicked, don't replace it.
if self.window.clicked_region.is_none() {
self.window.clicked_region_ids = self
.window
.mouse_regions
@@ -495,7 +499,17 @@ impl<'a> WindowContext<'a> {
})
.collect();
self.window.clicked_button = Some(e.button);
let mut highest_z_index = 0;
let mut clicked_region_id = None;
for (region, z_index) in self.window.mouse_regions.iter() {
if region.bounds.contains_point(e.position) && *z_index >= highest_z_index {
highest_z_index = *z_index;
clicked_region_id = Some(region.id());
}
}
self.window.clicked_region =
clicked_region_id.map(|region_id| (region_id, e.button));
}
mouse_events.push(MouseEvent::Down(MouseDown {
@@ -524,6 +538,10 @@ impl<'a> WindowContext<'a> {
region: Default::default(),
platform_event: e.clone(),
}));
mouse_events.push(MouseEvent::ClickOut(MouseClickOut {
region: Default::default(),
platform_event: e.clone(),
}));
}
Event::MouseMoved(
@@ -556,7 +574,7 @@ impl<'a> WindowContext<'a> {
prev_mouse_position: self.window.mouse_position,
platform_event: e.clone(),
}));
} else if let Some(clicked_button) = self.window.clicked_button {
} else if let Some((_, clicked_button)) = self.window.clicked_region {
// Mouse up event happened outside the current window. Simulate mouse up button event
let button_event = e.to_button_event(clicked_button);
mouse_events.push(MouseEvent::Up(MouseUp {
@@ -679,8 +697,8 @@ impl<'a> WindowContext<'a> {
// Only raise click events if the released button is the same as the one stored
if self
.window
.clicked_button
.map(|clicked_button| clicked_button == e.button)
.clicked_region
.map(|(_, clicked_button)| clicked_button == e.button)
.unwrap_or(false)
{
// Clear clicked regions and clicked button
@@ -688,7 +706,7 @@ impl<'a> WindowContext<'a> {
&mut self.window.clicked_region_ids,
Default::default(),
);
self.window.clicked_button = None;
self.window.clicked_region = None;
// Find regions which still overlap with the mouse since the last MouseDown happened
for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
@@ -712,7 +730,10 @@ impl<'a> WindowContext<'a> {
}
}
MouseEvent::MoveOut(_) | MouseEvent::UpOut(_) | MouseEvent::DownOut(_) => {
MouseEvent::MoveOut(_)
| MouseEvent::UpOut(_)
| MouseEvent::DownOut(_)
| MouseEvent::ClickOut(_) => {
for (mouse_region, _) in self.window.mouse_regions.iter().rev() {
// NOT contains
if !mouse_region
@@ -860,18 +881,10 @@ impl<'a> WindowContext<'a> {
}
for view_id in &invalidation.updated {
let titlebar_height = self.window.titlebar_height;
let hovered_region_ids = self.window.hovered_region_ids.clone();
let clicked_region_ids = self
.window
.clicked_button
.map(|button| (self.window.clicked_region_ids.clone(), button));
let element = self
.render_view(RenderParams {
view_id: *view_id,
titlebar_height,
hovered_region_ids,
clicked_region_ids,
refreshing: false,
appearance,
})
@@ -1085,6 +1098,10 @@ impl<'a> WindowContext<'a> {
self.window.focused_view_id
}
pub fn focus(&mut self, view_id: Option<usize>) {
self.app_context.focus(self.window_id, view_id);
}
pub fn window_bounds(&self) -> WindowBounds {
self.window.platform_window.bounds()
}
@@ -1176,8 +1193,6 @@ impl<'a> WindowContext<'a> {
pub struct RenderParams {
pub view_id: usize,
pub titlebar_height: f32,
pub hovered_region_ids: HashSet<MouseRegionId>,
pub clicked_region_ids: Option<(HashSet<MouseRegionId>, MouseButton)>,
pub refreshing: bool,
pub appearance: Appearance,
}
+3 -2
View File
@@ -6,15 +6,16 @@ use std::{
use crate::json::ToJson;
use pathfinder_color::{ColorF, ColorU};
use schemars::JsonSchema;
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer,
};
use serde_json::json;
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, JsonSchema)]
#[repr(transparent)]
pub struct Color(ColorU);
pub struct Color(#[schemars(with = "String")] ColorU);
impl Color {
pub fn transparent_black() -> Self {
+1 -91
View File
@@ -41,13 +41,7 @@ use collections::HashMap;
use core::panic;
use json::ToJson;
use smallvec::SmallVec;
use std::{
any::Any,
borrow::Cow,
marker::PhantomData,
mem,
ops::{Deref, DerefMut, Range},
};
use std::{any::Any, borrow::Cow, mem, ops::Range};
pub trait Element<V: View>: 'static {
type LayoutState;
@@ -567,90 +561,6 @@ impl<V: View> RootElement<V> {
}
}
pub trait Component<V: View>: 'static {
fn render(&self, view: &mut V, cx: &mut ViewContext<V>) -> AnyElement<V>;
}
pub struct ComponentHost<V: View, C: Component<V>> {
component: C,
view_type: PhantomData<V>,
}
impl<V: View, C: Component<V>> ComponentHost<V, C> {
pub fn new(c: C) -> Self {
Self {
component: c,
view_type: PhantomData,
}
}
}
impl<V: View, C: Component<V>> Deref for ComponentHost<V, C> {
type Target = C;
fn deref(&self) -> &Self::Target {
&self.component
}
}
impl<V: View, C: Component<V>> DerefMut for ComponentHost<V, C> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.component
}
}
impl<V: View, C: Component<V>> Element<V> for ComponentHost<V, C> {
type LayoutState = AnyElement<V>;
type PaintState = ();
fn layout(
&mut self,
constraint: SizeConstraint,
view: &mut V,
cx: &mut LayoutContext<V>,
) -> (Vector2F, AnyElement<V>) {
let mut element = self.component.render(view, cx);
let size = element.layout(constraint, view, cx);
(size, element)
}
fn paint(
&mut self,
scene: &mut SceneBuilder,
bounds: RectF,
visible_bounds: RectF,
element: &mut AnyElement<V>,
view: &mut V,
cx: &mut ViewContext<V>,
) {
element.paint(scene, bounds.origin(), visible_bounds, view, cx);
}
fn rect_for_text_range(
&self,
range_utf16: Range<usize>,
_: RectF,
_: RectF,
element: &AnyElement<V>,
_: &(),
view: &V,
cx: &ViewContext<V>,
) -> Option<RectF> {
element.rect_for_text_range(range_utf16, view, cx)
}
fn debug(
&self,
_: RectF,
element: &AnyElement<V>,
_: &(),
view: &V,
cx: &ViewContext<V>,
) -> serde_json::Value {
element.debug(view, cx)
}
}
pub trait AnyRootElement {
fn layout(
&mut self,
+6 -4
View File
@@ -12,10 +12,11 @@ use crate::{
scene::{self, Border, CursorRegion, Quad},
AnyElement, Element, LayoutContext, SceneBuilder, SizeConstraint, View, ViewContext,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]
pub struct ContainerStyle {
#[serde(default)]
pub margin: Margin,
@@ -332,7 +333,7 @@ impl ToJson for ContainerStyle {
}
}
#[derive(Clone, Copy, Debug, Default)]
#[derive(Clone, Copy, Debug, Default, JsonSchema)]
pub struct Margin {
pub top: f32,
pub left: f32,
@@ -359,7 +360,7 @@ impl ToJson for Margin {
}
}
#[derive(Clone, Copy, Debug, Default)]
#[derive(Clone, Copy, Debug, Default, JsonSchema)]
pub struct Padding {
pub top: f32,
pub left: f32,
@@ -486,9 +487,10 @@ impl ToJson for Padding {
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[derive(Clone, Copy, Debug, Default, Deserialize, JsonSchema)]
pub struct Shadow {
#[serde(default, deserialize_with = "deserialize_vec2f")]
#[schemars(with = "Vec::<f32>")]
offset: Vector2F,
#[serde(default)]
blur: f32,
+2 -1
View File
@@ -8,6 +8,7 @@ use crate::{
scene, Border, Element, ImageData, LayoutContext, SceneBuilder, SizeConstraint, View,
ViewContext,
};
use schemars::JsonSchema;
use serde::Deserialize;
use std::{ops::Range, sync::Arc};
@@ -21,7 +22,7 @@ pub struct Image {
style: ImageStyle,
}
#[derive(Copy, Clone, Default, Deserialize)]
#[derive(Copy, Clone, Default, Deserialize, JsonSchema)]
pub struct ImageStyle {
#[serde(default)]
pub border: Border,
+3 -1
View File
@@ -10,6 +10,7 @@ use crate::{
text_layout::{Line, RunStyle},
Element, LayoutContext, SceneBuilder, SizeConstraint, View, ViewContext,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use smallvec::{smallvec, SmallVec};
@@ -20,7 +21,7 @@ pub struct Label {
highlight_indices: Vec<usize>,
}
#[derive(Clone, Debug, Deserialize, Default)]
#[derive(Clone, Debug, Deserialize, Default, JsonSchema)]
pub struct LabelStyle {
pub text: TextStyle,
pub highlight_text: Option<TextStyle>,
@@ -164,6 +165,7 @@ impl<V: View> Element<V> for Label {
_: &mut V,
cx: &mut ViewContext<V>,
) -> Self::PaintState {
let visible_bounds = bounds.intersection(visible_bounds).unwrap_or_default();
line.paint(
scene,
bounds.origin(),
+5 -5
View File
@@ -211,7 +211,7 @@ impl<V: View> Element<V> for List<V> {
let mut cursor = old_items.cursor::<Count>();
if state.rendered_range.start < new_rendered_range.start {
new_items.push_tree(
new_items.append(
cursor.slice(&Count(state.rendered_range.start), Bias::Right, &()),
&(),
);
@@ -221,7 +221,7 @@ impl<V: View> Element<V> for List<V> {
cursor.next(&());
}
}
new_items.push_tree(
new_items.append(
cursor.slice(&Count(new_rendered_range.start), Bias::Right, &()),
&(),
);
@@ -230,7 +230,7 @@ impl<V: View> Element<V> for List<V> {
cursor.seek(&Count(new_rendered_range.end), Bias::Right, &());
if new_rendered_range.end < state.rendered_range.start {
new_items.push_tree(
new_items.append(
cursor.slice(&Count(state.rendered_range.start), Bias::Right, &()),
&(),
);
@@ -240,7 +240,7 @@ impl<V: View> Element<V> for List<V> {
cursor.next(&());
}
new_items.push_tree(cursor.suffix(&()), &());
new_items.append(cursor.suffix(&()), &());
state.items = new_items;
state.rendered_range = new_rendered_range;
@@ -413,7 +413,7 @@ impl<V: View> ListState<V> {
old_heights.seek_forward(&Count(old_range.end), Bias::Right, &());
new_heights.extend((0..count).map(|_| ListItem::Unrendered), &());
new_heights.push_tree(old_heights.suffix(&()), &());
new_heights.append(old_heights.suffix(&()), &());
drop(old_heights);
state.items = new_heights;
}
@@ -7,8 +7,8 @@ use crate::{
platform::CursorStyle,
platform::MouseButton,
scene::{
CursorRegion, HandlerSet, MouseClick, MouseDown, MouseDownOut, MouseDrag, MouseHover,
MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut,
CursorRegion, HandlerSet, MouseClick, MouseClickOut, MouseDown, MouseDownOut, MouseDrag,
MouseHover, MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut,
},
AnyElement, Element, EventContext, LayoutContext, MouseRegion, MouseState, SceneBuilder,
SizeConstraint, View, ViewContext,
@@ -136,6 +136,15 @@ impl<Tag, V: View> MouseEventHandler<Tag, V> {
self
}
pub fn on_click_out(
mut self,
button: MouseButton,
handler: impl Fn(MouseClickOut, &mut V, &mut EventContext<V>) + 'static,
) -> Self {
self.handlers = self.handlers.on_click_out(button, handler);
self
}
pub fn on_down_out(
mut self,
button: MouseButton,
+31 -6
View File
@@ -1,7 +1,5 @@
use std::{borrow::Cow, ops::Range};
use serde_json::json;
use super::constrain_size_preserving_aspect_ratio;
use crate::json::ToJson;
use crate::{
color::Color,
geometry::{
@@ -10,6 +8,10 @@ use crate::{
},
scene, Element, LayoutContext, SceneBuilder, SizeConstraint, View, ViewContext,
};
use schemars::JsonSchema;
use serde_derive::Deserialize;
use serde_json::json;
use std::{borrow::Cow, ops::Range};
pub struct Svg {
path: Cow<'static, str>,
@@ -24,6 +26,14 @@ impl Svg {
}
}
pub fn for_style<V: View>(style: SvgStyle) -> impl Element<V> {
Self::new(style.asset)
.with_color(style.color)
.constrained()
.with_width(style.dimensions.width)
.with_height(style.dimensions.height)
}
pub fn with_color(mut self, color: Color) -> Self {
self.color = color;
self
@@ -105,9 +115,24 @@ impl<V: View> Element<V> for Svg {
}
}
use crate::json::ToJson;
#[derive(Clone, Deserialize, Default, JsonSchema)]
pub struct SvgStyle {
pub color: Color,
pub asset: String,
pub dimensions: Dimensions,
}
use super::constrain_size_preserving_aspect_ratio;
#[derive(Clone, Deserialize, Default, JsonSchema)]
pub struct Dimensions {
pub width: f32,
pub height: f32,
}
impl Dimensions {
pub fn to_vec(&self) -> Vector2F {
vec2f(self.width, self.height)
}
}
fn from_usvg_rect(rect: usvg::Rect) -> RectF {
RectF::new(
+3 -2
View File
@@ -9,6 +9,7 @@ use crate::{
Action, Axis, ElementStateHandle, LayoutContext, SceneBuilder, SizeConstraint, Task, View,
ViewContext,
};
use schemars::JsonSchema;
use serde::Deserialize;
use std::{
cell::{Cell, RefCell},
@@ -33,7 +34,7 @@ struct TooltipState {
debounce: RefCell<Option<Task<()>>>,
}
#[derive(Clone, Deserialize, Default)]
#[derive(Clone, Deserialize, Default, JsonSchema)]
pub struct TooltipStyle {
#[serde(flatten)]
pub container: ContainerStyle,
@@ -42,7 +43,7 @@ pub struct TooltipStyle {
pub max_text_width: Option<f32>,
}
#[derive(Clone, Deserialize, Default)]
#[derive(Clone, Deserialize, Default, JsonSchema)]
pub struct KeystrokeStyle {
#[serde(flatten)]
container: ContainerStyle,
+4 -1
View File
@@ -7,6 +7,7 @@ use std::{
fmt::{self, Display},
marker::PhantomData,
mem,
panic::Location,
pin::Pin,
rc::Rc,
sync::Arc,
@@ -965,10 +966,12 @@ impl<T> Task<T> {
}
impl<T: 'static, E: 'static + Display> Task<Result<T, E>> {
#[track_caller]
pub fn detach_and_log_err(self, cx: &mut AppContext) {
let caller = Location::caller();
cx.spawn(|_| async move {
if let Err(err) = self.await {
log::error!("{:#}", err);
log::error!("{}:{}: {:#}", caller.file(), caller.line(), err);
}
})
.detach();
+2 -1
View File
@@ -7,13 +7,14 @@ use crate::{
use anyhow::{anyhow, Result};
use ordered_float::OrderedFloat;
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use schemars::JsonSchema;
use std::{
collections::HashMap,
ops::{Deref, DerefMut},
sync::Arc,
};
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, JsonSchema)]
pub struct FamilyId(usize);
struct Family {
+29 -4
View File
@@ -16,7 +16,7 @@ use serde::{de, Deserialize, Serialize};
use serde_json::Value;
use std::{cell::RefCell, sync::Arc};
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, JsonSchema)]
pub struct FontId(pub usize);
pub type GlyphId = u32;
@@ -59,20 +59,44 @@ pub struct Features {
pub zero: Option<bool>,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, JsonSchema)]
pub struct TextStyle {
pub color: Color,
pub font_family_name: Arc<str>,
pub font_family_id: FamilyId,
pub font_id: FontId,
pub font_size: f32,
#[schemars(with = "PropertiesDef")]
pub font_properties: Properties,
pub underline: Underline,
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
#[derive(JsonSchema)]
#[serde(remote = "Properties")]
pub struct PropertiesDef {
/// The font style, as defined in CSS.
pub style: StyleDef,
/// The font weight, as defined in CSS.
pub weight: f32,
/// The font stretchiness, as defined in CSS.
pub stretch: f32,
}
#[derive(JsonSchema)]
#[schemars(remote = "Style")]
pub enum StyleDef {
/// A face that is neither italic not obliqued.
Normal,
/// A form that is generally cursive in nature.
Italic,
/// A typically-sloped version of the regular face.
Oblique,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, JsonSchema)]
pub struct HighlightStyle {
pub color: Option<Color>,
#[schemars(with = "Option::<f32>")]
pub weight: Option<Weight>,
pub italic: Option<bool>,
pub underline: Option<Underline>,
@@ -81,9 +105,10 @@ pub struct HighlightStyle {
impl Eq for HighlightStyle {}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, JsonSchema)]
pub struct Underline {
pub color: Option<Color>,
#[schemars(with = "f32")]
pub thickness: OrderedFloat<f32>,
pub squiggly: bool,
}
+3 -1
View File
@@ -26,8 +26,10 @@ pub mod color;
pub mod json;
pub mod keymap_matcher;
pub mod platform;
pub use gpui_macros::test;
pub use gpui_macros::{test, Element};
pub use window::{Axis, SizeConstraint, Vector2FExt, WindowContext};
pub use anyhow;
pub use serde_json;
actions!(zed, [NoAction]);
+2 -1
View File
@@ -25,6 +25,7 @@ use anyhow::{anyhow, bail, Result};
use async_task::Runnable;
pub use event::*;
use postage::oneshot;
use schemars::JsonSchema;
use serde::Deserialize;
use sqlez::{
bindable::{Bind, Column, StaticColumnCount},
@@ -282,7 +283,7 @@ pub enum PromptLevel {
Critical,
}
#[derive(Copy, Clone, Debug, Deserialize)]
#[derive(Copy, Clone, Debug, Deserialize, JsonSchema)]
pub enum CursorStyle {
Arrow,
ResizeLeftRight,
+6 -3
View File
@@ -786,7 +786,7 @@ impl platform::Platform for MacPlatform {
fn set_cursor_style(&self, style: CursorStyle) {
unsafe {
let cursor: id = match style {
let new_cursor: id = match style {
CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
CursorStyle::ResizeLeftRight => {
msg_send![class!(NSCursor), resizeLeftRightCursor]
@@ -795,7 +795,11 @@ impl platform::Platform for MacPlatform {
CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
};
let _: () = msg_send![cursor, set];
let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
if new_cursor != old_cursor {
let _: () = msg_send![new_cursor, set];
}
}
}
@@ -935,7 +939,6 @@ extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
}
}
}
msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
}
}
+2 -1
View File
@@ -3,6 +3,7 @@ mod mouse_region;
#[cfg(debug_assertions)]
use collections::HashSet;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;
use std::{borrow::Cow, sync::Arc};
@@ -99,7 +100,7 @@ pub struct Icon {
pub color: Color,
}
#[derive(Clone, Copy, Default, Debug)]
#[derive(Clone, Copy, Default, Debug, JsonSchema)]
pub struct Border {
pub width: f32,
pub color: Color,
+22
View File
@@ -99,6 +99,20 @@ impl Deref for MouseClick {
}
}
#[derive(Debug, Default, Clone)]
pub struct MouseClickOut {
pub region: RectF,
pub platform_event: MouseButtonEvent,
}
impl Deref for MouseClickOut {
type Target = MouseButtonEvent;
fn deref(&self) -> &Self::Target {
&self.platform_event
}
}
#[derive(Debug, Default, Clone)]
pub struct MouseDownOut {
pub region: RectF,
@@ -150,6 +164,7 @@ pub enum MouseEvent {
Down(MouseDown),
Up(MouseUp),
Click(MouseClick),
ClickOut(MouseClickOut),
DownOut(MouseDownOut),
UpOut(MouseUpOut),
ScrollWheel(MouseScrollWheel),
@@ -165,6 +180,7 @@ impl MouseEvent {
MouseEvent::Down(r) => r.region = region,
MouseEvent::Up(r) => r.region = region,
MouseEvent::Click(r) => r.region = region,
MouseEvent::ClickOut(r) => r.region = region,
MouseEvent::DownOut(r) => r.region = region,
MouseEvent::UpOut(r) => r.region = region,
MouseEvent::ScrollWheel(r) => r.region = region,
@@ -182,6 +198,7 @@ impl MouseEvent {
MouseEvent::Down(_) => true,
MouseEvent::Up(_) => true,
MouseEvent::Click(_) => true,
MouseEvent::ClickOut(_) => true,
MouseEvent::DownOut(_) => false,
MouseEvent::UpOut(_) => false,
MouseEvent::ScrollWheel(_) => true,
@@ -222,6 +239,10 @@ impl MouseEvent {
discriminant(&MouseEvent::Click(Default::default()))
}
pub fn click_out_disc() -> Discriminant<MouseEvent> {
discriminant(&MouseEvent::ClickOut(Default::default()))
}
pub fn down_out_disc() -> Discriminant<MouseEvent> {
discriminant(&MouseEvent::DownOut(Default::default()))
}
@@ -239,6 +260,7 @@ impl MouseEvent {
MouseEvent::Down(e) => HandlerKey::new(Self::down_disc(), Some(e.button)),
MouseEvent::Up(e) => HandlerKey::new(Self::up_disc(), Some(e.button)),
MouseEvent::Click(e) => HandlerKey::new(Self::click_disc(), Some(e.button)),
MouseEvent::ClickOut(e) => HandlerKey::new(Self::click_out_disc(), Some(e.button)),
MouseEvent::UpOut(e) => HandlerKey::new(Self::up_out_disc(), Some(e.button)),
MouseEvent::DownOut(e) => HandlerKey::new(Self::down_out_disc(), Some(e.button)),
MouseEvent::ScrollWheel(_) => HandlerKey::new(Self::scroll_wheel_disc(), None),
+36 -1
View File
@@ -14,7 +14,7 @@ use super::{
MouseClick, MouseDown, MouseDownOut, MouseDrag, MouseEvent, MouseHover, MouseMove, MouseUp,
MouseUpOut,
},
MouseMoveOut, MouseScrollWheel,
MouseClickOut, MouseMoveOut, MouseScrollWheel,
};
#[derive(Clone)]
@@ -89,6 +89,15 @@ impl MouseRegion {
self
}
pub fn on_click_out<V, F>(mut self, button: MouseButton, handler: F) -> Self
where
V: View,
F: Fn(MouseClickOut, &mut V, &mut EventContext<V>) + 'static,
{
self.handlers = self.handlers.on_click_out(button, handler);
self
}
pub fn on_down_out<V, F>(mut self, button: MouseButton, handler: F) -> Self
where
V: View,
@@ -246,6 +255,10 @@ impl HandlerSet {
HandlerKey::new(MouseEvent::click_disc(), Some(button)),
SmallVec::from_buf([Rc::new(|_, _, _, _| true)]),
);
set.insert(
HandlerKey::new(MouseEvent::click_out_disc(), Some(button)),
SmallVec::from_buf([Rc::new(|_, _, _, _| true)]),
);
set.insert(
HandlerKey::new(MouseEvent::down_out_disc(), Some(button)),
SmallVec::from_buf([Rc::new(|_, _, _, _| true)]),
@@ -405,6 +418,28 @@ impl HandlerSet {
self
}
pub fn on_click_out<V, F>(mut self, button: MouseButton, handler: F) -> Self
where
V: View,
F: Fn(MouseClickOut, &mut V, &mut EventContext<V>) + 'static,
{
self.insert(MouseEvent::click_out_disc(), Some(button),
Rc::new(move |region_event, view, cx, view_id| {
if let MouseEvent::ClickOut(e) = region_event {
let view = view.downcast_mut().unwrap();
let mut cx = ViewContext::mutable(cx, view_id);
let mut cx = EventContext::new(&mut cx);
handler(e, view, &mut cx);
cx.handled
} else {
panic!(
"Mouse Region Event incorrectly called with mismatched event type. Expected MouseRegionEvent::ClickOut, found {:?}",
region_event);
}
}));
self
}
pub fn on_down_out<V, F>(mut self, button: MouseButton, handler: F) -> Self
where
V: View,
+67 -2
View File
@@ -3,8 +3,8 @@ use proc_macro2::Ident;
use quote::{format_ident, quote};
use std::mem;
use syn::{
parse_macro_input, parse_quote, spanned::Spanned as _, AttributeArgs, FnArg, ItemFn, Lit, Meta,
NestedMeta, Type,
parse_macro_input, parse_quote, spanned::Spanned as _, AttributeArgs, DeriveInput, FnArg,
ItemFn, Lit, Meta, NestedMeta, Type,
};
#[proc_macro_attribute]
@@ -275,3 +275,68 @@ fn parse_bool(literal: &Lit) -> Result<bool, TokenStream> {
result.map_err(|err| TokenStream::from(err.into_compile_error()))
}
#[proc_macro_derive(Element)]
pub fn element_derive(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as DeriveInput);
// The name of the struct/enum
let name = input.ident;
let expanded = quote! {
impl<V: gpui::View> gpui::elements::Element<V> for #name {
type LayoutState = gpui::elements::AnyElement<V>;
type PaintState = ();
fn layout(
&mut self,
constraint: gpui::SizeConstraint,
view: &mut V,
cx: &mut gpui::LayoutContext<V>,
) -> (gpui::geometry::vector::Vector2F, gpui::elements::AnyElement<V>) {
let mut element = self.render(view, cx);
let size = element.layout(constraint, view, cx);
(size, element)
}
fn paint(
&mut self,
scene: &mut gpui::SceneBuilder,
bounds: gpui::geometry::rect::RectF,
visible_bounds: gpui::geometry::rect::RectF,
element: &mut gpui::elements::AnyElement<V>,
view: &mut V,
cx: &mut gpui::ViewContext<V>,
) {
element.paint(scene, bounds.origin(), visible_bounds, view, cx);
}
fn rect_for_text_range(
&self,
range_utf16: std::ops::Range<usize>,
_: gpui::geometry::rect::RectF,
_: gpui::geometry::rect::RectF,
element: &gpui::elements::AnyElement<V>,
_: &(),
view: &V,
cx: &gpui::ViewContext<V>,
) -> Option<gpui::geometry::rect::RectF> {
element.rect_for_text_range(range_utf16, view, cx)
}
fn debug(
&self,
_: gpui::geometry::rect::RectF,
element: &gpui::elements::AnyElement<V>,
_: &(),
view: &V,
cx: &gpui::ViewContext<V>,
) -> serde_json::Value {
element.debug(view, cx)
}
}
};
// Return generated code
TokenStream::from(expanded)
}
+191 -75
View File
@@ -17,10 +17,10 @@ use futures::{
future::{BoxFuture, Shared},
FutureExt, TryFutureExt as _,
};
use gpui::{executor::Background, AppContext, Task};
use gpui::{executor::Background, AppContext, AsyncAppContext, Task};
use highlight_map::HighlightMap;
use lazy_static::lazy_static;
use lsp::CodeActionKind;
use lsp::{CodeActionKind, LanguageServerBinary};
use parking_lot::{Mutex, RwLock};
use postage::watch;
use regex::Regex;
@@ -30,7 +30,6 @@ use std::{
any::Any,
borrow::Cow,
cell::RefCell,
ffi::OsString,
fmt::Debug,
hash::Hash,
mem,
@@ -86,12 +85,6 @@ pub trait ToLspPosition {
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LanguageServerName(pub Arc<str>);
#[derive(Debug, Clone, Deserialize)]
pub struct LanguageServerBinary {
pub path: PathBuf,
pub arguments: Vec<OsString>,
}
/// Represents a Language Server, with certain cached sync properties.
/// Uses [`LspAdapter`] under the hood, but calls all 'static' methods
/// once at startup, and caches the results.
@@ -125,27 +118,57 @@ impl CachedLspAdapter {
pub async fn fetch_latest_server_version(
&self,
http: Arc<dyn HttpClient>,
delegate: &dyn LspAdapterDelegate,
) -> Result<Box<dyn 'static + Send + Any>> {
self.adapter.fetch_latest_server_version(http).await
self.adapter.fetch_latest_server_version(delegate).await
}
pub fn will_fetch_server(
&self,
delegate: &Arc<dyn LspAdapterDelegate>,
cx: &mut AsyncAppContext,
) -> Option<Task<Result<()>>> {
self.adapter.will_fetch_server(delegate, cx)
}
pub fn will_start_server(
&self,
delegate: &Arc<dyn LspAdapterDelegate>,
cx: &mut AsyncAppContext,
) -> Option<Task<Result<()>>> {
self.adapter.will_start_server(delegate, cx)
}
pub async fn fetch_server_binary(
&self,
version: Box<dyn 'static + Send + Any>,
http: Arc<dyn HttpClient>,
container_dir: PathBuf,
delegate: &dyn LspAdapterDelegate,
) -> Result<LanguageServerBinary> {
self.adapter
.fetch_server_binary(version, http, container_dir)
.fetch_server_binary(version, container_dir, delegate)
.await
}
pub async fn cached_server_binary(
&self,
container_dir: PathBuf,
delegate: &dyn LspAdapterDelegate,
) -> Option<LanguageServerBinary> {
self.adapter.cached_server_binary(container_dir).await
self.adapter
.cached_server_binary(container_dir, delegate)
.await
}
pub fn can_be_reinstalled(&self) -> bool {
self.adapter.can_be_reinstalled()
}
pub async fn installation_test_binary(
&self,
container_dir: PathBuf,
) -> Option<LanguageServerBinary> {
self.adapter.installation_test_binary(container_dir).await
}
pub fn code_action_kinds(&self) -> Option<Vec<CodeActionKind>> {
@@ -187,23 +210,57 @@ impl CachedLspAdapter {
}
}
pub trait LspAdapterDelegate: Send + Sync {
fn show_notification(&self, message: &str, cx: &mut AppContext);
fn http_client(&self) -> Arc<dyn HttpClient>;
}
#[async_trait]
pub trait LspAdapter: 'static + Send + Sync {
async fn name(&self) -> LanguageServerName;
async fn fetch_latest_server_version(
&self,
http: Arc<dyn HttpClient>,
delegate: &dyn LspAdapterDelegate,
) -> Result<Box<dyn 'static + Send + Any>>;
fn will_fetch_server(
&self,
_: &Arc<dyn LspAdapterDelegate>,
_: &mut AsyncAppContext,
) -> Option<Task<Result<()>>> {
None
}
fn will_start_server(
&self,
_: &Arc<dyn LspAdapterDelegate>,
_: &mut AsyncAppContext,
) -> Option<Task<Result<()>>> {
None
}
async fn fetch_server_binary(
&self,
version: Box<dyn 'static + Send + Any>,
http: Arc<dyn HttpClient>,
container_dir: PathBuf,
delegate: &dyn LspAdapterDelegate,
) -> Result<LanguageServerBinary>;
async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<LanguageServerBinary>;
async fn cached_server_binary(
&self,
container_dir: PathBuf,
delegate: &dyn LspAdapterDelegate,
) -> Option<LanguageServerBinary>;
fn can_be_reinstalled(&self) -> bool {
true
}
async fn installation_test_binary(
&self,
container_dir: PathBuf,
) -> Option<LanguageServerBinary>;
async fn process_diagnostics(&self, _: &mut lsp::PublishDiagnosticsParams) {}
@@ -513,10 +570,7 @@ pub struct LanguageRegistry {
login_shell_env_loaded: Shared<Task<()>>,
#[allow(clippy::type_complexity)]
lsp_binary_paths: Mutex<
HashMap<
LanguageServerName,
Shared<BoxFuture<'static, Result<LanguageServerBinary, Arc<anyhow::Error>>>>,
>,
HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>,
>,
executor: Option<Arc<Background>>,
}
@@ -535,7 +589,8 @@ struct LanguageRegistryState {
pub struct PendingLanguageServer {
pub server_id: LanguageServerId,
pub task: Task<Result<lsp::LanguageServer>>,
pub task: Task<Result<Option<lsp::LanguageServer>>>,
pub container_dir: Option<Arc<Path>>,
}
impl LanguageRegistry {
@@ -807,17 +862,17 @@ impl LanguageRegistry {
self.state.read().languages.iter().cloned().collect()
}
pub fn start_language_server(
pub fn create_pending_language_server(
self: &Arc<Self>,
language: Arc<Language>,
adapter: Arc<CachedLspAdapter>,
root_path: Arc<Path>,
http_client: Arc<dyn HttpClient>,
delegate: Arc<dyn LspAdapterDelegate>,
cx: &mut AppContext,
) -> Option<PendingLanguageServer> {
let server_id = self.state.write().next_language_server_id();
log::info!(
"starting language server name:{}, path:{root_path:?}, id:{server_id}",
"starting language server {:?}, path: {root_path:?}, id: {server_id}",
adapter.name.0
);
@@ -847,61 +902,81 @@ impl LanguageRegistry {
}
})
.detach();
Ok(server)
Ok(Some(server))
});
return Some(PendingLanguageServer { server_id, task });
return Some(PendingLanguageServer {
server_id,
task,
container_dir: None,
});
}
let download_dir = self
.language_server_download_dir
.clone()
.ok_or_else(|| anyhow!("language server download directory has not been assigned"))
.ok_or_else(|| anyhow!("language server download directory has not been assigned before starting server"))
.log_err()?;
let this = self.clone();
let language = language.clone();
let http_client = http_client.clone();
let download_dir = download_dir.clone();
let container_dir: Arc<Path> = Arc::from(download_dir.join(adapter.name.0.as_ref()));
let root_path = root_path.clone();
let adapter = adapter.clone();
let lsp_binary_statuses = self.lsp_binary_statuses_tx.clone();
let login_shell_env_loaded = self.login_shell_env_loaded.clone();
let task = cx.spawn(|cx| async move {
login_shell_env_loaded.await;
let task = {
let container_dir = container_dir.clone();
cx.spawn(|mut cx| async move {
login_shell_env_loaded.await;
let mut lock = this.lsp_binary_paths.lock();
let entry = lock
.entry(adapter.name.clone())
.or_insert_with(|| {
get_binary(
adapter.clone(),
language.clone(),
http_client,
download_dir,
lsp_binary_statuses,
)
.map_err(Arc::new)
.boxed()
.shared()
})
.clone();
drop(lock);
let binary = entry.clone().map_err(|e| anyhow!(e)).await?;
let mut lock = this.lsp_binary_paths.lock();
let entry = lock
.entry(adapter.name.clone())
.or_insert_with(|| {
cx.spawn(|cx| {
get_binary(
adapter.clone(),
language.clone(),
delegate.clone(),
container_dir,
lsp_binary_statuses,
cx,
)
.map_err(Arc::new)
})
.shared()
})
.clone();
drop(lock);
let server = lsp::LanguageServer::new(
server_id,
&binary.path,
&binary.arguments,
&root_path,
adapter.code_action_kinds(),
cx,
)?;
let binary = match entry.clone().await.log_err() {
Some(binary) => binary,
None => return Ok(None),
};
Ok(server)
});
if let Some(task) = adapter.will_start_server(&delegate, &mut cx) {
if task.await.log_err().is_none() {
return Ok(None);
}
}
Some(PendingLanguageServer { server_id, task })
Ok(Some(lsp::LanguageServer::new(
server_id,
binary,
&root_path,
adapter.code_action_kinds(),
cx,
)?))
})
};
Some(PendingLanguageServer {
server_id,
task,
container_dir: Some(container_dir),
})
}
pub fn language_server_binary_statuses(
@@ -909,6 +984,30 @@ impl LanguageRegistry {
) -> async_broadcast::Receiver<(Arc<Language>, LanguageServerBinaryStatus)> {
self.lsp_binary_statuses_rx.clone()
}
pub fn delete_server_container(
&self,
adapter: Arc<CachedLspAdapter>,
cx: &mut AppContext,
) -> Task<()> {
log::info!("deleting server container");
let mut lock = self.lsp_binary_paths.lock();
lock.remove(&adapter.name);
let download_dir = self
.language_server_download_dir
.clone()
.expect("language server download directory has not been assigned before deleting server container");
cx.spawn(|_| async move {
let container_dir = download_dir.join(adapter.name.0.as_ref());
smol::fs::remove_dir_all(container_dir)
.await
.context("server container removal")
.log_err();
})
}
}
impl LanguageRegistryState {
@@ -958,32 +1057,39 @@ impl Default for LanguageRegistry {
async fn get_binary(
adapter: Arc<CachedLspAdapter>,
language: Arc<Language>,
http_client: Arc<dyn HttpClient>,
download_dir: Arc<Path>,
delegate: Arc<dyn LspAdapterDelegate>,
container_dir: Arc<Path>,
statuses: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
mut cx: AsyncAppContext,
) -> Result<LanguageServerBinary> {
let container_dir = download_dir.join(adapter.name.0.as_ref());
if !container_dir.exists() {
smol::fs::create_dir_all(&container_dir)
.await
.context("failed to create container directory")?;
}
if let Some(task) = adapter.will_fetch_server(&delegate, &mut cx) {
task.await?;
}
let binary = fetch_latest_binary(
adapter.clone(),
language.clone(),
http_client,
delegate.as_ref(),
&container_dir,
statuses.clone(),
)
.await;
if let Err(error) = binary.as_ref() {
if let Some(cached) = adapter.cached_server_binary(container_dir).await {
if let Some(binary) = adapter
.cached_server_binary(container_dir.to_path_buf(), delegate.as_ref())
.await
{
statuses
.broadcast((language.clone(), LanguageServerBinaryStatus::Cached))
.await?;
return Ok(cached);
return Ok(binary);
} else {
statuses
.broadcast((
@@ -995,13 +1101,14 @@ async fn get_binary(
.await?;
}
}
binary
}
async fn fetch_latest_binary(
adapter: Arc<CachedLspAdapter>,
language: Arc<Language>,
http_client: Arc<dyn HttpClient>,
delegate: &dyn LspAdapterDelegate,
container_dir: &Path,
lsp_binary_statuses_tx: async_broadcast::Sender<(Arc<Language>, LanguageServerBinaryStatus)>,
) -> Result<LanguageServerBinary> {
@@ -1012,18 +1119,19 @@ async fn fetch_latest_binary(
LanguageServerBinaryStatus::CheckingForUpdate,
))
.await?;
let version_info = adapter
.fetch_latest_server_version(http_client.clone())
.await?;
let version_info = adapter.fetch_latest_server_version(delegate).await?;
lsp_binary_statuses_tx
.broadcast((language.clone(), LanguageServerBinaryStatus::Downloading))
.await?;
let binary = adapter
.fetch_server_binary(version_info, http_client, container_dir.to_path_buf())
.fetch_server_binary(version_info, container_dir.to_path_buf(), delegate)
.await?;
lsp_binary_statuses_tx
.broadcast((language.clone(), LanguageServerBinaryStatus::Downloaded))
.await?;
Ok(binary)
}
@@ -1543,7 +1651,7 @@ impl LspAdapter for Arc<FakeLspAdapter> {
async fn fetch_latest_server_version(
&self,
_: Arc<dyn HttpClient>,
_: &dyn LspAdapterDelegate,
) -> Result<Box<dyn 'static + Send + Any>> {
unreachable!();
}
@@ -1551,13 +1659,21 @@ impl LspAdapter for Arc<FakeLspAdapter> {
async fn fetch_server_binary(
&self,
_: Box<dyn 'static + Send + Any>,
_: Arc<dyn HttpClient>,
_: PathBuf,
_: &dyn LspAdapterDelegate,
) -> Result<LanguageServerBinary> {
unreachable!();
}
async fn cached_server_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
async fn cached_server_binary(
&self,
_: PathBuf,
_: &dyn LspAdapterDelegate,
) -> Option<LanguageServerBinary> {
unreachable!();
}
async fn installation_test_binary(&self, _: PathBuf) -> Option<LanguageServerBinary> {
unreachable!();
}
+60 -1
View File
@@ -1,6 +1,6 @@
use crate::{File, Language};
use anyhow::Result;
use collections::HashMap;
use collections::{HashMap, HashSet};
use globset::GlobMatcher;
use gpui::AppContext;
use schemars::{
@@ -52,6 +52,7 @@ pub struct LanguageSettings {
pub show_copilot_suggestions: bool,
pub show_whitespaces: ShowWhitespaceSetting,
pub extend_comment_on_newline: bool,
pub inlay_hints: InlayHintSettings,
}
#[derive(Clone, Debug, Default)]
@@ -98,6 +99,8 @@ pub struct LanguageSettingsContent {
pub show_whitespaces: Option<ShowWhitespaceSetting>,
#[serde(default)]
pub extend_comment_on_newline: Option<bool>,
#[serde(default)]
pub inlay_hints: Option<InlayHintSettings>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
@@ -150,6 +153,38 @@ pub enum Formatter {
},
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct InlayHintSettings {
#[serde(default)]
pub enabled: bool,
#[serde(default = "default_true")]
pub show_type_hints: bool,
#[serde(default = "default_true")]
pub show_parameter_hints: bool,
#[serde(default = "default_true")]
pub show_other_hints: bool,
}
fn default_true() -> bool {
true
}
impl InlayHintSettings {
pub fn enabled_inlay_hint_kinds(&self) -> HashSet<Option<InlayHintKind>> {
let mut kinds = HashSet::default();
if self.show_type_hints {
kinds.insert(Some(InlayHintKind::Type));
}
if self.show_parameter_hints {
kinds.insert(Some(InlayHintKind::Parameter));
}
if self.show_other_hints {
kinds.insert(None);
}
kinds
}
}
impl AllLanguageSettings {
pub fn language<'a>(&'a self, language_name: Option<&str>) -> &'a LanguageSettings {
if let Some(name) = language_name {
@@ -184,6 +219,29 @@ impl AllLanguageSettings {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InlayHintKind {
Type,
Parameter,
}
impl InlayHintKind {
pub fn from_name(name: &str) -> Option<Self> {
match name {
"type" => Some(InlayHintKind::Type),
"parameter" => Some(InlayHintKind::Parameter),
_ => None,
}
}
pub fn name(&self) -> &'static str {
match self {
InlayHintKind::Type => "type",
InlayHintKind::Parameter => "parameter",
}
}
}
impl settings::Setting for AllLanguageSettings {
const KEY: Option<&'static str> = None;
@@ -347,6 +405,7 @@ fn merge_settings(settings: &mut LanguageSettings, src: &LanguageSettingsContent
&mut settings.extend_comment_on_newline,
src.extend_comment_on_newline,
);
merge(&mut settings.inlay_hints, src.inlay_hints);
fn merge<T>(target: &mut T, value: Option<T>) {
if let Some(value) = value {
*target = value;
+172 -81
View File
@@ -11,7 +11,7 @@ use std::{
cell::RefCell,
cmp::{self, Ordering, Reverse},
collections::BinaryHeap,
iter,
fmt, iter,
ops::{Deref, DerefMut, Range},
sync::Arc,
};
@@ -288,7 +288,7 @@ impl SyntaxSnapshot {
};
if target.cmp(&cursor.start(), text).is_gt() {
let slice = cursor.slice(&target, Bias::Left, text);
layers.push_tree(slice, text);
layers.append(slice, text);
}
}
// If this layer follows all of the edits, then preserve it and any
@@ -303,7 +303,7 @@ impl SyntaxSnapshot {
Bias::Left,
text,
);
layers.push_tree(slice, text);
layers.append(slice, text);
continue;
};
@@ -369,7 +369,7 @@ impl SyntaxSnapshot {
cursor.next(text);
}
layers.push_tree(cursor.suffix(&text), &text);
layers.append(cursor.suffix(&text), &text);
drop(cursor);
self.layers = layers;
}
@@ -428,6 +428,8 @@ impl SyntaxSnapshot {
invalidated_ranges: Vec<Range<usize>>,
registry: Option<&Arc<LanguageRegistry>>,
) {
log::trace!("reparse. invalidated ranges:{:?}", invalidated_ranges);
let max_depth = self.layers.summary().max_depth;
let mut cursor = self.layers.cursor::<SyntaxLayerSummary>();
cursor.next(&text);
@@ -478,7 +480,7 @@ impl SyntaxSnapshot {
if bounded_position.cmp(&cursor.start(), &text).is_gt() {
let slice = cursor.slice(&bounded_position, Bias::Left, text);
if !slice.is_empty() {
layers.push_tree(slice, &text);
layers.append(slice, &text);
if changed_regions.prune(cursor.end(text), text) {
done = false;
}
@@ -489,6 +491,15 @@ impl SyntaxSnapshot {
let Some(layer) = cursor.item() else { break };
if changed_regions.intersects(&layer, text) {
if let SyntaxLayerContent::Parsed { language, .. } = &layer.content {
log::trace!(
"discard layer. language:{}, range:{:?}. changed_regions:{:?}",
language.name(),
LogAnchorRange(&layer.range, text),
LogChangedRegions(&changed_regions, text),
);
}
changed_regions.insert(
ChangedRegion {
depth: layer.depth + 1,
@@ -541,26 +552,24 @@ impl SyntaxSnapshot {
.to_ts_point();
}
if included_ranges.is_empty() {
included_ranges.push(tree_sitter::Range {
start_byte: 0,
end_byte: 0,
start_point: Default::default(),
end_point: Default::default(),
});
}
if let Some(SyntaxLayerContent::Parsed { tree: old_tree, .. }) =
old_layer.map(|layer| &layer.content)
if let Some((SyntaxLayerContent::Parsed { tree: old_tree, .. }, layer_start)) =
old_layer.map(|layer| (&layer.content, layer.range.start))
{
log::trace!(
"existing layer. language:{}, start:{:?}, ranges:{:?}",
language.name(),
LogPoint(layer_start.to_point(&text)),
LogIncludedRanges(&old_tree.included_ranges())
);
if let ParseMode::Combined {
mut parent_layer_changed_ranges,
..
} = step.mode
{
for range in &mut parent_layer_changed_ranges {
range.start -= step_start_byte;
range.end -= step_start_byte;
range.start = range.start.saturating_sub(step_start_byte);
range.end = range.end.saturating_sub(step_start_byte);
}
included_ranges = splice_included_ranges(
@@ -570,6 +579,22 @@ impl SyntaxSnapshot {
);
}
if included_ranges.is_empty() {
included_ranges.push(tree_sitter::Range {
start_byte: 0,
end_byte: 0,
start_point: Default::default(),
end_point: Default::default(),
});
}
log::trace!(
"update layer. language:{}, start:{:?}, ranges:{:?}",
language.name(),
LogAnchorRange(&step.range, text),
LogIncludedRanges(&included_ranges),
);
tree = parse_text(
grammar,
text.as_rope(),
@@ -586,6 +611,22 @@ impl SyntaxSnapshot {
}),
);
} else {
if included_ranges.is_empty() {
included_ranges.push(tree_sitter::Range {
start_byte: 0,
end_byte: 0,
start_point: Default::default(),
end_point: Default::default(),
});
}
log::trace!(
"create layer. language:{}, range:{:?}, included_ranges:{:?}",
language.name(),
LogAnchorRange(&step.range, text),
LogIncludedRanges(&included_ranges),
);
tree = parse_text(
grammar,
text.as_rope(),
@@ -613,6 +654,7 @@ impl SyntaxSnapshot {
get_injections(
config,
text,
step.range.clone(),
tree.root_node_with_offset(
step_start_byte,
step_start_point.to_ts_point(),
@@ -1117,6 +1159,7 @@ fn parse_text(
fn get_injections(
config: &InjectionConfig,
text: &BufferSnapshot,
outer_range: Range<Anchor>,
node: Node,
language_registry: &Arc<LanguageRegistry>,
depth: usize,
@@ -1153,16 +1196,17 @@ fn get_injections(
continue;
}
// Avoid duplicate matches if two changed ranges intersect the same injection.
let content_range =
content_ranges.first().unwrap().start_byte..content_ranges.last().unwrap().end_byte;
if let Some((last_pattern_ix, last_range)) = &prev_match {
if mat.pattern_index == *last_pattern_ix && content_range == *last_range {
// Avoid duplicate matches if two changed ranges intersect the same injection.
if let Some((prev_pattern_ix, prev_range)) = &prev_match {
if mat.pattern_index == *prev_pattern_ix && content_range == *prev_range {
continue;
}
}
prev_match = Some((mat.pattern_index, content_range.clone()));
prev_match = Some((mat.pattern_index, content_range.clone()));
let combined = config.patterns[mat.pattern_index].combined;
let mut language_name = None;
@@ -1218,11 +1262,10 @@ fn get_injections(
for (language, mut included_ranges) in combined_injection_ranges.drain() {
included_ranges.sort_unstable();
let range = text.anchor_before(node.start_byte())..text.anchor_after(node.end_byte());
queue.push(ParseStep {
depth,
language: ParseStepLanguage::Loaded { language },
range,
range: outer_range.clone(),
included_ranges,
mode: ParseMode::Combined {
parent_layer_range: node.start_byte()..node.end_byte(),
@@ -1234,72 +1277,77 @@ fn get_injections(
pub(crate) fn splice_included_ranges(
mut ranges: Vec<tree_sitter::Range>,
changed_ranges: &[Range<usize>],
removed_ranges: &[Range<usize>],
new_ranges: &[tree_sitter::Range],
) -> Vec<tree_sitter::Range> {
let mut changed_ranges = changed_ranges.into_iter().peekable();
let mut new_ranges = new_ranges.into_iter().peekable();
let mut removed_ranges = removed_ranges.iter().cloned().peekable();
let mut new_ranges = new_ranges.into_iter().cloned().peekable();
let mut ranges_ix = 0;
loop {
let new_range = new_ranges.peek();
let mut changed_range = changed_ranges.peek();
let next_new_range = new_ranges.peek();
let next_removed_range = removed_ranges.peek();
// Remove ranges that have changed before inserting any new ranges
// into those ranges.
if let Some((changed, new)) = changed_range.zip(new_range) {
if new.end_byte < changed.start {
changed_range = None;
let (remove, insert) = match (next_removed_range, next_new_range) {
(None, None) => break,
(Some(_), None) => (removed_ranges.next().unwrap(), None),
(Some(next_removed_range), Some(next_new_range)) => {
if next_removed_range.end < next_new_range.start_byte {
(removed_ranges.next().unwrap(), None)
} else {
let mut start = next_new_range.start_byte;
let mut end = next_new_range.end_byte;
while let Some(next_removed_range) = removed_ranges.peek() {
if next_removed_range.start > next_new_range.end_byte {
break;
}
let next_removed_range = removed_ranges.next().unwrap();
start = cmp::min(start, next_removed_range.start);
end = cmp::max(end, next_removed_range.end);
}
(start..end, Some(new_ranges.next().unwrap()))
}
}
(None, Some(next_new_range)) => (
next_new_range.start_byte..next_new_range.end_byte,
Some(new_ranges.next().unwrap()),
),
};
let mut start_ix = ranges_ix
+ match ranges[ranges_ix..].binary_search_by_key(&remove.start, |r| r.end_byte) {
Ok(ix) => ix,
Err(ix) => ix,
};
let mut end_ix = ranges_ix
+ match ranges[ranges_ix..].binary_search_by_key(&remove.end, |r| r.start_byte) {
Ok(ix) => ix + 1,
Err(ix) => ix,
};
// If there are empty ranges, then there may be multiple ranges with the same
// start or end. Expand the splice to include any adjacent ranges that touch
// the changed range.
while start_ix > 0 {
if ranges[start_ix - 1].end_byte == remove.start {
start_ix -= 1;
} else {
break;
}
}
while let Some(range) = ranges.get(end_ix) {
if range.start_byte == remove.end {
end_ix += 1;
} else {
break;
}
}
if let Some(changed) = changed_range {
let mut start_ix = ranges_ix
+ match ranges[ranges_ix..].binary_search_by_key(&changed.start, |r| r.end_byte) {
Ok(ix) | Err(ix) => ix,
};
let mut end_ix = ranges_ix
+ match ranges[ranges_ix..].binary_search_by_key(&changed.end, |r| r.start_byte) {
Ok(ix) => ix + 1,
Err(ix) => ix,
};
// If there are empty ranges, then there may be multiple ranges with the same
// start or end. Expand the splice to include any adjacent ranges that touch
// the changed range.
while start_ix > 0 {
if ranges[start_ix - 1].end_byte == changed.start {
start_ix -= 1;
} else {
break;
}
}
while let Some(range) = ranges.get(end_ix) {
if range.start_byte == changed.end {
end_ix += 1;
} else {
break;
}
}
if end_ix > start_ix {
ranges.splice(start_ix..end_ix, []);
}
changed_ranges.next();
ranges_ix = start_ix;
} else if let Some(new_range) = new_range {
let ix = ranges_ix
+ match ranges[ranges_ix..]
.binary_search_by_key(&new_range.start_byte, |r| r.start_byte)
{
Ok(ix) | Err(ix) => ix,
};
ranges.insert(ix, **new_range);
new_ranges.next();
ranges_ix = ix + 1;
} else {
break;
}
ranges.splice(start_ix..end_ix, insert);
ranges_ix = start_ix;
}
ranges
}
@@ -1628,3 +1676,46 @@ impl ToTreeSitterPoint for Point {
Point::new(point.row as u32, point.column as u32)
}
}
struct LogIncludedRanges<'a>(&'a [tree_sitter::Range]);
struct LogPoint(Point);
struct LogAnchorRange<'a>(&'a Range<Anchor>, &'a text::BufferSnapshot);
struct LogChangedRegions<'a>(&'a ChangeRegionSet, &'a text::BufferSnapshot);
impl<'a> fmt::Debug for LogIncludedRanges<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.0.iter().map(|range| {
let start = range.start_point;
let end = range.end_point;
(start.row, start.column)..(end.row, end.column)
}))
.finish()
}
}
impl<'a> fmt::Debug for LogAnchorRange<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let range = self.0.to_point(self.1);
(LogPoint(range.start)..LogPoint(range.end)).fmt(f)
}
}
impl<'a> fmt::Debug for LogChangedRegions<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(
self.0
.0
.iter()
.map(|region| LogAnchorRange(&region.range, self.1)),
)
.finish()
}
}
impl fmt::Debug for LogPoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(self.0.row, self.0.column).fmt(f)
}
}
@@ -48,6 +48,13 @@ fn test_splice_included_ranges() {
let new_ranges = splice_included_ranges(ranges.clone(), &[30..50], &[ts_range(25..55)]);
assert_eq!(new_ranges, &[ts_range(25..55), ts_range(80..90)]);
// does not create overlapping ranges
let new_ranges = splice_included_ranges(ranges.clone(), &[0..18], &[ts_range(20..32)]);
assert_eq!(
new_ranges,
&[ts_range(20..32), ts_range(50..60), ts_range(80..90)]
);
fn ts_range(range: Range<usize>) -> tree_sitter::Range {
tree_sitter::Range {
start_byte: range.start,
@@ -624,6 +631,26 @@ fn test_combined_injections_splitting_some_injections() {
);
}
#[gpui::test]
fn test_combined_injections_editing_after_last_injection() {
test_edit_sequence(
"ERB",
&[
r#"
<% foo %>
<div></div>
<% bar %>
"#,
r#"
<% foo %>
<div></div>
<% bar %>«
more text»
"#,
],
);
}
#[gpui::test]
fn test_combined_injections_inside_injections() {
let (_buffer, _syntax_map) = test_edit_sequence(
@@ -974,13 +1001,16 @@ fn test_edit_sequence(language_name: &str, steps: &[&str]) -> (Buffer, SyntaxMap
mutated_syntax_map.reparse(language.clone(), &buffer);
for (i, marked_string) in steps.into_iter().enumerate() {
buffer.edit_via_marked_text(&marked_string.unindent());
let marked_string = marked_string.unindent();
log::info!("incremental parse {i}: {marked_string:?}");
buffer.edit_via_marked_text(&marked_string);
// Reparse the syntax map
mutated_syntax_map.interpolate(&buffer);
mutated_syntax_map.reparse(language.clone(), &buffer);
// Create a second syntax map from scratch
log::info!("fresh parse {i}: {marked_string:?}");
let mut reference_syntax_map = SyntaxMap::new();
reference_syntax_map.set_language_registry(registry.clone());
reference_syntax_map.reparse(language.clone(), &buffer);
@@ -1133,6 +1163,7 @@ fn range_for_text(buffer: &Buffer, text: &str) -> Range<usize> {
start..start + text.len()
}
#[track_caller]
fn assert_layers_for_range(
syntax_map: &SyntaxMap,
buffer: &BufferSnapshot,
@@ -55,7 +55,7 @@ impl View for ActiveBufferLanguage {
MouseEventHandler::<Self, Self>::new(0, cx, |state, cx| {
let theme = &theme::current(cx).workspace.status_bar;
let style = theme.active_language.style_for(state, false);
let style = theme.active_language.style_for(state);
Label::new(active_language_text, style.text.clone())
.contained()
.with_style(style.container)
@@ -180,7 +180,7 @@ impl PickerDelegate for LanguageSelectorDelegate {
) -> AnyElement<Picker<Self>> {
let theme = theme::current(cx);
let mat = &self.matches[ix];
let style = theme.picker.item.style_for(mouse_state, selected);
let style = theme.picker.item.in_state(selected).style_for(mouse_state);
let buffer_language_name = self.buffer.read(cx).language().map(|l| l.name());
let mut label = mat.string.clone();
if buffer_language_name.as_deref() == Some(mat.string.as_str()) {
+5 -3
View File
@@ -681,7 +681,7 @@ impl LspLogToolbarItemView {
)
})
.unwrap_or_else(|| "No server selected".into());
let style = theme.toolbar_dropdown_menu.header.style_for(state, false);
let style = theme.toolbar_dropdown_menu.header.style_for(state);
Label::new(label, style.text.clone())
.contained()
.with_style(style.container)
@@ -722,7 +722,8 @@ impl LspLogToolbarItemView {
let style = theme
.toolbar_dropdown_menu
.item
.style_for(state, logs_selected);
.in_state(logs_selected)
.style_for(state);
Label::new(SERVER_LOGS, style.text.clone())
.contained()
.with_style(style.container)
@@ -739,7 +740,8 @@ impl LspLogToolbarItemView {
let style = theme
.toolbar_dropdown_menu
.item
.style_for(state, rpc_trace_selected);
.in_state(rpc_trace_selected)
.style_for(state);
Flex::row()
.with_child(
Label::new(RPC_MESSAGES, style.text.clone())
@@ -565,7 +565,7 @@ impl SyntaxTreeToolbarItemView {
) -> impl Element<Self> {
enum ToggleMenu {}
MouseEventHandler::<ToggleMenu, Self>::new(0, cx, move |state, _| {
let style = theme.toolbar_dropdown_menu.header.style_for(state, false);
let style = theme.toolbar_dropdown_menu.header.style_for(state);
Flex::row()
.with_child(
Label::new(active_layer.language.name().to_string(), style.text.clone())
@@ -601,7 +601,8 @@ impl SyntaxTreeToolbarItemView {
let style = theme
.toolbar_dropdown_menu
.item
.style_for(state, is_selected);
.in_state(is_selected)
.style_for(state);
Flex::row()
.with_child(
Label::new(layer.language.name().to_string(), style.text.clone())
@@ -6,19 +6,31 @@ import ScreenCaptureKit
class LKRoomDelegate: RoomDelegate {
var data: UnsafeRawPointer
var onDidDisconnect: @convention(c) (UnsafeRawPointer) -> Void
var onDidSubscribeToRemoteAudioTrack: @convention(c) (UnsafeRawPointer, CFString, CFString, UnsafeRawPointer) -> Void
var onDidUnsubscribeFromRemoteAudioTrack: @convention(c) (UnsafeRawPointer, CFString, CFString) -> Void
var onMuteChangedFromRemoteAudioTrack: @convention(c) (UnsafeRawPointer, CFString, Bool) -> Void
var onActiveSpeakersChanged: @convention(c) (UnsafeRawPointer, CFArray) -> Void
var onDidSubscribeToRemoteVideoTrack: @convention(c) (UnsafeRawPointer, CFString, CFString, UnsafeRawPointer) -> Void
var onDidUnsubscribeFromRemoteVideoTrack: @convention(c) (UnsafeRawPointer, CFString, CFString) -> Void
init(
data: UnsafeRawPointer,
onDidDisconnect: @escaping @convention(c) (UnsafeRawPointer) -> Void,
onDidSubscribeToRemoteAudioTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString, UnsafeRawPointer) -> Void,
onDidUnsubscribeFromRemoteAudioTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString) -> Void,
onMuteChangedFromRemoteAudioTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, Bool) -> Void,
onActiveSpeakersChanged: @convention(c) (UnsafeRawPointer, CFArray) -> Void,
onDidSubscribeToRemoteVideoTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString, UnsafeRawPointer) -> Void,
onDidUnsubscribeFromRemoteVideoTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString) -> Void)
{
self.data = data
self.onDidDisconnect = onDidDisconnect
self.onDidSubscribeToRemoteAudioTrack = onDidSubscribeToRemoteAudioTrack
self.onDidUnsubscribeFromRemoteAudioTrack = onDidUnsubscribeFromRemoteAudioTrack
self.onDidSubscribeToRemoteVideoTrack = onDidSubscribeToRemoteVideoTrack
self.onDidUnsubscribeFromRemoteVideoTrack = onDidUnsubscribeFromRemoteVideoTrack
self.onMuteChangedFromRemoteAudioTrack = onMuteChangedFromRemoteAudioTrack
self.onActiveSpeakersChanged = onActiveSpeakersChanged
}
func room(_ room: Room, didUpdate connectionState: ConnectionState, oldValue: ConnectionState) {
@@ -30,12 +42,27 @@ class LKRoomDelegate: RoomDelegate {
func room(_ room: Room, participant: RemoteParticipant, didSubscribe publication: RemoteTrackPublication, track: Track) {
if track.kind == .video {
self.onDidSubscribeToRemoteVideoTrack(self.data, participant.identity as CFString, track.sid! as CFString, Unmanaged.passUnretained(track).toOpaque())
} else if track.kind == .audio {
self.onDidSubscribeToRemoteAudioTrack(self.data, participant.identity as CFString, track.sid! as CFString, Unmanaged.passUnretained(track).toOpaque())
}
}
func room(_ room: Room, participant: Participant, didUpdate publication: TrackPublication, muted: Bool) {
if publication.kind == .audio {
self.onMuteChangedFromRemoteAudioTrack(self.data, publication.sid as CFString, muted)
}
}
func room(_ room: Room, didUpdate speakers: [Participant]) {
guard let speaker_ids = speakers.compactMap({ $0.identity as CFString }) as CFArray? else { return }
self.onActiveSpeakersChanged(self.data, speaker_ids)
}
func room(_ room: Room, participant: RemoteParticipant, didUnsubscribe publication: RemoteTrackPublication, track: Track) {
if track.kind == .video {
self.onDidUnsubscribeFromRemoteVideoTrack(self.data, participant.identity as CFString, track.sid! as CFString)
} else if track.kind == .audio {
self.onDidUnsubscribeFromRemoteAudioTrack(self.data, participant.identity as CFString, track.sid! as CFString)
}
}
}
@@ -77,12 +104,20 @@ class LKVideoRenderer: NSObject, VideoRenderer {
public func LKRoomDelegateCreate(
data: UnsafeRawPointer,
onDidDisconnect: @escaping @convention(c) (UnsafeRawPointer) -> Void,
onDidSubscribeToRemoteAudioTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString, UnsafeRawPointer) -> Void,
onDidUnsubscribeFromRemoteAudioTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString) -> Void,
onMuteChangedFromRemoteAudioTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, Bool) -> Void,
onActiveSpeakerChanged: @escaping @convention(c) (UnsafeRawPointer, CFArray) -> Void,
onDidSubscribeToRemoteVideoTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString, UnsafeRawPointer) -> Void,
onDidUnsubscribeFromRemoteVideoTrack: @escaping @convention(c) (UnsafeRawPointer, CFString, CFString) -> Void
) -> UnsafeMutableRawPointer {
let delegate = LKRoomDelegate(
data: data,
onDidDisconnect: onDidDisconnect,
onDidSubscribeToRemoteAudioTrack: onDidSubscribeToRemoteAudioTrack,
onDidUnsubscribeFromRemoteAudioTrack: onDidUnsubscribeFromRemoteAudioTrack,
onMuteChangedFromRemoteAudioTrack: onMuteChangedFromRemoteAudioTrack,
onActiveSpeakersChanged: onActiveSpeakerChanged,
onDidSubscribeToRemoteVideoTrack: onDidSubscribeToRemoteVideoTrack,
onDidUnsubscribeFromRemoteVideoTrack: onDidUnsubscribeFromRemoteVideoTrack
)
@@ -123,6 +158,18 @@ public func LKRoomPublishVideoTrack(room: UnsafeRawPointer, track: UnsafeRawPoin
}
}
@_cdecl("LKRoomPublishAudioTrack")
public func LKRoomPublishAudioTrack(room: UnsafeRawPointer, track: UnsafeRawPointer, callback: @escaping @convention(c) (UnsafeRawPointer, UnsafeMutableRawPointer?, CFString?) -> Void, callback_data: UnsafeRawPointer) {
let room = Unmanaged<Room>.fromOpaque(room).takeUnretainedValue()
let track = Unmanaged<LocalAudioTrack>.fromOpaque(track).takeUnretainedValue()
room.localParticipant?.publishAudioTrack(track: track).then { publication in
callback(callback_data, Unmanaged.passRetained(publication).toOpaque(), nil)
}.catch { error in
callback(callback_data, nil, error.localizedDescription as CFString)
}
}
@_cdecl("LKRoomUnpublishTrack")
public func LKRoomUnpublishTrack(room: UnsafeRawPointer, publication: UnsafeRawPointer) {
let room = Unmanaged<Room>.fromOpaque(room).takeUnretainedValue()
@@ -130,6 +177,32 @@ public func LKRoomUnpublishTrack(room: UnsafeRawPointer, publication: UnsafeRawP
let _ = room.localParticipant?.unpublish(publication: publication)
}
@_cdecl("LKRoomAudioTracksForRemoteParticipant")
public func LKRoomAudioTracksForRemoteParticipant(room: UnsafeRawPointer, participantId: CFString) -> CFArray? {
let room = Unmanaged<Room>.fromOpaque(room).takeUnretainedValue()
for (_, participant) in room.remoteParticipants {
if participant.identity == participantId as String {
return participant.audioTracks.compactMap { $0.track as? RemoteAudioTrack } as CFArray?
}
}
return nil;
}
@_cdecl("LKRoomAudioTrackPublicationsForRemoteParticipant")
public func LKRoomAudioTrackPublicationsForRemoteParticipant(room: UnsafeRawPointer, participantId: CFString) -> CFArray? {
let room = Unmanaged<Room>.fromOpaque(room).takeUnretainedValue()
for (_, participant) in room.remoteParticipants {
if participant.identity == participantId as String {
return participant.audioTracks.compactMap { $0 as? RemoteTrackPublication } as CFArray?
}
}
return nil;
}
@_cdecl("LKRoomVideoTracksForRemoteParticipant")
public func LKRoomVideoTracksForRemoteParticipant(room: UnsafeRawPointer, participantId: CFString) -> CFArray? {
let room = Unmanaged<Room>.fromOpaque(room).takeUnretainedValue()
@@ -143,6 +216,17 @@ public func LKRoomVideoTracksForRemoteParticipant(room: UnsafeRawPointer, partic
return nil;
}
@_cdecl("LKLocalAudioTrackCreateTrack")
public func LKLocalAudioTrackCreateTrack() -> UnsafeMutableRawPointer {
let track = LocalAudioTrack.createTrack(options: AudioCaptureOptions(
echoCancellation: true,
noiseSuppression: true
))
return Unmanaged.passRetained(track).toOpaque()
}
@_cdecl("LKCreateScreenShareTrackForDisplay")
public func LKCreateScreenShareTrackForDisplay(display: UnsafeMutableRawPointer) -> UnsafeMutableRawPointer {
let display = Unmanaged<MacOSDisplay>.fromOpaque(display).takeUnretainedValue()
@@ -169,6 +253,12 @@ public func LKRemoteVideoTrackGetSid(track: UnsafeRawPointer) -> CFString {
return track.sid! as CFString
}
@_cdecl("LKRemoteAudioTrackGetSid")
public func LKRemoteAudioTrackGetSid(track: UnsafeRawPointer) -> CFString {
let track = Unmanaged<RemoteAudioTrack>.fromOpaque(track).takeUnretainedValue()
return track.sid! as CFString
}
@_cdecl("LKDisplaySources")
public func LKDisplaySources(data: UnsafeRawPointer, callback: @escaping @convention(c) (UnsafeRawPointer, CFArray?, CFString?) -> Void) {
MacOSScreenCapturer.sources(for: .display, includeCurrentApplication: false, preferredMethod: .legacy).then { displaySources in
@@ -177,3 +267,43 @@ public func LKDisplaySources(data: UnsafeRawPointer, callback: @escaping @conven
callback(data, nil, error.localizedDescription as CFString)
}
}
@_cdecl("LKLocalTrackPublicationSetMute")
public func LKLocalTrackPublicationSetMute(
publication: UnsafeRawPointer,
muted: Bool,
on_complete: @escaping @convention(c) (UnsafeRawPointer, CFString?) -> Void,
callback_data: UnsafeRawPointer
) {
let publication = Unmanaged<LocalTrackPublication>.fromOpaque(publication).takeUnretainedValue()
if muted {
publication.mute().then {
on_complete(callback_data, nil)
}.catch { error in
on_complete(callback_data, error.localizedDescription as CFString)
}
} else {
publication.unmute().then {
on_complete(callback_data, nil)
}.catch { error in
on_complete(callback_data, error.localizedDescription as CFString)
}
}
}
@_cdecl("LKRemoteTrackPublicationSetEnabled")
public func LKRemoteTrackPublicationSetEnabled(
publication: UnsafeRawPointer,
enabled: Bool,
on_complete: @escaping @convention(c) (UnsafeRawPointer, CFString?) -> Void,
callback_data: UnsafeRawPointer
) {
let publication = Unmanaged<RemoteTrackPublication>.fromOpaque(publication).takeUnretainedValue()
publication.set(enabled: enabled).then {
on_complete(callback_data, nil)
}.catch { error in
on_complete(callback_data, error.localizedDescription as CFString)
}
}
+96 -14
View File
@@ -1,6 +1,10 @@
use std::time::Duration;
use futures::StreamExt;
use gpui::{actions, keymap_matcher::Binding, Menu, MenuItem};
use live_kit_client::{LocalVideoTrack, RemoteVideoTrackUpdate, Room};
use live_kit_client::{
LocalAudioTrack, LocalVideoTrack, RemoteAudioTrackUpdate, RemoteVideoTrackUpdate, Room,
};
use live_kit_server::token::{self, VideoGrant};
use log::LevelFilter;
use simplelog::SimpleLogger;
@@ -11,6 +15,12 @@ fn main() {
SimpleLogger::init(LevelFilter::Info, Default::default()).expect("could not initialize logger");
gpui::App::new(()).unwrap().run(|cx| {
#[cfg(any(test, feature = "test-support"))]
println!("USING TEST LIVEKIT");
#[cfg(not(any(test, feature = "test-support")))]
println!("USING REAL LIVEKIT");
cx.platform().activate(true);
cx.add_global_action(quit);
@@ -49,16 +59,14 @@ fn main() {
let room_b = Room::new();
room_b.connect(&live_kit_url, &user2_token).await.unwrap();
let mut track_changes = room_b.remote_video_track_updates();
let mut audio_track_updates = room_b.remote_audio_track_updates();
let audio_track = LocalAudioTrack::create();
let audio_track_publication = room_a.publish_audio_track(&audio_track).await.unwrap();
let displays = room_a.display_sources().await.unwrap();
let display = displays.into_iter().next().unwrap();
let track_a = LocalVideoTrack::screen_share_for_display(&display);
let track_a_publication = room_a.publish_video_track(&track_a).await.unwrap();
if let RemoteVideoTrackUpdate::Subscribed(track) = track_changes.next().await.unwrap() {
let remote_tracks = room_b.remote_video_tracks("test-participant-1");
if let RemoteAudioTrackUpdate::Subscribed(track) =
audio_track_updates.next().await.unwrap()
{
let remote_tracks = room_b.remote_audio_tracks("test-participant-1");
assert_eq!(remote_tracks.len(), 1);
assert_eq!(remote_tracks[0].publisher_id(), "test-participant-1");
assert_eq!(track.publisher_id(), "test-participant-1");
@@ -66,18 +74,92 @@ fn main() {
panic!("unexpected message");
}
let remote_track = room_b
audio_track_publication.set_mute(true).await.unwrap();
println!("waiting for mute changed!");
if let RemoteAudioTrackUpdate::MuteChanged { track_id, muted } =
audio_track_updates.next().await.unwrap()
{
let remote_tracks = room_b.remote_audio_tracks("test-participant-1");
assert_eq!(remote_tracks[0].sid(), track_id);
assert_eq!(muted, true);
} else {
panic!("unexpected message");
}
audio_track_publication.set_mute(false).await.unwrap();
if let RemoteAudioTrackUpdate::MuteChanged { track_id, muted } =
audio_track_updates.next().await.unwrap()
{
let remote_tracks = room_b.remote_audio_tracks("test-participant-1");
assert_eq!(remote_tracks[0].sid(), track_id);
assert_eq!(muted, false);
} else {
panic!("unexpected message");
}
println!("Pausing for 5 seconds to test audio, make some noise!");
let timer = cx.background().timer(Duration::from_secs(5));
timer.await;
let remote_audio_track = room_b
.remote_audio_tracks("test-participant-1")
.pop()
.unwrap();
room_a.unpublish_track(audio_track_publication);
// Clear out any active speakers changed messages
let mut next = audio_track_updates.next().await.unwrap();
while let RemoteAudioTrackUpdate::ActiveSpeakersChanged { speakers } = next {
println!("Speakers changed: {:?}", speakers);
next = audio_track_updates.next().await.unwrap();
}
if let RemoteAudioTrackUpdate::Unsubscribed {
publisher_id,
track_id,
} = next
{
assert_eq!(publisher_id, "test-participant-1");
assert_eq!(remote_audio_track.sid(), track_id);
assert_eq!(room_b.remote_audio_tracks("test-participant-1").len(), 0);
} else {
panic!("unexpected message");
}
let mut video_track_updates = room_b.remote_video_track_updates();
let displays = room_a.display_sources().await.unwrap();
let display = displays.into_iter().next().unwrap();
let local_video_track = LocalVideoTrack::screen_share_for_display(&display);
let local_video_track_publication = room_a
.publish_video_track(&local_video_track)
.await
.unwrap();
if let RemoteVideoTrackUpdate::Subscribed(track) =
video_track_updates.next().await.unwrap()
{
let remote_video_tracks = room_b.remote_video_tracks("test-participant-1");
assert_eq!(remote_video_tracks.len(), 1);
assert_eq!(remote_video_tracks[0].publisher_id(), "test-participant-1");
assert_eq!(track.publisher_id(), "test-participant-1");
} else {
panic!("unexpected message");
}
let remote_video_track = room_b
.remote_video_tracks("test-participant-1")
.pop()
.unwrap();
room_a.unpublish_track(track_a_publication);
room_a.unpublish_track(local_video_track_publication);
if let RemoteVideoTrackUpdate::Unsubscribed {
publisher_id,
track_id,
} = track_changes.next().await.unwrap()
} = video_track_updates.next().await.unwrap()
{
assert_eq!(publisher_id, "test-participant-1");
assert_eq!(remote_track.sid(), track_id);
assert_eq!(remote_video_track.sid(), track_id);
assert_eq!(room_b.remote_video_tracks("test-participant-1").len(), 0);
} else {
panic!("unexpected message");
@@ -4,7 +4,7 @@ pub mod prod;
pub use prod::*;
#[cfg(any(test, feature = "test-support"))]
mod test;
pub mod test;
#[cfg(any(test, feature = "test-support"))]
pub use test::*;
+384 -1
View File
@@ -21,6 +21,26 @@ extern "C" {
fn LKRoomDelegateCreate(
callback_data: *mut c_void,
on_did_disconnect: extern "C" fn(callback_data: *mut c_void),
on_did_subscribe_to_remote_audio_track: extern "C" fn(
callback_data: *mut c_void,
publisher_id: CFStringRef,
track_id: CFStringRef,
remote_track: *const c_void,
),
on_did_unsubscribe_from_remote_audio_track: extern "C" fn(
callback_data: *mut c_void,
publisher_id: CFStringRef,
track_id: CFStringRef,
),
on_mute_changed_from_remote_audio_track: extern "C" fn(
callback_data: *mut c_void,
track_id: CFStringRef,
muted: bool,
),
on_active_speakers_changed: extern "C" fn(
callback_data: *mut c_void,
participants: CFArrayRef,
),
on_did_subscribe_to_remote_video_track: extern "C" fn(
callback_data: *mut c_void,
publisher_id: CFStringRef,
@@ -49,7 +69,23 @@ extern "C" {
callback: extern "C" fn(*mut c_void, *mut c_void, CFStringRef),
callback_data: *mut c_void,
);
fn LKRoomPublishAudioTrack(
room: *const c_void,
track: *const c_void,
callback: extern "C" fn(*mut c_void, *mut c_void, CFStringRef),
callback_data: *mut c_void,
);
fn LKRoomUnpublishTrack(room: *const c_void, publication: *const c_void);
fn LKRoomAudioTracksForRemoteParticipant(
room: *const c_void,
participant_id: CFStringRef,
) -> CFArrayRef;
fn LKRoomAudioTrackPublicationsForRemoteParticipant(
room: *const c_void,
participant_id: CFStringRef,
) -> CFArrayRef;
fn LKRoomVideoTracksForRemoteParticipant(
room: *const c_void,
participant_id: CFStringRef,
@@ -61,6 +97,7 @@ extern "C" {
on_drop: extern "C" fn(callback_data: *mut c_void),
) -> *const c_void;
fn LKRemoteAudioTrackGetSid(track: *const c_void) -> CFStringRef;
fn LKVideoTrackAddRenderer(track: *const c_void, renderer: *const c_void);
fn LKRemoteVideoTrackGetSid(track: *const c_void) -> CFStringRef;
@@ -73,6 +110,21 @@ extern "C" {
),
);
fn LKCreateScreenShareTrackForDisplay(display: *const c_void) -> *const c_void;
fn LKLocalAudioTrackCreateTrack() -> *const c_void;
fn LKLocalTrackPublicationSetMute(
publication: *const c_void,
muted: bool,
on_complete: extern "C" fn(callback_data: *mut c_void, error: CFStringRef),
callback_data: *mut c_void,
);
fn LKRemoteTrackPublicationSetEnabled(
publication: *const c_void,
enabled: bool,
on_complete: extern "C" fn(callback_data: *mut c_void, error: CFStringRef),
callback_data: *mut c_void,
);
}
pub type Sid = String;
@@ -89,6 +141,7 @@ pub struct Room {
watch::Sender<ConnectionState>,
watch::Receiver<ConnectionState>,
)>,
remote_audio_track_subscribers: Mutex<Vec<mpsc::UnboundedSender<RemoteAudioTrackUpdate>>>,
remote_video_track_subscribers: Mutex<Vec<mpsc::UnboundedSender<RemoteVideoTrackUpdate>>>,
_delegate: RoomDelegate,
}
@@ -100,6 +153,7 @@ impl Room {
Self {
native_room: unsafe { LKRoomCreate(delegate.native_delegate) },
connection: Mutex::new(watch::channel_with(ConnectionState::Disconnected)),
remote_audio_track_subscribers: Default::default(),
remote_video_track_subscribers: Default::default(),
_delegate: delegate,
}
@@ -174,7 +228,7 @@ impl Room {
let tx =
unsafe { Box::from_raw(tx as *mut oneshot::Sender<Result<LocalTrackPublication>>) };
if error.is_null() {
let _ = tx.send(Ok(LocalTrackPublication(publication)));
let _ = tx.send(Ok(LocalTrackPublication::new(publication)));
} else {
let error = unsafe { CFString::wrap_under_get_rule(error).to_string() };
let _ = tx.send(Err(anyhow!(error)));
@@ -191,6 +245,32 @@ impl Room {
async { rx.await.unwrap().context("error publishing video track") }
}
pub fn publish_audio_track(
self: &Arc<Self>,
track: &LocalAudioTrack,
) -> impl Future<Output = Result<LocalTrackPublication>> {
let (tx, rx) = oneshot::channel::<Result<LocalTrackPublication>>();
extern "C" fn callback(tx: *mut c_void, publication: *mut c_void, error: CFStringRef) {
let tx =
unsafe { Box::from_raw(tx as *mut oneshot::Sender<Result<LocalTrackPublication>>) };
if error.is_null() {
let _ = tx.send(Ok(LocalTrackPublication::new(publication)));
} else {
let error = unsafe { CFString::wrap_under_get_rule(error).to_string() };
let _ = tx.send(Err(anyhow!(error)));
}
}
unsafe {
LKRoomPublishAudioTrack(
self.native_room,
track.0,
callback,
Box::into_raw(Box::new(tx)) as *mut c_void,
);
}
async { rx.await.unwrap().context("error publishing audio track") }
}
pub fn unpublish_track(&self, publication: LocalTrackPublication) {
unsafe {
LKRoomUnpublishTrack(self.native_room, publication.0);
@@ -226,12 +306,112 @@ impl Room {
}
}
pub fn remote_audio_tracks(&self, participant_id: &str) -> Vec<Arc<RemoteAudioTrack>> {
unsafe {
let tracks = LKRoomAudioTracksForRemoteParticipant(
self.native_room,
CFString::new(participant_id).as_concrete_TypeRef(),
);
if tracks.is_null() {
Vec::new()
} else {
let tracks = CFArray::wrap_under_get_rule(tracks);
tracks
.into_iter()
.map(|native_track| {
let native_track = *native_track;
let id =
CFString::wrap_under_get_rule(LKRemoteAudioTrackGetSid(native_track))
.to_string();
Arc::new(RemoteAudioTrack::new(
native_track,
id,
participant_id.into(),
))
})
.collect()
}
}
}
pub fn remote_audio_track_publications(
&self,
participant_id: &str,
) -> Vec<Arc<RemoteTrackPublication>> {
unsafe {
let tracks = LKRoomAudioTrackPublicationsForRemoteParticipant(
self.native_room,
CFString::new(participant_id).as_concrete_TypeRef(),
);
if tracks.is_null() {
Vec::new()
} else {
let tracks = CFArray::wrap_under_get_rule(tracks);
tracks
.into_iter()
.map(|native_track_publication| {
let native_track_publication = *native_track_publication;
Arc::new(RemoteTrackPublication::new(native_track_publication))
})
.collect()
}
}
}
pub fn remote_audio_track_updates(&self) -> mpsc::UnboundedReceiver<RemoteAudioTrackUpdate> {
let (tx, rx) = mpsc::unbounded();
self.remote_audio_track_subscribers.lock().push(tx);
rx
}
pub fn remote_video_track_updates(&self) -> mpsc::UnboundedReceiver<RemoteVideoTrackUpdate> {
let (tx, rx) = mpsc::unbounded();
self.remote_video_track_subscribers.lock().push(tx);
rx
}
fn did_subscribe_to_remote_audio_track(&self, track: RemoteAudioTrack) {
let track = Arc::new(track);
self.remote_audio_track_subscribers.lock().retain(|tx| {
tx.unbounded_send(RemoteAudioTrackUpdate::Subscribed(track.clone()))
.is_ok()
});
}
fn did_unsubscribe_from_remote_audio_track(&self, publisher_id: String, track_id: String) {
self.remote_audio_track_subscribers.lock().retain(|tx| {
tx.unbounded_send(RemoteAudioTrackUpdate::Unsubscribed {
publisher_id: publisher_id.clone(),
track_id: track_id.clone(),
})
.is_ok()
});
}
fn mute_changed_from_remote_audio_track(&self, track_id: String, muted: bool) {
self.remote_audio_track_subscribers.lock().retain(|tx| {
tx.unbounded_send(RemoteAudioTrackUpdate::MuteChanged {
track_id: track_id.clone(),
muted,
})
.is_ok()
});
}
// A vec of publisher IDs
fn active_speakers_changed(&self, speakers: Vec<String>) {
self.remote_audio_track_subscribers
.lock()
.retain(move |tx| {
tx.unbounded_send(RemoteAudioTrackUpdate::ActiveSpeakersChanged {
speakers: speakers.clone(),
})
.is_ok()
});
}
fn did_subscribe_to_remote_video_track(&self, track: RemoteVideoTrack) {
let track = Arc::new(track);
self.remote_video_track_subscribers.lock().retain(|tx| {
@@ -294,6 +474,10 @@ impl RoomDelegate {
LKRoomDelegateCreate(
weak_room as *mut c_void,
Self::on_did_disconnect,
Self::on_did_subscribe_to_remote_audio_track,
Self::on_did_unsubscribe_from_remote_audio_track,
Self::on_mute_change_from_remote_audio_track,
Self::on_active_speakers_changed,
Self::on_did_subscribe_to_remote_video_track,
Self::on_did_unsubscribe_from_remote_video_track,
)
@@ -312,6 +496,72 @@ impl RoomDelegate {
let _ = Weak::into_raw(room);
}
extern "C" fn on_did_subscribe_to_remote_audio_track(
room: *mut c_void,
publisher_id: CFStringRef,
track_id: CFStringRef,
track: *const c_void,
) {
let room = unsafe { Weak::from_raw(room as *mut Room) };
let publisher_id = unsafe { CFString::wrap_under_get_rule(publisher_id).to_string() };
let track_id = unsafe { CFString::wrap_under_get_rule(track_id).to_string() };
let track = RemoteAudioTrack::new(track, track_id, publisher_id);
if let Some(room) = room.upgrade() {
room.did_subscribe_to_remote_audio_track(track);
}
let _ = Weak::into_raw(room);
}
extern "C" fn on_did_unsubscribe_from_remote_audio_track(
room: *mut c_void,
publisher_id: CFStringRef,
track_id: CFStringRef,
) {
let room = unsafe { Weak::from_raw(room as *mut Room) };
let publisher_id = unsafe { CFString::wrap_under_get_rule(publisher_id).to_string() };
let track_id = unsafe { CFString::wrap_under_get_rule(track_id).to_string() };
if let Some(room) = room.upgrade() {
room.did_unsubscribe_from_remote_audio_track(publisher_id, track_id);
}
let _ = Weak::into_raw(room);
}
extern "C" fn on_mute_change_from_remote_audio_track(
room: *mut c_void,
track_id: CFStringRef,
muted: bool,
) {
let room = unsafe { Weak::from_raw(room as *mut Room) };
let track_id = unsafe { CFString::wrap_under_get_rule(track_id).to_string() };
if let Some(room) = room.upgrade() {
room.mute_changed_from_remote_audio_track(track_id, muted);
}
let _ = Weak::into_raw(room);
}
extern "C" fn on_active_speakers_changed(room: *mut c_void, participants: CFArrayRef) {
if participants.is_null() {
return;
}
let room = unsafe { Weak::from_raw(room as *mut Room) };
let speakers = unsafe {
CFArray::wrap_under_get_rule(participants)
.into_iter()
.map(
|speaker: core_foundation::base::ItemRef<'_, *const c_void>| {
CFString::wrap_under_get_rule(*speaker as CFStringRef).to_string()
},
)
.collect()
};
if let Some(room) = room.upgrade() {
room.active_speakers_changed(speakers);
}
let _ = Weak::into_raw(room);
}
extern "C" fn on_did_subscribe_to_remote_video_track(
room: *mut c_void,
publisher_id: CFStringRef,
@@ -352,6 +602,20 @@ impl Drop for RoomDelegate {
}
}
pub struct LocalAudioTrack(*const c_void);
impl LocalAudioTrack {
pub fn create() -> Self {
Self(unsafe { LKLocalAudioTrackCreateTrack() })
}
}
impl Drop for LocalAudioTrack {
fn drop(&mut self) {
unsafe { CFRelease(self.0) }
}
}
pub struct LocalVideoTrack(*const c_void);
impl LocalVideoTrack {
@@ -368,12 +632,124 @@ impl Drop for LocalVideoTrack {
pub struct LocalTrackPublication(*const c_void);
impl LocalTrackPublication {
pub fn new(native_track_publication: *const c_void) -> Self {
unsafe {
CFRetain(native_track_publication);
}
Self(native_track_publication)
}
pub fn set_mute(&self, muted: bool) -> impl Future<Output = Result<()>> {
let (tx, rx) = futures::channel::oneshot::channel();
extern "C" fn complete_callback(callback_data: *mut c_void, error: CFStringRef) {
let tx = unsafe { Box::from_raw(callback_data as *mut oneshot::Sender<Result<()>>) };
if error.is_null() {
tx.send(Ok(())).ok();
} else {
let error = unsafe { CFString::wrap_under_get_rule(error).to_string() };
tx.send(Err(anyhow!(error))).ok();
}
}
unsafe {
LKLocalTrackPublicationSetMute(
self.0,
muted,
complete_callback,
Box::into_raw(Box::new(tx)) as *mut c_void,
)
}
async move { rx.await.unwrap() }
}
}
impl Drop for LocalTrackPublication {
fn drop(&mut self) {
unsafe { CFRelease(self.0) }
}
}
pub struct RemoteTrackPublication(*const c_void);
impl RemoteTrackPublication {
pub fn new(native_track_publication: *const c_void) -> Self {
unsafe {
CFRetain(native_track_publication);
}
Self(native_track_publication)
}
pub fn set_enabled(&self, enabled: bool) -> impl Future<Output = Result<()>> {
let (tx, rx) = futures::channel::oneshot::channel();
extern "C" fn complete_callback(callback_data: *mut c_void, error: CFStringRef) {
let tx = unsafe { Box::from_raw(callback_data as *mut oneshot::Sender<Result<()>>) };
if error.is_null() {
tx.send(Ok(())).ok();
} else {
let error = unsafe { CFString::wrap_under_get_rule(error).to_string() };
tx.send(Err(anyhow!(error))).ok();
}
}
unsafe {
LKRemoteTrackPublicationSetEnabled(
self.0,
enabled,
complete_callback,
Box::into_raw(Box::new(tx)) as *mut c_void,
)
}
async move { rx.await.unwrap() }
}
}
impl Drop for RemoteTrackPublication {
fn drop(&mut self) {
unsafe { CFRelease(self.0) }
}
}
#[derive(Debug)]
pub struct RemoteAudioTrack {
_native_track: *const c_void,
sid: Sid,
publisher_id: String,
}
impl RemoteAudioTrack {
fn new(native_track: *const c_void, sid: Sid, publisher_id: String) -> Self {
unsafe {
CFRetain(native_track);
}
Self {
_native_track: native_track,
sid,
publisher_id,
}
}
pub fn sid(&self) -> &str {
&self.sid
}
pub fn publisher_id(&self) -> &str {
&self.publisher_id
}
pub fn enable(&self) -> impl Future<Output = Result<()>> {
async { Ok(()) }
}
pub fn disable(&self) -> impl Future<Output = Result<()>> {
async { Ok(()) }
}
}
#[derive(Debug)]
pub struct RemoteVideoTrack {
native_track: *const c_void,
@@ -453,6 +829,13 @@ pub enum RemoteVideoTrackUpdate {
Unsubscribed { publisher_id: Sid, track_id: Sid },
}
pub enum RemoteAudioTrackUpdate {
ActiveSpeakersChanged { speakers: Vec<Sid> },
MuteChanged { track_id: Sid, muted: bool },
Subscribed(Arc<RemoteAudioTrack>),
Unsubscribed { publisher_id: Sid, track_id: Sid },
}
pub struct MacOSDisplay(*const c_void);
impl MacOSDisplay {
+162 -6
View File
@@ -67,7 +67,7 @@ impl TestServer {
}
}
async fn create_room(&self, room: String) -> Result<()> {
pub async fn create_room(&self, room: String) -> Result<()> {
self.background.simulate_random_delay().await;
let mut server_rooms = self.rooms.lock();
if server_rooms.contains_key(&room) {
@@ -104,7 +104,7 @@ impl TestServer {
room_name
))
} else {
for track in &room.tracks {
for track in &room.video_tracks {
client_room
.0
.lock()
@@ -182,7 +182,7 @@ impl TestServer {
frames_rx: local_track.frames_rx.clone(),
});
room.tracks.push(track.clone());
room.video_tracks.push(track.clone());
for (id, client_room) in &room.client_rooms {
if *id != identity {
@@ -199,6 +199,43 @@ impl TestServer {
Ok(())
}
async fn publish_audio_track(
&self,
token: String,
_local_track: &LocalAudioTrack,
) -> Result<()> {
self.background.simulate_random_delay().await;
let claims = live_kit_server::token::validate(&token, &self.secret_key)?;
let identity = claims.sub.unwrap().to_string();
let room_name = claims.video.room.unwrap();
let mut server_rooms = self.rooms.lock();
let room = server_rooms
.get_mut(&*room_name)
.ok_or_else(|| anyhow!("room {} does not exist", room_name))?;
let track = Arc::new(RemoteAudioTrack {
sid: nanoid::nanoid!(17),
publisher_id: identity.clone(),
});
room.audio_tracks.push(track.clone());
for (id, client_room) in &room.client_rooms {
if *id != identity {
let _ = client_room
.0
.lock()
.audio_track_updates
.0
.try_broadcast(RemoteAudioTrackUpdate::Subscribed(track.clone()))
.unwrap();
}
}
Ok(())
}
fn video_tracks(&self, token: String) -> Result<Vec<Arc<RemoteVideoTrack>>> {
let claims = live_kit_server::token::validate(&token, &self.secret_key)?;
let room_name = claims.video.room.unwrap();
@@ -207,14 +244,26 @@ impl TestServer {
let room = server_rooms
.get_mut(&*room_name)
.ok_or_else(|| anyhow!("room {} does not exist", room_name))?;
Ok(room.tracks.clone())
Ok(room.video_tracks.clone())
}
fn audio_tracks(&self, token: String) -> Result<Vec<Arc<RemoteAudioTrack>>> {
let claims = live_kit_server::token::validate(&token, &self.secret_key)?;
let room_name = claims.video.room.unwrap();
let mut server_rooms = self.rooms.lock();
let room = server_rooms
.get_mut(&*room_name)
.ok_or_else(|| anyhow!("room {} does not exist", room_name))?;
Ok(room.audio_tracks.clone())
}
}
#[derive(Default)]
struct TestServerRoom {
client_rooms: HashMap<Sid, Arc<Room>>,
tracks: Vec<Arc<RemoteVideoTrack>>,
video_tracks: Vec<Arc<RemoteVideoTrack>>,
audio_tracks: Vec<Arc<RemoteAudioTrack>>,
}
impl TestServerRoom {}
@@ -266,6 +315,10 @@ struct RoomState {
watch::Receiver<ConnectionState>,
),
display_sources: Vec<MacOSDisplay>,
audio_track_updates: (
async_broadcast::Sender<RemoteAudioTrackUpdate>,
async_broadcast::Receiver<RemoteAudioTrackUpdate>,
),
video_track_updates: (
async_broadcast::Sender<RemoteVideoTrackUpdate>,
async_broadcast::Receiver<RemoteVideoTrackUpdate>,
@@ -286,6 +339,7 @@ impl Room {
connection: watch::channel_with(ConnectionState::Disconnected),
display_sources: Default::default(),
video_track_updates: async_broadcast::broadcast(128),
audio_track_updates: async_broadcast::broadcast(128),
})))
}
@@ -327,8 +381,51 @@ impl Room {
Ok(LocalTrackPublication)
}
}
pub fn publish_audio_track(
self: &Arc<Self>,
track: &LocalAudioTrack,
) -> impl Future<Output = Result<LocalTrackPublication>> {
let this = self.clone();
let track = track.clone();
async move {
this.test_server()
.publish_audio_track(this.token(), &track)
.await?;
Ok(LocalTrackPublication)
}
}
pub fn unpublish_track(&self, _: LocalTrackPublication) {}
pub fn unpublish_track(&self, _publication: LocalTrackPublication) {}
pub fn remote_audio_tracks(&self, publisher_id: &str) -> Vec<Arc<RemoteAudioTrack>> {
if !self.is_connected() {
return Vec::new();
}
self.test_server()
.audio_tracks(self.token())
.unwrap()
.into_iter()
.filter(|track| track.publisher_id() == publisher_id)
.collect()
}
pub fn remote_audio_track_publications(
&self,
publisher_id: &str,
) -> Vec<Arc<RemoteTrackPublication>> {
if !self.is_connected() {
return Vec::new();
}
self.test_server()
.audio_tracks(self.token())
.unwrap()
.into_iter()
.filter(|track| track.publisher_id() == publisher_id)
.map(|_track| Arc::new(RemoteTrackPublication {}))
.collect()
}
pub fn remote_video_tracks(&self, publisher_id: &str) -> Vec<Arc<RemoteVideoTrack>> {
if !self.is_connected() {
@@ -343,6 +440,10 @@ impl Room {
.collect()
}
pub fn remote_audio_track_updates(&self) -> impl Stream<Item = RemoteAudioTrackUpdate> {
self.0.lock().audio_track_updates.1.clone()
}
pub fn remote_video_track_updates(&self) -> impl Stream<Item = RemoteVideoTrackUpdate> {
self.0.lock().video_track_updates.1.clone()
}
@@ -391,6 +492,20 @@ impl Drop for Room {
pub struct LocalTrackPublication;
impl LocalTrackPublication {
pub fn set_mute(&self, _mute: bool) -> impl Future<Output = Result<()>> {
async { Ok(()) }
}
}
pub struct RemoteTrackPublication;
impl RemoteTrackPublication {
pub fn set_enabled(&self, _enabled: bool) -> impl Future<Output = Result<()>> {
async { Ok(()) }
}
}
#[derive(Clone)]
pub struct LocalVideoTrack {
frames_rx: async_broadcast::Receiver<Frame>,
@@ -404,6 +519,15 @@ impl LocalVideoTrack {
}
}
#[derive(Clone)]
pub struct LocalAudioTrack;
impl LocalAudioTrack {
pub fn create() -> Self {
Self
}
}
pub struct RemoteVideoTrack {
sid: Sid,
publisher_id: Sid,
@@ -424,12 +548,44 @@ impl RemoteVideoTrack {
}
}
#[derive(Debug)]
pub struct RemoteAudioTrack {
sid: Sid,
publisher_id: Sid,
}
impl RemoteAudioTrack {
pub fn sid(&self) -> &str {
&self.sid
}
pub fn publisher_id(&self) -> &str {
&self.publisher_id
}
pub fn enable(&self) -> impl Future<Output = Result<()>> {
async { Ok(()) }
}
pub fn disable(&self) -> impl Future<Output = Result<()>> {
async { Ok(()) }
}
}
#[derive(Clone)]
pub enum RemoteVideoTrackUpdate {
Subscribed(Arc<RemoteVideoTrack>),
Unsubscribed { publisher_id: Sid, track_id: Sid },
}
#[derive(Clone)]
pub enum RemoteAudioTrackUpdate {
ActiveSpeakersChanged { speakers: Vec<Sid> },
MuteChanged { track_id: Sid, muted: bool },
Subscribed(Arc<RemoteAudioTrack>),
Unsubscribed { publisher_id: Sid, track_id: Sid },
}
#[derive(Clone)]
pub struct MacOSDisplay {
frames: (
+61 -24
View File
@@ -16,6 +16,7 @@ use smol::{
process::{self, Child},
};
use std::{
ffi::OsString,
fmt,
future::Future,
io::Write,
@@ -33,9 +34,15 @@ const JSON_RPC_VERSION: &str = "2.0";
const CONTENT_LEN_HEADER: &str = "Content-Length: ";
type NotificationHandler = Box<dyn Send + FnMut(Option<usize>, &str, AsyncAppContext)>;
type ResponseHandler = Box<dyn Send + FnOnce(Result<&str, Error>)>;
type ResponseHandler = Box<dyn Send + FnOnce(Result<String, Error>)>;
type IoHandler = Box<dyn Send + FnMut(bool, &str)>;
#[derive(Debug, Clone, Deserialize)]
pub struct LanguageServerBinary {
pub path: PathBuf,
pub arguments: Vec<OsString>,
}
pub struct LanguageServer {
server_id: LanguageServerId,
next_id: AtomicUsize,
@@ -51,7 +58,7 @@ pub struct LanguageServer {
io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
output_done_rx: Mutex<Option<barrier::Receiver>>,
root_path: PathBuf,
_server: Option<Child>,
_server: Option<Mutex<Child>>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -103,14 +110,14 @@ struct Notification<'a, T> {
params: T,
}
#[derive(Deserialize)]
#[derive(Debug, Clone, Deserialize)]
struct AnyNotification<'a> {
#[serde(default)]
id: Option<usize>,
#[serde(borrow)]
method: &'a str,
#[serde(borrow)]
params: &'a RawValue,
#[serde(borrow, default)]
params: Option<&'a RawValue>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -119,10 +126,9 @@ struct Error {
}
impl LanguageServer {
pub fn new<T: AsRef<std::ffi::OsStr>>(
pub fn new(
server_id: LanguageServerId,
binary_path: &Path,
arguments: &[T],
binary: LanguageServerBinary,
root_path: &Path,
code_action_kinds: Option<Vec<CodeActionKind>>,
cx: AsyncAppContext,
@@ -133,9 +139,9 @@ impl LanguageServer {
root_path.parent().unwrap_or_else(|| Path::new("/"))
};
let mut server = process::Command::new(binary_path)
let mut server = process::Command::new(&binary.path)
.current_dir(working_dir)
.args(arguments)
.args(binary.arguments)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
@@ -157,16 +163,20 @@ impl LanguageServer {
"unhandled notification {}:\n{}",
notification.method,
serde_json::to_string_pretty(
&Value::from_str(notification.params.get()).unwrap()
&notification
.params
.and_then(|params| Value::from_str(params.get()).ok())
.unwrap_or(Value::Null)
)
.unwrap()
.unwrap(),
);
},
);
if let Some(name) = binary_path.file_name() {
if let Some(name) = binary.path.file_name() {
server.name = name.to_string_lossy().to_string();
}
Ok(server)
}
@@ -228,7 +238,7 @@ impl LanguageServer {
io_tasks: Mutex::new(Some((input_task, output_task))),
output_done_rx: Mutex::new(Some(output_done_rx)),
root_path: root_path.to_path_buf(),
_server: server,
_server: server.map(|server| Mutex::new(server)),
}
}
@@ -279,7 +289,11 @@ impl LanguageServer {
if let Ok(msg) = serde_json::from_slice::<AnyNotification>(&buffer) {
if let Some(handler) = notification_handlers.lock().get_mut(msg.method) {
handler(msg.id, msg.params.get(), cx.clone());
handler(
msg.id,
&msg.params.map(|params| params.get()).unwrap_or("null"),
cx.clone(),
);
} else {
on_unhandled_notification(msg);
}
@@ -295,9 +309,9 @@ impl LanguageServer {
if let Some(error) = error {
handler(Err(error));
} else if let Some(result) = result {
handler(Ok(result.get()));
handler(Ok(result.get().into()));
} else {
handler(Ok("null"));
handler(Ok("null".into()));
}
}
} else {
@@ -374,6 +388,9 @@ impl LanguageServer {
resolve_support: None,
..WorkspaceSymbolClientCapabilities::default()
}),
inlay_hint: Some(InlayHintWorkspaceClientCapabilities {
refresh_support: Some(true),
}),
..Default::default()
}),
text_document: Some(TextDocumentClientCapabilities {
@@ -415,6 +432,10 @@ impl LanguageServer {
content_format: Some(vec![MarkupKind::Markdown]),
..Default::default()
}),
inlay_hint: Some(InlayHintClientCapabilities {
resolve_support: None,
dynamic_registration: Some(false),
}),
..Default::default()
}),
experimental: Some(json!({
@@ -450,11 +471,13 @@ impl LanguageServer {
let response_handlers = self.response_handlers.clone();
let next_id = AtomicUsize::new(self.next_id.load(SeqCst));
let outbound_tx = self.outbound_tx.clone();
let executor = self.executor.clone();
let mut output_done = self.output_done_rx.lock().take().unwrap();
let shutdown_request = Self::request_internal::<request::Shutdown>(
&next_id,
&response_handlers,
&outbound_tx,
&executor,
(),
);
let exit = Self::notify_internal::<notification::Exit>(&outbound_tx, ());
@@ -591,6 +614,7 @@ impl LanguageServer {
})
.detach();
}
Err(error) => {
log::error!(
"error deserializing {} request: {:?}, message: {:?}",
@@ -651,6 +675,7 @@ impl LanguageServer {
&self.next_id,
&self.response_handlers,
&self.outbound_tx,
&self.executor,
params,
)
}
@@ -659,6 +684,7 @@ impl LanguageServer {
next_id: &AtomicUsize,
response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
outbound_tx: &channel::Sender<String>,
executor: &Arc<executor::Background>,
params: T::Params,
) -> impl 'static + Future<Output = Result<T::Result>>
where
@@ -679,15 +705,20 @@ impl LanguageServer {
.as_mut()
.ok_or_else(|| anyhow!("server shut down"))
.map(|handlers| {
let executor = executor.clone();
handlers.insert(
id,
Box::new(move |result| {
let response = match result {
Ok(response) => serde_json::from_str(response)
.context("failed to deserialize response"),
Err(error) => Err(anyhow!("{}", error.message)),
};
let _ = tx.send(response);
executor
.spawn(async move {
let response = match result {
Ok(response) => serde_json::from_str(&response)
.context("failed to deserialize response"),
Err(error) => Err(anyhow!("{}", error.message)),
};
_ = tx.send(response);
})
.detach();
}),
);
});
@@ -828,7 +859,13 @@ impl LanguageServer {
cx,
move |msg| {
notifications_tx
.try_send((msg.method.to_string(), msg.params.get().to_string()))
.try_send((
msg.method.to_string(),
msg.params
.map(|raw_value| raw_value.get())
.unwrap_or("null")
.to_string(),
))
.ok();
},
)),
+1
View File
@@ -20,3 +20,4 @@ serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true
smol.workspace = true
log.workspace = true
+119 -82
View File
@@ -1,21 +1,24 @@
use anyhow::{anyhow, bail, Context, Result};
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use futures::lock::Mutex;
use futures::{future::Shared, FutureExt};
use gpui::{executor::Background, Task};
use parking_lot::Mutex;
use serde::Deserialize;
use smol::{fs, io::BufReader, process::Command};
use std::process::Output;
use std::{
env::consts,
path::{Path, PathBuf},
sync::Arc,
sync::{Arc, OnceLock},
};
use util::http::HttpClient;
use util::{http::HttpClient, ResultExt};
const VERSION: &str = "v18.15.0";
#[derive(Deserialize)]
static RUNTIME_INSTANCE: OnceLock<Arc<NodeRuntime>> = OnceLock::new();
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct NpmInfo {
#[serde(default)]
@@ -23,7 +26,7 @@ pub struct NpmInfo {
versions: Vec<String>,
}
#[derive(Deserialize, Default)]
#[derive(Debug, Deserialize, Default)]
pub struct NpmInfoDistTags {
latest: Option<String>,
}
@@ -35,12 +38,16 @@ pub struct NodeRuntime {
}
impl NodeRuntime {
pub fn new(http: Arc<dyn HttpClient>, background: Arc<Background>) -> Arc<NodeRuntime> {
Arc::new(NodeRuntime {
http,
background,
installation_path: Mutex::new(None),
})
pub fn instance(http: Arc<dyn HttpClient>, background: Arc<Background>) -> Arc<NodeRuntime> {
RUNTIME_INSTANCE
.get_or_init(|| {
Arc::new(NodeRuntime {
http,
background,
installation_path: Mutex::new(None),
})
})
.clone()
}
pub async fn binary_path(&self) -> Result<PathBuf> {
@@ -50,55 +57,74 @@ impl NodeRuntime {
pub async fn run_npm_subcommand(
&self,
directory: &Path,
directory: Option<&Path>,
subcommand: &str,
args: &[&str],
) -> Result<()> {
) -> Result<Output> {
let attempt = |installation_path: PathBuf| async move {
let node_binary = installation_path.join("bin/node");
let npm_file = installation_path.join("bin/npm");
if smol::fs::metadata(&node_binary).await.is_err() {
return Err(anyhow!("missing node binary file"));
}
if smol::fs::metadata(&npm_file).await.is_err() {
return Err(anyhow!("missing npm file"));
}
let mut command = Command::new(node_binary);
command.arg(npm_file).arg(subcommand).args(args);
if let Some(directory) = directory {
command.current_dir(directory);
}
command.output().await.map_err(|e| anyhow!("{e}"))
};
let installation_path = self.install_if_needed().await?;
let node_binary = installation_path.join("bin/node");
let npm_file = installation_path.join("bin/npm");
let output = Command::new(node_binary)
.arg(npm_file)
.arg(subcommand)
.args(args)
.current_dir(directory)
.output()
.await?;
if !output.status.success() {
return Err(anyhow!(
"failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
let mut output = attempt(installation_path).await;
if output.is_err() {
let installation_path = self.reinstall().await?;
output = attempt(installation_path).await;
if output.is_err() {
return Err(anyhow!(
"failed to launch npm subcommand {subcommand} subcommand"
));
}
}
Ok(())
if let Ok(output) = &output {
if !output.status.success() {
return Err(anyhow!(
"failed to execute npm {subcommand} subcommand:\nstdout: {:?}\nstderr: {:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
}
output.map_err(|e| anyhow!("{e}"))
}
pub async fn npm_package_latest_version(&self, name: &str) -> Result<String> {
let installation_path = self.install_if_needed().await?;
let node_binary = installation_path.join("bin/node");
let npm_file = installation_path.join("bin/npm");
let output = Command::new(node_binary)
.arg(npm_file)
.args(["-fetch-retry-mintimeout", "2000"])
.args(["-fetch-retry-maxtimeout", "5000"])
.args(["-fetch-timeout", "5000"])
.args(["info", name, "--json"])
.output()
.await
.context("failed to run npm info")?;
if !output.status.success() {
return Err(anyhow!(
"failed to execute npm info:\nstdout: {:?}\nstderr: {:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
let output = self
.run_npm_subcommand(
None,
"info",
&[
name,
"--json",
"-fetch-retry-mintimeout",
"2000",
"-fetch-retry-maxtimeout",
"5000",
"-fetch-timeout",
"5000",
],
)
.await?;
let mut info: NpmInfo = serde_json::from_slice(&output.stdout)?;
info.dist_tags
@@ -112,41 +138,54 @@ impl NodeRuntime {
directory: &Path,
packages: impl IntoIterator<Item = (&str, &str)>,
) -> Result<()> {
let installation_path = self.install_if_needed().await?;
let node_binary = installation_path.join("bin/node");
let npm_file = installation_path.join("bin/npm");
let packages: Vec<_> = packages
.into_iter()
.map(|(name, version)| format!("{name}@{version}"))
.collect();
let output = Command::new(node_binary)
.arg(npm_file)
.args(["-fetch-retry-mintimeout", "2000"])
.args(["-fetch-retry-maxtimeout", "5000"])
.args(["-fetch-timeout", "5000"])
.arg("install")
.arg("--prefix")
.arg(directory)
.args(
packages
.into_iter()
.map(|(name, version)| format!("{name}@{version}")),
)
.output()
.await
.context("failed to run npm install")?;
let mut arguments: Vec<_> = packages.iter().map(|p| p.as_str()).collect();
arguments.extend_from_slice(&[
"-fetch-retry-mintimeout",
"2000",
"-fetch-retry-maxtimeout",
"5000",
"-fetch-timeout",
"5000",
]);
if !output.status.success() {
return Err(anyhow!(
"failed to execute npm install:\nstdout: {:?}\nstderr: {:?}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
));
}
self.run_npm_subcommand(Some(directory), "install", &arguments)
.await?;
Ok(())
}
async fn reinstall(&self) -> Result<PathBuf> {
log::info!("beginnning to reinstall Node runtime");
let mut installation_path = self.installation_path.lock().await;
if let Some(task) = installation_path.as_ref().cloned() {
if let Ok(installation_path) = task.await {
smol::fs::remove_dir_all(&installation_path)
.await
.context("node dir removal")
.log_err();
}
}
let http = self.http.clone();
let task = self
.background
.spawn(async move { Self::install(http).await.map_err(Arc::new) })
.shared();
*installation_path = Some(task.clone());
task.await.map_err(|e| anyhow!("{}", e))
}
async fn install_if_needed(&self) -> Result<PathBuf> {
let task = self
.installation_path
.lock()
.await
.get_or_insert_with(|| {
let http = self.http.clone();
self.background
@@ -155,13 +194,11 @@ impl NodeRuntime {
})
.clone();
match task.await {
Ok(path) => Ok(path),
Err(error) => Err(anyhow!("{}", error)),
}
task.await.map_err(|e| anyhow!("{}", e))
}
async fn install(http: Arc<dyn HttpClient>) -> Result<PathBuf> {
log::info!("installing Node runtime");
let arch = match consts::ARCH {
"x86_64" => "x64",
"aarch64" => "arm64",
+1 -1
View File
@@ -204,7 +204,7 @@ impl PickerDelegate for OutlineViewDelegate {
cx: &AppContext,
) -> AnyElement<Picker<Self>> {
let theme = theme::current(cx);
let style = theme.picker.item.style_for(mouse_state, selected);
let style = theme.picker.item.in_state(selected).style_for(mouse_state);
let string_match = &self.matches[ix];
let outline_item = &self.outline.items[string_match.candidate_id];
+25
View File
@@ -25,6 +25,7 @@ pub struct Picker<D: PickerDelegate> {
theme: Arc<Mutex<Box<dyn Fn(&theme::Theme) -> theme::Picker>>>,
confirmed: bool,
pending_update_matches: Task<Option<()>>,
has_focus: bool,
}
pub trait PickerDelegate: Sized + 'static {
@@ -45,6 +46,18 @@ pub trait PickerDelegate: Sized + 'static {
fn center_selection_after_match_updates(&self) -> bool {
false
}
fn render_header(
&self,
_cx: &mut ViewContext<Picker<Self>>,
) -> Option<AnyElement<Picker<Self>>> {
None
}
fn render_footer(
&self,
_cx: &mut ViewContext<Picker<Self>>,
) -> Option<AnyElement<Picker<Self>>> {
None
}
}
impl<D: PickerDelegate> Entity for Picker<D> {
@@ -77,6 +90,7 @@ impl<D: PickerDelegate> View for Picker<D> {
.contained()
.with_style(editor_style),
)
.with_children(self.delegate.render_header(cx))
.with_children(if match_count == 0 {
if query.is_empty() {
None
@@ -118,6 +132,7 @@ impl<D: PickerDelegate> View for Picker<D> {
.into_any(),
)
})
.with_children(self.delegate.render_footer(cx))
.contained()
.with_style(container_style)
.constrained()
@@ -132,13 +147,22 @@ impl<D: PickerDelegate> View for Picker<D> {
}
fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
self.has_focus = true;
if cx.is_self_focused() {
cx.focus(&self.query_editor);
}
}
fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {
self.has_focus = false;
}
}
impl<D: PickerDelegate> Modal for Picker<D> {
fn has_focus(&self) -> bool {
self.has_focus
}
fn dismiss_on_event(event: &Self::Event) -> bool {
matches!(event, PickerEvent::Dismiss)
}
@@ -183,6 +207,7 @@ impl<D: PickerDelegate> Picker<D> {
theme,
confirmed: false,
pending_update_matches: Task::ready(None),
has_focus: false,
};
this.update_matches(String::new(), cx);
this
+1 -1
View File
@@ -64,7 +64,7 @@ itertools = "0.10"
[dev-dependencies]
ctor.workspace = true
env_logger.workspace = true
pretty_assertions = "1.3.0"
pretty_assertions.workspace = true
client = { path = "../client", features = ["test-support"] }
collections = { path = "../collections", features = ["test-support"] }
db = { path = "../db", features = ["test-support"] }
+349 -4
View File
@@ -1,14 +1,15 @@
use crate::{
DocumentHighlight, Hover, HoverBlock, HoverBlockKind, Location, LocationLink, Project,
ProjectTransaction,
DocumentHighlight, Hover, HoverBlock, HoverBlockKind, InlayHint, InlayHintLabel,
InlayHintLabelPart, InlayHintLabelPartTooltip, InlayHintTooltip, Location, LocationLink,
MarkupContent, Project, ProjectTransaction,
};
use anyhow::{anyhow, Result};
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use client::proto::{self, PeerId};
use fs::LineEnding;
use gpui::{AppContext, AsyncAppContext, ModelHandle};
use language::{
language_settings::language_settings,
language_settings::{language_settings, InlayHintKind},
point_from_lsp, point_to_lsp,
proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CharKind, CodeAction,
@@ -126,6 +127,10 @@ pub(crate) struct OnTypeFormatting {
pub push_to_history: bool,
}
pub(crate) struct InlayHints {
pub range: Range<Anchor>,
}
pub(crate) struct FormattingOptions {
tab_size: u32,
}
@@ -1780,3 +1785,343 @@ impl LspCommand for OnTypeFormatting {
message.buffer_id
}
}
#[async_trait(?Send)]
impl LspCommand for InlayHints {
type Response = Vec<InlayHint>;
type LspRequest = lsp::InlayHintRequest;
type ProtoRequest = proto::InlayHints;
fn check_capabilities(&self, server_capabilities: &lsp::ServerCapabilities) -> bool {
let Some(inlay_hint_provider) = &server_capabilities.inlay_hint_provider else { return false };
match inlay_hint_provider {
lsp::OneOf::Left(enabled) => *enabled,
lsp::OneOf::Right(inlay_hint_capabilities) => match inlay_hint_capabilities {
lsp::InlayHintServerCapabilities::Options(_) => true,
lsp::InlayHintServerCapabilities::RegistrationOptions(_) => false,
},
}
}
fn to_lsp(
&self,
path: &Path,
buffer: &Buffer,
_: &Arc<LanguageServer>,
_: &AppContext,
) -> lsp::InlayHintParams {
lsp::InlayHintParams {
text_document: lsp::TextDocumentIdentifier {
uri: lsp::Url::from_file_path(path).unwrap(),
},
range: range_to_lsp(self.range.to_point_utf16(buffer)),
work_done_progress_params: Default::default(),
}
}
async fn response_from_lsp(
self,
message: Option<Vec<lsp::InlayHint>>,
project: ModelHandle<Project>,
buffer: ModelHandle<Buffer>,
server_id: LanguageServerId,
mut cx: AsyncAppContext,
) -> Result<Vec<InlayHint>> {
let (lsp_adapter, _) = language_server_for_buffer(&project, &buffer, server_id, &mut cx)?;
// `typescript-language-server` adds padding to the left for type hints, turning
// `const foo: boolean` into `const foo : boolean` which looks odd.
// `rust-analyzer` does not have the padding for this case, and we have to accomodate both.
//
// We could trim the whole string, but being pessimistic on par with the situation above,
// there might be a hint with multiple whitespaces at the end(s) which we need to display properly.
// Hence let's use a heuristic first to handle the most awkward case and look for more.
let force_no_type_left_padding =
lsp_adapter.name.0.as_ref() == "typescript-language-server";
cx.read(|cx| {
let origin_buffer = buffer.read(cx);
Ok(message
.unwrap_or_default()
.into_iter()
.map(|lsp_hint| {
let kind = lsp_hint.kind.and_then(|kind| match kind {
lsp::InlayHintKind::TYPE => Some(InlayHintKind::Type),
lsp::InlayHintKind::PARAMETER => Some(InlayHintKind::Parameter),
_ => None,
});
let position = origin_buffer
.clip_point_utf16(point_from_lsp(lsp_hint.position), Bias::Left);
let padding_left =
if force_no_type_left_padding && kind == Some(InlayHintKind::Type) {
false
} else {
lsp_hint.padding_left.unwrap_or(false)
};
InlayHint {
buffer_id: origin_buffer.remote_id(),
position: if kind == Some(InlayHintKind::Parameter) {
origin_buffer.anchor_before(position)
} else {
origin_buffer.anchor_after(position)
},
padding_left,
padding_right: lsp_hint.padding_right.unwrap_or(false),
label: match lsp_hint.label {
lsp::InlayHintLabel::String(s) => InlayHintLabel::String(s),
lsp::InlayHintLabel::LabelParts(lsp_parts) => {
InlayHintLabel::LabelParts(
lsp_parts
.into_iter()
.map(|label_part| InlayHintLabelPart {
value: label_part.value,
tooltip: label_part.tooltip.map(
|tooltip| {
match tooltip {
lsp::InlayHintLabelPartTooltip::String(s) => {
InlayHintLabelPartTooltip::String(s)
}
lsp::InlayHintLabelPartTooltip::MarkupContent(
markup_content,
) => InlayHintLabelPartTooltip::MarkupContent(
MarkupContent {
kind: format!("{:?}", markup_content.kind),
value: markup_content.value,
},
),
}
},
),
location: label_part.location.map(|lsp_location| {
let target_start = origin_buffer.clip_point_utf16(
point_from_lsp(lsp_location.range.start),
Bias::Left,
);
let target_end = origin_buffer.clip_point_utf16(
point_from_lsp(lsp_location.range.end),
Bias::Left,
);
Location {
buffer: buffer.clone(),
range: origin_buffer.anchor_after(target_start)
..origin_buffer.anchor_before(target_end),
}
}),
})
.collect(),
)
}
},
kind,
tooltip: lsp_hint.tooltip.map(|tooltip| match tooltip {
lsp::InlayHintTooltip::String(s) => InlayHintTooltip::String(s),
lsp::InlayHintTooltip::MarkupContent(markup_content) => {
InlayHintTooltip::MarkupContent(MarkupContent {
kind: format!("{:?}", markup_content.kind),
value: markup_content.value,
})
}
}),
}
})
.collect())
})
}
fn to_proto(&self, project_id: u64, buffer: &Buffer) -> proto::InlayHints {
proto::InlayHints {
project_id,
buffer_id: buffer.remote_id(),
start: Some(language::proto::serialize_anchor(&self.range.start)),
end: Some(language::proto::serialize_anchor(&self.range.end)),
version: serialize_version(&buffer.version()),
}
}
async fn from_proto(
message: proto::InlayHints,
_: ModelHandle<Project>,
buffer: ModelHandle<Buffer>,
mut cx: AsyncAppContext,
) -> Result<Self> {
let start = message
.start
.and_then(language::proto::deserialize_anchor)
.context("invalid start")?;
let end = message
.end
.and_then(language::proto::deserialize_anchor)
.context("invalid end")?;
buffer
.update(&mut cx, |buffer, _| {
buffer.wait_for_version(deserialize_version(&message.version))
})
.await?;
Ok(Self { range: start..end })
}
fn response_to_proto(
response: Vec<InlayHint>,
_: &mut Project,
_: PeerId,
buffer_version: &clock::Global,
cx: &mut AppContext,
) -> proto::InlayHintsResponse {
proto::InlayHintsResponse {
hints: response
.into_iter()
.map(|response_hint| proto::InlayHint {
position: Some(language::proto::serialize_anchor(&response_hint.position)),
padding_left: response_hint.padding_left,
padding_right: response_hint.padding_right,
label: Some(proto::InlayHintLabel {
label: Some(match response_hint.label {
InlayHintLabel::String(s) => proto::inlay_hint_label::Label::Value(s),
InlayHintLabel::LabelParts(label_parts) => {
proto::inlay_hint_label::Label::LabelParts(proto::InlayHintLabelParts {
parts: label_parts.into_iter().map(|label_part| proto::InlayHintLabelPart {
value: label_part.value,
tooltip: label_part.tooltip.map(|tooltip| {
let proto_tooltip = match tooltip {
InlayHintLabelPartTooltip::String(s) => proto::inlay_hint_label_part_tooltip::Content::Value(s),
InlayHintLabelPartTooltip::MarkupContent(markup_content) => proto::inlay_hint_label_part_tooltip::Content::MarkupContent(proto::MarkupContent {
kind: markup_content.kind,
value: markup_content.value,
}),
};
proto::InlayHintLabelPartTooltip {content: Some(proto_tooltip)}
}),
location: label_part.location.map(|location| proto::Location {
start: Some(serialize_anchor(&location.range.start)),
end: Some(serialize_anchor(&location.range.end)),
buffer_id: location.buffer.read(cx).remote_id(),
}),
}).collect()
})
}
}),
}),
kind: response_hint.kind.map(|kind| kind.name().to_string()),
tooltip: response_hint.tooltip.map(|response_tooltip| {
let proto_tooltip = match response_tooltip {
InlayHintTooltip::String(s) => {
proto::inlay_hint_tooltip::Content::Value(s)
}
InlayHintTooltip::MarkupContent(markup_content) => {
proto::inlay_hint_tooltip::Content::MarkupContent(
proto::MarkupContent {
kind: markup_content.kind,
value: markup_content.value,
},
)
}
};
proto::InlayHintTooltip {
content: Some(proto_tooltip),
}
}),
})
.collect(),
version: serialize_version(buffer_version),
}
}
async fn response_from_proto(
self,
message: proto::InlayHintsResponse,
project: ModelHandle<Project>,
buffer: ModelHandle<Buffer>,
mut cx: AsyncAppContext,
) -> Result<Vec<InlayHint>> {
buffer
.update(&mut cx, |buffer, _| {
buffer.wait_for_version(deserialize_version(&message.version))
})
.await?;
let mut hints = Vec::new();
for message_hint in message.hints {
let buffer_id = message_hint
.position
.as_ref()
.and_then(|location| location.buffer_id)
.context("missing buffer id")?;
let hint = InlayHint {
buffer_id,
position: message_hint
.position
.and_then(language::proto::deserialize_anchor)
.context("invalid position")?,
label: match message_hint
.label
.and_then(|label| label.label)
.context("missing label")?
{
proto::inlay_hint_label::Label::Value(s) => InlayHintLabel::String(s),
proto::inlay_hint_label::Label::LabelParts(parts) => {
let mut label_parts = Vec::new();
for part in parts.parts {
label_parts.push(InlayHintLabelPart {
value: part.value,
tooltip: part.tooltip.map(|tooltip| match tooltip.content {
Some(proto::inlay_hint_label_part_tooltip::Content::Value(s)) => InlayHintLabelPartTooltip::String(s),
Some(proto::inlay_hint_label_part_tooltip::Content::MarkupContent(markup_content)) => InlayHintLabelPartTooltip::MarkupContent(MarkupContent {
kind: markup_content.kind,
value: markup_content.value,
}),
None => InlayHintLabelPartTooltip::String(String::new()),
}),
location: match part.location {
Some(location) => {
let target_buffer = project
.update(&mut cx, |this, cx| {
this.wait_for_remote_buffer(location.buffer_id, cx)
})
.await?;
Some(Location {
range: location
.start
.and_then(language::proto::deserialize_anchor)
.context("invalid start")?
..location
.end
.and_then(language::proto::deserialize_anchor)
.context("invalid end")?,
buffer: target_buffer,
})},
None => None,
},
});
}
InlayHintLabel::LabelParts(label_parts)
}
},
padding_left: message_hint.padding_left,
padding_right: message_hint.padding_right,
kind: message_hint
.kind
.as_deref()
.and_then(InlayHintKind::from_name),
tooltip: message_hint.tooltip.and_then(|tooltip| {
Some(match tooltip.content? {
proto::inlay_hint_tooltip::Content::Value(s) => InlayHintTooltip::String(s),
proto::inlay_hint_tooltip::Content::MarkupContent(markup_content) => {
InlayHintTooltip::MarkupContent(MarkupContent {
kind: markup_content.kind,
value: markup_content.value,
})
}
})
}),
};
hints.push(hint);
}
Ok(hints)
}
fn buffer_id_from_proto(message: &proto::InlayHints) -> u64 {
message.buffer_id
}
}

Some files were not shown because too many files have changed in this diff Show More