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 platform::PromptLevel,
15 serde_json, AnyViewHandle, AppContext, Drawable, Element, Entity, ModelHandle, Task, View,
16 ViewContext, ViewHandle,
17};
18use isahc::Request;
19use language::Buffer;
20use postage::prelude::Stream;
21
22use project::Project;
23use serde::Serialize;
24use util::ResultExt;
25use workspace::{
26 item::{Item, ItemHandle},
27 searchable::{SearchableItem, SearchableItemHandle},
28 AppState, Pane, 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 AppContext) {
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(_) => this.update(&mut cx, |_, cx| {
136 cx.dispatch_action(workspace::CloseActiveItem);
137 }),
138 Err(error) => {
139 log::error!("{}", error);
140 this.update(&mut cx, |_, cx| {
141 cx.prompt(
142 PromptLevel::Critical,
143 FEEDBACK_SUBMISSION_ERROR_TEXT,
144 &["OK"],
145 );
146 })
147 }
148 }
149 }
150 })
151 .detach();
152
153 Task::ready(Ok(()))
154 }
155
156 async fn submit_feedback(
157 feedback_text: &str,
158 zed_client: Arc<Client>,
159 system_specs: SystemSpecs,
160 ) -> anyhow::Result<()> {
161 let feedback_endpoint = format!("{}/api/feedback", *ZED_SERVER_URL);
162
163 let metrics_id = zed_client.metrics_id();
164 let is_staff = zed_client.is_staff();
165 let http_client = zed_client.http_client();
166
167 let request = FeedbackRequestBody {
168 feedback_text: &feedback_text,
169 metrics_id,
170 system_specs,
171 is_staff: is_staff.unwrap_or(false),
172 token: ZED_SECRET_CLIENT_TOKEN,
173 };
174
175 let json_bytes = serde_json::to_vec(&request)?;
176
177 let request = Request::post(feedback_endpoint)
178 .header("content-type", "application/json")
179 .body(json_bytes.into())?;
180
181 let mut response = http_client.send(request).await?;
182 let mut body = String::new();
183 response.body_mut().read_to_string(&mut body).await?;
184
185 let response_status = response.status();
186
187 if !response_status.is_success() {
188 bail!("Feedback API failed with error: {}", response_status)
189 }
190
191 Ok(())
192 }
193}
194
195impl FeedbackEditor {
196 pub fn deploy(
197 system_specs: SystemSpecs,
198 _: &mut Workspace,
199 app_state: Arc<AppState>,
200 cx: &mut ViewContext<Workspace>,
201 ) {
202 let markdown = app_state.languages.language_for_name("Markdown");
203 cx.spawn(|workspace, mut cx| async move {
204 let markdown = markdown.await.log_err();
205 workspace
206 .update(&mut cx, |workspace, cx| {
207 workspace.with_local_workspace(&app_state, cx, |workspace, cx| {
208 let project = workspace.project().clone();
209 let buffer = project
210 .update(cx, |project, cx| project.create_buffer("", markdown, cx))
211 .expect("creating buffers on a local workspace always succeeds");
212 let feedback_editor = cx
213 .add_view(|cx| FeedbackEditor::new(system_specs, project, buffer, cx));
214 workspace.add_item(Box::new(feedback_editor), cx);
215 })
216 })
217 .await;
218 })
219 .detach();
220 }
221}
222
223impl View for FeedbackEditor {
224 fn ui_name() -> &'static str {
225 "FeedbackEditor"
226 }
227
228 fn render(&mut self, cx: &mut ViewContext<Self>) -> Element<Self> {
229 ChildView::new(&self.editor, cx).boxed()
230 }
231
232 fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
233 if cx.is_self_focused() {
234 cx.focus(&self.editor);
235 }
236 }
237}
238
239impl Entity for FeedbackEditor {
240 type Event = editor::Event;
241}
242
243impl Item for FeedbackEditor {
244 fn tab_content(&self, _: Option<usize>, style: &theme::Tab, _: &AppContext) -> Element<Pane> {
245 Flex::row()
246 .with_child(
247 Svg::new("icons/feedback_16.svg")
248 .with_color(style.label.text.color)
249 .constrained()
250 .with_width(style.type_icon_width)
251 .aligned()
252 .contained()
253 .with_margin_right(style.spacing)
254 .boxed(),
255 )
256 .with_child(
257 Label::new("Send Feedback", style.label.clone())
258 .aligned()
259 .contained()
260 .boxed(),
261 )
262 .boxed()
263 }
264
265 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
266 self.editor.for_each_project_item(cx, f)
267 }
268
269 fn is_singleton(&self, _: &AppContext) -> bool {
270 true
271 }
272
273 fn can_save(&self, _: &AppContext) -> bool {
274 true
275 }
276
277 fn save(
278 &mut self,
279 _: ModelHandle<Project>,
280 cx: &mut ViewContext<Self>,
281 ) -> Task<anyhow::Result<()>> {
282 self.handle_save(cx)
283 }
284
285 fn save_as(
286 &mut self,
287 _: ModelHandle<Project>,
288 _: std::path::PathBuf,
289 cx: &mut ViewContext<Self>,
290 ) -> Task<anyhow::Result<()>> {
291 self.handle_save(cx)
292 }
293
294 fn reload(
295 &mut self,
296 _: ModelHandle<Project>,
297 _: &mut ViewContext<Self>,
298 ) -> Task<anyhow::Result<()>> {
299 Task::Ready(Some(Ok(())))
300 }
301
302 fn clone_on_split(
303 &self,
304 _workspace_id: workspace::WorkspaceId,
305 cx: &mut ViewContext<Self>,
306 ) -> Option<Self>
307 where
308 Self: Sized,
309 {
310 let buffer = self
311 .editor
312 .read(cx)
313 .buffer()
314 .read(cx)
315 .as_singleton()
316 .expect("Feedback buffer is only ever singleton");
317
318 Some(Self::new(
319 self.system_specs.clone(),
320 self.project.clone(),
321 buffer.clone(),
322 cx,
323 ))
324 }
325
326 fn as_searchable(&self, handle: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
327 Some(Box::new(handle.clone()))
328 }
329
330 fn act_as_type<'a>(
331 &'a self,
332 type_id: TypeId,
333 self_handle: &'a ViewHandle<Self>,
334 _: &'a AppContext,
335 ) -> Option<&'a AnyViewHandle> {
336 if type_id == TypeId::of::<Self>() {
337 Some(self_handle)
338 } else if type_id == TypeId::of::<Editor>() {
339 Some(&self.editor)
340 } else {
341 None
342 }
343 }
344}
345
346impl SearchableItem for FeedbackEditor {
347 type Match = Range<Anchor>;
348
349 fn to_search_event(event: &Self::Event) -> Option<workspace::searchable::SearchEvent> {
350 Editor::to_search_event(event)
351 }
352
353 fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
354 self.editor
355 .update(cx, |editor, cx| editor.clear_matches(cx))
356 }
357
358 fn update_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
359 self.editor
360 .update(cx, |editor, cx| editor.update_matches(matches, cx))
361 }
362
363 fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
364 self.editor
365 .update(cx, |editor, cx| editor.query_suggestion(cx))
366 }
367
368 fn activate_match(
369 &mut self,
370 index: usize,
371 matches: Vec<Self::Match>,
372 cx: &mut ViewContext<Self>,
373 ) {
374 self.editor
375 .update(cx, |editor, cx| editor.activate_match(index, matches, cx))
376 }
377
378 fn find_matches(
379 &mut self,
380 query: project::search::SearchQuery,
381 cx: &mut ViewContext<Self>,
382 ) -> Task<Vec<Self::Match>> {
383 self.editor
384 .update(cx, |editor, cx| editor.find_matches(query, cx))
385 }
386
387 fn active_match_index(
388 &mut self,
389 matches: Vec<Self::Match>,
390 cx: &mut ViewContext<Self>,
391 ) -> Option<usize> {
392 self.editor
393 .update(cx, |editor, cx| editor.active_match_index(matches, cx))
394 }
395}