5188: Implement StatusBar r=matklad a=matklad



Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2020-07-02 14:02:52 +00:00 committed by GitHub
commit 1a3a7f4237
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 144 additions and 12 deletions

View file

@ -130,6 +130,7 @@ pub struct ClientCapsConfig {
pub code_action_group: bool, pub code_action_group: bool,
pub resolve_code_action: bool, pub resolve_code_action: bool,
pub hover_actions: bool, pub hover_actions: bool,
pub status_notification: bool,
} }
impl Config { impl Config {
@ -365,6 +366,7 @@ impl Config {
self.client_caps.code_action_group = get_bool("codeActionGroup"); self.client_caps.code_action_group = get_bool("codeActionGroup");
self.client_caps.resolve_code_action = get_bool("resolveCodeAction"); self.client_caps.resolve_code_action = get_bool("resolveCodeAction");
self.client_caps.hover_actions = get_bool("hoverActions"); self.client_caps.hover_actions = get_bool("hoverActions");
self.client_caps.status_notification = get_bool("statusNotification");
} }
} }
} }

View file

@ -31,6 +31,8 @@ use crate::{
pub(crate) enum Status { pub(crate) enum Status {
Loading, Loading,
Ready, Ready,
Invalid,
NeedsReload,
} }
impl Default for Status { impl Default for Status {

View file

@ -3,7 +3,7 @@
use std::{collections::HashMap, path::PathBuf}; use std::{collections::HashMap, path::PathBuf};
use lsp_types::request::Request; use lsp_types::request::Request;
use lsp_types::{Position, Range, TextDocumentIdentifier}; use lsp_types::{notification::Notification, Position, Range, TextDocumentIdentifier};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub enum AnalyzerStatus {} pub enum AnalyzerStatus {}
@ -208,6 +208,22 @@ pub struct SsrParams {
pub parse_only: bool, pub parse_only: bool,
} }
pub enum StatusNotification {}
#[serde(rename_all = "camelCase")]
#[derive(Serialize, Deserialize)]
pub enum Status {
Loading,
Ready,
NeedsReload,
Invalid,
}
impl Notification for StatusNotification {
type Params = Status;
const METHOD: &'static str = "rust-analyzer/status";
}
pub enum CodeActionRequest {} pub enum CodeActionRequest {}
impl Request for CodeActionRequest { impl Request for CodeActionRequest {

View file

@ -111,6 +111,35 @@ impl GlobalState {
} }
fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> { fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
let registration_options = lsp_types::TextDocumentRegistrationOptions {
document_selector: Some(vec![
lsp_types::DocumentFilter {
language: None,
scheme: None,
pattern: Some("**/*.rs".into()),
},
lsp_types::DocumentFilter {
language: None,
scheme: None,
pattern: Some("**/Cargo.toml".into()),
},
lsp_types::DocumentFilter {
language: None,
scheme: None,
pattern: Some("**/Cargo.lock".into()),
},
]),
};
let registration = lsp_types::Registration {
id: "textDocument/didSave".to_string(),
method: "textDocument/didSave".to_string(),
register_options: Some(serde_json::to_value(registration_options).unwrap()),
};
self.send_request::<lsp_types::request::RegisterCapability>(
lsp_types::RegistrationParams { registrations: vec![registration] },
|_, _| (),
);
self.reload(); self.reload();
while let Some(event) = self.next_event(&inbox) { while let Some(event) = self.next_event(&inbox) {
@ -169,16 +198,16 @@ impl GlobalState {
} }
vfs::loader::Message::Progress { n_total, n_done } => { vfs::loader::Message::Progress { n_total, n_done } => {
if n_total == 0 { if n_total == 0 {
self.status = Status::Ready; self.transition(Status::Invalid);
} else { } else {
let state = if n_done == 0 { let state = if n_done == 0 {
self.status = Status::Loading; self.transition(Status::Loading);
Progress::Begin Progress::Begin
} else if n_done < n_total { } else if n_done < n_total {
Progress::Report Progress::Report
} else { } else {
assert_eq!(n_done, n_total); assert_eq!(n_done, n_total);
self.status = Status::Ready; self.transition(Status::Ready);
Progress::End Progress::End
}; };
self.report_progress( self.report_progress(
@ -274,6 +303,19 @@ impl GlobalState {
Ok(()) Ok(())
} }
fn transition(&mut self, new_status: Status) {
self.status = Status::Ready;
if self.config.client_caps.status_notification {
let lsp_status = match new_status {
Status::Loading => lsp_ext::Status::Loading,
Status::Ready => lsp_ext::Status::Ready,
Status::Invalid => lsp_ext::Status::Invalid,
Status::NeedsReload => lsp_ext::Status::NeedsReload,
};
self.send_notification::<lsp_ext::StatusNotification>(lsp_status);
}
}
fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> { fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
self.register_request(&req, request_received); self.register_request(&req, request_received);
@ -383,10 +425,16 @@ impl GlobalState {
); );
Ok(()) Ok(())
})? })?
.on::<lsp_types::notification::DidSaveTextDocument>(|this, _params| { .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
if let Some(flycheck) = &this.flycheck { if let Some(flycheck) = &this.flycheck {
flycheck.handle.update(); flycheck.handle.update();
} }
let uri = params.text_document.uri.as_str();
if uri.ends_with("Cargo.toml") || uri.ends_with("Cargo.lock") {
if matches!(this.status, Status::Ready | Status::Invalid) {
this.transition(Status::NeedsReload);
}
}
Ok(()) Ok(())
})? })?
.on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| { .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {

View file

@ -78,7 +78,7 @@ impl GlobalState {
.collect(), .collect(),
}; };
let registration = lsp_types::Registration { let registration = lsp_types::Registration {
id: "file-watcher".to_string(), id: "workspace/didChangeWatchedFiles".to_string(),
method: "workspace/didChangeWatchedFiles".to_string(), method: "workspace/didChangeWatchedFiles".to_string(),
register_options: Some(serde_json::to_value(registration_options).unwrap()), register_options: Some(serde_json::to_value(registration_options).unwrap()),
}; };

View file

@ -176,12 +176,19 @@ impl Server {
while let Some(msg) = self.recv() { while let Some(msg) = self.recv() {
match msg { match msg {
Message::Request(req) => { Message::Request(req) => {
if req.method != "window/workDoneProgress/create" if req.method == "window/workDoneProgress/create" {
&& !(req.method == "client/registerCapability" continue;
&& req.params.to_string().contains("workspace/didChangeWatchedFiles"))
{
panic!("unexpected request: {:?}", req)
} }
if req.method == "client/registerCapability" {
let params = req.params.to_string();
if ["workspace/didChangeWatchedFiles", "textDocument/didSave"]
.iter()
.any(|&it| params.contains(it))
{
continue;
}
}
panic!("unexpected request: {:?}", req)
} }
Message::Notification(_) => (), Message::Notification(_) => (),
Message::Response(res) => { Message::Response(res) => {

View file

@ -399,6 +399,18 @@ Returns internal status message, mostly for debugging purposes.
Reloads project information (that is, re-executes `cargo metadata`). Reloads project information (that is, re-executes `cargo metadata`).
## Status Notification
**Client Capability:** `{ "statusNotification": boolean }`
**Method:** `rust-analyzer/status`
**Notification:** `"loading" | "ready" | "invalid" | "needsReload"`
This notification is sent from server to client.
The client can use it to display persistent status to the user (in modline).
For `needsReload` state, the client can provide a context-menu action to run `rust-analyzer/reloadWorkspace` request.
## Syntax Tree ## Syntax Tree
**Method:** `rust-analyzer/syntaxTree` **Method:** `rust-analyzer/syntaxTree`

View file

@ -161,6 +161,7 @@ class ExperimentalFeatures implements lc.StaticFeature {
caps.codeActionGroup = true; caps.codeActionGroup = true;
caps.resolveCodeAction = true; caps.resolveCodeAction = true;
caps.hoverActions = true; caps.hoverActions = true;
caps.statusNotification = true;
capabilities.experimental = caps; capabilities.experimental = caps;
} }
initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void { initialize(_capabilities: lc.ServerCapabilities<any>, _documentSelector: lc.DocumentSelector | undefined): void {

View file

@ -1,9 +1,11 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient'; import * as lc from 'vscode-languageclient';
import * as ra from './lsp_ext';
import { Config } from './config'; import { Config } from './config';
import { createClient } from './client'; import { createClient } from './client';
import { isRustEditor, RustEditor } from './util'; import { isRustEditor, RustEditor } from './util';
import { Status } from './lsp_ext';
export class Ctx { export class Ctx {
private constructor( private constructor(
@ -11,6 +13,7 @@ export class Ctx {
private readonly extCtx: vscode.ExtensionContext, private readonly extCtx: vscode.ExtensionContext,
readonly client: lc.LanguageClient, readonly client: lc.LanguageClient,
readonly serverPath: string, readonly serverPath: string,
readonly statusBar: vscode.StatusBarItem,
) { ) {
} }
@ -22,9 +25,18 @@ export class Ctx {
cwd: string, cwd: string,
): Promise<Ctx> { ): Promise<Ctx> {
const client = createClient(serverPath, cwd); const client = createClient(serverPath, cwd);
const res = new Ctx(config, extCtx, client, serverPath);
const statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
extCtx.subscriptions.push(statusBar);
statusBar.text = "rust-analyzer";
statusBar.tooltip = "ready";
statusBar.show();
const res = new Ctx(config, extCtx, client, serverPath, statusBar);
res.pushCleanup(client.start()); res.pushCleanup(client.start());
await client.onReady(); await client.onReady();
client.onNotification(ra.status, (status) => res.setStatus(status));
return res; return res;
} }
@ -54,6 +66,35 @@ export class Ctx {
return this.extCtx.subscriptions; return this.extCtx.subscriptions;
} }
setStatus(status: Status) {
switch (status) {
case "loading":
this.statusBar.text = "$(sync~spin) rust-analyzer";
this.statusBar.tooltip = "Loading the project";
this.statusBar.command = undefined;
this.statusBar.color = undefined;
break;
case "ready":
this.statusBar.text = "rust-analyzer";
this.statusBar.tooltip = "Ready";
this.statusBar.command = undefined;
this.statusBar.color = undefined;
break;
case "invalid":
this.statusBar.text = "$(error) rust-analyzer";
this.statusBar.tooltip = "Failed to load the project";
this.statusBar.command = undefined;
this.statusBar.color = new vscode.ThemeColor("notificationsErrorIcon.foreground");
break;
case "needsReload":
this.statusBar.text = "$(warning) rust-analyzer";
this.statusBar.tooltip = "Click to reload";
this.statusBar.command = "rust-analyzer.reloadWorkspace";
this.statusBar.color = new vscode.ThemeColor("notificationsWarningIcon.foreground");
break;
}
}
pushCleanup(d: Disposable) { pushCleanup(d: Disposable) {
this.extCtx.subscriptions.push(d); this.extCtx.subscriptions.push(d);
} }

View file

@ -6,6 +6,9 @@ import * as lc from "vscode-languageclient";
export const analyzerStatus = new lc.RequestType<null, string, void>("rust-analyzer/analyzerStatus"); export const analyzerStatus = new lc.RequestType<null, string, void>("rust-analyzer/analyzerStatus");
export type Status = "loading" | "ready" | "invalid" | "needsReload";
export const status = new lc.NotificationType<Status>("rust-analyzer/status");
export const reloadWorkspace = new lc.RequestType<null, null, void>("rust-analyzer/reloadWorkspace"); export const reloadWorkspace = new lc.RequestType<null, null, void>("rust-analyzer/reloadWorkspace");
export interface SyntaxTreeParams { export interface SyntaxTreeParams {