1use std::{
2 any::TypeId,
3 ops::{Range, RangeInclusive},
4 sync::Arc,
5};
6
7use anyhow::bail;
8use client::{Client, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
9use editor::{Anchor, Editor};
10use futures::AsyncReadExt;
11use gpui::{
12 actions,
13 elements::{ChildView, Flex, Label, ParentElement},
14 serde_json, AnyViewHandle, AppContext, Element, ElementBox, Entity, ModelHandle,
15 MutableAppContext, PromptLevel, RenderContext, Task, View, ViewContext, ViewHandle,
16 WeakViewHandle,
17};
18use isahc::Request;
19use language::Buffer;
20use postage::prelude::Stream;
21
22use project::Project;
23use serde::Serialize;
24use workspace::{
25 item::{Item, ItemHandle},
26 searchable::{SearchableItem, SearchableItemHandle},
27 smallvec::SmallVec,
28 AppState, Workspace,
29};
30
31use crate::{submit_feedback_button::SubmitFeedbackButton, system_specs::SystemSpecs};
32
33const FEEDBACK_CHAR_LIMIT: RangeInclusive<usize> = 10..=5000;
34const FEEDBACK_SUBMISSION_ERROR_TEXT: &str =
35 "Feedback failed to submit, see error log for details.";
36
37actions!(feedback, [GiveFeedback, SubmitFeedback]);
38
39pub fn init(system_specs: SystemSpecs, app_state: Arc<AppState>, cx: &mut MutableAppContext) {
40 cx.add_action({
41 move |workspace: &mut Workspace, _: &GiveFeedback, cx: &mut ViewContext<Workspace>| {
42 FeedbackEditor::deploy(system_specs.clone(), workspace, app_state.clone(), cx);
43 }
44 });
45
46 cx.add_async_action(
47 |submit_feedback_button: &mut SubmitFeedbackButton, _: &SubmitFeedback, cx| {
48 if let Some(active_item) = submit_feedback_button.active_item.as_ref() {
49 Some(active_item.update(cx, |feedback_editor, cx| feedback_editor.handle_save(cx)))
50 } else {
51 None
52 }
53 },
54 );
55}
56
57#[derive(Serialize)]
58struct FeedbackRequestBody<'a> {
59 feedback_text: &'a str,
60 metrics_id: Option<Arc<str>>,
61 system_specs: SystemSpecs,
62 is_staff: bool,
63 token: &'a str,
64}
65
66#[derive(Clone)]
67pub(crate) struct FeedbackEditor {
68 system_specs: SystemSpecs,
69 editor: ViewHandle<Editor>,
70 project: ModelHandle<Project>,
71}
72
73impl FeedbackEditor {
74 fn new(
75 system_specs: SystemSpecs,
76 project: ModelHandle<Project>,
77 buffer: ModelHandle<Buffer>,
78 cx: &mut ViewContext<Self>,
79 ) -> Self {
80 let editor = cx.add_view(|cx| {
81 let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
82 editor.set_vertical_scroll_margin(5, cx);
83 editor
84 });
85
86 cx.subscribe(&editor, |_, _, e, cx| cx.emit(e.clone()))
87 .detach();
88
89 Self {
90 system_specs: system_specs.clone(),
91 editor,
92 project,
93 }
94 }
95
96 fn handle_save(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
97 let feedback_text = self.editor.read(cx).text(cx);
98 let feedback_char_count = feedback_text.chars().count();
99 let feedback_text = feedback_text.trim().to_string();
100
101 let error = if feedback_char_count < *FEEDBACK_CHAR_LIMIT.start() {
102 Some(format!(
103 "Feedback can't be shorter than {} characters.",
104 FEEDBACK_CHAR_LIMIT.start()
105 ))
106 } else if feedback_char_count > *FEEDBACK_CHAR_LIMIT.end() {
107 Some(format!(
108 "Feedback can't be longer than {} characters.",
109 FEEDBACK_CHAR_LIMIT.end()
110 ))
111 } else {
112 None
113 };
114
115 if let Some(error) = error {
116 cx.prompt(PromptLevel::Critical, &error, &["OK"]);
117 return Task::ready(Ok(()));
118 }
119
120 let mut answer = cx.prompt(
121 PromptLevel::Info,
122 "Ready to submit your feedback?",
123 &["Yes, Submit!", "No"],
124 );
125
126 let this = cx.handle();
127 let client = cx.global::<Arc<Client>>().clone();
128 let specs = self.system_specs.clone();
129
130 cx.spawn(|_, mut cx| async move {
131 let answer = answer.recv().await;
132
133 if answer == Some(0) {
134 match FeedbackEditor::submit_feedback(&feedback_text, client, specs).await {
135 Ok(_) => {
136 cx.update(|cx| {
137 this.update(cx, |_, cx| {
138 cx.dispatch_action(workspace::CloseActiveItem);
139 })
140 });
141 }
142 Err(error) => {
143 log::error!("{}", error);
144
145 cx.update(|cx| {
146 this.update(cx, |_, cx| {
147 cx.prompt(
148 PromptLevel::Critical,
149 FEEDBACK_SUBMISSION_ERROR_TEXT,
150 &["OK"],
151 );
152 })
153 });
154 }
155 }
156 }
157 })
158 .detach();
159
160 Task::ready(Ok(()))
161 }
162
163 async fn submit_feedback(
164 feedback_text: &str,
165 zed_client: Arc<Client>,
166 system_specs: SystemSpecs,
167 ) -> anyhow::Result<()> {
168 let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
169
170 let metrics_id = zed_client.metrics_id();
171 let is_staff = zed_client.is_staff();
172 let http_client = zed_client.http_client();
173
174 let request = FeedbackRequestBody {
175 feedback_text: &feedback_text,
176 metrics_id,
177 system_specs,
178 is_staff: is_staff.unwrap_or(false),
179 token: ZED_SECRET_CLIENT_TOKEN,
180 };
181
182 let json_bytes = serde_json::to_vec(&request)?;
183
184 let request = Request::post(feedback_endpoint)
185 .header("content-type", "application/json")
186 .body(json_bytes.into())?;
187
188 let mut response = http_client.send(request).await?;
189 let mut body = String::new();
190 response.body_mut().read_to_string(&mut body).await?;
191
192 let response_status = response.status();
193
194 if !response_status.is_success() {
195 bail!("Feedback API failed with error: {}", response_status)
196 }
197
198 Ok(())
199 }
200}
201
202impl FeedbackEditor {
203 pub fn deploy(
204 system_specs: SystemSpecs,
205 workspace: &mut Workspace,
206 app_state: Arc<AppState>,
207 cx: &mut ViewContext<Workspace>,
208 ) {
209 workspace
210 .with_local_workspace(&app_state, cx, |workspace, cx| {
211 let project = workspace.project().clone();
212 let markdown_language = project.read(cx).languages().language_for_name("Markdown");
213 let buffer = project
214 .update(cx, |project, cx| {
215 project.create_buffer("", markdown_language, cx)
216 })
217 .expect("creating buffers on a local workspace always succeeds");
218 let feedback_editor =
219 cx.add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
220 workspace.add_item(Box::new(feedback_editor), cx);
221 })
222 .detach();
223 }
224}
225
226impl View for FeedbackEditor {
227 fn ui_name() -> &'static str {
228 "FeedbackEditor"
229 }
230
231 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
232 ChildView::new(&self.editor, cx).boxed()
233 }
234
235 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
236 if cx.is_self_focused() {
237 cx.focus(&self.editor);
238 }
239 }
240}
241
242impl Entity for FeedbackEditor {
243 type Event = editor::Event;
244}
245
246impl Item for FeedbackEditor {
247 fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> ElementBox {
248 Flex::row()
249 .with_child(
250 Label::new("Feedback".to_string(), style.label.clone())
251 .aligned()
252 .contained()
253 .boxed(),
254 )
255 .boxed()
256 }
257
258 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
259 self.editor.for_each_project_item(cx, f)
260 }
261
262 fn to_item_events(_: &Self::Event) -> SmallVec<[workspace::item::ItemEvent; 2]> {
263 SmallVec::new()
264 }
265
266 fn is_singleton(&self, _: &AppContext) -> bool {
267 true
268 }
269
270 fn set_nav_history(&mut self, _: workspace::ItemNavHistory, _: &mut ViewContext<Self>) {}
271
272 fn can_save(&self, _: &AppContext) -> bool {
273 true
274 }
275
276 fn save(
277 &mut self,
278 _: ModelHandle<Project>,
279 cx: &mut ViewContext<Self>,
280 ) -> Task<anyhow::Result<()>> {
281 self.handle_save(cx)
282 }
283
284 fn save_as(
285 &mut self,
286 _: ModelHandle<Project>,
287 _: std::path::PathBuf,
288 cx: &mut ViewContext<Self>,
289 ) -> Task<anyhow::Result<()>> {
290 self.handle_save(cx)
291 }
292
293 fn reload(
294 &mut self,
295 _: ModelHandle<Project>,
296 _: &mut ViewContext<Self>,
297 ) -> Task<anyhow::Result<()>> {
298 unreachable!("reload should not have been called")
299 }
300
301 fn clone_on_split(
302 &self,
303 _workspace_id: workspace::WorkspaceId,
304 cx: &mut ViewContext<Self>,
305 ) -> Option<Self>
306 where
307 Self: Sized,
308 {
309 let buffer = self
310 .editor
311 .read(cx)
312 .buffer()
313 .read(cx)
314 .as_singleton()
315 .expect("Feedback buffer is only ever singleton");
316
317 Some(Self::new(
318 self.system_specs.clone(),
319 self.project.clone(),
320 buffer.clone(),
321 cx,
322 ))
323 }
324
325 fn serialized_item_kind() -> Option<&'static str> {
326 None
327 }
328
329 fn deserialize(
330 _: ModelHandle<Project>,
331 _: WeakViewHandle<Workspace>,
332 _: workspace::WorkspaceId,
333 _: workspace::ItemId,
334 _: &mut ViewContext<workspace::Pane>,
335 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
336 unreachable!()
337 }
338
339 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
340 Some(Box::new(handle.clone()))
341 }
342
343 fn act_as_type(
344 &self,
345 type_id: TypeId,
346 self_handle: &ViewHandle<Self>,
347 _: &AppContext,
348 ) -> Option<AnyViewHandle> {
349 if type_id == TypeId::of::<Self>() {
350 Some(self_handle.into())
351 } else if type_id == TypeId::of::<Editor>() {
352 Some((&self.editor).into())
353 } else {
354 None
355 }
356 }
357}
358
359impl SearchableItem for FeedbackEditor {
360 type Match = Range<Anchor>;
361
362 fn to_search_event(event: &Self::Event) -> Option<workspace::searchable::SearchEvent> {
363 Editor::to_search_event(event)
364 }
365
366 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
367 self.editor
368 .update(cx, |editor, cx| editor.clear_matches(cx))
369 }
370
371 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
372 self.editor
373 .update(cx, |editor, cx| editor.update_matches(matches, cx))
374 }
375
376 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
377 self.editor
378 .update(cx, |editor, cx| editor.query_suggestion(cx))
379 }
380
381 fn activate_match(
382 &mut self,
383 index: usize,
384 matches: Vec<Self::Match>,
385 cx: &mut ViewContext<Self>,
386 ) {
387 self.editor
388 .update(cx, |editor, cx| editor.activate_match(index, matches, cx))
389 }
390
391 fn find_matches(
392 &mut self,
393 query: project::search::SearchQuery,
394 cx: &mut ViewContext<Self>,
395 ) -> Task<Vec<Self::Match>> {
396 self.editor
397 .update(cx, |editor, cx| editor.find_matches(query, cx))
398 }
399
400 fn active_match_index(
401 &mut self,
402 matches: Vec<Self::Match>,
403 cx: &mut ViewContext<Self>,
404 ) -> Option<usize> {
405 self.editor
406 .update(cx, |editor, cx| editor.active_match_index(matches, cx))
407 }
408}