Skip to content

Commit

Permalink
lsp wip
Browse files Browse the repository at this point in the history
  • Loading branch information
Redhawk18 committed Jan 28, 2025
1 parent 32602ce commit c6ed96d
Show file tree
Hide file tree
Showing 13 changed files with 97 additions and 55 deletions.
12 changes: 6 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ license.workspace = true

[dependencies]
kuiper_gui.workspace = true
tokio.workspace = true
pretty_env_logger.workspace = true
pretty_env_logger = "0.5.0"

tracing-subscriber.workspace = true

[dev-dependencies]
console-subscriber = "0.4.0"
Expand All @@ -29,19 +30,18 @@ license = "MPL-2.0"
kuiper_gui = { path = "gui" }
kuiper_lsp = { path = "lsp" }

async-lsp = { version = "0.2", features = ["tokio"] }
dark-light = "1.0"
async-lsp = { version = "0.2", features = ["tracing"] }
iced = { version = "0.13.1", features = ["advanced", "tokio"] }
iced_aw = { version = "0.10", features = ["icons", "tab_bar"], default-features = false }
log = "0.4"
pattern_code = "0.1"
pretty_env_logger = "0.5"
rfd = { version = "0.15", features = ["xdg-portal", "tokio"], default-features = false}
slotmap = "1.0"
snafu = "0.8"
tokio = { version = "1", features = ["fs", "process", "tracing"] }
tokio-util = { version = "0.7", features = ["compat"] }
tower = "0.4"
tracing = "0.1"
tracing-subscriber = "0.3"

[patch.crates-io]
# iced = { git = 'https://github.com/iced-rs/iced.git' }
Expand Down
2 changes: 2 additions & 0 deletions config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[build]
rustflags = ["--cfg", "tracing_unstable"]
30 changes: 17 additions & 13 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
systems = nixpkgs.lib.systems.flakeExposed;

