// The CodeChat Editor, a word processor for software developers.
Copyright // (C) 2024-2026 Bryan A. Jones. // // This file is part of the CodeChat Editor. The CodeChat Editor is free // software: you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, either // version 3 of the License, or (at your option) any later version. // // The CodeChat Editor is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more // details. // // You should have received a copy of the GNU General Public License along with // the CodeChat Editor. If not, see // [http://www.gnu.org/licenses](http://www.gnu.org/licenses). //! `vscode.rs` -- Implement server-side functionality for the Visual Studio //! Code IDE //! ======================================================================== // Modules // ------- #[cfg(test)] pub mod tests; // Imports // ------- // // ### Standard library // // None. // // ### Third-party use actix_web::{ App, HttpRequest, HttpResponse, dev::{ServiceFactory, ServiceRequest}, error::{Error, ErrorBadRequest}, get, web, }; use htmlize::{escape_attribute, escape_text}; use indoc::formatdoc; use log::{debug, error}; // ### Local use crate::{ queue_send, translation::{ CreateTranslationQueuesError, CreatedTranslationQueues, create_translation_queues, translation_task, }, webserver::{ EditorMessage, EditorMessageContents, IdeType, RESERVED_MESSAGE_ID, RegisterRoutes, ResultErrTypes, ResultOkTypes, WebAppState, client_websocket, filesystem_endpoint, get_client_framework, get_server_url, html_wrapper, send_response, }, }; // Globals // ------- const VSCODE_PATH_PREFIX: &[&str] = &["vsc", "fs"]; const VSC: &str = "vsc-"; // Code // ---- // // Registers the VSCode IDE's routes with the server's `configure_app` (see // `crate::webserver::RegisterRoutes`). #[derive(Clone)] pub struct VscodeRoutes; impl RegisterRoutes for VscodeRoutes { fn register(&self, app: App) -> App where T: ServiceFactory, { app.service(serve_vscode_fs) .service(vscode_ide_websocket) .service(vscode_client_websocket) .service(vscode_client_framework) } } #[get("/vsc/ws-ide/{connection_id_raw}")] pub async fn vscode_ide_websocket( connection_id_raw: web::Path, req: HttpRequest, body: web::Payload, app_state: WebAppState, ) -> Result { let connection_id_raw = connection_id_raw.to_string(); let connection_id = format!("{VSC}{connection_id_raw}"); let translation_queues = match create_translation_queues(connection_id.clone(), &app_state) { Ok(tq) => tq, Err(err) => match err { CreateTranslationQueuesError::IdInUse(_) => { return Err(ErrorBadRequest(err.to_string())); } CreateTranslationQueuesError::IdeInUse(connection_id_str) => { return client_websocket( connection_id_str, &req, body, app_state.ide_queues.clone(), ); } }, }; vscode_ide_core(connection_id_raw, app_state.clone(), translation_queues); // Move data between the IDE and the processing task via queues. The // websocket connection between the client and the IDE will run in the // endpoint for that connection. client_websocket(connection_id, &req, body, app_state.ide_queues.clone()) } // Given a (random) connection ID produced by the IDE, return a string that // gives a VSCode-specific ID. #[must_use] pub fn connection_id_raw_to_str(connection_id_raw: &str) -> String { format!("{VSC}{connection_id_raw}") } // Create queues, perform the IDE startup sequence, then enter a loop // translating between the IDE and Client. The caller must provide a task to // move data to/from the IDE queues. #[allow(clippy::too_many_lines)] pub fn vscode_ide_core( connection_id_raw: String, app_state: WebAppState, translation_queues: CreatedTranslationQueues, ) { let (mut from_ide_rx, to_ide_tx, from_client_rx, to_client_tx) = ( translation_queues.from_ide_rx, translation_queues.to_ide_tx, translation_queues.from_client_rx, translation_queues.to_client_tx, ); actix_rt::spawn(async move { let app_state_task = app_state.clone(); let mut shutdown_only = true; 'task: { // Get the first message sent by the IDE. let Some(first_message): std::option::Option = from_ide_rx.recv().await else { error!("{}", "IDE websocket received no data."); break 'task; }; // Make sure it's the `Opened` message. let EditorMessageContents::Opened(ide_type) = first_message.message else { let err = ResultErrTypes::UnexpectedMessage(format!("{first_message:#?}")); error!("{err}"); send_response(&to_ide_tx, first_message.id, Err(err)).await; // Send a `Closed` message to shut down the websocket. queue_send!(to_ide_tx.send(EditorMessage { id: RESERVED_MESSAGE_ID, message: EditorMessageContents::Closed}), 'task); break 'task; }; debug!("Received IDE Opened message."); // Ensure the IDE type (VSCode) is correct. if let IdeType::VSCode(is_self_hosted) = ide_type { // Get the address for the server. let port = *app_state_task.port.lock().unwrap(); let address = match get_server_url(port).await { Ok(address) => address, Err(err) => { error!("{err:?}"); break 'task; } }; if is_self_hosted { // Send a response (successful) to the `Opened` message. debug!( "Sending response = OK to IDE Opened message, id {}.", first_message.id ); send_response(&to_ide_tx, first_message.id, Ok(ResultOkTypes::Void)).await; // Send the HTML for the internal browser. The ID of // this message is `RESERVED_MESSAGE_ID`. Escape the // connection ID before embedding it in an HTML // attribute, since it's supplied by whoever connects to // the IDE websocket and could otherwise be used to break // out of the `src` attribute and inject markup. let escaped_connection_id_raw = escape_attribute(connection_id_raw.as_str()); let client_html = formatdoc!( r#" "# ); debug!("Sending ClientHtml message to IDE: {client_html}"); queue_send!(to_ide_tx.send(EditorMessage { id: RESERVED_MESSAGE_ID, message: EditorMessageContents::ClientHtml(client_html) }), 'task); // Wait for the response. let Some(message) = from_ide_rx.recv().await else { error!("{}", "IDE websocket received no data."); break 'task; }; // Make sure it's the `Result` message with no errors. let res = // First, make sure the ID matches. if message.id == RESERVED_MESSAGE_ID { match message.message { EditorMessageContents::Result(message_result) => match message_result { Err(err) => Err(format!("Error in ClientHtml: {err}")), Ok(result_ok) => if let ResultOkTypes::Void = result_ok { Ok(()) } else { Err(format!( "Unexpected Result message with LoadFile contents {result_ok:?}." )) } }, _ => Err(format!("Unexpected message {message:?}")), } } else { Err(format!("Unexpected message ID {}.", message.id)) }; if let Err(err) = res { error!("{err}"); // Send a `Closed` message using the next available // ID (`RESERVED_MESSAGE_ID + 1`). queue_send!(to_ide_tx.send(EditorMessage { id: RESERVED_MESSAGE_ID + 1.0, message: EditorMessageContents::Closed }), 'task); break 'task; } } else { // Open the Client in an external browser. if let Err(err) = webbrowser::open(&format!("{address}/vsc/cf/{connection_id_raw}")) { let err = ResultErrTypes::WebBrowserOpenFailed(err.to_string()); error!("{err:?}"); send_response(&to_ide_tx, first_message.id, Err(err)).await; // Send a `Closed` message; use an ID of // `RESERVED_MESSAGE_ID`, since this is the first // message from the IDE. queue_send!(to_ide_tx.send(EditorMessage{ id: RESERVED_MESSAGE_ID, message: EditorMessageContents::Closed }), 'task); break 'task; } // Send a response (successful) to the `Opened` message. send_response(&to_ide_tx, first_message.id, Ok(ResultOkTypes::Void)).await; } } else { // This is the wrong IDE type. Report the error. let err = ResultErrTypes::InvalidIdeType(ide_type); error!("{err:?}"); send_response(&to_ide_tx, first_message.id, Err(err)).await; // Close the connection, again using the first available ID // of `RESERVED_MESSAGE_ID`. queue_send!(to_ide_tx.send(EditorMessage { id: RESERVED_MESSAGE_ID, message: EditorMessageContents::Closed}), 'task); break 'task; } shutdown_only = false; } translation_task( VSC.to_string(), connection_id_raw, VSCODE_PATH_PREFIX, app_state_task, shutdown_only, true, to_ide_tx, from_ide_rx, to_client_tx, from_client_rx, ) .await; }); } /// Serve the Client Framework. #[get("/vsc/cf/{connection_id}")] pub async fn vscode_client_framework(connection_id: web::Path) -> HttpResponse { HttpResponse::Ok().content_type("text/html").body( // Send the HTML for the internal browser. match get_client_framework(false, "vsc/ws-client", &connection_id) { Ok(web_page) => web_page, Err(html_string) => { error!("{html_string}"); html_wrapper(&escape_text(&html_string)) } }, ) } /// Define a websocket handler for the CodeChat Editor Client. #[get("/vsc/ws-client/{connection_id}")] pub async fn vscode_client_websocket( connection_id: web::Path, req: HttpRequest, body: web::Payload, app_state: WebAppState, ) -> Result { client_websocket( format!("{VSC}{connection_id}"), &req, body, app_state.client_queues.clone(), ) } // Respond to requests for the filesystem. #[get("/vsc/fs/{connection_id}/{file_path:.*}")] async fn serve_vscode_fs( request_path: web::Path<(String, String)>, req: HttpRequest, app_state: WebAppState, ) -> HttpResponse { let (connection_id, file_path) = request_path.into_inner(); filesystem_endpoint(format!("{VSC}{connection_id}"), file_path, &req, &app_state).await }