Merge pull request #2343 from zed-industries/handles

Nathan Sobo created

Make typed handles wrappers around their untyped equivalents

Change summary

crates/client/src/client.rs                       |   6 
crates/collab_ui/src/contact_finder.rs            |   2 
crates/collab_ui/src/contact_list.rs              |   2 
crates/command_palette/src/command_palette.rs     |   6 
crates/diagnostics/src/diagnostics.rs             |  14 
crates/editor/src/editor.rs                       |   2 
crates/editor/src/items.rs                        |   2 
crates/feedback/src/feedback_editor.rs            |  14 
crates/file_finder/src/file_finder.rs             |   6 
crates/gpui/src/app.rs                            | 304 ++++++----------
crates/gpui/src/app/test_app_context.rs           |   6 
crates/gpui/src/presenter.rs                      |   5 
crates/language_selector/src/language_selector.rs |   2 
crates/outline/src/outline.rs                     |   2 
crates/project/src/project.rs                     |   4 
crates/project_panel/src/project_panel.rs         |   2 
crates/project_symbols/src/project_symbols.rs     |   2 
crates/recent_projects/src/recent_projects.rs     |   2 
crates/search/src/buffer_search.rs                |   4 
crates/search/src/project_search.rs               |  20 
crates/terminal_view/src/terminal_view.rs         |   2 
crates/theme_selector/src/theme_selector.rs       |   2 
crates/welcome/src/base_keymap_picker.rs          |   2 
crates/welcome/src/welcome.rs                     |   2 
crates/workspace/src/dock.rs                      |   6 
crates/workspace/src/item.rs                      |  32 
crates/workspace/src/notifications.rs             |   8 
crates/workspace/src/pane.rs                      |  24 
crates/workspace/src/searchable.rs                |  10 
crates/workspace/src/sidebar.rs                   |  10 
crates/workspace/src/status_bar.rs                |  16 
crates/workspace/src/toolbar.rs                   |  16 
crates/workspace/src/workspace.rs                 |  40 +-
crates/zed/src/zed.rs                             |  18 
34 files changed, 253 insertions(+), 342 deletions(-)

Detailed changes

crates/client/src/client.rs 🔗

