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, MouseEventHandler, ParentElement, Stack, Text},
14 serde_json, AnyViewHandle, AppContext, CursorStyle, Element, ElementBox, Entity, ModelHandle,
15 MouseButton, MutableAppContext, PromptLevel, RenderContext, Task, View, ViewContext,
16 ViewHandle, WeakViewHandle,
17};
18use isahc::Request;
19use language::Buffer;
20use postage::prelude::Stream;
21
22use project::Project;
23use serde::Serialize;
24use settings::Settings;
25use workspace::{
26 item::{Item, ItemHandle},
27 searchable::{SearchableItem, SearchableItemHandle},
28 AppState, StatusItemView, ToolbarItemLocation, ToolbarItemView, Workspace,
29};
30
31use crate::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
57pub struct DeployFeedbackButton;
58
59impl Entity for DeployFeedbackButton {
60 type Event = ();
61}
62
63impl View for DeployFeedbackButton {
64 fn ui_name() -> &'static str {
65 "DeployFeedbackButton"
66 }
67
68 fn render(&mut self, cx: &mut RenderContext<'_, Self>) -> ElementBox {
69 Stack::new()
70 .with_child(
71 MouseEventHandler::<Self>::new(0, cx, |state, cx| {
72 let theme = &cx.global::<Settings>().theme;
73 let theme = &theme.workspace.status_bar.feedback;
74
75 Text::new(
76 "Give Feedback".to_string(),
77 theme.style_for(state, true).clone(),
78 )
79 .boxed()
80 })
81 .with_cursor_style(CursorStyle::PointingHand)
82 .on_click(MouseButton::Left, |_, cx| cx.dispatch_action(GiveFeedback))
83 .boxed(),
84 )
85 .boxed()
86 }
87}
88
89impl StatusItemView for DeployFeedbackButton {
90 fn set_active_pane_item(&mut self, _: Option<&dyn ItemHandle>, _: &mut ViewContext<Self>) {}
91}
92
93#[derive(Serialize)]
94struct FeedbackRequestBody<'a> {
95 feedback_text: &'a str,
96 metrics_id: Option<Arc<str>>,
97 system_specs: SystemSpecs,
98 is_staff: bool,
99 token: &'a str,
100}
101
102#[derive(Clone)]
103struct FeedbackEditor {
104 system_specs: SystemSpecs,
105 editor: ViewHandle<Editor>,
106 project: ModelHandle<Project>,
107}
108
109impl FeedbackEditor {
110 fn new(
111 system_specs: SystemSpecs,
112 project: ModelHandle<Project>,
113 buffer: ModelHandle<Buffer>,
114 cx: &mut ViewContext<Self>,
115 ) -> Self {
116 let editor = cx.add_view(|cx| {
117 let mut editor = Editor::for_buffer(buffer, Some(project.clone()), cx);
118 editor.set_vertical_scroll_margin(5, cx);
119 editor
120 });
121
122 cx.subscribe(&editor, |_, _, e, cx| cx.emit(e.clone()))
123 .detach();
124
125 Self {
126 system_specs: system_specs.clone(),
127 editor,
128 project,
129 }
130 }
131
132 fn handle_save(&mut self, cx: &mut ViewContext<Self>) -> Task<anyhow::Result<()>> {
133 let feedback_text = self.editor.read(cx).text(cx);
134 let feedback_char_count = feedback_text.chars().count();
135 let feedback_text = feedback_text.trim().to_string();
136
137 let error = if feedback_char_count < *FEEDBACK_CHAR_LIMIT.start() {
138 Some(format!(
139 "Feedback can't be shorter than {} characters.",
140 FEEDBACK_CHAR_LIMIT.start()
141 ))
142 } else if feedback_char_count > *FEEDBACK_CHAR_LIMIT.end() {
143 Some(format!(
144 "Feedback can't be longer than {} characters.",
145 FEEDBACK_CHAR_LIMIT.end()
146 ))
147 } else {
148 None
149 };
150
151 if let Some(error) = error {
152 cx.prompt(PromptLevel::Critical, &error, &["OK"]);
153 return Task::ready(Ok(()));
154 }
155
156 let mut answer = cx.prompt(
157 PromptLevel::Info,
158 "Ready to submit your feedback?",
159 &["Yes, Submit!", "No"],
160 );
161
162 let this = cx.handle();
163 let client = cx.global::<Arc<Client>>().clone();
164 let specs = self.system_specs.clone();
165
166 cx.spawn(|_, mut cx| async move {
167 let answer = answer.recv().await;
168
169 if answer == Some(0) {
170 match FeedbackEditor::submit_feedback(&feedback_text, client, specs).await {
171 Ok(_) => {
172 cx.update(|cx| {
173 this.update(cx, |_, cx| {
174 cx.dispatch_action(workspace::CloseActiveItem);
175 })
176 });
177 }
178 Err(error) => {
179 log::error!("{}", error);
180
181 cx.update(|cx| {
182 this.update(cx, |_, cx| {
183 cx.prompt(
184 PromptLevel::Critical,
185 FEEDBACK_SUBMISSION_ERROR_TEXT,
186 &["OK"],
187 );
188 })
189 });
190 }
191 }
192 }
193 })
194 .detach();
195
196 Task::ready(Ok(()))
197 }
198
199 async fn submit_feedback(
200 feedback_text: &str,
201 zed_client: Arc<Client>,
202 system_specs: SystemSpecs,
203 ) -> anyhow::Result<()> {
204 let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
205
206 let metrics_id = zed_client.metrics_id();
207 let is_staff = zed_client.is_staff();
208 let http_client = zed_client.http_client();
209
210 let request = FeedbackRequestBody {
211 feedback_text: &feedback_text,
212 metrics_id,
213 system_specs,
214 is_staff: is_staff.unwrap_or(false),
215 token: ZED_SECRET_CLIENT_TOKEN,
216 };
217
218 let json_bytes = serde_json::to_vec(&request)?;
219
220 let request = Request::post(feedback_endpoint)
221 .header("content-type", "application/json")
222 .body(json_bytes.into())?;
223
224 let mut response = http_client.send(request).await?;
225 let mut body = String::new();
226 response.body_mut().read_to_string(&mut body).await?;
227
228 let response_status = response.status();
229
230 if !response_status.is_success() {
231 bail!("Feedback API failed with error: {}", response_status)
232 }
233
234 Ok(())
235 }
236}
237
238impl FeedbackEditor {
239 pub fn deploy(
240 system_specs: SystemSpecs,
241 workspace: &mut Workspace,
242 app_state: Arc<AppState>,
243 cx: &mut ViewContext<Workspace>,
244 ) {
245 workspace
246 .with_local_workspace(&app_state, cx, |workspace, cx| {
247 let project = workspace.project().clone();
248 let markdown_language = project.read(cx).languages().language_for_name("Markdown");
249 let buffer = project
250 .update(cx, |project, cx| {
251 project.create_buffer("", markdown_language, cx)
252 })
253 .expect("creating buffers on a local workspace always succeeds");
254 let feedback_editor =
255 cx.add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
256 workspace.add_item(Box::new(feedback_editor), cx);
257 })
258 .detach();
259 }
260}
261
262impl View for FeedbackEditor {
263 fn ui_name() -> &'static str {
264 "FeedbackEditor"
265 }
266
267 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
268 ChildView::new(&self.editor, cx).boxed()
269 }
270
271 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
272 if cx.is_self_focused() {
273 cx.focus(&self.editor);
274 }
275 }
276}
277
278impl Entity for FeedbackEditor {
279 type Event = editor::Event;
280}
281
282impl Item for FeedbackEditor {
283 fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> ElementBox {
284 Flex::row()
285 .with_child(
286 Label::new("Feedback".to_string(), style.label.clone())
287 .aligned()
288 .contained()
289 .boxed(),
290 )
291 .boxed()
292 }
293
294 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
295 self.editor.for_each_project_item(cx, f)
296 }
297
298 fn to_item_events(_: &Self::Event) -> Vec<workspace::item::ItemEvent> {
299 Vec::new()
300 }
301
302 fn is_singleton(&self, _: &AppContext) -> bool {
303 true
304 }
305
306 fn set_nav_history(&mut self, _: workspace::ItemNavHistory, _: &mut ViewContext<Self>) {}
307
308 fn can_save(&self, _: &AppContext) -> bool {
309 true
310 }
311
312 fn save(
313 &mut self,
314 _: ModelHandle<Project>,
315 cx: &mut ViewContext<Self>,
316 ) -> Task<anyhow::Result<()>> {
317 self.handle_save(cx)
318 }
319
320 fn save_as(
321 &mut self,
322 _: ModelHandle<Project>,
323 _: std::path::PathBuf,
324 cx: &mut ViewContext<Self>,
325 ) -> Task<anyhow::Result<()>> {
326 self.handle_save(cx)
327 }
328
329 fn reload(
330 &mut self,
331 _: ModelHandle<Project>,
332 _: &mut ViewContext<Self>,
333 ) -> Task<anyhow::Result<()>> {
334 unreachable!("reload should not have been called")
335 }
336
337 fn clone_on_split(
338 &self,
339 _workspace_id: workspace::WorkspaceId,
340 cx: &mut ViewContext<Self>,
341 ) -> Option<Self>
342 where
343 Self: Sized,
344 {
345 let buffer = self
346 .editor
347 .read(cx)
348 .buffer()
349 .read(cx)
350 .as_singleton()
351 .expect("Feedback buffer is only ever singleton");
352
353 Some(Self::new(
354 self.system_specs.clone(),
355 self.project.clone(),
356 buffer.clone(),
357 cx,
358 ))
359 }
360
361 fn serialized_item_kind() -> Option<&'static str> {
362 None
363 }
364
365 fn deserialize(
366 _: ModelHandle<Project>,
367 _: WeakViewHandle<Workspace>,
368 _: workspace::WorkspaceId,
369 _: workspace::ItemId,
370 _: &mut ViewContext<workspace::Pane>,
371 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
372 unreachable!()
373 }
374
375 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
376 Some(Box::new(handle.clone()))
377 }
378
379 fn act_as_type(
380 &self,
381 type_id: TypeId,
382 self_handle: &ViewHandle<Self>,
383 _: &AppContext,
384 ) -> Option<AnyViewHandle> {
385 if type_id == TypeId::of::<Self>() {
386 Some(self_handle.into())
387 } else if type_id == TypeId::of::<Editor>() {
388 Some((&self.editor).into())
389 } else {
390 None
391 }
392 }
393}
394
395impl SearchableItem for FeedbackEditor {
396 type Match = Range<Anchor>;
397
398 fn to_search_event(event: &Self::Event) -> Option<workspace::searchable::SearchEvent> {
399 Editor::to_search_event(event)
400 }
401
402 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
403 self.editor
404 .update(cx, |editor, cx| editor.clear_matches(cx))
405 }
406
407 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
408 self.editor
409 .update(cx, |editor, cx| editor.update_matches(matches, cx))
410 }
411
412 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
413 self.editor
414 .update(cx, |editor, cx| editor.query_suggestion(cx))
415 }
416
417 fn activate_match(
418 &mut self,
419 index: usize,
420 matches: Vec<Self::Match>,
421 cx: &mut ViewContext<Self>,
422 ) {
423 self.editor
424 .update(cx, |editor, cx| editor.activate_match(index, matches, cx))
425 }
426
427 fn find_matches(
428 &mut self,
429 query: project::search::SearchQuery,
430 cx: &mut ViewContext<Self>,
431 ) -> Task<Vec<Self::Match>> {
432 self.editor
433 .update(cx, |editor, cx| editor.find_matches(query, cx))
434 }
435
436 fn active_match_index(
437 &mut self,
438 matches: Vec<Self::Match>,
439 cx: &mut ViewContext<Self>,
440 ) -> Option<usize> {
441 self.editor
442 .update(cx, |editor, cx| editor.active_match_index(matches, cx))
443 }
444}
445
446pub struct SubmitFeedbackButton {
447 active_item: Option<ViewHandle<FeedbackEditor>>,
448}
449
450impl SubmitFeedbackButton {
451 pub fn new() -> Self {
452 Self {
453 active_item: Default::default(),
454 }
455 }
456}
457
458impl Entity for SubmitFeedbackButton {
459 type Event = ();
460}
461
462impl View for SubmitFeedbackButton {
463 fn ui_name() -> &'static str {
464 "SubmitFeedbackButton"
465 }
466
467 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
468 let theme = cx.global::<Settings>().theme.clone();
469 enum SubmitFeedbackButton {}
470 MouseEventHandler::<SubmitFeedbackButton>::new(0, cx, |state, _| {
471 let style = theme.feedback.submit_button.style_for(state, false);
472 Label::new("Submit as Markdown".into(), style.text.clone())
473 .contained()
474 .with_style(style.container)
475 .boxed()
476 })
477 .with_cursor_style(CursorStyle::PointingHand)
478 .on_click(MouseButton::Left, |_, cx| {
479 cx.dispatch_action(SubmitFeedback)
480 })
481 .aligned()
482 .contained()
483 .with_margin_left(theme.feedback.button_margin)
484 .with_tooltip::<Self, _>(
485 0,
486 "cmd-s".into(),
487 Some(Box::new(SubmitFeedback)),
488 theme.tooltip.clone(),
489 cx,
490 )
491 .boxed()
492 }
493}
494
495impl ToolbarItemView for SubmitFeedbackButton {
496 fn set_active_pane_item(
497 &mut self,
498 active_pane_item: Option<&dyn ItemHandle>,
499 cx: &mut ViewContext<Self>,
500 ) -> workspace::ToolbarItemLocation {
501 cx.notify();
502 if let Some(feedback_editor) = active_pane_item.and_then(|i| i.downcast::<FeedbackEditor>())
503 {
504 self.active_item = Some(feedback_editor);
505 ToolbarItemLocation::PrimaryRight { flex: None }
506 } else {
507 self.active_item = None;
508 ToolbarItemLocation::Hidden
509 }
510 }
511}
512
513pub struct FeedbackInfoText {
514 active_item: Option<ViewHandle<FeedbackEditor>>,
515}
516
517impl FeedbackInfoText {
518 pub fn new() -> Self {
519 Self {
520 active_item: Default::default(),
521 }
522 }
523}
524
525impl Entity for FeedbackInfoText {
526 type Event = ();
527}
528
529impl View for FeedbackInfoText {
530 fn ui_name() -> &'static str {
531 "FeedbackInfoText"
532 }
533
534 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
535 let theme = cx.global::<Settings>().theme.clone();
536 let text = "We read whatever you submit here. For issues and discussions, visit the community repo on GitHub.";
537 Label::new(text.to_string(), theme.feedback.info_text.text.clone())
538 .contained()
539 .aligned()
540 .left()
541 .clipped()
542 .boxed()
543 }
544}
545
546impl ToolbarItemView for FeedbackInfoText {
547 fn set_active_pane_item(
548 &mut self,
549 active_pane_item: Option<&dyn ItemHandle>,
550 cx: &mut ViewContext<Self>,
551 ) -> workspace::ToolbarItemLocation {
552 cx.notify();
553 if let Some(feedback_editor) = active_pane_item.and_then(|i| i.downcast::<FeedbackEditor>())
554 {
555 self.active_item = Some(feedback_editor);
556 ToolbarItemLocation::PrimaryLeft {
557 flex: Some((1., false)),
558 }
559 } else {
560 self.active_item = None;
561 ToolbarItemLocation::Hidden
562 }
563 }
564}