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