perSystem =
{ lib
, pkgs
, ...
{
lib,
pkgs,
...
}:
{
# Per-system attributes can be defined here. The self' and inputs'
Expand All @@ -27,16 +28,19 @@
# packages = with pkgs; [ rust-analyzer ];

env = {
LD_LIBRARY_PATH = lib.makeLibraryPath (with pkgs; [
libGL
libxkbcommon
vulkan-loader
wayland
xorg.libXcursor
xorg.libXrandr
xorg.libXi
xorg.libX11
]);
LD_LIBRARY_PATH = lib.makeLibraryPath (
with pkgs;
[
libGL
libxkbcommon
vulkan-loader
wayland
xorg.libXcursor
xorg.libXrandr
xorg.libXi
xorg.libX11
]
);
RUST_LOG = "info";
};
};
Expand Down
3 changes: 1 addition & 2 deletions gui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ license.workspace = true
[dependencies]
kuiper_lsp.workspace = true

dark-light.workspace = true
iced.workspace = true
iced_aw.workspace = true
log.workspace = true
pattern_code.workspace = true
rfd.workspace = true
slotmap.workspace = true
snafu.workspace = true
tokio.workspace = true
tracing.workspace = true
46 changes: 27 additions & 19 deletions gui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ mod style;
mod widgets;

use buffer::{Buffer, FileBuffer};
use log::info;
pub use messages::{Button, LanguageServer, Message, PaneGrid, Tab, TextEditor, Widgets};
use widgets::{menu_bar, pane_grid};

use kuiper_lsp::{
client::LSPClient,
commands::{did_open::did_open, initialize, shutdown},
};
use messages::Syncronize;
pub use messages::{Button, LanguageServer, Message, PaneGrid, Tab, TextEditor, Widgets};
use widgets::{menu_bar, pane_grid};

use iced::{
application, exit, font,
Expand All @@ -25,6 +24,7 @@ use iced::{
};
use slotmap::{DefaultKey, SlotMap};
use std::path::PathBuf;
use tracing::{error, info, warn};

pub fn start_gui() -> iced::Result {
application(Kuiper::title, Kuiper::update, Kuiper::view)
Expand Down Expand Up @@ -79,7 +79,7 @@ impl Kuiper {
Message::LanguageServer(lsp) => match lsp {
LanguageServer::Initalize(result) => {
let Ok(server) = result else {
log::error!("Error initializing language server");
error!("Error initializing language server");
return Task::none();
};

Expand All @@ -89,7 +89,14 @@ impl Kuiper {
LanguageServer::Syncronize(sync) => match sync {
messages::Syncronize::DidClose => todo!(),
messages::Syncronize::DidChange => todo!(),
messages::Syncronize::DidOpen => did_open(path, server),
messages::Syncronize::DidOpen(path, server) => {
// TODO too many moves and clones, may jesus help.
return Task::perform(did_open(path.clone(), server.clone()), move |_| {
Message::LanguageServer(LanguageServer::Syncronize(
Syncronize::DidOpen(path.clone(), server.clone()),
))
});
}
},
},
Message::Widgets(widget) => match widget {
Expand Down Expand Up @@ -128,7 +135,7 @@ impl Kuiper {
}
Button::Save => {
let Some(buffer) = self.get_buffer() else {
log::warn!("No file open to save");
warn!("No file open to save");
return Task::none();
};

Expand All @@ -147,7 +154,7 @@ impl Kuiper {
Button::Saved(_) => {}
Button::SaveAs => {
let Some(buffer) = self.get_buffer() else {
log::warn!("No file open to save");
warn!("No file open to save");
return Task::none();
};

Expand All @@ -168,9 +175,10 @@ impl Kuiper {
let mut tasks: Vec<Task<Message>> = Vec::new();

if let Some(client) = &self.lsp_client {
let task = Task::perform(shutdown(client.clone().socket), |_| {
Message::LanguageServer(LanguageServer::Shutdown())
});
let task =
Task::perform(shutdown(client.clone().socket.clone()), |_| {
Message::LanguageServer(LanguageServer::Shutdown())
});
info!("Shutting down lsp");
tasks.push(task);
}
Expand Down Expand Up @@ -239,14 +247,14 @@ impl Kuiper {

match &self.lsp_client {
Some(client) => {
return Task::perform(
synchronize(path, client.clone().socket),
|x| {
Message::LanguageServer(LanguageServer::Syncronize(
x,
))
},
);
// return Task::perform(
// synchronize(path, client.clone().socket),
// |x| {
// Message::LanguageServer(LanguageServer::Syncronize(
// x,
// ))
// },
// );
}
None => {}
}
Expand Down
2 changes: 1 addition & 1 deletion lsp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ license.workspace = true

[dependencies]
async-lsp.workspace = true
log.workspace = true
snafu.workspace = true
tokio.workspace = true
tokio-util.workspace = true
tower.workspace = true
tracing.workspace = true
22 changes: 20 additions & 2 deletions lsp/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
pub use async_lsp::ServerSocket;
use tokio::{
process::{Child, Command},
runtime::Runtime,
};
use tracing::error;

use crate::commands::shutdown;

#[derive(Clone)]
pub struct LSPClient {
process: Child,
pub socket: ServerSocket,
}

impl LSPClient {
pub fn new(socket: ServerSocket) -> Self {
Self { socket }
pub fn new(process: Child, socket: ServerSocket) -> Self {
Self { process, socket }
}
}

impl Drop for LSPClient {
fn drop(&mut self) {
error!("we are dropping");
Runtime::new()
.expect("Create tokio runtime")
.block_on(shutdown(self.socket.clone()));
}
}
19 changes: 11 additions & 8 deletions lsp/src/commands/initialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ use async_lsp::{
tracing::TracingLayer,
LanguageClient, LanguageServer, ResponseError, ServerSocket,
};
use log::{info, trace};
use std::{ops::ControlFlow, path::Path, process::Stdio};
use std::{borrow::Borrow, ops::ControlFlow, path::Path, process::Stdio};
use tokio::{process::Command, sync::oneshot, task::spawn};
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};
use tower::builder::ServiceBuilder;
use tracing::{debug, info, trace};

use crate::client::LSPClient;

const TEST_ROOT: &str = ".";

Expand All @@ -29,7 +31,7 @@ impl LanguageClient for ClientState {
type NotifyResult = ControlFlow<async_lsp::Result<()>>;
}

pub async fn initialize() -> Result<ServerSocket, crate::Error> {
pub async fn initialize() -> Result<LSPClient, crate::Error> {
let root_dir = Path::new(TEST_ROOT)
.canonicalize()
.expect("test root should be valid");
Expand Down Expand Up @@ -58,7 +60,7 @@ pub async fn initialize() -> Result<ServerSocket, crate::Error> {
})
.notification::<PublishDiagnostics>(|_, _| ControlFlow::Continue(()))
.notification::<ShowMessage>(|_, params| {
trace!("Message {:?}: {}", params.typ, params.message);
debug!("Message {:?}: {}", params.typ, params.message);
ControlFlow::Continue(())
})
.event(|_, _: Stop| ControlFlow::Break(Ok(())));
Expand All @@ -70,16 +72,16 @@ pub async fn initialize() -> Result<ServerSocket, crate::Error> {
.service(router)
});

let child = Command::new("rust-analyzer")
let mut child = Command::new("rust-analyzer")
.current_dir(&root_dir)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
// .kill_on_drop(true)
.spawn()
.expect("Failed run rust-analyzer");
let stdout = child.stdout.unwrap().compat();
let stdin = child.stdin.unwrap().compat_write();
let stdout = child.stdout.take().unwrap().compat();
let stdin = child.stdin.take().unwrap().compat_write();

let _mainloop_fut = spawn(async move { mainloop.run_buffered(stdout, stdin).await });

Expand Down Expand Up @@ -131,5 +133,6 @@ pub async fn initialize() -> Result<ServerSocket, crate::Error> {

// Ok((mainloop_fut, child, server))

Ok(server)
let client = LSPClient::new(child, server);
Ok(client)
}
5 changes: 5 additions & 0 deletions lsp/src/commands/shutdown.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use async_lsp::{LanguageServer, ServerSocket};
use snafu::ResultExt;
use tracing::{debug, info};

use crate::{Error, LspSnafu};

struct Stop;

pub async fn shutdown(mut server: ServerSocket) -> Result<(), crate::Error> {
info!("Language Server Protocol Client shutting down.");

server.shutdown(()).await.context(LspSnafu);
server.exit(()).context(LspSnafu);
server.emit(Stop).context(LspSnafu);
// TODO
// mainloop_fut.await.unwrap();

debug!("Language Server Protocol Client shutdown complete.");

Ok(())
}
4 changes: 2 additions & 2 deletions lsp/src/commands/synchronize/did_change.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::LspSnafu;

use async_lsp::{
lsp_types::{DidOpenTextDocumentParams, TextDocumentItem, Url},
lsp_types::{DidChangeTextDocumentParams, DidOpenTextDocumentParams, TextDocumentItem, Url},
LanguageServer, ServerSocket,
};
use snafu::ResultExt;
use std::path::PathBuf;

pub async fn did_change() -> Result<ServerSocket, crate::Error> {
pub async fn did_change(mut server: ServerSocket) -> Result<ServerSocket, crate::Error> {
todo!()
}
2 changes: 1 addition & 1 deletion lsp/src/commands/synchronize/did_close.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ use async_lsp::{
use snafu::ResultExt;
use std::path::PathBuf;

pub async fn did_close() -> Result<ServerSocket, crate::Error> {
pub async fn did_close(mut server: ServerSocket) -> Result<ServerSocket, crate::Error> {
todo!()
}
2 changes: 2 additions & 0 deletions lsp/src/commands/synchronize/did_open.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ pub async fn did_open(
mut server: ServerSocket,
) -> Result<ServerSocket, crate::Error> {
let text = tokio::fs::read_to_string(path.clone()).await.unwrap();
// TODO We already have the text else where in the program,
// so we shouldn't need to re-read it.
let uri = Url::from_file_path(path).unwrap();

match server.did_open(DidOpenTextDocumentParams {
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use kuiper_gui::start_gui;

fn main() {
pretty_env_logger::init();
tracing_subscriber::fmt::init();
// pretty_env_logger::init();

let _ = start_gui();
}

0 comments on commit c6ed96d

Please sign in to comment.