Skip to content

Commit 1a3a7f4

Browse files
bors[bot]matklad
andauthored
Merge #5188
5188: Implement StatusBar r=matklad a=matklad Co-authored-by: Aleksey Kladov <[email protected]>
2 parents e75b4fc + 4f26a37 commit 1a3a7f4

File tree

10 files changed

+144
-12
lines changed

10 files changed

+144
-12
lines changed

crates/rust-analyzer/src/config.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ pub struct ClientCapsConfig {
130130
pub code_action_group: bool,
131131
pub resolve_code_action: bool,
132132
pub hover_actions: bool,
133+
pub status_notification: bool,
133134
}
134135

135136
impl Config {
@@ -365,6 +366,7 @@ impl Config {
365366
self.client_caps.code_action_group = get_bool("codeActionGroup");
366367
self.client_caps.resolve_code_action = get_bool("resolveCodeAction");
367368
self.client_caps.hover_actions = get_bool("hoverActions");
369+
self.client_caps.status_notification = get_bool("statusNotification");
368370
}
369371
}
370372
}

crates/rust-analyzer/src/global_state.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ use crate::{
3131
pub(crate) enum Status {
3232
Loading,
3333
Ready,
34+
Invalid,
35+
NeedsReload,
3436
}
3537

3638
impl Default for Status {

crates/rust-analyzer/src/lsp_ext.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use std::{collections::HashMap, path::PathBuf};
44

55
use lsp_types::request::Request;
6-
use lsp_types::{Position, Range, TextDocumentIdentifier};
6+
use lsp_types::{notification::Notification, Position, Range, TextDocumentIdentifier};
77
use serde::{Deserialize, Serialize};
88

99
pub enum AnalyzerStatus {}
@@ -208,6 +208,22 @@ pub struct SsrParams {
208208
pub parse_only: bool,
209209
}
210210

211+
pub enum StatusNotification {}
212+
213+
#[serde(rename_all = "camelCase")]
214+
#[derive(Serialize, Deserialize)]
215+
pub enum Status {
216+
Loading,
217+
Ready,
218+
NeedsReload,
219+
Invalid,
220+
}
221+
222+
impl Notification for StatusNotification {
223+
type Params = Status;
224+
const METHOD: &'static str = "rust-analyzer/status";
225+
}
226+
211227
pub enum CodeActionRequest {}
212228

213229
impl Request for CodeActionRequest {

crates/rust-analyzer/src/main_loop.rs

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,35 @@ impl GlobalState {
111111
}
112112

113113
fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
114+
let registration_options = lsp_types::TextDocumentRegistrationOptions {
115+
document_selector: Some(vec![
116+
lsp_types::DocumentFilter {
117+
language: None,
118+
scheme: None,
119+
pattern: Some("**/*.rs".into()),
120+
},
121+
lsp_types::DocumentFilter {
122+
language: None,
123+
scheme: None,
124+
pattern: Some("**/Cargo.toml".into()),
125+
},
126+
lsp_types::DocumentFilter {
127+
language: None,
128+
scheme: None,
129+
pattern: Some("**/Cargo.lock".into()),
130+
},
131+
]),
132+
};
133+
let registration = lsp_types::Registration {
134+
id: "textDocument/didSave".to_string(),
135+
method: "textDocument/didSave".to_string(),
136+
register_options: Some(serde_json::to_value(registration_options).unwrap()),
137+
};
138+
self.send_request::<lsp_types::request::RegisterCapability>(
139+
lsp_types::RegistrationParams { registrations: vec![registration] },
140+
|_, _| (),
141+
);
142+
114143
self.reload();
115144

116145
while let Some(event) = self.next_event(&inbox) {
@@ -169,16 +198,16 @@ impl GlobalState {
169198
}
170199
vfs::loader::Message::Progress { n_total, n_done } => {
171200
if n_total == 0 {
172-
self.status = Status::Ready;
201+
self.transition(Status::Invalid);
173202
} else {
174203
let state = if n_done == 0 {
175-
self.status = Status::Loading;
204+
self.transition(Status::Loading);
176205
Progress::Begin
177206
} else if n_done < n_total {
178207
Progress::Report
179208
} else {
180209
assert_eq!(n_done, n_total);
181-
self.status = Status::Ready;
210+
self.transition(Status::Ready);
182211
Progress::End
183212
};
184213
self.report_progress(
@@ -274,6 +303,19 @@ impl GlobalState {
274303
Ok(())
275304
}
276305

306+
fn transition(&mut self, new_status: Status) {
307+
self.status = Status::Ready;
308+
if self.config.client_caps.status_notification {
309+
let lsp_status = match new_status {
310+
Status::Loading => lsp_ext::Status::Loading,
311+
Status::Ready => lsp_ext::Status::Ready,
312+
Status::Invalid => lsp_ext::Status::Invalid,
313+
Status::NeedsReload => lsp_ext::Status::NeedsReload,
314+
};
315+
self.send_notification::<lsp_ext::StatusNotification>(lsp_status);
316+
}
317+
}
318+
277319
fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
278320
self.register_request(&req, request_received);
279321

@@ -383,10 +425,16 @@ impl GlobalState {
383425
);
384426
Ok(())
385427
})?
386-
.on::<lsp_types::notification::DidSaveTextDocument>(|this, _params| {
428+
.on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
387429
if let Some(flycheck) = &this.flycheck {
388430
flycheck.handle.update();
389431
}
432+
let uri = params.text_document.uri.as_str();
433+
if uri.ends_with("Cargo.toml") || uri.ends_with("Cargo.lock") {
434+
if matches!(this.status, Status::Ready | Status::Invalid) {
435+
this.transition(Status::NeedsReload);
436+
}
437+
}
390438
Ok(())
391439
})?
392440
.on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {

crates/rust-analyzer/src/reload.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl GlobalState {
7878
.collect(),
7979
};
8080
let registration = lsp_types::Registration {
81-
id: "file-watcher".to_string(),
81+
id: "workspace/didChangeWatchedFiles".to_string(),
8282
method: "workspace/didChangeWatchedFiles".to_string(),
8383
register_options: Some(serde_json::to_value(registration_options).unwrap()),
8484
};

crates/rust-analyzer/tests/heavy_tests/support.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,12 +176,19 @@ impl Server {
176176
while let Some(msg) = self.recv() {
177177
match msg {
178178
Message::Request(req) => {
179-
if req.method != "window/workDoneProgress/create"
180-
&& !(req.method == "client/registerCapability"
181-
&& req.params.to_string().contains("workspace/didChangeWatchedFiles"))
182-
{
183-
panic!("unexpected request: {:?}", req)
179+
if req.method == "window/workDoneProgress/create" {
180+
continue;
184181
}
182+
if req.method == "client/registerCapability" {
183+
let params = req.params.to_string();
184+
if ["workspace/didChangeWatchedFiles", "textDocument/didSave"]
185+
.iter()
186+
.any(|&it| params.contains(it))
187+
{
188+
continue;
189+
}
190+
}
191+
panic!("unexpected request: {:?}", req)
185192
}
186193
Message::Notification(_) => (),
187194
Message::Response(res) => {

docs/dev/lsp-extensions.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,18 @@ Returns internal status message, mostly for debugging purposes.
399399

400400
Reloads project information (that is, re-executes `cargo metadata`).
401401

402+
## Status Notification
403+
404+
**Client Capability:** `{ "statusNotification": boolean }`
405+
406+
**Method:** `rust-analyzer/status`
407+
408+
**Notification:** `"loading" | "ready" | "invalid" | "needsReload"`
409+
410+
This notification is sent from server to client.
411+
The client can use it to display persistent status to the user (in modline).
412+
For `needsReload` state, the client can provide a context-menu action to run `rust-analyzer/reloadWorkspace` request.
413+
402414
## Syntax Tree
403415

404416
**Method:** `rust-analyzer/syntaxTree`

editors/code/src/client.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ class ExperimentalFeatures implements lc.StaticFeature {
161161
caps.codeActionGroup = true;
162162
caps.resolveCodeAction = true;
163163
caps.hoverActions = true;
164+
caps.statusNotification = true;
164165
capabilities.experimental = caps;
165166
}
166167
initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {

editors/code/src/ctx.ts

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
import * as vscode from 'vscode';
22
import * as lc from 'vscode-languageclient';
3+
import * as ra from './lsp_ext';
34

45
import { Config } from './config';
56
import { createClient } from './client';
67
import { isRustEditor, RustEditor } from './util';
8+
import { Status } from './lsp_ext';
79

810
export class Ctx {
911
private constructor(
1012
readonly config: Config,
1113
private readonly extCtx: vscode.ExtensionContext,
1214
readonly client: lc.LanguageClient,
1315
readonly serverPath: string,
16+
readonly statusBar: vscode.StatusBarItem,
1417
) {
1518

1619
}
@@ -22,9 +25,18 @@ export class Ctx {
2225
cwd: string,
2326
): Promise<Ctx> {
2427
const client = createClient(serverPath, cwd);
25-
const res = new Ctx(config, extCtx, client, serverPath);
28+
29+
const statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
30+
extCtx.subscriptions.push(statusBar);
31+
statusBar.text = "rust-analyzer";
32+
statusBar.tooltip = "ready";
33+
statusBar.show();
34+
35+
const res = new Ctx(config, extCtx, client, serverPath, statusBar);
36+
2637
res.pushCleanup(client.start());
2738
await client.onReady();
39+
client.onNotification(ra.status, (status) => res.setStatus(status));
2840
return res;
2941
}
3042

@@ -54,6 +66,35 @@ export class Ctx {
5466
return this.extCtx.subscriptions;
5567
}
5668

69+
setStatus(status: Status) {
70+
switch (status) {
71+
case "loading":
72+
this.statusBar.text = "$(sync~spin) rust-analyzer";
73+
this.statusBar.tooltip = "Loading the project";
74+
this.statusBar.command = undefined;
75+
this.statusBar.color = undefined;
76+
break;
77+
case "ready":
78+
this.statusBar.text = "rust-analyzer";
79+
this.statusBar.tooltip = "Ready";
80+
this.statusBar.command = undefined;
81+
this.statusBar.color = undefined;
82+
break;
83+
case "invalid":
84+
this.statusBar.text = "$(error) rust-analyzer";
85+
this.statusBar.tooltip = "Failed to load the project";
86+
this.statusBar.command = undefined;
87+
this.statusBar.color = new vscode.ThemeColor("notificationsErrorIcon.foreground");
88+
break;
89+
case "needsReload":
90+
this.statusBar.text = "$(warning) rust-analyzer";
91+
this.statusBar.tooltip = "Click to reload";
92+
this.statusBar.command = "rust-analyzer.reloadWorkspace";
93+
this.statusBar.color = new vscode.ThemeColor("notificationsWarningIcon.foreground");
94+
break;
95+
}
96+
}
97+
5798
pushCleanup(d: Disposable) {
5899
this.extCtx.subscriptions.push(d);
59100
}

editors/code/src/lsp_ext.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ import * as lc from "vscode-languageclient";
66

77
export const analyzerStatus = new lc.RequestType<null, string, void>("rust-analyzer/analyzerStatus");
88

9+
export type Status = "loading" | "ready" | "invalid" | "needsReload";
10+
export const status = new lc.NotificationType<Status>("rust-analyzer/status");
11+
912
export const reloadWorkspace = new lc.RequestType<null, null, void>("rust-analyzer/reloadWorkspace");
1013

1114
export interface SyntaxTreeParams {

0 commit comments

Comments
 (0)