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