@@ -293,7 +293,7 @@ impl<T: Entity> PendingEntitySubscription<T> {
 
         state
             .entities_by_type_and_remote_id
-            .insert(id, WeakSubscriber::Model(model.downgrade().into()));
+            .insert(id, WeakSubscriber::Model(model.downgrade().into_any()));
         drop(state);
         for message in messages {
             self.client.handle_message(message, cx);
@@ -460,7 +460,7 @@ impl Client {
         self.state
             .write()
             .entities_by_type_and_remote_id
-            .insert(id, WeakSubscriber::View(cx.weak_handle().into()));
+            .insert(id, WeakSubscriber::View(cx.weak_handle().into_any()));
         Subscription::Entity {
             client: Arc::downgrade(self),
             id,
@@ -504,7 +504,7 @@ impl Client {
         let mut state = self.state.write();
         state
             .models_by_message_type
-            .insert(message_type_id, model.downgrade().into());
+            .insert(message_type_id, model.downgrade().into_any());
 
         let prev_handler = state.message_handlers.insert(
             message_type_id,

crates/collab_ui/src/contact_finder.rs 🔗

@@ -33,7 +33,7 @@ impl View for ContactFinder {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/collab_ui/src/contact_list.rs 🔗

@@ -1339,7 +1339,7 @@ impl View for ContactList {
             .with_child(
                 Flex::row()
                     .with_child(
-                        ChildView::new(self.filter_editor.clone(), cx)
+                        ChildView::new(&self.filter_editor, cx)
                             .contained()
                             .with_style(theme.contact_list.user_query_editor.container)
                             .flex(1., true)

crates/command_palette/src/command_palette.rs 🔗

@@ -85,7 +85,7 @@ impl CommandPalette {
             .unwrap_or_else(|| workspace.id());
 
         cx.as_mut().defer(move |cx| {
-            let this = cx.add_view(workspace.clone(), |cx| Self::new(focused_view_id, cx));
+            let this = cx.add_view(&workspace, |cx| Self::new(focused_view_id, cx));
             workspace.update(cx, |workspace, cx| {
                 workspace.toggle_modal(cx, |_, cx| {
                     cx.subscribe(&this, Self::on_event).detach();
@@ -129,7 +129,7 @@ impl View for CommandPalette {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> gpui::ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
@@ -355,7 +355,7 @@ mod tests {
         });
 
         workspace.update(cx, |workspace, cx| {
-            cx.focus(editor.clone());
+            cx.focus(&editor);
             workspace.add_item(Box::new(editor.clone()), cx)
         });
 

crates/diagnostics/src/diagnostics.rs 🔗

@@ -602,16 +602,16 @@ impl Item for ProjectDiagnosticsEditor {
         ))
     }
 
-    fn act_as_type(
-        &self,
+    fn act_as_type<'a>(
+        &'a self,
         type_id: TypeId,
-        self_handle: &ViewHandle<Self>,
-        _: &AppContext,
-    ) -> Option<AnyViewHandle> {
+        self_handle: &'a ViewHandle<Self>,
+        _: &'a AppContext,
+    ) -> Option<&AnyViewHandle> {
         if type_id == TypeId::of::<Self>() {
-            Some(self_handle.into())
+            Some(self_handle)
         } else if type_id == TypeId::of::<Editor>() {
-            Some((&self.editor).into())
+            Some(&self.editor)
         } else {
             None
         }

crates/editor/src/editor.rs 🔗

@@ -5730,7 +5730,7 @@ impl Editor {
                             render: Arc::new({
                                 let editor = rename_editor.clone();
                                 move |cx: &mut BlockContext| {
-                                    ChildView::new(editor.clone(), cx)
+                                    ChildView::new(&editor, cx)
                                         .contained()
                                         .with_padding_left(cx.anchor_x)
                                         .boxed()

crates/editor/src/items.rs 🔗

@@ -835,7 +835,7 @@ impl Item for Editor {
                         .context("Project item at stored path was not a buffer")?;
 
                     Ok(cx.update(|cx| {
-                        cx.add_view(pane, |cx| {
+                        cx.add_view(&pane, |cx| {
                             let mut editor = Editor::for_buffer(buffer, Some(project), cx);
                             editor.read_scroll_position_from_db(item_id, workspace_id, cx);
                             editor

crates/feedback/src/feedback_editor.rs 🔗

@@ -333,16 +333,16 @@ impl Item for FeedbackEditor {
         Some(Box::new(handle.clone()))
     }
 
-    fn act_as_type(
-        &self,
+    fn act_as_type<'a>(
+        &'a self,
         type_id: TypeId,
-        self_handle: &ViewHandle<Self>,
-        _: &AppContext,
-    ) -> Option<AnyViewHandle> {
+        self_handle: &'a ViewHandle<Self>,
+        _: &'a AppContext,
+    ) -> Option<&'a AnyViewHandle> {
         if type_id == TypeId::of::<Self>() {
-            Some(self_handle.into())
+            Some(self_handle)
         } else if type_id == TypeId::of::<Editor>() {
-            Some((&self.editor).into())
+            Some(&self.editor)
         } else {
             None
         }

crates/file_finder/src/file_finder.rs 🔗

@@ -51,7 +51,7 @@ impl View for FileFinder {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
@@ -352,8 +352,8 @@ mod tests {
             let active_item = active_pane.read(cx).active_item().unwrap();
             assert_eq!(
                 active_item
-                    .to_any()
-                    .downcast::<Editor>()
+                    .as_any()
+                    .downcast_ref::<Editor>()
                     .unwrap()
                     .read(cx)
                     .title(cx),

crates/gpui/src/app.rs 🔗

@@ -1633,14 +1633,14 @@ impl MutableAppContext {
             this.cx.windows.insert(
                 window_id,
                 Window {
-                    root_view: root_view.clone().into(),
+                    root_view: root_view.clone().into_any(),
                     focused_view_id: Some(root_view.id()),
                     is_active: false,
                     invalidation: None,
                     is_fullscreen: false,
                 },
             );
-            root_view.update(this, |view, cx| view.focus_in(cx.handle().into(), cx));
+            root_view.update(this, |view, cx| view.focus_in(cx.handle().into_any(), cx));
 
             let window =
                 this.cx
@@ -1662,17 +1662,18 @@ impl MutableAppContext {
             let root_view = this
                 .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
                 .unwrap();
+            let focused_view_id = root_view.id();
             this.cx.windows.insert(
                 window_id,
                 Window {
-                    root_view: root_view.clone().into(),
-                    focused_view_id: Some(root_view.id()),
+                    root_view: root_view.clone().into_any(),
+                    focused_view_id: Some(focused_view_id),
                     is_active: false,
                     invalidation: None,
                     is_fullscreen: false,
                 },
             );
-            root_view.update(this, |view, cx| view.focus_in(cx.handle().into(), cx));
+            root_view.update(this, |view, cx| view.focus_in(cx.handle().into_any(), cx));
 
             let status_item = this.cx.platform.add_status_item();
             this.register_platform_window(window_id, status_item);
@@ -1783,7 +1784,7 @@ impl MutableAppContext {
                 .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
                 .unwrap();
             let window = this.cx.windows.get_mut(&window_id).unwrap();
-            window.root_view = root_view.clone().into();
+            window.root_view = root_view.clone().into_any();
             window.focused_view_id = Some(root_view.id());
             root_view
         })
@@ -1812,16 +1813,11 @@ impl MutableAppContext {
         )
     }
 
-    pub fn add_view<T, F>(
-        &mut self,
-        parent_handle: impl Into<AnyViewHandle>,
-        build_view: F,
-    ) -> ViewHandle<T>
+    pub fn add_view<T, F>(&mut self, parent_handle: &AnyViewHandle, build_view: F) -> ViewHandle<T>
     where
         T: View,
         F: FnOnce(&mut ViewContext<T>) -> T,
     {
-        let parent_handle = parent_handle.into();
         self.build_and_insert_view(
             parent_handle.window_id,
             ParentId::View(parent_handle.view_id),
@@ -2828,8 +2824,7 @@ impl AppContext {
         }
     }
 
-    pub fn is_child_focused(&self, view: impl Into<AnyViewHandle>) -> bool {
-        let view = view.into();
+    pub fn is_child_focused(&self, view: &AnyViewHandle) -> bool {
         if let Some(focused_view_id) = self.focused_view_id(view.window_id) {
             self.ancestors(view.window_id, focused_view_id)
                 .skip(1) // Skip self id
@@ -3368,7 +3363,7 @@ where
     ) {
         let mut cx = ViewContext::new(cx, window_id, view_id);
         let focused_view_handle: AnyViewHandle = if view_id == focused_id {
-            cx.handle().into()
+            cx.handle().into_any()
         } else {
             let focused_type = cx
                 .views
@@ -3390,7 +3385,7 @@ where
     ) {
         let mut cx = ViewContext::new(cx, window_id, view_id);
         let blurred_view_handle: AnyViewHandle = if view_id == blurred_id {
-            cx.handle().into()
+            cx.handle().into_any()
         } else {
             let blurred_type = cx
                 .views
@@ -3794,11 +3789,7 @@ impl<'a, T: View> ViewContext<'a, T> {
         self.app.debug_elements(self.window_id).unwrap()
     }
 
-    pub fn focus<S>(&mut self, handle: S)
-    where
-        S: Into<AnyViewHandle>,
-    {
-        let handle = handle.into();
+    pub fn focus(&mut self, handle: &AnyViewHandle) {
         self.app.focus(handle.window_id, Some(handle.view_id));
     }
 
@@ -3890,8 +3881,7 @@ impl<'a, T: View> ViewContext<'a, T> {
         self.cx.parent(self.window_id, self.view_id)
     }
 
-    pub fn reparent(&mut self, view_handle: impl Into<AnyViewHandle>) {
-        let view_handle = view_handle.into();
+    pub fn reparent(&mut self, view_handle: &AnyViewHandle) {
         if self.window_id != view_handle.window_id {
             panic!("Can't reparent view to a view from a different window");
         }
@@ -3916,7 +3906,7 @@ impl<'a, T: View> ViewContext<'a, T> {
                 .build_and_insert_view(window_id, ParentId::Root, |cx| Some(build_root_view(cx)))
                 .unwrap();
             let window = this.cx.windows.get_mut(&window_id).unwrap();
-            window.root_view = root_view.clone().into();
+            window.root_view = root_view.clone().into_any();
             window.focused_view_id = Some(root_view.id());
             root_view
         })
@@ -4465,32 +4455,23 @@ pub enum EntityLocation {
 }
 
 pub struct ModelHandle<T: Entity> {
-    model_id: usize,
+    any_handle: AnyModelHandle,
     model_type: PhantomData<T>,
-    ref_counts: Arc<Mutex<RefCounts>>,
+}
 
-    #[cfg(any(test, feature = "test-support"))]
-    handle_id: usize,
+impl<T: Entity> Deref for ModelHandle<T> {
+    type Target = AnyModelHandle;
+
+    fn deref(&self) -> &Self::Target {
+        &self.any_handle
+    }
 }
 
 impl<T: Entity> ModelHandle<T> {
     fn new(model_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
-        ref_counts.lock().inc_model(model_id);
-
-        #[cfg(any(test, feature = "test-support"))]
-        let handle_id = ref_counts
-            .lock()
-            .leak_detector
-            .lock()
-            .handle_created(Some(type_name::<T>()), model_id);
-
         Self {
-            model_id,
+            any_handle: AnyModelHandle::new(model_id, TypeId::of::<T>(), ref_counts.clone()),
             model_type: PhantomData,
-            ref_counts: ref_counts.clone(),
-
-            #[cfg(any(test, feature = "test-support"))]
-            handle_id,
         }
     }
 
@@ -4574,19 +4555,6 @@ impl<T: Entity> Debug for ModelHandle<T> {
 unsafe impl<T: Entity> Send for ModelHandle<T> {}
 unsafe impl<T: Entity> Sync for ModelHandle<T> {}
 
-impl<T: Entity> Drop for ModelHandle<T> {
-    fn drop(&mut self) {
-        let mut ref_counts = self.ref_counts.lock();
-        ref_counts.dec_model(self.model_id);
-
-        #[cfg(any(test, feature = "test-support"))]
-        ref_counts
-            .leak_detector
-            .lock()
-            .handle_dropped(self.model_id, self.handle_id);
-    }
-}
-
 impl<T: Entity> Handle<T> for ModelHandle<T> {
     type Weak = WeakModelHandle<T>;
 
@@ -4611,10 +4579,24 @@ impl<T: Entity> Handle<T> for ModelHandle<T> {
 }
 
 pub struct WeakModelHandle<T> {
-    model_id: usize,
+    any_handle: AnyWeakModelHandle,
     model_type: PhantomData<T>,
 }
 
+impl<T> WeakModelHandle<T> {
+    pub fn into_any(self) -> AnyWeakModelHandle {
+        self.any_handle
+    }
+}
+
+impl<T> Deref for WeakModelHandle<T> {
+    type Target = AnyWeakModelHandle;
+
+    fn deref(&self) -> &Self::Target {
+        &self.any_handle
+    }
+}
+
 impl<T> WeakHandle for WeakModelHandle<T> {
     fn id(&self) -> usize {
         self.model_id
@@ -4627,7 +4609,10 @@ unsafe impl<T> Sync for WeakModelHandle<T> {}
 impl<T: Entity> WeakModelHandle<T> {
     fn new(model_id: usize) -> Self {
         Self {
-            model_id,
+            any_handle: AnyWeakModelHandle {
+                model_id,
+                model_type: TypeId::of::<T>(),
+            },
             model_type: PhantomData,
         }
     }
@@ -4668,7 +4653,7 @@ impl<T: Entity> PartialEq<ModelHandle<T>> for WeakModelHandle<T> {
 impl<T> Clone for WeakModelHandle<T> {
     fn clone(&self) -> Self {
         Self {
-            model_id: self.model_id,
+            any_handle: self.any_handle.clone(),
             model_type: PhantomData,
         }
     }
@@ -4676,33 +4661,30 @@ impl<T> Clone for WeakModelHandle<T> {
 
 impl<T> Copy for WeakModelHandle<T> {}
 
+#[repr(transparent)]
 pub struct ViewHandle<T> {
-    window_id: usize,
-    view_id: usize,
+    any_handle: AnyViewHandle,
     view_type: PhantomData<T>,
-    ref_counts: Arc<Mutex<RefCounts>>,
-    #[cfg(any(test, feature = "test-support"))]
-    handle_id: usize,
+}
+
+impl<T> Deref for ViewHandle<T> {
+    type Target = AnyViewHandle;
+
+    fn deref(&self) -> &Self::Target {
+        &self.any_handle
+    }
 }
 
 impl<T: View> ViewHandle<T> {
     fn new(window_id: usize, view_id: usize, ref_counts: &Arc<Mutex<RefCounts>>) -> Self {
-        ref_counts.lock().inc_view(window_id, view_id);
-        #[cfg(any(test, feature = "test-support"))]
-        let handle_id = ref_counts
-            .lock()
-            .leak_detector
-            .lock()
-            .handle_created(Some(type_name::<T>()), view_id);
-
         Self {
-            window_id,
-            view_id,
+            any_handle: AnyViewHandle::new(
+                window_id,
+                view_id,
+                TypeId::of::<T>(),
+                ref_counts.clone(),
+            ),
             view_type: PhantomData,
-            ref_counts: ref_counts.clone(),
-
-            #[cfg(any(test, feature = "test-support"))]
-            handle_id,
         }
     }
 
@@ -4710,6 +4692,10 @@ impl<T: View> ViewHandle<T> {
         WeakViewHandle::new(self.window_id, self.view_id)
     }
 
+    pub fn into_any(self) -> AnyViewHandle {
+        self.any_handle
+    }
+
     pub fn window_id(&self) -> usize {
         self.window_id
     }
@@ -4805,20 +4791,6 @@ impl<T> Debug for ViewHandle<T> {
     }
 }
 
-impl<T> Drop for ViewHandle<T> {
-    fn drop(&mut self) {
-        self.ref_counts
-            .lock()
-            .dec_view(self.window_id, self.view_id);
-        #[cfg(any(test, feature = "test-support"))]
-        self.ref_counts
-            .lock()
-            .leak_detector
-            .lock()
-            .handle_dropped(self.view_id, self.handle_id);
-    }
-}
-
 impl<T: View> Handle<T> for ViewHandle<T> {
     type Weak = WeakViewHandle<T>;
 
@@ -4897,19 +4869,18 @@ impl AnyViewHandle {
 
     pub fn downcast<T: View>(self) -> Option<ViewHandle<T>> {
         if self.is::<T>() {
-            let result = Some(ViewHandle {
-                window_id: self.window_id,
-                view_id: self.view_id,
-                ref_counts: self.ref_counts.clone(),
+            Some(ViewHandle {
+                any_handle: self,
                 view_type: PhantomData,
-                #[cfg(any(test, feature = "test-support"))]
-                handle_id: self.handle_id,
-            });
-            unsafe {
-                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
-            }
-            std::mem::forget(self);
-            result
+            })
+        } else {
+            None
+        }
+    }
+
+    pub fn downcast_ref<T: View>(&self) -> Option<&ViewHandle<T>> {
+        if self.is::<T>() {
+            Some(unsafe { mem::transmute(self) })
         } else {
             None
         }
@@ -4945,42 +4916,6 @@ impl Clone for AnyViewHandle {
     }
 }
 
-impl From<&AnyViewHandle> for AnyViewHandle {
-    fn from(handle: &AnyViewHandle) -> Self {
-        handle.clone()
-    }
-}
-
-impl<T: View> From<&ViewHandle<T>> for AnyViewHandle {
-    fn from(handle: &ViewHandle<T>) -> Self {
-        Self::new(
-            handle.window_id,
-            handle.view_id,
-            TypeId::of::<T>(),
-            handle.ref_counts.clone(),
-        )
-    }
-}
-
-impl<T: View> From<ViewHandle<T>> for AnyViewHandle {
-    fn from(handle: ViewHandle<T>) -> Self {
-        let any_handle = AnyViewHandle {
-            window_id: handle.window_id,
-            view_id: handle.view_id,
-            view_type: TypeId::of::<T>(),
-            ref_counts: handle.ref_counts.clone(),
-            #[cfg(any(test, feature = "test-support"))]
-            handle_id: handle.handle_id,
-        };
-
-        unsafe {
-            Arc::decrement_strong_count(Arc::as_ptr(&handle.ref_counts));
-        }
-        std::mem::forget(handle);
-        any_handle
-    }
-}
-
 impl<T> PartialEq<ViewHandle<T>> for AnyViewHandle {
     fn eq(&self, other: &ViewHandle<T>) -> bool {
         self.window_id == other.window_id && self.view_id == other.view_id
@@ -5033,19 +4968,10 @@ impl AnyModelHandle {
 
     pub fn downcast<T: Entity>(self) -> Option<ModelHandle<T>> {
         if self.is::<T>() {
-            let result = Some(ModelHandle {
-                model_id: self.model_id,
+            Some(ModelHandle {
+                any_handle: self,
                 model_type: PhantomData,
-                ref_counts: self.ref_counts.clone(),
-
-                #[cfg(any(test, feature = "test-support"))]
-                handle_id: self.handle_id,
-            });
-            unsafe {
-                Arc::decrement_strong_count(Arc::as_ptr(&self.ref_counts));
-            }
-            std::mem::forget(self);
-            result
+            })
         } else {
             None
         }
@@ -5067,16 +4993,6 @@ impl AnyModelHandle {
     }
 }
 
-impl<T: Entity> From<ModelHandle<T>> for AnyModelHandle {
-    fn from(handle: ModelHandle<T>) -> Self {
-        Self::new(
-            handle.model_id,
-            TypeId::of::<T>(),
-            handle.ref_counts.clone(),
-        )
-    }
-}
-
 impl Clone for AnyModelHandle {
     fn clone(&self) -> Self {
         Self::new(self.model_id, self.model_type, self.ref_counts.clone())
@@ -5096,7 +5012,7 @@ impl Drop for AnyModelHandle {
     }
 }
 
-#[derive(Hash, PartialEq, Eq, Debug)]
+#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
 pub struct AnyWeakModelHandle {
     model_id: usize,
     model_type: TypeId,
@@ -5114,10 +5030,10 @@ impl AnyWeakModelHandle {
         TypeId::of::<T>() == self.model_type
     }
 
-    pub fn downcast<T: Entity>(&self) -> Option<WeakModelHandle<T>> {
+    pub fn downcast<T: Entity>(self) -> Option<WeakModelHandle<T>> {
         if self.is::<T>() {
             let result = Some(WeakModelHandle {
-                model_id: self.model_id,
+                any_handle: self,
                 model_type: PhantomData,
             });
 
@@ -5128,19 +5044,9 @@ impl AnyWeakModelHandle {
     }
 }
 
-impl<T: Entity> From<WeakModelHandle<T>> for AnyWeakModelHandle {
-    fn from(handle: WeakModelHandle<T>) -> Self {
-        AnyWeakModelHandle {
-            model_id: handle.model_id,
-            model_type: TypeId::of::<T>(),
-        }
-    }
-}
-
 #[derive(Debug, Copy)]
 pub struct WeakViewHandle<T> {
-    window_id: usize,
-    view_id: usize,
+    any_handle: AnyWeakViewHandle,
     view_type: PhantomData<T>,
 }
 
@@ -5153,8 +5059,11 @@ impl<T> WeakHandle for WeakViewHandle<T> {
 impl<T: View> WeakViewHandle<T> {
     fn new(window_id: usize, view_id: usize) -> Self {
         Self {
-            window_id,
-            view_id,
+            any_handle: AnyWeakViewHandle {
+                window_id,
+                view_id,
+                view_type: TypeId::of::<T>(),
+            },
             view_type: PhantomData,
         }
     }
@@ -5167,16 +5076,27 @@ impl<T: View> WeakViewHandle<T> {
         self.window_id
     }
 
+    pub fn into_any(self) -> AnyWeakViewHandle {
+        self.any_handle
+    }
+
     pub fn upgrade(&self, cx: &impl UpgradeViewHandle) -> Option<ViewHandle<T>> {
         cx.upgrade_view_handle(self)
     }
 }
 
+impl<T> Deref for WeakViewHandle<T> {
+    type Target = AnyWeakViewHandle;
+
+    fn deref(&self) -> &Self::Target {
+        &self.any_handle
+    }
+}
+
 impl<T> Clone for WeakViewHandle<T> {
     fn clone(&self) -> Self {
         Self {
-            window_id: self.window_id,
-            view_id: self.view_id,
+            any_handle: self.any_handle.clone(),
             view_type: PhantomData,
         }
     }
@@ -5192,11 +5112,11 @@ impl<T> Eq for WeakViewHandle<T> {}
 
 impl<T> Hash for WeakViewHandle<T> {
     fn hash<H: Hasher>(&self, state: &mut H) {
-        self.window_id.hash(state);
-        self.view_id.hash(state);
+        self.any_handle.hash(state);
     }
 }
 
+#[derive(Debug, Clone, Copy)]
 pub struct AnyWeakViewHandle {
     window_id: usize,
     view_id: usize,
@@ -5213,13 +5133,11 @@ impl AnyWeakViewHandle {
     }
 }
 
-impl<T: View> From<WeakViewHandle<T>> for AnyWeakViewHandle {
-    fn from(handle: WeakViewHandle<T>) -> Self {
-        AnyWeakViewHandle {
-            window_id: handle.window_id,
-            view_id: handle.view_id,
-            view_type: TypeId::of::<T>(),
-        }
+impl Hash for AnyWeakViewHandle {
+    fn hash<H: Hasher>(&self, state: &mut H) {
+        self.window_id.hash(state);
+        self.view_id.hash(state);
+        self.view_type.hash(state);
     }
 }
 
@@ -6142,7 +6060,7 @@ mod tests {
         }
 
         let (_, root_view) = cx.add_window(Default::default(), |_| TestView::default());
-        let observing_view = cx.add_view(root_view, |_| TestView::default());
+        let observing_view = cx.add_view(&root_view, |_| TestView::default());
         let observing_model = cx.add_model(|_| Model);
         let observed_model = cx.add_model(|_| Model);
 
@@ -6391,8 +6309,8 @@ mod tests {
             cx.focus(&view_1);
             cx.focus(&view_2);
         });
-        assert!(cx.is_child_focused(view_1.clone()));
-        assert!(!cx.is_child_focused(view_2.clone()));
+        assert!(cx.is_child_focused(&view_1));
+        assert!(!cx.is_child_focused(&view_2));
         assert_eq!(
             mem::take(&mut *view_events.lock()),
             [
@@ -6417,8 +6335,8 @@ mod tests {
         );
 
         view_1.update(cx, |_, cx| cx.focus(&view_1));
-        assert!(!cx.is_child_focused(view_1.clone()));
-        assert!(!cx.is_child_focused(view_2.clone()));
+        assert!(!cx.is_child_focused(&view_1));
+        assert!(!cx.is_child_focused(&view_2));
         assert_eq!(
             mem::take(&mut *view_events.lock()),
             ["view 2 blurred", "view 1 focused"],

crates/gpui/src/app/test_app_context.rs 🔗

@@ -137,11 +137,7 @@ impl TestAppContext {
         (window_id, view)
     }
 
-    pub fn add_view<T, F>(
-        &mut self,
-        parent_handle: impl Into<AnyViewHandle>,
-        build_view: F,
-    ) -> ViewHandle<T>
+    pub fn add_view<T, F>(&mut self, parent_handle: &AnyViewHandle, build_view: F) -> ViewHandle<T>
     where
         T: View,
         F: FnOnce(&mut ViewContext<T>) -> T,

crates/gpui/src/presenter.rs 🔗

@@ -638,7 +638,7 @@ impl<'a> LayoutContext<'a> {
             (Some(layout_parent), Some(ParentId::View(app_parent))) => {
                 if layout_parent != app_parent {
                     panic!(
-                        "View {} was laid out with parent {} when it was constructed with parent {}", 
+                        "View {} was laid out with parent {} when it was constructed with parent {}",
                         print_error(view_id),
                         print_error(*layout_parent),
                         print_error(*app_parent))
@@ -1059,8 +1059,7 @@ pub struct ChildView {
 }
 
 impl ChildView {
-    pub fn new(view: impl Into<AnyViewHandle>, cx: &AppContext) -> Self {
-        let view = view.into();
+    pub fn new(view: &AnyViewHandle, cx: &AppContext) -> Self {
         let view_name = cx.view_ui_name(view.window_id(), view.id()).unwrap();
         Self {
             view: view.downgrade(),

crates/language_selector/src/language_selector.rs 🔗

@@ -121,7 +121,7 @@ impl View for LanguageSelector {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/outline/src/outline.rs 🔗

@@ -49,7 +49,7 @@ impl View for OutlineView {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/project/src/project.rs 🔗

@@ -1231,7 +1231,9 @@ impl Project {
                     File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
                 })
                 .ok_or_else(|| anyhow!("no project entry"))?;
-            Ok((project_entry_id, buffer.into()))
+
+            let buffer: &AnyModelHandle = &buffer;
+            Ok((project_entry_id, buffer.clone()))
         })
     }
 

crates/project_panel/src/project_panel.rs 🔗

@@ -1109,7 +1109,7 @@ impl ProjectPanel {
                 .boxed(),
             )
             .with_child(if show_editor && editor.is_some() {
-                ChildView::new(editor.unwrap().clone(), cx)
+                ChildView::new(editor.as_ref().unwrap(), cx)
                     .contained()
                     .with_margin_left(style.icon_spacing)
                     .aligned()

crates/project_symbols/src/project_symbols.rs 🔗

@@ -49,7 +49,7 @@ impl View for ProjectSymbolsView {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/recent_projects/src/recent_projects.rs 🔗

@@ -103,7 +103,7 @@ impl View for RecentProjectsView {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/search/src/buffer_search.rs 🔗

@@ -273,7 +273,7 @@ impl BufferSearchBar {
             }
         }
         if let Some(active_editor) = self.active_searchable_item.as_ref() {
-            cx.focus(active_editor);
+            cx.focus(active_editor.as_any());
         }
         cx.emit(Event::UpdateLocation);
         cx.notify();
@@ -458,7 +458,7 @@ impl BufferSearchBar {
 
     fn focus_editor(&mut self, _: &FocusEditor, cx: &mut ViewContext<Self>) {
         if let Some(active_editor) = self.active_searchable_item.as_ref() {
-            cx.focus(active_editor);
+            cx.focus(active_editor.as_any());
         }
     }
 

crates/search/src/project_search.rs 🔗

@@ -222,16 +222,16 @@ impl View for ProjectSearchView {
 }
 
 impl Item for ProjectSearchView {
-    fn act_as_type(
-        &self,
+    fn act_as_type<'a>(
+        &'a self,
         type_id: TypeId,
-        self_handle: &ViewHandle<Self>,
-        _: &gpui::AppContext,
-    ) -> Option<gpui::AnyViewHandle> {
+        self_handle: &'a ViewHandle<Self>,
+        _: &'a AppContext,
+    ) -> Option<&'a AnyViewHandle> {
         if type_id == TypeId::of::<Self>() {
-            Some(self_handle.into())
+            Some(self_handle)
         } else if type_id == TypeId::of::<Editor>() {
-            Some((&self.results_editor).into())
+            Some(&self.results_editor)
         } else {
             None
         }
@@ -246,7 +246,7 @@ impl Item for ProjectSearchView {
         &self,
         _detail: Option<usize>,
         tab_theme: &theme::Tab,
-        cx: &gpui::AppContext,
+        cx: &AppContext,
     ) -> ElementBox {
         Flex::row()
             .with_child(
@@ -277,7 +277,7 @@ impl Item for ProjectSearchView {
         false
     }
 
-    fn can_save(&self, _: &gpui::AppContext) -> bool {
+    fn can_save(&self, _: &AppContext) -> bool {
         true
     }
 
@@ -930,7 +930,7 @@ impl ToolbarItemView for ProjectSearchBar {
         self.active_project_search = None;
         if let Some(search) = active_pane_item.and_then(|i| i.downcast::<ProjectSearchView>()) {
             let query_editor = search.read(cx).query_editor.clone();
-            cx.reparent(query_editor);
+            cx.reparent(&query_editor);
             self.subscription = Some(cx.observe(&search, |_, _, cx| cx.notify()));
             self.active_project_search = Some(search);
             ToolbarItemLocation::PrimaryLeft {

crates/terminal_view/src/terminal_view.rs 🔗

@@ -651,7 +651,7 @@ impl Item for TerminalView {
                     project.create_terminal(cwd, window_id, cx)
                 })?;
 
-                Ok(cx.add_view(pane, |cx| TerminalView::new(terminal, workspace_id, cx)))
+                Ok(cx.add_view(&pane, |cx| TerminalView::new(terminal, workspace_id, cx)))
             })
         })
     }

crates/theme_selector/src/theme_selector.rs 🔗

@@ -256,7 +256,7 @@ impl View for ThemeSelector {
     }
 
     fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/welcome/src/base_keymap_picker.rs 🔗

@@ -75,7 +75,7 @@ impl View for BaseKeymapSelector {
     }
 
     fn render(&mut self, cx: &mut gpui::RenderContext<'_, Self>) -> gpui::ElementBox {
-        ChildView::new(self.picker.clone(), cx).boxed()
+        ChildView::new(&self.picker, cx).boxed()
     }
 
     fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {

crates/welcome/src/welcome.rs 🔗

@@ -32,7 +32,7 @@ pub fn show_welcome_experience(app_state: &Arc<AppState>, cx: &mut MutableAppCon
         workspace.toggle_sidebar(SidebarSide::Left, cx);
         let welcome_page = cx.add_view(|cx| WelcomePage::new(cx));
         workspace.add_item_to_center(Box::new(welcome_page.clone()), cx);
-        cx.focus(welcome_page);
+        cx.focus(&welcome_page);
         cx.notify();
     })
     .detach();

crates/workspace/src/dock.rs 🔗

@@ -255,7 +255,7 @@ impl Dock {
                 }
             } else {
                 if focus {
-                    cx.focus(pane);
+                    cx.focus(&pane);
                 }
             }
         } else if let Some(last_active_center_pane) = workspace
@@ -264,7 +264,7 @@ impl Dock {
             .and_then(|pane| pane.upgrade(cx))
         {
             if focus {
-                cx.focus(last_active_center_pane);
+                cx.focus(&last_active_center_pane);
             }
         }
         cx.emit(crate::Event::DockAnchorChanged);
@@ -347,7 +347,7 @@ impl Dock {
 
                     enum DockResizeHandle {}
 
-                    let resizable = Container::new(ChildView::new(self.pane.clone(), cx).boxed())
+                    let resizable = Container::new(ChildView::new(&self.pane, cx).boxed())
                         .with_style(panel_style)
                         .with_resize_handle::<DockResizeHandle, _>(
                             resize_side as usize,

crates/workspace/src/item.rs 🔗

@@ -110,14 +110,14 @@ pub trait Item: View {
     fn is_edit_event(_: &Self::Event) -> bool {
         false
     }
-    fn act_as_type(
-        &self,
+    fn act_as_type<'a>(
+        &'a self,
         type_id: TypeId,
-        self_handle: &ViewHandle<Self>,
-        _: &AppContext,
-    ) -> Option<AnyViewHandle> {
+        self_handle: &'a ViewHandle<Self>,
+        _: &'a AppContext,
+    ) -> Option<&AnyViewHandle> {
         if TypeId::of::<Self>() == type_id {
-            Some(self_handle.into())
+            Some(self_handle)
         } else {
             None
         }
@@ -187,7 +187,7 @@ pub trait ItemHandle: 'static + fmt::Debug {
     fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
     fn id(&self) -> usize;
     fn window_id(&self) -> usize;
-    fn to_any(&self) -> AnyViewHandle;
+    fn as_any(&self) -> &AnyViewHandle;
     fn is_dirty(&self, cx: &AppContext) -> bool;
     fn has_conflict(&self, cx: &AppContext) -> bool;
     fn can_save(&self, cx: &AppContext) -> bool;
@@ -205,7 +205,7 @@ pub trait ItemHandle: 'static + fmt::Debug {
         project: ModelHandle<Project>,
         cx: &mut MutableAppContext,
     ) -> Task<Result<()>>;
-    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
+    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<&'a AnyViewHandle>;
     fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
     fn on_release(
         &self,
@@ -227,12 +227,12 @@ pub trait WeakItemHandle {
 
 impl dyn ItemHandle {
     pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
-        self.to_any().downcast()
+        self.as_any().clone().downcast()
     }
 
     pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
         self.act_as_type(TypeId::of::<T>(), cx)
-            .and_then(|t| t.downcast())
+            .and_then(|t| t.clone().downcast())
     }
 }
 
@@ -513,8 +513,8 @@ impl<T: Item> ItemHandle for ViewHandle<T> {
         self.window_id()
     }
 
-    fn to_any(&self) -> AnyViewHandle {
-        self.into()
+    fn as_any(&self) -> &AnyViewHandle {
+        self
     }
 
     fn is_dirty(&self, cx: &AppContext) -> bool {
@@ -558,14 +558,14 @@ impl<T: Item> ItemHandle for ViewHandle<T> {
         self.update(cx, |item, cx| item.git_diff_recalc(project, cx))
     }
 
-    fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
+    fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<&'a AnyViewHandle> {
         self.read(cx).act_as_type(type_id, self, cx)
     }
 
     fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
         if cx.has_global::<FollowableItemBuilders>() {
             let builders = cx.global::<FollowableItemBuilders>();
-            let item = self.to_any();
+            let item = self.as_any();
             Some(builders.get(&item.view_type())?.1(item))
         } else {
             None
@@ -603,13 +603,13 @@ impl<T: Item> ItemHandle for ViewHandle<T> {
 
 impl From<Box<dyn ItemHandle>> for AnyViewHandle {
     fn from(val: Box<dyn ItemHandle>) -> Self {
-        val.to_any()
+        val.as_any().clone()
     }
 }
 
 impl From<&Box<dyn ItemHandle>> for AnyViewHandle {
     fn from(val: &Box<dyn ItemHandle>) -> Self {
-        val.to_any()
+        val.as_any().clone()
     }
 }
 

crates/workspace/src/notifications.rs 🔗

@@ -16,7 +16,7 @@ pub trait Notification: View {
 
 pub trait NotificationHandle {
     fn id(&self) -> usize;
-    fn to_any(&self) -> AnyViewHandle;
+    fn as_any(&self) -> &AnyViewHandle;
 }
 
 impl<T: Notification> NotificationHandle for ViewHandle<T> {
@@ -24,14 +24,14 @@ impl<T: Notification> NotificationHandle for ViewHandle<T> {
         self.id()
     }
 
-    fn to_any(&self) -> AnyViewHandle {
-        self.into()
+    fn as_any(&self) -> &AnyViewHandle {
+        self
     }
 }
 
 impl From<&dyn NotificationHandle> for AnyViewHandle {
     fn from(val: &dyn NotificationHandle) -> Self {
-        val.to_any()
+        val.as_any().clone()
     }
 }
 

crates/workspace/src/pane.rs 🔗

@@ -413,7 +413,7 @@ impl Pane {
         mode: NavigationMode,
         cx: &mut ViewContext<Workspace>,
     ) -> Task<()> {
-        cx.focus(pane.clone());
+        cx.focus(&pane);
 
         let to_load = pane.update(cx, |pane, cx| {
             loop {
@@ -596,7 +596,7 @@ impl Pane {
             // If the item already exists, move it to the desired destination and activate it
             pane.update(cx, |pane, cx| {
                 if existing_item_index != insertion_index {
-                    cx.reparent(&item);
+                    cx.reparent(item.as_any());
                     let existing_item_is_active = existing_item_index == pane.active_item_index;
 
                     // If the caller didn't specify a destination and the added item is already
@@ -626,7 +626,7 @@ impl Pane {
             });
         } else {
             pane.update(cx, |pane, cx| {
-                cx.reparent(&item);
+                cx.reparent(item.as_any());
                 pane.items.insert(insertion_index, item);
                 if insertion_index <= pane.active_item_index {
                     pane.active_item_index += 1;
@@ -649,7 +649,7 @@ impl Pane {
     pub fn items_of_type<T: View>(&self) -> impl '_ + Iterator<Item = ViewHandle<T>> {
         self.items
             .iter()
-            .filter_map(|item| item.to_any().downcast())
+            .filter_map(|item| item.as_any().clone().downcast())
     }
 
     pub fn active_item(&self) -> Option<Box<dyn ItemHandle>> {
@@ -1048,7 +1048,7 @@ impl Pane {
 
     pub fn focus_active_item(&mut self, cx: &mut ViewContext<Self>) {
         if let Some(active_item) = self.active_item() {
-            cx.focus(active_item);
+            cx.focus(active_item.as_any());
         }
     }
 
@@ -1091,7 +1091,7 @@ impl Pane {
             cx,
         );
 
-        cx.focus(to);
+        cx.focus(&to);
     }
 
     pub fn split(&mut self, direction: SplitDirection, cx: &mut ViewContext<Self>) {
@@ -1556,7 +1556,7 @@ impl View for Pane {
                                                     ChildView::new(&toolbar, cx).expanded().boxed()
                                                 }))
                                                 .with_child(
-                                                    ChildView::new(active_item, cx)
+                                                    ChildView::new(active_item.as_any(), cx)
                                                         .flex(1., true)
                                                         .boxed(),
                                                 )
@@ -1615,14 +1615,14 @@ impl View for Pane {
                     self.last_focused_view_by_item.get(&active_item.id())
                 {
                     if let Some(last_focused_view) = weak_last_focused_view.upgrade(cx) {
-                        cx.focus(last_focused_view);
+                        cx.focus(&last_focused_view);
                         return;
                     } else {
                         self.last_focused_view_by_item.remove(&active_item.id());
                     }
                 }
 
-                cx.focus(active_item);
+                cx.focus(active_item.as_any());
             } else if focused != self.tab_bar_context_menu.handle {
                 self.last_focused_view_by_item
                     .insert(active_item.id(), focused.downgrade());
@@ -1676,7 +1676,7 @@ fn render_tab_bar_button<A: Action + Clone>(
             .boxed(),
         )
         .with_children(
-            context_menu.map(|menu| ChildView::new(menu, cx).aligned().bottom().right().boxed()),
+            context_menu.map(|menu| ChildView::new(&menu, cx).aligned().bottom().right().boxed()),
         )
         .flex(1., false)
         .boxed()
@@ -2278,8 +2278,8 @@ mod tests {
                 .enumerate()
                 .map(|(ix, item)| {
                     let mut state = item
-                        .to_any()
-                        .downcast::<TestItem>()
+                        .as_any()
+                        .downcast_ref::<TestItem>()
                         .unwrap()
                         .read(cx)
                         .label

crates/workspace/src/searchable.rs 🔗

@@ -213,13 +213,13 @@ fn downcast_matches<T: Any + Clone>(matches: &Vec<Box<dyn Any + Send>>) -> Vec<T
 
 impl From<Box<dyn SearchableItemHandle>> for AnyViewHandle {
     fn from(this: Box<dyn SearchableItemHandle>) -> Self {
-        this.to_any()
+        this.as_any().clone()
     }
 }
 
 impl From<&Box<dyn SearchableItemHandle>> for AnyViewHandle {
     fn from(this: &Box<dyn SearchableItemHandle>) -> Self {
-        this.to_any()
+        this.as_any().clone()
     }
 }
 
@@ -234,7 +234,7 @@ impl Eq for Box<dyn SearchableItemHandle> {}
 pub trait WeakSearchableItemHandle: WeakItemHandle {
     fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
 
-    fn to_any(self) -> AnyWeakViewHandle;
+    fn into_any(self) -> AnyWeakViewHandle;
 }
 
 impl<T: SearchableItem> WeakSearchableItemHandle for WeakViewHandle<T> {
@@ -242,8 +242,8 @@ impl<T: SearchableItem> WeakSearchableItemHandle for WeakViewHandle<T> {
         Some(Box::new(self.upgrade(cx)?))
     }
 
-    fn to_any(self) -> AnyWeakViewHandle {
-        self.into()
+    fn into_any(self) -> AnyWeakViewHandle {
+        self.into_any()
     }
 }
 

crates/workspace/src/sidebar.rs 🔗

@@ -23,7 +23,7 @@ pub trait SidebarItemHandle {
     fn id(&self) -> usize;
     fn should_show_badge(&self, cx: &AppContext) -> bool;
     fn is_focused(&self, cx: &AppContext) -> bool;
-    fn to_any(&self) -> AnyViewHandle;
+    fn as_any(&self) -> &AnyViewHandle;
 }
 
 impl<T> SidebarItemHandle for ViewHandle<T>
@@ -42,14 +42,14 @@ where
         ViewHandle::is_focused(self, cx) || self.read(cx).contains_focused_view(cx)
     }
 
-    fn to_any(&self) -> AnyViewHandle {
-        self.into()
+    fn as_any(&self) -> &AnyViewHandle {
+        self
     }
 }
 
 impl From<&dyn SidebarItemHandle> for AnyViewHandle {
     fn from(val: &dyn SidebarItemHandle) -> Self {
-        val.to_any()
+        val.as_any().clone()
     }
 }
 
@@ -192,7 +192,7 @@ impl View for Sidebar {
         if let Some(active_item) = self.active_item() {
             enum ResizeHandleTag {}
             let style = &cx.global::<Settings>().theme.workspace.sidebar;
-            ChildView::new(active_item.to_any(), cx)
+            ChildView::new(active_item.as_any(), cx)
                 .contained()
                 .with_style(style.container)
                 .with_resize_handle::<ResizeHandleTag, _>(

crates/workspace/src/status_bar.rs 🔗

@@ -14,7 +14,7 @@ pub trait StatusItemView: View {
 }
 
 trait StatusItemViewHandle {
-    fn to_any(&self) -> AnyViewHandle;
+    fn as_any(&self) -> &AnyViewHandle;
     fn set_active_pane_item(
         &self,
         active_pane_item: Option<&dyn ItemHandle>,
@@ -42,14 +42,14 @@ impl View for StatusBar {
         let theme = &cx.global::<Settings>().theme.workspace.status_bar;
         Flex::row()
             .with_children(self.left_items.iter().map(|i| {
-                ChildView::new(i.as_ref(), cx)
+                ChildView::new(i.as_any(), cx)
                     .aligned()
                     .contained()
                     .with_margin_right(theme.item_spacing)
                     .boxed()
             }))
             .with_children(self.right_items.iter().rev().map(|i| {
-                ChildView::new(i.as_ref(), cx)
+                ChildView::new(i.as_any(), cx)
                     .aligned()
                     .contained()
                     .with_margin_left(theme.item_spacing)
@@ -81,7 +81,7 @@ impl StatusBar {
     where
         T: 'static + StatusItemView,
     {
-        cx.reparent(&item);
+        cx.reparent(item.as_any());
         self.left_items.push(Box::new(item));
         cx.notify();
     }
@@ -90,7 +90,7 @@ impl StatusBar {
     where
         T: 'static + StatusItemView,
     {
-        cx.reparent(&item);
+        cx.reparent(item.as_any());
         self.right_items.push(Box::new(item));
         cx.notify();
     }
@@ -111,8 +111,8 @@ impl StatusBar {
 }
 
 impl<T: StatusItemView> StatusItemViewHandle for ViewHandle<T> {
-    fn to_any(&self) -> AnyViewHandle {
-        self.into()
+    fn as_any(&self) -> &AnyViewHandle {
+        self
     }
 
     fn set_active_pane_item(
@@ -128,6 +128,6 @@ impl<T: StatusItemView> StatusItemViewHandle for ViewHandle<T> {
 
 impl From<&dyn StatusItemViewHandle> for AnyViewHandle {
     fn from(val: &dyn StatusItemViewHandle) -> Self {
-        val.to_any()
+        val.as_any().clone()
     }
 }

crates/workspace/src/toolbar.rs 🔗

@@ -26,7 +26,7 @@ pub trait ToolbarItemView: View {
 
 trait ToolbarItemViewHandle {
     fn id(&self) -> usize;
-    fn to_any(&self) -> AnyViewHandle;
+    fn as_any(&self) -> &AnyViewHandle;
     fn set_active_pane_item(
         &self,
         active_pane_item: Option<&dyn ItemHandle>,
@@ -71,7 +71,7 @@ impl View for Toolbar {
             match *position {
                 ToolbarItemLocation::Hidden => {}
                 ToolbarItemLocation::PrimaryLeft { flex } => {
-                    let left_item = ChildView::new(item.as_ref(), cx)
+                    let left_item = ChildView::new(item.as_any(), cx)
                         .aligned()
                         .contained()
                         .with_margin_right(spacing);
@@ -82,7 +82,7 @@ impl View for Toolbar {
                     }
                 }
                 ToolbarItemLocation::PrimaryRight { flex } => {
-                    let right_item = ChildView::new(item.as_ref(), cx)
+                    let right_item = ChildView::new(item.as_any(), cx)
                         .aligned()
                         .contained()
                         .with_margin_left(spacing)
@@ -95,7 +95,7 @@ impl View for Toolbar {
                 }
                 ToolbarItemLocation::Secondary => {
                     secondary_item = Some(
-                        ChildView::new(item.as_ref(), cx)
+                        ChildView::new(item.as_any(), cx)
                             .constrained()
                             .with_height(theme.height)
                             .boxed(),
@@ -272,7 +272,7 @@ impl Toolbar {
     pub fn item_of_type<T: ToolbarItemView>(&self) -> Option<ViewHandle<T>> {
         self.items
             .iter()
-            .find_map(|(item, _)| item.to_any().downcast())
+            .find_map(|(item, _)| item.as_any().clone().downcast())
     }
 
     pub fn hidden(&self) -> bool {
@@ -285,8 +285,8 @@ impl<T: ToolbarItemView> ToolbarItemViewHandle for ViewHandle<T> {
         self.id()
     }
 
-    fn to_any(&self) -> AnyViewHandle {
-        self.into()
+    fn as_any(&self) -> &AnyViewHandle {
+        self
     }
 
     fn set_active_pane_item(
@@ -306,6 +306,6 @@ impl<T: ToolbarItemView> ToolbarItemViewHandle for ViewHandle<T> {
 
 impl From<&dyn ToolbarItemViewHandle> for AnyViewHandle {
     fn from(val: &dyn ToolbarItemViewHandle) -> Self {
-        val.to_any()
+        val.as_any().clone()
     }
 }

crates/workspace/src/workspace.rs 🔗

@@ -464,7 +464,7 @@ type FollowableItemBuilders = HashMap<
     TypeId,
     (
         FollowableItemBuilder,
-        fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
+        fn(&AnyViewHandle) -> Box<dyn FollowableItemHandle>,
     ),
 >;
 pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
@@ -478,7 +478,7 @@ pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
                             .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
                     })
                 },
-                |this| Box::new(this.downcast::<I>().unwrap()),
+                |this| Box::new(this.clone().downcast::<I>().unwrap()),
             ),
         );
     });
@@ -1036,12 +1036,8 @@ impl Workspace {
         &self.client
     }
 
-    pub fn set_titlebar_item(
-        &mut self,
-        item: impl Into<AnyViewHandle>,
-        cx: &mut ViewContext<Self>,
-    ) {
-        self.titlebar_item = Some(item.into());
+    pub fn set_titlebar_item(&mut self, item: AnyViewHandle, cx: &mut ViewContext<Self>) {
+        self.titlebar_item = Some(item);
         cx.notify();
     }
 
@@ -1355,7 +1351,7 @@ impl Workspace {
         } else {
             let modal = add_view(self, cx);
             cx.focus(&modal);
-            self.modal = Some(modal.into());
+            self.modal = Some(modal.into_any());
             None
         }
     }
@@ -1491,7 +1487,7 @@ impl Workspace {
             if active_item.is_focused(cx) {
                 cx.focus_self();
             } else {
-                cx.focus(active_item.to_any());
+                cx.focus(active_item.as_any());
             }
         } else {
             cx.focus_self();
@@ -1523,7 +1519,7 @@ impl Workspace {
             if active_item.is_focused(cx) {
                 cx.focus_self();
             } else {
-                cx.focus(active_item.to_any());
+                cx.focus(active_item.as_any());
             }
         }
 
@@ -1546,7 +1542,7 @@ impl Workspace {
         })
         .detach();
         self.panes.push(pane.clone());
-        cx.focus(pane.clone());
+        cx.focus(&pane);
         cx.emit(Event::PaneAdded(pane.clone()));
         pane
     }
@@ -1688,7 +1684,7 @@ impl Workspace {
     fn activate_pane_at_index(&mut self, action: &ActivatePane, cx: &mut ViewContext<Self>) {
         let panes = self.center.panes();
         if let Some(pane) = panes.get(action.0).map(|p| (*p).clone()) {
-            cx.focus(pane);
+            cx.focus(&pane);
         } else {
             self.split_pane(self.active_pane.clone(), SplitDirection::Right, cx);
         }
@@ -1699,7 +1695,7 @@ impl Workspace {
         if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
             let next_ix = (ix + 1) % panes.len();
             let next_pane = panes[next_ix].clone();
-            cx.focus(next_pane);
+            cx.focus(&next_pane);
         }
     }
 
@@ -1708,7 +1704,7 @@ impl Workspace {
         if let Some(ix) = panes.iter().position(|pane| **pane == self.active_pane) {
             let prev_ix = cmp::min(ix.wrapping_sub(1), panes.len() - 1);
             let prev_pane = panes[prev_ix].clone();
-            cx.focus(prev_pane);
+            cx.focus(&prev_pane);
         }
     }
 
@@ -1871,7 +1867,7 @@ impl Workspace {
     fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
         if self.center.remove(&pane).unwrap() {
             self.panes.retain(|p| p != &pane);
-            cx.focus(self.panes.last().unwrap().clone());
+            cx.focus(self.panes.last().unwrap());
             self.unfollow(&pane, cx);
             self.last_leaders_by_pane.remove(&pane.downgrade());
             for removed_item in pane.read(cx).items() {
@@ -2191,7 +2187,7 @@ impl Workspace {
             Some(
                 Flex::column()
                     .with_children(self.notifications.iter().map(|(_, _, notification)| {
-                        ChildView::new(notification.as_ref(), cx)
+                        ChildView::new(notification.as_any(), cx)
                             .contained()
                             .with_style(theme.notification)
                             .boxed()
@@ -2488,7 +2484,7 @@ impl Workspace {
             let active_item_was_focused = pane
                 .read(cx)
                 .active_item()
-                .map(|active_item| cx.is_child_focused(active_item.to_any()))
+                .map(|active_item| cx.is_child_focused(active_item.as_any()))
                 .unwrap_or_default();
 
             if let Some(index) = pane.update(cx, |pane, _| pane.index_for_item(item.as_ref())) {
@@ -2715,14 +2711,14 @@ impl Workspace {
                         cx.focus_self();
 
                         if let Some(active_pane) = active_pane {
-                            cx.focus(active_pane);
+                            cx.focus(&active_pane);
                         } else {
-                            cx.focus(workspace.panes.last().unwrap().clone());
+                            cx.focus(workspace.panes.last().unwrap());
                         }
                     } else {
                         let old_center_handle = old_center_pane.and_then(|weak| weak.upgrade(cx));
                         if let Some(old_center_handle) = old_center_handle {
-                            cx.focus(old_center_handle)
+                            cx.focus(&old_center_handle)
                         } else {
                             cx.focus_self()
                         }
@@ -3503,7 +3499,7 @@ mod tests {
         //Need to cause an effect flush in order to respect new focus
         workspace.update(cx, |workspace, cx| {
             workspace.add_item(Box::new(item_3_4.clone()), cx);
-            cx.focus(left_pane.clone());
+            cx.focus(&left_pane);
         });
 
         // When closing all of the items in the left pane, we should be prompted twice:

crates/zed/src/zed.rs 🔗

@@ -299,7 +299,7 @@ pub fn initialize_workspace(
 
     let collab_titlebar_item =
         cx.add_view(|cx| CollabTitlebarItem::new(&workspace_handle, &app_state.user_store, cx));
-    workspace.set_titlebar_item(collab_titlebar_item, cx);
+    workspace.set_titlebar_item(collab_titlebar_item.into_any(), cx);
 
     let project_panel = ProjectPanel::new(workspace.project().clone(), cx);
     workspace.left_sidebar().update(cx, |sidebar, cx| {
@@ -1020,8 +1020,8 @@ mod tests {
                     .read(cx)
                     .active_item()
                     .unwrap()
-                    .to_any()
-                    .downcast::<Editor>()
+                    .as_any()
+                    .downcast_ref::<Editor>()
                     .unwrap()
                     .read(cx)
                     .title(cx),
@@ -1056,8 +1056,8 @@ mod tests {
                     .read(cx)
                     .active_item()
                     .unwrap()
-                    .to_any()
-                    .downcast::<Editor>()
+                    .as_any()
+                    .downcast_ref::<Editor>()
                     .unwrap()
                     .read(cx)
                     .title(cx),
@@ -1092,8 +1092,8 @@ mod tests {
                     .read(cx)
                     .active_item()
                     .unwrap()
-                    .to_any()
-                    .downcast::<Editor>()
+                    .as_any()
+                    .downcast_ref::<Editor>()
                     .unwrap()
                     .read(cx)
                     .title(cx),
@@ -1142,8 +1142,8 @@ mod tests {
                     .read(cx)
                     .active_item()
                     .unwrap()
-                    .to_any()
-                    .downcast::<Editor>()
+                    .as_any()
+                    .downcast_ref::<Editor>()
                     .unwrap()
                     .read(cx)
                     .title(cx),