From a6153a9da6699815d77b455cec52ebeee7090c1d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:30:27 +0000 Subject: [PATCH 1/2] Remove duplicated blocks from the editor and LSP sources and format them Second batch of the files left unformatted because the copy/paste detector rejects them. Each duplicated block becomes a helper; no suppression markers are used. - command_history.hpp: getPreviousCommand / getNextCommand share stepHistory(). - debugger_interface.cpp: one breakpoint lookup instead of four, and one report_step_outcome() for the three step functions. - editor_pane.cpp: makeStoreDocument(). - lsp_editor_bridge.cpp: the six request functions share getConnectedClientForOpenDocument(); documentChanged / documentClosed share lookupOpenDocument(); toEditorLocation() for the two location callbacks. Locks taken and their order are unchanged. - split_view_manager.cpp: createSplit() behind the horizontal and vertical entry points. - syntax_highlighter.cpp: tokenizeWithRules(). - tab_bar.cpp: findTabById / findTabByPath and activateAdjacentTab(). - src/bolt/lsp/lsp_client.cpp: makePositionParams() and parseLocation(). Four headers gain the private declarations for the new members. Three of these files are not part of any build target and did not compile before this change (src/bolt/lsp/lsp_client.cpp, src/bolt/editor/syntax_highlighter.cpp, and command_history.hpp on its own); they show the same errors as before and no new ones. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71 --- include/bolt/editor/command_history.hpp | 45 +- include/bolt/editor/debugger_interface.hpp | 3 + include/bolt/editor/lsp_editor_bridge.hpp | 9 + include/bolt/editor/split_view_manager.hpp | 2 + include/bolt/editor/tab_bar.hpp | 2 + src/bolt/editor/debugger_interface.cpp | 260 +++++---- src/bolt/editor/editor_pane.cpp | 155 +++--- src/bolt/editor/lsp_editor_bridge.cpp | 583 ++++++++++++--------- src/bolt/editor/split_view_manager.cpp | 323 +++++------- src/bolt/editor/syntax_highlighter.cpp | 128 ++--- src/bolt/editor/tab_bar.cpp | 209 ++++---- src/bolt/lsp/lsp_client.cpp | 174 +++--- 12 files changed, 919 insertions(+), 974 deletions(-) diff --git a/include/bolt/editor/command_history.hpp b/include/bolt/editor/command_history.hpp index 7447df09..9af13b3b 100644 --- a/include/bolt/editor/command_history.hpp +++ b/include/bolt/editor/command_history.hpp @@ -1,20 +1,21 @@ -#ifndef COMMAND_HISTORY_HPP -#define COMMAND_HISTORY_HPP +#ifndef BOLT_EDITOR_COMMAND_HISTORY_HPP_ +#define BOLT_EDITOR_COMMAND_HISTORY_HPP_ #include #include + #include "bolt/core/thread_safety.hpp" namespace bolt { class CommandHistory { -private: + private: ThreadSafe> history_; ThreadSafe maxSize_{100}; ThreadSafe currentIndex_{0}; -public: + public: static CommandHistory& getInstance() { static CommandHistory instance; return instance; @@ -34,32 +35,38 @@ class CommandHistory { } std::string getPreviousCommand() { - return history_.read([&](const auto& hist) { - if (hist.empty()) return std::string(); - - size_t idx = currentIndex_.write([&](auto& current) { - if (current > 0) current--; - return current; - }); - - return idx < hist.size() ? hist[idx] : std::string(); + return stepHistory([](size_t& current, size_t) { + if (current > 0) + current--; }); } std::string getNextCommand() { + return stepHistory([](size_t& current, size_t historySize) { + if (current < historySize) + current++; + }); + } + + private: + // Moves currentIndex_ with step(index, history size) and returns the command at the new index, or an empty + // string if there is none. Takes the history_ read lock first, then the currentIndex_ write lock. + template + std::string stepHistory(Step&& step) { return history_.read([&](const auto& hist) { - if (hist.empty()) return std::string(); - + if (hist.empty()) + return std::string(); + size_t idx = currentIndex_.write([&](auto& current) { - if (current < hist.size()) current++; + step(current, hist.size()); return current; }); - + return idx < hist.size() ? hist[idx] : std::string(); }); } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_EDITOR_COMMAND_HISTORY_HPP_ diff --git a/include/bolt/editor/debugger_interface.hpp b/include/bolt/editor/debugger_interface.hpp index 16610ce8..ecdc678d 100644 --- a/include/bolt/editor/debugger_interface.hpp +++ b/include/bolt/editor/debugger_interface.hpp @@ -162,6 +162,9 @@ class DebuggerInterface { std::pair find_line_for_pc(size_t pc) const; std::string evaluate_watch_expression(const std::string& expression); void setup_vm_handlers(); + // Updates state, fires the event and adjusts the line highlight after a step_over/step_into/step_out. + void report_step_outcome(const std::string& breakpoint_message, const std::string& paused_message, + const std::string& completed_message); }; } // namespace bolt diff --git a/include/bolt/editor/lsp_editor_bridge.hpp b/include/bolt/editor/lsp_editor_bridge.hpp index b2760c3e..1fba0f73 100644 --- a/include/bolt/editor/lsp_editor_bridge.hpp +++ b/include/bolt/editor/lsp_editor_bridge.hpp @@ -483,6 +483,15 @@ class LspEditorBridge { void handleDiagnostics(const std::string& uri, std::shared_ptr diagnostics); EditorCompletionItem convertCompletionItem(std::shared_ptr item); EditorDiagnostic convertDiagnostic(std::shared_ptr diagnostic); + + using OpenDocumentIterator = std::map::iterator; + // Takes documentsMutex_, looks up filePath in openDocuments_, stores its language id in languageId and then + // calls visit (if any) on the entry with the lock still held. Returns false if the document is not open. + bool lookupOpenDocument(const std::string& filePath, std::string& languageId, + const std::function& visit = nullptr); + // Returns the connected client for an open document, or nullptr if it is not open or has no connected client. + // Takes and releases documentsMutex_ before the client lookup. + LspClient* getConnectedClientForOpenDocument(const std::string& filePath); }; } // namespace lsp diff --git a/include/bolt/editor/split_view_manager.hpp b/include/bolt/editor/split_view_manager.hpp index 9201e2b2..ea12cef8 100644 --- a/include/bolt/editor/split_view_manager.hpp +++ b/include/bolt/editor/split_view_manager.hpp @@ -115,6 +115,8 @@ class SplitViewManager { // Internal helpers std::string generatePaneId(); + // Shared implementation of createHorizontalSplit / createVerticalSplit. + std::string createSplit(const std::string& sourcePaneId, SplitDirection direction); void notifyPaneOperation(PaneOperation op, const std::string& paneId); bool isValidPaneId(const std::string& paneId) const; void removePaneFromLayout(const std::string& paneId); diff --git a/include/bolt/editor/tab_bar.hpp b/include/bolt/editor/tab_bar.hpp index 0095f668..c105312f 100644 --- a/include/bolt/editor/tab_bar.hpp +++ b/include/bolt/editor/tab_bar.hpp @@ -204,6 +204,8 @@ class TabBar { // Helper to find tab index by ID std::optional findTabIndexById(size_t tabId) const; std::optional findTabIndexByPath(const std::string& filePath) const; + // Shared implementation of activateNextTab (forward) / activatePreviousTab (backward), wrapping around. + void activateAdjacentTab(bool forward); }; } // namespace bolt diff --git a/src/bolt/editor/debugger_interface.cpp b/src/bolt/editor/debugger_interface.cpp index 7f7815ba..80769938 100644 --- a/src/bolt/editor/debugger_interface.cpp +++ b/src/bolt/editor/debugger_interface.cpp @@ -1,21 +1,31 @@ #include "bolt/editor/debugger_interface.hpp" -#include "bolt/editor/integrated_editor.hpp" -#include "bolt/drawkern/dis_vm.hpp" -#include -#include + #include +#include #include +#include + +#include "bolt/drawkern/dis_vm.hpp" +#include "bolt/editor/integrated_editor.hpp" namespace bolt { -DebuggerInterface::DebuggerInterface() - : vm_(std::make_unique()) - , state_(DebugState::STOPPED) - , event_callback_(nullptr) - , editor_(nullptr) - , debug_output_enabled_(true) - , current_debug_line_(0) { - +namespace { + +// Returns an iterator to the breakpoint registered at `pc`, or end() if there is none. +std::vector::iterator find_breakpoint_by_pc(std::vector& breakpoints, size_t pc) { + return std::find_if(breakpoints.begin(), breakpoints.end(), [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); +} + +} // namespace + +DebuggerInterface::DebuggerInterface() + : vm_(std::make_unique()), + state_(DebugState::STOPPED), + event_callback_(nullptr), + editor_(nullptr), + debug_output_enabled_(true), + current_debug_line_(0) { setup_vm_handlers(); } @@ -27,27 +37,27 @@ bool DebuggerInterface::start_debug_session(const drawkern::DISProgram& program) if (state_ != DebugState::STOPPED) { stop_debug_session(); } - + if (!vm_->load_program(program)) { transition_state(DebugState::ERROR, "Failed to load program"); return false; } - + // Restore breakpoints for (const auto& bp : breakpoints_) { if (bp.enabled) { vm_->set_breakpoint(bp.pc); } } - + transition_state(DebugState::PAUSED, "Debug session started"); fire_event(DebugEvent::SESSION_STARTED, "Debugging session initialized"); - + highlight_current_line(); refresh_breakpoint_markers(); - + log_debug_message("Debug session started with " + std::to_string(program.instructions.size()) + " instructions"); - + return true; } @@ -55,27 +65,27 @@ bool DebuggerInterface::start_debug_session_from_source(const std::string& limbo if (state_ != DebugState::STOPPED) { stop_debug_session(); } - + if (!vm_->load_limbo_source(limbo_source)) { transition_state(DebugState::ERROR, "Failed to compile Limbo source"); return false; } - + // Restore breakpoints for (const auto& bp : breakpoints_) { if (bp.enabled) { vm_->set_breakpoint(bp.pc); } } - + transition_state(DebugState::PAUSED, "Debug session started from source"); fire_event(DebugEvent::SESSION_STARTED, "Debugging session initialized from Limbo source"); - + highlight_current_line(); refresh_breakpoint_markers(); - + log_debug_message("Debug session started from Limbo source"); - + return true; } @@ -83,13 +93,13 @@ void DebuggerInterface::stop_debug_session() { if (state_ == DebugState::STOPPED) { return; } - + vm_->halt(); clear_current_line_highlight(); - + transition_state(DebugState::STOPPED, "Debug session stopped"); fire_event(DebugEvent::SESSION_STOPPED, "Debugging session ended"); - + log_debug_message("Debug session stopped"); } @@ -105,11 +115,11 @@ void DebuggerInterface::continue_execution() { if (state_ != DebugState::PAUSED) { return; } - + transition_state(DebugState::RUNNING, "Continuing execution"); - + vm_->continue_execution(); - + if (vm_->is_at_breakpoint()) { transition_state(DebugState::PAUSED, "Breakpoint hit"); fire_event(DebugEvent::BREAKPOINT_HIT, "Execution paused at breakpoint"); @@ -119,31 +129,36 @@ void DebuggerInterface::continue_execution() { fire_event(DebugEvent::EXECUTION_FINISHED, "Program execution completed"); clear_current_line_highlight(); } - + update_watch_expressions(); } -void DebuggerInterface::step_over() { - if (state_ != DebugState::PAUSED) { - return; - } - - size_t old_pc = vm_->get_pc(); - vm_->step_over(); - +void DebuggerInterface::report_step_outcome(const std::string& breakpoint_message, const std::string& paused_message, + const std::string& completed_message) { if (vm_->is_at_breakpoint()) { - transition_state(DebugState::PAUSED, "Breakpoint hit during step"); + transition_state(DebugState::PAUSED, breakpoint_message); fire_event(DebugEvent::BREAKPOINT_HIT, "Execution paused at breakpoint"); } else if (!vm_->is_running()) { transition_state(DebugState::FINISHED, "Execution completed"); fire_event(DebugEvent::EXECUTION_FINISHED, "Program execution completed"); clear_current_line_highlight(); } else { - transition_state(DebugState::PAUSED, "Step completed"); - fire_event(DebugEvent::STEP_COMPLETED, "Step over completed"); + transition_state(DebugState::PAUSED, paused_message); + fire_event(DebugEvent::STEP_COMPLETED, completed_message); highlight_current_line(); } - +} + +void DebuggerInterface::step_over() { + if (state_ != DebugState::PAUSED) { + return; + } + + size_t old_pc = vm_->get_pc(); + vm_->step_over(); + + report_step_outcome("Breakpoint hit during step", "Step completed", "Step over completed"); + update_watch_expressions(); log_debug_message("Step over: PC " + std::to_string(old_pc) + " -> " + std::to_string(vm_->get_pc())); } @@ -152,23 +167,12 @@ void DebuggerInterface::step_into() { if (state_ != DebugState::PAUSED) { return; } - + size_t old_pc = vm_->get_pc(); vm_->step_into(); - - if (vm_->is_at_breakpoint()) { - transition_state(DebugState::PAUSED, "Breakpoint hit during step"); - fire_event(DebugEvent::BREAKPOINT_HIT, "Execution paused at breakpoint"); - } else if (!vm_->is_running()) { - transition_state(DebugState::FINISHED, "Execution completed"); - fire_event(DebugEvent::EXECUTION_FINISHED, "Program execution completed"); - clear_current_line_highlight(); - } else { - transition_state(DebugState::PAUSED, "Step completed"); - fire_event(DebugEvent::STEP_COMPLETED, "Step into completed"); - highlight_current_line(); - } - + + report_step_outcome("Breakpoint hit during step", "Step completed", "Step into completed"); + update_watch_expressions(); log_debug_message("Step into: PC " + std::to_string(old_pc) + " -> " + std::to_string(vm_->get_pc())); } @@ -177,28 +181,17 @@ void DebuggerInterface::step_out() { if (state_ != DebugState::PAUSED) { return; } - + size_t old_pc = vm_->get_pc(); size_t old_depth = vm_->get_call_stack_depth(); - + vm_->step_out(); - - if (vm_->is_at_breakpoint()) { - transition_state(DebugState::PAUSED, "Breakpoint hit during step out"); - fire_event(DebugEvent::BREAKPOINT_HIT, "Execution paused at breakpoint"); - } else if (!vm_->is_running()) { - transition_state(DebugState::FINISHED, "Execution completed"); - fire_event(DebugEvent::EXECUTION_FINISHED, "Program execution completed"); - clear_current_line_highlight(); - } else { - transition_state(DebugState::PAUSED, "Step out completed"); - fire_event(DebugEvent::STEP_COMPLETED, "Step out completed"); - highlight_current_line(); - } - + + report_step_outcome("Breakpoint hit during step out", "Step out completed", "Step out completed"); + update_watch_expressions(); - log_debug_message("Step out: PC " + std::to_string(old_pc) + " -> " + std::to_string(vm_->get_pc()) + - ", depth " + std::to_string(old_depth) + " -> " + std::to_string(vm_->get_call_stack_depth())); + log_debug_message("Step out: PC " + std::to_string(old_pc) + " -> " + std::to_string(vm_->get_pc()) + ", depth " + + std::to_string(old_depth) + " -> " + std::to_string(vm_->get_call_stack_depth())); } void DebuggerInterface::pause_execution() { @@ -214,11 +207,10 @@ bool DebuggerInterface::set_breakpoint(size_t pc) { if (!is_valid_pc(pc)) { return false; } - + // Check if breakpoint already exists - auto it = std::find_if(breakpoints_.begin(), breakpoints_.end(), - [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); - + auto it = find_breakpoint_by_pc(breakpoints_, pc); + if (it != breakpoints_.end()) { // Re-enable existing breakpoint it->enabled = true; @@ -228,19 +220,19 @@ bool DebuggerInterface::set_breakpoint(size_t pc) { log_debug_message("Re-enabled breakpoint at PC " + std::to_string(pc)); return true; } - + // Create new breakpoint auto [file_path, line] = find_line_for_pc(pc); breakpoints_.emplace_back(pc, file_path, line); - + if (is_debugging()) { vm_->set_breakpoint(pc); } - + refresh_breakpoint_markers(); - log_debug_message("Set breakpoint at PC " + std::to_string(pc) + - (file_path.empty() ? "" : " (" + file_path + ":" + std::to_string(line) + ")")); - + log_debug_message("Set breakpoint at PC " + std::to_string(pc) + + (file_path.empty() ? "" : " (" + file_path + ":" + std::to_string(line) + ")")); + return true; } @@ -249,25 +241,24 @@ bool DebuggerInterface::set_breakpoint_at_line(const std::string& file_path, siz if (pc == SIZE_MAX) { return false; } - + return set_breakpoint(pc); } bool DebuggerInterface::remove_breakpoint(size_t pc) { - auto it = std::find_if(breakpoints_.begin(), breakpoints_.end(), - [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); - + auto it = find_breakpoint_by_pc(breakpoints_, pc); + if (it == breakpoints_.end()) { return false; } - + if (is_debugging()) { vm_->remove_breakpoint(pc); } - + breakpoints_.erase(it); refresh_breakpoint_markers(); - + log_debug_message("Removed breakpoint at PC " + std::to_string(pc)); return true; } @@ -277,7 +268,7 @@ bool DebuggerInterface::remove_breakpoint_at_line(const std::string& file_path, if (pc == SIZE_MAX) { return false; } - + return remove_breakpoint(pc); } @@ -285,10 +276,10 @@ void DebuggerInterface::clear_all_breakpoints() { if (is_debugging()) { vm_->clear_all_breakpoints(); } - + breakpoints_.clear(); refresh_breakpoint_markers(); - + log_debug_message("Cleared all breakpoints"); } @@ -301,15 +292,14 @@ bool DebuggerInterface::toggle_breakpoint(size_t pc) { } bool DebuggerInterface::enable_breakpoint(size_t pc, bool enabled) { - auto it = std::find_if(breakpoints_.begin(), breakpoints_.end(), - [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); - + auto it = find_breakpoint_by_pc(breakpoints_, pc); + if (it == breakpoints_.end()) { return false; } - + it->enabled = enabled; - + if (is_debugging()) { if (enabled) { vm_->set_breakpoint(pc); @@ -317,29 +307,28 @@ bool DebuggerInterface::enable_breakpoint(size_t pc, bool enabled) { vm_->remove_breakpoint(pc); } } - + refresh_breakpoint_markers(); log_debug_message((enabled ? "Enabled" : "Disabled") + std::string(" breakpoint at PC ") + std::to_string(pc)); - + return true; } bool DebuggerInterface::set_breakpoint_condition(size_t pc, const std::string& condition) { - auto it = std::find_if(breakpoints_.begin(), breakpoints_.end(), - [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); - + auto it = find_breakpoint_by_pc(breakpoints_, pc); + if (it == breakpoints_.end()) { return false; } - + it->condition = condition; - + if (condition.empty()) { log_debug_message("Removed condition from breakpoint at PC " + std::to_string(pc)); } else { log_debug_message("Set condition for breakpoint at PC " + std::to_string(pc) + ": " + condition); } - + return true; } @@ -349,7 +338,7 @@ std::vector DebuggerInterface::get_all_breakpoints() const { bool DebuggerInterface::has_breakpoint(size_t pc) const { return std::any_of(breakpoints_.begin(), breakpoints_.end(), - [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); + [pc](const BreakpointInfo& bp) { return bp.pc == pc; }); } size_t DebuggerInterface::get_current_pc() const { @@ -451,31 +440,27 @@ std::map DebuggerInterface::get_global_variables() con bool DebuggerInterface::add_watch_expression(const std::string& expression) { // Check if already exists auto it = std::find_if(watch_expressions_.begin(), watch_expressions_.end(), - [&expression](const WatchExpression& we) { - return we.expression == expression; - }); - + [&expression](const WatchExpression& we) { return we.expression == expression; }); + if (it != watch_expressions_.end()) { - return false; // Already exists + return false; // Already exists } - + watch_expressions_.emplace_back(expression); update_watch_expressions(); - + log_debug_message("Added watch expression: " + expression); return true; } bool DebuggerInterface::remove_watch_expression(const std::string& expression) { auto it = std::find_if(watch_expressions_.begin(), watch_expressions_.end(), - [&expression](const WatchExpression& we) { - return we.expression == expression; - }); - + [&expression](const WatchExpression& we) { return we.expression == expression; }); + if (it == watch_expressions_.end()) { return false; } - + watch_expressions_.erase(it); log_debug_message("Removed watch expression: " + expression); return true; @@ -494,7 +479,7 @@ void DebuggerInterface::update_watch_expressions() { for (auto& watch : watch_expressions_) { watch.value = evaluate_watch_expression(watch.expression); watch.valid = !watch.value.empty(); - watch.type = watch.valid ? "string" : "invalid"; // Simplified type detection + watch.type = watch.valid ? "string" : "invalid"; // Simplified type detection } } @@ -516,7 +501,7 @@ void DebuggerInterface::highlight_current_line() { // Clear any previous debug current line highlight if (!current_debug_file_.empty()) { editor_->clearHighlight(current_debug_file_, current_debug_line_, - IntegratedEditor::HighlightType::DebugCurrent); + IntegratedEditor::HighlightType::DebugCurrent); } // Store current debug location @@ -538,7 +523,7 @@ void DebuggerInterface::clear_current_line_highlight() { // Clear the current debug line highlight in the editor if (!current_debug_file_.empty()) { editor_->clearHighlight(current_debug_file_, current_debug_line_, - IntegratedEditor::HighlightType::DebugCurrent); + IntegratedEditor::HighlightType::DebugCurrent); current_debug_file_.clear(); current_debug_line_ = 0; @@ -607,8 +592,8 @@ void DebuggerInterface::clear_debug_log() { void DebuggerInterface::transition_state(DebugState new_state, const std::string& message) { if (state_ != new_state) { state_ = new_state; - log_debug_message("State transition to " + std::to_string(static_cast(new_state)) + - (message.empty() ? "" : ": " + message)); + log_debug_message("State transition to " + std::to_string(static_cast(new_state)) + + (message.empty() ? "" : ": " + message)); } } @@ -652,9 +637,8 @@ void DebuggerInterface::update_breakpoint_mapping() { size_t colon = source_info.rfind(':'); size_t file_end = source_info.rfind(')'); - if (file_start != std::string::npos && colon != std::string::npos && - file_end != std::string::npos && colon > file_start && colon < file_end) { - + if (file_start != std::string::npos && colon != std::string::npos && file_end != std::string::npos && + colon > file_start && colon < file_end) { std::string file_path = source_info.substr(file_start + 1, colon - file_start - 1); std::string line_str = source_info.substr(colon + 1, file_end - colon - 1); @@ -677,9 +661,8 @@ void DebuggerInterface::update_breakpoint_mapping() { } } - log_debug_message("Updated breakpoint mappings: " + - std::to_string(file_line_to_pc_.size()) + " line->PC, " + - std::to_string(pc_to_file_line_.size()) + " PC->line"); + log_debug_message("Updated breakpoint mappings: " + std::to_string(file_line_to_pc_.size()) + " line->PC, " + + std::to_string(pc_to_file_line_.size()) + " PC->line"); } size_t DebuggerInterface::find_pc_for_line(const std::string& file_path, size_t line) const { @@ -695,18 +678,19 @@ std::pair DebuggerInterface::find_line_for_pc(size_t pc) co std::string DebuggerInterface::evaluate_watch_expression(const std::string& expression) { // Basic expression evaluation implementation // This is a simplified version - a full implementation would use a proper parser - + if (!is_debugging()) { return ""; } - + // Check if it's a simple variable name (alphanumeric and underscore only) - if (expression.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") == std::string::npos) { + if (expression.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") == + std::string::npos) { // Try to find variable in VM state // For now, return a descriptive message since VM doesn't expose variable inspection yet return ""; } - + // For complex expressions, return a message return ""; } @@ -767,4 +751,4 @@ void DebuggerInterface::setup_vm_handlers() { log_debug_message("VM handlers initialized"); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/editor_pane.cpp b/src/bolt/editor/editor_pane.cpp index 737a9803..1e97e7e6 100644 --- a/src/bolt/editor/editor_pane.cpp +++ b/src/bolt/editor/editor_pane.cpp @@ -1,16 +1,33 @@ #include "bolt/editor/editor_pane.hpp" -#include "bolt/core/editor_store.hpp" + #include -#include #include +#include + +#include "bolt/core/editor_store.hpp" namespace bolt { -EditorPane::EditorPane(const std::string& paneId) - : paneId_(paneId) - , position_{0, 0, 800, 600} // Default size - , editorStore_(EditorStore::getInstance()) { - +namespace { + +// Builds the editor-store document for a pane from its state and the given content. +EditorDocument makeStoreDocument(const EditorPane::PaneState& state, const std::string& content) { + EditorDocument newDoc; + newDoc.value = content; + newDoc.filePath = state.documentPath; + newDoc.scroll = {static_cast(state.scrollLine), static_cast(state.scrollColumn)}; + newDoc.cursor = {static_cast(state.cursorLine), std::nullopt}; + newDoc.foldingRanges = {}; + return newDoc; +} + +} // namespace + +EditorPane::EditorPane(const std::string& paneId) + : paneId_(paneId), + position_{0, 0, 800, 600} // Default size + , + editorStore_(EditorStore::getInstance()) { state_.documentPath = ""; state_.cursorLine = 0; state_.cursorColumn = 0; @@ -18,7 +35,7 @@ EditorPane::EditorPane(const std::string& paneId) state_.scrollColumn = 0; state_.hasFocus = false; state_.isVisible = true; - + // Initialize minimap initializeMinimap(); } @@ -35,40 +52,39 @@ void EditorPane::openDocument(const std::string& filePath) { if (filePath.empty()) { return; } - + // If we already have this document open, just focus it if (state_.documentPath == filePath) { setFocus(true); return; } - + // Close current document if any if (hasDocument()) { closeDocument(); } - + state_.documentPath = filePath; state_.cursorLine = 0; state_.cursorColumn = 0; state_.scrollLine = 0; state_.scrollColumn = 0; - + // Try to load document content try { std::ifstream file(filePath); if (file.is_open()) { - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); - + // Create editor document for the store EditorDocument doc; doc.value = content; doc.filePath = filePath; doc.scroll = {static_cast(state_.scrollLine), static_cast(state_.scrollColumn)}; doc.cursor = {static_cast(state_.cursorLine), std::nullopt}; - doc.foldingRanges = {}; // Will be populated by folding system - + doc.foldingRanges = {}; // Will be populated by folding system + editorStore_.setDocument(filePath, doc); syncWithEditorStore(); } @@ -77,10 +93,10 @@ void EditorPane::openDocument(const std::string& filePath) { state_.documentPath = filePath; updateDocumentContent(""); } - + // Update minimap with new document updateMinimap(); - + refresh(); } @@ -88,28 +104,28 @@ void EditorPane::closeDocument() { if (!hasDocument()) { return; } - + // Save any pending changes before closing syncWithEditorStore(); - + state_.documentPath = ""; state_.cursorLine = 0; state_.cursorColumn = 0; state_.scrollLine = 0; state_.scrollColumn = 0; - + refresh(); } void EditorPane::setFocus(bool focus) { state_.hasFocus = focus; - + if (focus && hasDocument()) { // When gaining focus, make this document the selected one in the editor store editorStore_.setSelectedFile(state_.documentPath); syncWithEditorStore(); } - + refresh(); } @@ -123,11 +139,11 @@ void EditorPane::setVisible(bool visible) { void EditorPane::setCursorPosition(size_t line, size_t column) { state_.cursorLine = line; state_.cursorColumn = column; - + if (hasDocument() && state_.hasFocus) { syncWithEditorStore(); } - + // Update minimap viewport updateMinimapViewport(); } @@ -140,13 +156,11 @@ void EditorPane::getCursorPosition(size_t& line, size_t& column) const { void EditorPane::setScrollPosition(size_t line, size_t column) { state_.scrollLine = line; state_.scrollColumn = column; - + if (hasDocument() && state_.hasFocus) { - editorStore_.updateScrollPosition(state_.documentPath, - static_cast(line), - static_cast(column)); + editorStore_.updateScrollPosition(state_.documentPath, static_cast(line), static_cast(column)); } - + // Update minimap viewport updateMinimapViewport(); } @@ -160,26 +174,25 @@ std::string EditorPane::getDocumentContent() const { if (!hasDocument()) { return ""; } - + // Try to get content from editor store first auto* doc = editorStore_.getCurrentDocument(); if (doc && doc->filePath == state_.documentPath) { return doc->value; } - + // Fallback: read from file try { std::ifstream file(state_.documentPath); if (file.is_open()) { - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); return content; } } catch (const std::exception&) { // File reading failed } - + return ""; } @@ -187,25 +200,18 @@ void EditorPane::updateDocumentContent(const std::string& content) { if (!hasDocument()) { return; } - + updateEditorStoreDocument(); - + // Update the document in the editor store auto* doc = editorStore_.getCurrentDocument(); if (doc && doc->filePath == state_.documentPath) { doc->value = content; } else { // Create new document if it doesn't exist in store - EditorDocument newDoc; - newDoc.value = content; - newDoc.filePath = state_.documentPath; - newDoc.scroll = {static_cast(state_.scrollLine), static_cast(state_.scrollColumn)}; - newDoc.cursor = {static_cast(state_.cursorLine), std::nullopt}; - newDoc.foldingRanges = {}; - - editorStore_.setDocument(state_.documentPath, newDoc); + editorStore_.setDocument(state_.documentPath, makeStoreDocument(state_, content)); } - + refresh(); } @@ -213,7 +219,7 @@ void EditorPane::render() { if (!state_.isVisible) { return; } - + // Basic rendering logic - in a real implementation this would draw to screen // For now, we just ensure the state is synchronized if (hasDocument() && state_.hasFocus) { @@ -228,7 +234,7 @@ void EditorPane::refresh() { void EditorPane::restoreState(const PaneState& state) { state_ = state; - + if (hasDocument()) { syncWithEditorStore(); refresh(); @@ -239,11 +245,11 @@ void EditorPane::syncWithEditorStore() { if (!hasDocument()) { return; } - + // Ensure the document is selected in the store if this pane has focus if (state_.hasFocus) { editorStore_.setSelectedFile(state_.documentPath); - + // Update cursor position in store auto* doc = editorStore_.getCurrentDocument(); if (doc && doc->filePath == state_.documentPath) { @@ -257,18 +263,11 @@ void EditorPane::updateEditorStoreDocument() { if (!hasDocument()) { return; } - + // Ensure document exists in editor store auto* doc = editorStore_.getCurrentDocument(); if (!doc || doc->filePath != state_.documentPath) { - EditorDocument newDoc; - newDoc.filePath = state_.documentPath; - newDoc.value = getDocumentContent(); - newDoc.scroll = {static_cast(state_.scrollLine), static_cast(state_.scrollColumn)}; - newDoc.cursor = {static_cast(state_.cursorLine), std::nullopt}; - newDoc.foldingRanges = {}; - - editorStore_.setDocument(state_.documentPath, newDoc); + editorStore_.setDocument(state_.documentPath, makeStoreDocument(state_, getDocumentContent())); } } @@ -283,7 +282,7 @@ void EditorPane::updateMinimap() { if (!minimapEnabled_ || !minimap_ || !hasDocument()) { return; } - + auto lines = getDocumentLines(); minimap_->setDocument(state_.documentPath, lines); updateMinimapViewport(); @@ -293,40 +292,40 @@ std::vector EditorPane::renderMinimap() const { if (!minimapEnabled_ || !minimapUI_ || !minimapUI_->isVisible()) { return {}; } - + return minimapUI_->render(); } void EditorPane::initializeMinimap() { // Create minimap with appropriate configuration for pane size Minimap::MinimapConfig config; - config.width = std::min(size_t{60}, static_cast(position_.width / 8)); // Proportional to pane width - config.height = std::min(size_t{30}, static_cast(position_.height / 4)); // Proportional to pane height - + config.width = std::min(size_t{60}, static_cast(position_.width / 8)); // Proportional to pane width + config.height = std::min(size_t{30}, static_cast(position_.height / 4)); // Proportional to pane height + minimap_ = std::make_unique(config); - + // Create UI with configuration MinimapUI::UIConfig uiConfig; uiConfig.showBorder = true; uiConfig.showTitle = true; uiConfig.showScrollIndicator = true; uiConfig.title = "Minimap"; - + minimapUI_ = std::make_unique(*minimap_, uiConfig); - + // Set navigation callback to update pane cursor position minimapUI_->setNavigationCallback([this](size_t line) { setCursorPosition(line, 0); setScrollPosition(line > 10 ? line - 10 : 0, 0); }); - + // Set UI position relative to pane MinimapUI::Position minimapPos; minimapPos.x = position_.x + position_.width - minimapUI_->getRequiredWidth() - 10; minimapPos.y = position_.y + 10; minimapPos.width = minimapUI_->getRequiredWidth(); minimapPos.height = minimapUI_->getRequiredHeight(); - + minimapUI_->setPosition(minimapPos); } @@ -334,16 +333,16 @@ void EditorPane::updateMinimapViewport() { if (!minimap_ || !hasDocument()) { return; } - + auto lines = getDocumentLines(); - size_t visibleLines = position_.height / 20; // Estimate visible lines - + size_t visibleLines = position_.height / 20; // Estimate visible lines + Minimap::ViewportInfo viewport; viewport.startLine = state_.scrollLine; viewport.endLine = std::min(state_.scrollLine + visibleLines, lines.size()); viewport.currentLine = state_.cursorLine; viewport.totalLines = lines.size(); - + minimap_->updateViewport(viewport); } @@ -351,17 +350,17 @@ std::vector EditorPane::getDocumentLines() const { if (!hasDocument()) { return {}; } - + std::string content = getDocumentContent(); std::vector lines; std::istringstream stream(content); std::string line; - + while (std::getline(stream, line)) { lines.push_back(line); } - + return lines; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/lsp_editor_bridge.cpp b/src/bolt/editor/lsp_editor_bridge.cpp index 79c9aa0a..bf35d06d 100644 --- a/src/bolt/editor/lsp_editor_bridge.cpp +++ b/src/bolt/editor/lsp_editor_bridge.cpp @@ -4,12 +4,28 @@ */ #include "bolt/editor/lsp_editor_bridge.hpp" + #include #include namespace bolt { namespace lsp { +namespace { + +// Converts an LSP location into the editor's file path / line / column form. +EditorLocation toEditorLocation(const Location& loc) { + EditorLocation editorLoc; + editorLoc.filePath = LspEditorBridge::uriToPath(loc.uri); + editorLoc.line = loc.range.start.line; + editorLoc.column = loc.range.start.character; + editorLoc.endLine = loc.range.end.line; + editorLoc.endColumn = loc.range.end.character; + return editorLoc; +} + +} // namespace + // Simple LspServerConfigManager implementation void LspServerConfigManager::autoConfigureServers() { // Auto-detection is handled by LspServerConfigs @@ -37,37 +53,38 @@ std::optional LspServerConfigManager::getConfig(const std::stri return std::nullopt; } -LspEditorBridge::LspEditorBridge() - : clientManager_(std::make_unique()) - , configManager_(std::make_unique()) { -} +LspEditorBridge::LspEditorBridge() + : clientManager_(std::make_unique()), + configManager_(std::make_unique()) {} LspEditorBridge::~LspEditorBridge() { shutdown(); } bool LspEditorBridge::initialize() { - if (initialized_) return true; - + if (initialized_) + return true; + // Auto-configure available language servers configManager_->autoConfigureServers(); - + // Get available servers and register them with the client manager auto configs = configManager_->getAllConfigs(); - + for (const auto& [language, config] : configs) { if (configManager_->isServerAvailable(language)) { clientManager_->registerLanguageServer(language, config); } } - + initialized_ = true; return !configs.empty(); } void LspEditorBridge::shutdown() { - if (!initialized_) return; - + if (!initialized_) + return; + // Close all open documents { std::lock_guard lock(documentsMutex_); @@ -81,10 +98,10 @@ void LspEditorBridge::shutdown() { } openDocuments_.clear(); } - + // Shutdown client manager clientManager_->shutdown(); - + initialized_ = false; } @@ -92,12 +109,13 @@ bool LspEditorBridge::isLanguageSupported(const std::string& languageId) const { return configManager_->isServerAvailable(languageId); } -void LspEditorBridge::documentOpened(const std::string& filePath, const std::string& content, +void LspEditorBridge::documentOpened(const std::string& filePath, const std::string& content, const std::string& languageId) { - if (!initialized_) return; - + if (!initialized_) + return; + std::string langId = languageId.empty() ? detectLanguageId(filePath) : languageId; - + // Store document state { std::lock_guard lock(documentsMutex_); @@ -107,7 +125,7 @@ void LspEditorBridge::documentOpened(const std::string& filePath, const std::str state.content = content; openDocuments_[filePath] = state; } - + // Notify LSP client auto* client = getClientForLanguage(langId); if (client) { @@ -118,17 +136,17 @@ void LspEditorBridge::documentOpened(const std::string& filePath, const std::str // Set root path to file's directory config->rootPath = std::filesystem::path(filePath).parent_path().string(); client->connect(*config); - + // Initialize the session client->initialize([](bool success) { // Initialization callback - could log or handle errors }); - + // Wait a bit for initialization std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } - + if (client->isConnected()) { TextDocumentItem doc; doc.uri = pathToUri(filePath); @@ -140,46 +158,65 @@ void LspEditorBridge::documentOpened(const std::string& filePath, const std::str } } +bool LspEditorBridge::lookupOpenDocument(const std::string& filePath, std::string& languageId, + const std::function& visit) { + std::lock_guard lock(documentsMutex_); + auto it = openDocuments_.find(filePath); + if (it == openDocuments_.end()) + return false; + + languageId = it->second.languageId; + if (visit) { + visit(it); + } + return true; +} + +LspClient* LspEditorBridge::getConnectedClientForOpenDocument(const std::string& filePath) { + std::string langId; + if (!lookupOpenDocument(filePath, langId)) + return nullptr; + + auto* client = getClientForLanguage(langId); + if (!client || !client->isConnected()) + return nullptr; + return client; +} + void LspEditorBridge::documentChanged(const std::string& filePath, const std::string& content, int version) { - if (!initialized_) return; - + if (!initialized_) + return; + std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - - it->second.content = content; - it->second.version = version; - langId = it->second.languageId; + if (!lookupOpenDocument(filePath, langId, [&](OpenDocumentIterator it) { + it->second.content = content; + it->second.version = version; + })) { + return; } - + auto* client = getClientForLanguage(langId); if (client && client->isConnected()) { VersionedTextDocumentIdentifier docId; docId.uri = pathToUri(filePath); docId.version = version; - + TextDocumentContentChangeEvent change; change.text = content; - + client->didChangeTextDocument(docId, {change}); } } void LspEditorBridge::documentClosed(const std::string& filePath) { - if (!initialized_) return; - + if (!initialized_) + return; + std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - - langId = it->second.languageId; - openDocuments_.erase(it); + if (!lookupOpenDocument(filePath, langId, [this](OpenDocumentIterator it) { openDocuments_.erase(it); })) { + return; } - + auto* client = getClientForLanguage(langId); if (client && client->isConnected()) { TextDocumentIdentifier docId; @@ -190,29 +227,23 @@ void LspEditorBridge::documentClosed(const std::string& filePath) { void LspEditorBridge::requestCompletion(const std::string& filePath, size_t line, size_t column, const std::string& triggerChar) { - if (!initialized_) return; - - std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - langId = it->second.languageId; - } - - auto* client = getClientForLanguage(langId); - if (!client || !client->isConnected()) return; - + if (!initialized_) + return; + + auto* client = getConnectedClientForOpenDocument(filePath); + if (!client) + return; + completionPending_ = true; - + TextDocumentPositionParams params; params.textDocument.uri = pathToUri(filePath); params.position.line = static_cast(line); params.position.character = static_cast(column); - + client->completion(params, [this](const CompletionList& completions) { std::lock_guard lock(completionMutex_); - + completionState_.items.clear(); for (const auto& item : completions.items) { EditorCompletionItem editorItem; @@ -220,42 +251,94 @@ void LspEditorBridge::requestCompletion(const std::string& filePath, size_t line editorItem.detail = item.detail.value_or(""); editorItem.documentation = item.documentation.value_or(""); editorItem.insertText = item.insertText.value_or(item.label); - + // Convert kind to string int kindValue = item.kind.has_value() ? static_cast(item.kind.value()) : 0; switch (kindValue) { - case 1: editorItem.kind = "text"; break; - case 2: editorItem.kind = "method"; break; - case 3: editorItem.kind = "function"; break; - case 4: editorItem.kind = "constructor"; break; - case 5: editorItem.kind = "field"; break; - case 6: editorItem.kind = "variable"; break; - case 7: editorItem.kind = "class"; break; - case 8: editorItem.kind = "interface"; break; - case 9: editorItem.kind = "module"; break; - case 10: editorItem.kind = "property"; break; - case 11: editorItem.kind = "unit"; break; - case 12: editorItem.kind = "value"; break; - case 13: editorItem.kind = "enum"; break; - case 14: editorItem.kind = "keyword"; break; - case 15: editorItem.kind = "snippet"; break; - case 16: editorItem.kind = "color"; break; - case 17: editorItem.kind = "file"; break; - case 18: editorItem.kind = "reference"; break; - case 19: editorItem.kind = "folder"; break; - case 20: editorItem.kind = "enum_member"; break; - case 21: editorItem.kind = "constant"; break; - case 22: editorItem.kind = "struct"; break; - case 23: editorItem.kind = "event"; break; - case 24: editorItem.kind = "operator"; break; - case 25: editorItem.kind = "type_parameter"; break; - default: editorItem.kind = "unknown"; break; + case 1: + editorItem.kind = "text"; + break; + case 2: + editorItem.kind = "method"; + break; + case 3: + editorItem.kind = "function"; + break; + case 4: + editorItem.kind = "constructor"; + break; + case 5: + editorItem.kind = "field"; + break; + case 6: + editorItem.kind = "variable"; + break; + case 7: + editorItem.kind = "class"; + break; + case 8: + editorItem.kind = "interface"; + break; + case 9: + editorItem.kind = "module"; + break; + case 10: + editorItem.kind = "property"; + break; + case 11: + editorItem.kind = "unit"; + break; + case 12: + editorItem.kind = "value"; + break; + case 13: + editorItem.kind = "enum"; + break; + case 14: + editorItem.kind = "keyword"; + break; + case 15: + editorItem.kind = "snippet"; + break; + case 16: + editorItem.kind = "color"; + break; + case 17: + editorItem.kind = "file"; + break; + case 18: + editorItem.kind = "reference"; + break; + case 19: + editorItem.kind = "folder"; + break; + case 20: + editorItem.kind = "enum_member"; + break; + case 21: + editorItem.kind = "constant"; + break; + case 22: + editorItem.kind = "struct"; + break; + case 23: + editorItem.kind = "event"; + break; + case 24: + editorItem.kind = "operator"; + break; + case 25: + editorItem.kind = "type_parameter"; + break; + default: + editorItem.kind = "unknown"; + break; } - + editorItem.sortOrder = 0; // Default sort order completionState_.items.push_back(editorItem); } - + completionState_.isVisible = !completionState_.items.empty(); completionState_.selectedIndex = 0; completionState_.lastRequestTime = std::chrono::steady_clock::now(); @@ -265,11 +348,11 @@ void LspEditorBridge::requestCompletion(const std::string& filePath, size_t line std::string LspEditorBridge::acceptCompletion() { std::lock_guard lock(completionMutex_); - + if (!completionState_.isVisible || completionState_.items.empty()) { return ""; } - + std::string insertText = completionState_.items[completionState_.selectedIndex].insertText; dismissCompletion(); return insertText; @@ -292,45 +375,39 @@ void LspEditorBridge::selectNextCompletion() { void LspEditorBridge::selectPreviousCompletion() { std::lock_guard lock(completionMutex_); if (!completionState_.items.empty()) { - completionState_.selectedIndex = (completionState_.selectedIndex + completionState_.items.size() - 1) - % completionState_.items.size(); + completionState_.selectedIndex = + (completionState_.selectedIndex + completionState_.items.size() - 1) % completionState_.items.size(); } } void LspEditorBridge::requestHover(const std::string& filePath, size_t line, size_t column) { - if (!initialized_) return; - - std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - langId = it->second.languageId; - } - - auto* client = getClientForLanguage(langId); - if (!client || !client->isConnected()) return; - + if (!initialized_) + return; + + auto* client = getConnectedClientForOpenDocument(filePath); + if (!client) + return; + hoverPending_ = true; - + TextDocumentPositionParams params; params.textDocument.uri = pathToUri(filePath); params.position.line = static_cast(line); params.position.character = static_cast(column); - + client->hover(params, [this](const std::optional& hover) { std::lock_guard lock(hoverMutex_); - + if (hover.has_value() && !hover->contents.empty()) { hoverState_.info.content = hover->contents; - hoverState_.info.language = ""; // Could parse from markdown code blocks - hoverState_.info.hasRange = false; // Simplified + hoverState_.info.language = ""; // Could parse from markdown code blocks + hoverState_.info.hasRange = false; // Simplified hoverState_.isVisible = true; hoverState_.showTime = std::chrono::steady_clock::now(); } else { hoverState_.isVisible = false; } - + hoverPending_ = false; }); } @@ -360,13 +437,13 @@ size_t LspEditorBridge::getDiagnosticCount(const std::string& filePath) const { size_t LspEditorBridge::getErrorCount(const std::string& filePath) const { auto diagnostics = getDiagnostics(filePath); return std::count_if(diagnostics.begin(), diagnostics.end(), - [](const EditorDiagnostic& d) { return d.severity == DiagnosticSeverity::Error; }); + [](const EditorDiagnostic& d) { return d.severity == DiagnosticSeverity::Error; }); } size_t LspEditorBridge::getWarningCount(const std::string& filePath) const { auto diagnostics = getDiagnostics(filePath); return std::count_if(diagnostics.begin(), diagnostics.end(), - [](const EditorDiagnostic& d) { return d.severity == DiagnosticSeverity::Warning; }); + [](const EditorDiagnostic& d) { return d.severity == DiagnosticSeverity::Warning; }); } std::string LspEditorBridge::pathToUri(const std::string& path) { @@ -383,12 +460,12 @@ std::string LspEditorBridge::uriToPath(const std::string& uri) { std::string LspEditorBridge::detectLanguageId(const std::string& filePath) { std::filesystem::path p(filePath); std::string ext = p.extension().string(); - + // Convert to lowercase std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - - if (ext == ".cpp" || ext == ".cxx" || ext == ".cc" || ext == ".c++" || - ext == ".hpp" || ext == ".hxx" || ext == ".hh" || ext == ".h") { + + if (ext == ".cpp" || ext == ".cxx" || ext == ".cc" || ext == ".c++" || ext == ".hpp" || ext == ".hxx" || + ext == ".hh" || ext == ".h") { return "cpp"; } else if (ext == ".c") { return "c"; @@ -415,14 +492,14 @@ std::string LspEditorBridge::detectLanguageId(const std::string& filePath) { } else if (ext == ".md" || ext == ".markdown") { return "markdown"; } - + return "plaintext"; } void LspEditorBridge::update() { // Process any pending responses or state updates // This is called each frame from the main loop - + // Auto-hide hover after timeout { std::lock_guard lock(hoverMutex_); @@ -449,9 +526,9 @@ void LspEditorBridge::handleHoverResponse(std::shared_ptr result) { void LspEditorBridge::handleDiagnostics(const std::string& uri, std::shared_ptr diagnostics) { std::string filePath = uriToPath(uri); - + std::vector editorDiagnostics; - + if (diagnostics && diagnostics->getType() == JsonValue::Array) { for (size_t i = 0; i < diagnostics->getArraySize(); ++i) { auto diag = diagnostics->getArrayElement(i); @@ -460,7 +537,7 @@ void LspEditorBridge::handleDiagnostics(const std::string& uri, std::shared_ptr< } } } - + { std::lock_guard lock(documentsMutex_); auto it = openDocuments_.find(filePath); @@ -468,7 +545,7 @@ void LspEditorBridge::handleDiagnostics(const std::string& uri, std::shared_ptr< it->second.diagnostics = editorDiagnostics; } } - + if (diagnosticsCallback_) { diagnosticsCallback_(uri, editorDiagnostics); } @@ -476,73 +553,77 @@ void LspEditorBridge::handleDiagnostics(const std::string& uri, std::shared_ptr< EditorCompletionItem LspEditorBridge::convertCompletionItem(std::shared_ptr item) { EditorCompletionItem result; - + if (!item || item->getType() != JsonValue::Object) { return result; } - + auto label = item->getProperty("label"); if (label && label->getType() == JsonValue::String) { result.label = label->asString(); } - + auto detail = item->getProperty("detail"); if (detail && detail->getType() == JsonValue::String) { result.detail = detail->asString(); } - + auto insertText = item->getProperty("insertText"); if (insertText && insertText->getType() == JsonValue::String) { result.insertText = insertText->asString(); } else { result.insertText = result.label; } - + return result; } EditorDiagnostic LspEditorBridge::convertDiagnostic(std::shared_ptr diagnostic) { EditorDiagnostic result; - + if (!diagnostic || diagnostic->getType() != JsonValue::Object) { return result; } - + auto range = diagnostic->getProperty("range"); if (range && range->getType() == JsonValue::Object) { auto start = range->getProperty("start"); auto end = range->getProperty("end"); - + if (start && start->getType() == JsonValue::Object) { auto line = start->getProperty("line"); auto character = start->getProperty("character"); - if (line) result.startLine = static_cast(line->asNumber()); - if (character) result.startColumn = static_cast(character->asNumber()); + if (line) + result.startLine = static_cast(line->asNumber()); + if (character) + result.startColumn = static_cast(character->asNumber()); } - + if (end && end->getType() == JsonValue::Object) { auto line = end->getProperty("line"); auto character = end->getProperty("character"); - if (line) result.endLine = static_cast(line->asNumber()); - if (character) result.endColumn = static_cast(character->asNumber()); + if (line) + result.endLine = static_cast(line->asNumber()); + if (character) + result.endColumn = static_cast(character->asNumber()); } } - + auto severity = diagnostic->getProperty("severity"); if (severity && severity->getType() == JsonValue::Number) { result.severity = static_cast(static_cast(severity->asNumber())); } - + auto message = diagnostic->getProperty("message"); if (message && message->getType() == JsonValue::String) { result.message = message->asString(); } - + auto source = diagnostic->getProperty("source"); if (source && source->getType() == JsonValue::String) { result.source = source->asString(); } - + return result; } @@ -551,40 +632,28 @@ EditorDiagnostic LspEditorBridge::convertDiagnostic(std::shared_ptr d // ============================================================================ void LspEditorBridge::requestDefinition(const std::string& filePath, size_t line, size_t column) { - if (!initialized_) return; - - std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - langId = it->second.languageId; - } - - auto* client = getClientForLanguage(langId); - if (!client || !client->isConnected()) return; - + if (!initialized_) + return; + + auto* client = getConnectedClientForOpenDocument(filePath); + if (!client) + return; + definitionPending_ = true; - + TextDocumentPositionParams params; params.textDocument.uri = pathToUri(filePath); params.position.line = line; params.position.character = column; - + client->definition(params, [this](const std::vector& locations) { std::lock_guard lock(definitionMutex_); - + definitionState_.locations.clear(); for (const auto& loc : locations) { - EditorLocation editorLoc; - editorLoc.filePath = uriToPath(loc.uri); - editorLoc.line = loc.range.start.line; - editorLoc.column = loc.range.start.character; - editorLoc.endLine = loc.range.end.line; - editorLoc.endColumn = loc.range.end.character; - definitionState_.locations.push_back(editorLoc); + definitionState_.locations.push_back(toEditorLocation(loc)); } - + definitionState_.isVisible = !definitionState_.locations.empty(); definitionState_.selectedIndex = 0; definitionState_.requestType = "definition"; @@ -594,11 +663,11 @@ void LspEditorBridge::requestDefinition(const std::string& filePath, size_t line std::optional LspEditorBridge::acceptDefinition() { std::lock_guard lock(definitionMutex_); - + if (!definitionState_.isVisible || definitionState_.locations.empty()) { return std::nullopt; } - + EditorLocation result = definitionState_.locations[definitionState_.selectedIndex]; dismissDefinition(); return result; @@ -616,40 +685,28 @@ void LspEditorBridge::dismissDefinition() { // ============================================================================ void LspEditorBridge::requestReferences(const std::string& filePath, size_t line, size_t column) { - if (!initialized_) return; - - std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - langId = it->second.languageId; - } - - auto* client = getClientForLanguage(langId); - if (!client || !client->isConnected()) return; - + if (!initialized_) + return; + + auto* client = getConnectedClientForOpenDocument(filePath); + if (!client) + return; + referencesPending_ = true; - + TextDocumentPositionParams params; params.textDocument.uri = pathToUri(filePath); params.position.line = line; params.position.character = column; - + client->references(params, [this](const std::vector& locations) { std::lock_guard lock(referencesMutex_); - + referencesState_.locations.clear(); for (const auto& loc : locations) { - EditorLocation editorLoc; - editorLoc.filePath = uriToPath(loc.uri); - editorLoc.line = loc.range.start.line; - editorLoc.column = loc.range.start.character; - editorLoc.endLine = loc.range.end.line; - editorLoc.endColumn = loc.range.end.character; - referencesState_.locations.push_back(editorLoc); + referencesState_.locations.push_back(toEditorLocation(loc)); } - + referencesState_.isVisible = !referencesState_.locations.empty(); referencesState_.selectedIndex = 0; referencesState_.requestType = "references"; @@ -659,11 +716,11 @@ void LspEditorBridge::requestReferences(const std::string& filePath, size_t line std::optional LspEditorBridge::acceptReference() { std::lock_guard lock(referencesMutex_); - + if (!referencesState_.isVisible || referencesState_.locations.empty()) { return std::nullopt; } - + EditorLocation result = referencesState_.locations[referencesState_.selectedIndex]; dismissReferences(); return result; @@ -682,25 +739,44 @@ void LspEditorBridge::dismissReferences() { static std::string symbolKindToString(SymbolKind kind) { switch (kind) { - case SymbolKind::File: return "file"; - case SymbolKind::Module: return "module"; - case SymbolKind::Namespace: return "namespace"; - case SymbolKind::Package: return "package"; - case SymbolKind::Class: return "class"; - case SymbolKind::Method: return "method"; - case SymbolKind::Property: return "property"; - case SymbolKind::Field: return "field"; - case SymbolKind::Constructor: return "constructor"; - case SymbolKind::Enum: return "enum"; - case SymbolKind::Interface: return "interface"; - case SymbolKind::Function: return "function"; - case SymbolKind::Variable: return "variable"; - case SymbolKind::Constant: return "constant"; - case SymbolKind::String: return "string"; - case SymbolKind::Number: return "number"; - case SymbolKind::Boolean: return "boolean"; - case SymbolKind::Array: return "array"; - default: return "unknown"; + case SymbolKind::File: + return "file"; + case SymbolKind::Module: + return "module"; + case SymbolKind::Namespace: + return "namespace"; + case SymbolKind::Package: + return "package"; + case SymbolKind::Class: + return "class"; + case SymbolKind::Method: + return "method"; + case SymbolKind::Property: + return "property"; + case SymbolKind::Field: + return "field"; + case SymbolKind::Constructor: + return "constructor"; + case SymbolKind::Enum: + return "enum"; + case SymbolKind::Interface: + return "interface"; + case SymbolKind::Function: + return "function"; + case SymbolKind::Variable: + return "variable"; + case SymbolKind::Constant: + return "constant"; + case SymbolKind::String: + return "string"; + case SymbolKind::Number: + return "number"; + case SymbolKind::Boolean: + return "boolean"; + case SymbolKind::Array: + return "array"; + default: + return "unknown"; } } @@ -713,45 +789,39 @@ static EditorSymbol convertDocumentSymbol(const DocumentSymbol& sym) { result.column = sym.selectionRange.start.character; result.endLine = sym.range.end.line; result.endColumn = sym.range.end.character; - + for (const auto& child : sym.children) { result.children.push_back(convertDocumentSymbol(child)); } - + return result; } void LspEditorBridge::requestDocumentSymbols(const std::string& filePath) { - if (!initialized_) return; - - std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - langId = it->second.languageId; - } - - auto* client = getClientForLanguage(langId); - if (!client || !client->isConnected()) return; - + if (!initialized_) + return; + + auto* client = getConnectedClientForOpenDocument(filePath); + if (!client) + return; + symbolsPending_ = true; - + TextDocumentIdentifier docId; docId.uri = pathToUri(filePath); - + client->documentSymbol(docId, [this](const std::vector& symbols) { std::lock_guard lock(symbolsMutex_); - + allSymbols_.clear(); symbolOutlineState_.symbols.clear(); - + for (const auto& sym : symbols) { EditorSymbol editorSym = convertDocumentSymbol(sym); allSymbols_.push_back(editorSym); symbolOutlineState_.symbols.push_back(editorSym); } - + symbolOutlineState_.isVisible = !symbolOutlineState_.symbols.empty(); symbolOutlineState_.selectedIndex = 0; symbolOutlineState_.filterText = ""; @@ -761,11 +831,11 @@ void LspEditorBridge::requestDocumentSymbols(const std::string& filePath) { std::optional LspEditorBridge::acceptSymbol() { std::lock_guard lock(symbolsMutex_); - + if (!symbolOutlineState_.isVisible || symbolOutlineState_.symbols.empty()) { return std::nullopt; } - + const auto& sym = symbolOutlineState_.symbols[symbolOutlineState_.selectedIndex]; EditorLocation result; result.filePath = ""; // Same file @@ -773,7 +843,7 @@ std::optional LspEditorBridge::acceptSymbol() { result.column = sym.column; result.endLine = sym.endLine; result.endColumn = sym.endColumn; - + dismissSymbolOutline(); return result; } @@ -795,8 +865,7 @@ static bool symbolMatchesFilter(const EditorSymbol& sym, const std::string& filt return lowerName.find(lowerFilter) != std::string::npos; } -static void collectMatchingSymbols(const std::vector& symbols, - const std::string& filter, +static void collectMatchingSymbols(const std::vector& symbols, const std::string& filter, std::vector& result) { for (const auto& sym : symbols) { if (symbolMatchesFilter(sym, filter)) { @@ -809,10 +878,10 @@ static void collectMatchingSymbols(const std::vector& symbols, void LspEditorBridge::filterSymbols(const std::string& filter) { std::lock_guard lock(symbolsMutex_); - + symbolOutlineState_.filterText = filter; symbolOutlineState_.symbols.clear(); - + if (filter.empty()) { // Show all symbols symbolOutlineState_.symbols = allSymbols_; @@ -820,7 +889,7 @@ void LspEditorBridge::filterSymbols(const std::string& filter) { // Filter symbols collectMatchingSymbols(allSymbols_, filter, symbolOutlineState_.symbols); } - + symbolOutlineState_.selectedIndex = 0; } @@ -829,31 +898,25 @@ void LspEditorBridge::filterSymbols(const std::string& filter) { // ============================================================================ void LspEditorBridge::requestFormatting(const std::string& filePath, size_t tabSize, bool insertSpaces) { - if (!initialized_) return; - - std::string langId; - { - std::lock_guard lock(documentsMutex_); - auto it = openDocuments_.find(filePath); - if (it == openDocuments_.end()) return; - langId = it->second.languageId; - } - - auto* client = getClientForLanguage(langId); - if (!client || !client->isConnected()) return; - + if (!initialized_) + return; + + auto* client = getConnectedClientForOpenDocument(filePath); + if (!client) + return; + formattingPending_ = true; - + TextDocumentIdentifier docId; docId.uri = pathToUri(filePath); - + FormattingOptions options; options.tabSize = tabSize; options.insertSpaces = insertSpaces; - + client->formatting(docId, options, [this](const std::vector& edits) { std::lock_guard lock(formattingMutex_); - + formattingEdits_.clear(); for (const auto& edit : edits) { EditorTextEdit editorEdit; @@ -864,7 +927,7 @@ void LspEditorBridge::requestFormatting(const std::string& filePath, size_t tabS editorEdit.newText = edit.newText; formattingEdits_.push_back(editorEdit); } - + formattingPending_ = false; }); } @@ -876,5 +939,5 @@ std::vector LspEditorBridge::getFormattingEdits() { return result; } -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/editor/split_view_manager.cpp b/src/bolt/editor/split_view_manager.cpp index 1acecd8c..58bc2f87 100644 --- a/src/bolt/editor/split_view_manager.cpp +++ b/src/bolt/editor/split_view_manager.cpp @@ -1,163 +1,114 @@ #include "bolt/editor/split_view_manager.hpp" + #include -#include #include +#include namespace bolt { SplitViewManager::SplitViewManager() { // Create initial default pane std::string initialPaneId = createPane(); - activePaneId_.write([&](std::string& activeId) { - activeId = initialPaneId; - }); + activePaneId_.write([&](std::string& activeId) { activeId = initialPaneId; }); } std::string SplitViewManager::createHorizontalSplit(const std::string& sourcePaneId) { - std::string sourceId = sourcePaneId.empty() ? getActivePaneId() : sourcePaneId; - - std::string newPaneId; - EditorPane::PanePosition newPanePosition; - - newPaneId = withPanes([&](auto& panes) -> std::string { - auto it = panes.find(sourceId); - if (it == panes.end()) { - return ""; // Source pane not found - } - - EditorPane* sourcePane = it->second.get(); - EditorPane::PanePosition sourcePos = sourcePane->getPosition(); - - // Calculate new positions for horizontal split (left/right) - EditorPane::PanePosition leftPos = sourcePos; - leftPos.width = sourcePos.width / 2; - - EditorPane::PanePosition rightPos = sourcePos; - rightPos.x = sourcePos.x + leftPos.width; - rightPos.width = sourcePos.width - leftPos.width; - - // Validate sizes - if (!validatePaneSize(leftPos.width, leftPos.height) || - !validatePaneSize(rightPos.width, rightPos.height)) { - return ""; // Split would create too small panes - } - - // Update source pane position - sourcePane->setPosition(leftPos); - - // Create new pane - std::string newPaneIdLocal = generatePaneId(); - auto newPane = std::make_unique(newPaneIdLocal); - newPane->setPosition(rightPos); - - // Copy document from source if it has one - if (sourcePane->hasDocument()) { - newPane->openDocument(sourcePane->getDocumentPath()); - } - - panes[newPaneIdLocal] = std::move(newPane); - - // Store position for later use - newPanePosition = rightPos; - - return newPaneIdLocal; - }); - - if (!newPaneId.empty()) { - // Update layout and focus outside of withPanes to avoid deadlock - addPaneToLayout(newPaneId, newPanePosition); - focusPane(newPaneId); - notifyPaneOperation(PaneOperation::Create, newPaneId); - } - - return newPaneId; + return createSplit(sourcePaneId, SplitDirection::Horizontal); } std::string SplitViewManager::createVerticalSplit(const std::string& sourcePaneId) { + return createSplit(sourcePaneId, SplitDirection::Vertical); +} + +std::string SplitViewManager::createSplit(const std::string& sourcePaneId, SplitDirection direction) { std::string sourceId = sourcePaneId.empty() ? getActivePaneId() : sourcePaneId; - + std::string newPaneId; EditorPane::PanePosition newPanePosition; - + newPaneId = withPanes([&](auto& panes) -> std::string { auto it = panes.find(sourceId); if (it == panes.end()) { return ""; // Source pane not found } - + EditorPane* sourcePane = it->second.get(); EditorPane::PanePosition sourcePos = sourcePane->getPosition(); - - // Calculate new positions for vertical split (top/bottom) - EditorPane::PanePosition topPos = sourcePos; - topPos.height = sourcePos.height / 2; - - EditorPane::PanePosition bottomPos = sourcePos; - bottomPos.y = sourcePos.y + topPos.height; - bottomPos.height = sourcePos.height - topPos.height; - + + // Calculate new positions: the source pane keeps the first half (left or top), + // the new pane gets the second half (right or bottom) + EditorPane::PanePosition firstPos = sourcePos; + EditorPane::PanePosition secondPos = sourcePos; + if (direction == SplitDirection::Horizontal) { + firstPos.width = sourcePos.width / 2; + secondPos.x = sourcePos.x + firstPos.width; + secondPos.width = sourcePos.width - firstPos.width; + } else { + firstPos.height = sourcePos.height / 2; + secondPos.y = sourcePos.y + firstPos.height; + secondPos.height = sourcePos.height - firstPos.height; + } + // Validate sizes - if (!validatePaneSize(topPos.width, topPos.height) || - !validatePaneSize(bottomPos.width, bottomPos.height)) { + if (!validatePaneSize(firstPos.width, firstPos.height) || + !validatePaneSize(secondPos.width, secondPos.height)) { return ""; // Split would create too small panes } - + // Update source pane position - sourcePane->setPosition(topPos); - + sourcePane->setPosition(firstPos); + // Create new pane std::string newPaneIdLocal = generatePaneId(); auto newPane = std::make_unique(newPaneIdLocal); - newPane->setPosition(bottomPos); - + newPane->setPosition(secondPos); + // Copy document from source if it has one if (sourcePane->hasDocument()) { newPane->openDocument(sourcePane->getDocumentPath()); } - + panes[newPaneIdLocal] = std::move(newPane); - + // Store position for later use - newPanePosition = bottomPos; - + newPanePosition = secondPos; + return newPaneIdLocal; }); - + if (!newPaneId.empty()) { // Update layout and focus outside of withPanes to avoid deadlock addPaneToLayout(newPaneId, newPanePosition); focusPane(newPaneId); notifyPaneOperation(PaneOperation::Create, newPaneId); } - + return newPaneId; } bool SplitViewManager::closePane(const std::string& paneId) { // Check validity first (avoid nested lock in withPanes) - bool paneExists = withPanes([&](const auto& panes) -> bool { - return panes.find(paneId) != panes.end(); - }); - + bool paneExists = withPanes([&](const auto& panes) -> bool { return panes.find(paneId) != panes.end(); }); + if (!paneExists) { return false; } - + // Get active pane ID outside of the withPanes call to avoid deadlock std::string activeId = getActivePaneId(); std::string newActivePaneId; - + bool success = withPanes([&](auto& panes) -> bool { // Don't allow closing the last pane if (panes.size() <= 1) { return false; } - + auto it = panes.find(paneId); if (it == panes.end()) { return false; } - + // If closing the active pane, find next available pane if (activeId == paneId) { for (const auto& pair : panes) { @@ -167,41 +118,41 @@ bool SplitViewManager::closePane(const std::string& paneId) { } } } - + // Remove the pane panes.erase(it); - + return true; }); - + if (success) { // Update focus if needed (outside of panes lock) if (!newActivePaneId.empty()) { focusPane(newActivePaneId); } - + // Remove from layout removePaneFromLayout(paneId); - + // Redistribute remaining panes redistributeLayout(); - + notifyPaneOperation(PaneOperation::Close, paneId); } - + return success; } bool SplitViewManager::focusPane(const std::string& paneId) { // Get current active pane ID outside of the withPanes call to avoid deadlock std::string oldActiveId = getActivePaneId(); - + bool success = withPanes([&](auto& panes) -> bool { auto it = panes.find(paneId); if (it == panes.end()) { return false; } - + // Remove focus from current active pane if (!oldActiveId.empty() && oldActiveId != paneId) { auto oldIt = panes.find(oldActiveId); @@ -209,46 +160,44 @@ bool SplitViewManager::focusPane(const std::string& paneId) { oldIt->second->setFocus(false); } } - + // Set focus to new pane it->second->setFocus(true); - + return true; }); - + if (success) { // Update active pane ID outside of the panes lock - activePaneId_.write([&](std::string& activeId) { - activeId = paneId; - }); - + activePaneId_.write([&](std::string& activeId) { activeId = paneId; }); + notifyPaneOperation(PaneOperation::Focus, paneId); } - + return success; } std::string SplitViewManager::createPane() { std::string paneId = generatePaneId(); - + auto updatePanes = [&](std::map>& panes) { auto newPane = std::make_unique(paneId); - + // Set default position based on existing panes EditorPane::PanePosition pos{0, 0, 800, 600}; if (!panes.empty()) { // Position new pane relative to existing ones pos = calculateSplitPosition(pos, SplitDirection::Horizontal); } - + newPane->setPosition(pos); panes[paneId] = std::move(newPane); - + addPaneToLayout(paneId, pos); }; - + panes_.write(updatePanes); - + notifyPaneOperation(PaneOperation::Create, paneId); return paneId; } @@ -278,9 +227,7 @@ const EditorPane* SplitViewManager::getActivePane() const { } std::string SplitViewManager::getActivePaneId() const { - return activePaneId_.read([](const std::string& activeId) { - return activeId; - }); + return activePaneId_.read([](const std::string& activeId) { return activeId; }); } void SplitViewManager::setContainerSize(int width, int height) { @@ -306,7 +253,7 @@ void SplitViewManager::resizePane(const std::string& paneId, int width, int heig pos.height = height; enforceSizeConstraints(pos); it->second->setPosition(pos); - + notifyPaneOperation(PaneOperation::Resize, paneId); } }); @@ -317,15 +264,15 @@ void SplitViewManager::redistributeLayout() { if (panes.empty()) { return; } - + // Simple redistribution: arrange panes in a grid size_t paneCount = panes.size(); int cols = static_cast(std::ceil(std::sqrt(paneCount))); int rows = static_cast(std::ceil(static_cast(paneCount) / cols)); - + int containerWidth = 800; // Default container size int containerHeight = 600; - + // Get container size from first pane if available if (!panes.empty()) { const auto& firstPane = panes.begin()->second; @@ -333,22 +280,17 @@ void SplitViewManager::redistributeLayout() { containerWidth = pos.width * cols; containerHeight = pos.height * rows; } - + int paneWidth = containerWidth / cols; int paneHeight = containerHeight / rows; - + int index = 0; for (auto& pair : panes) { int col = index % cols; int row = index / cols; - - EditorPane::PanePosition pos{ - col * paneWidth, - row * paneHeight, - paneWidth, - paneHeight - }; - + + EditorPane::PanePosition pos{col * paneWidth, row * paneHeight, paneWidth, paneHeight}; + enforceSizeConstraints(pos); pair.second->setPosition(pos); index++; @@ -368,9 +310,7 @@ std::vector SplitViewManager::getAllPaneIds() const { } size_t SplitViewManager::getPaneCount() const { - return withPanes([](const auto& panes) -> size_t { - return panes.size(); - }); + return withPanes([](const auto& panes) -> size_t { return panes.size(); }); } void SplitViewManager::openDocumentInPane(const std::string& paneId, const std::string& filePath) { @@ -382,7 +322,7 @@ void SplitViewManager::openDocumentInPane(const std::string& paneId, const std:: } return false; }); - + if (success) { // Focus the pane with the new document (outside of withPanes to avoid deadlock) focusPane(paneId); @@ -396,7 +336,7 @@ void SplitViewManager::openDocumentInNewPane(const std::string& filePath, SplitD } else { newPaneId = createVerticalSplit(); } - + if (!newPaneId.empty()) { openDocumentInPane(newPaneId, filePath); } @@ -430,10 +370,8 @@ bool SplitViewManager::isEnabled() const { } void SplitViewManager::setEnabled(bool enabled) { - isEnabled_.write([enabled](bool& currentEnabled) { - currentEnabled = enabled; - }); - + isEnabled_.write([enabled](bool& currentEnabled) { currentEnabled = enabled; }); + if (!enabled) { collapseAllSplits(); } @@ -448,13 +386,13 @@ void SplitViewManager::collapseAllSplits() { if (panes.size() <= 1) { return; } - + // Keep only the active pane std::string activeId = getActivePaneId(); if (activeId.empty() && !panes.empty()) { activeId = panes.begin()->first; } - + // Remove all panes except the active one auto it = panes.begin(); while (it != panes.end()) { @@ -464,20 +402,18 @@ void SplitViewManager::collapseAllSplits() { ++it; } } - + // Resize remaining pane to full size if (!panes.empty()) { EditorPane::PanePosition fullSize{0, 0, 800, 600}; panes.begin()->second->setPosition(fullSize); } }; - + panes_.write(updatePanes); - + // Clear layouts - layouts_.write([](auto& layouts) { - layouts.clear(); - }); + layouts_.write([](auto& layouts) { layouts.clear(); }); } std::string SplitViewManager::getNextPane(const std::string& currentPaneId, bool forward) const { @@ -485,17 +421,17 @@ std::string SplitViewManager::getNextPane(const std::string& currentPaneId, bool if (panes.size() <= 1) { return currentPaneId; } - + std::vector paneIds; for (const auto& pair : panes) { paneIds.push_back(pair.first); } - + auto it = std::find(paneIds.begin(), paneIds.end(), currentPaneId); if (it == paneIds.end()) { return paneIds.empty() ? "" : paneIds[0]; } - + if (forward) { ++it; if (it == paneIds.end()) { @@ -508,7 +444,7 @@ std::string SplitViewManager::getNextPane(const std::string& currentPaneId, bool --it; } } - + return *it; }); } @@ -548,40 +484,36 @@ std::string SplitViewManager::serializeLayout() const { bool SplitViewManager::restoreLayout(const std::string& layoutData) { // Basic layout restoration - would be more robust in practice clearAllPanes(); - + std::istringstream iss(layoutData); std::string paneData; - + while (std::getline(iss, paneData, ';')) { - if (paneData.empty()) continue; - + if (paneData.empty()) + continue; + // Parse pane data (simplified) size_t colonPos = paneData.find(':'); - if (colonPos == std::string::npos) continue; - + if (colonPos == std::string::npos) + continue; + std::string paneId = paneData.substr(0, colonPos); // Would parse position and document path here - + createPane(); // Simplified - just create panes } - + return true; } void SplitViewManager::clearAllPanes() { - auto clearPanes = [](std::map>& panes) { - panes.clear(); - }; - + auto clearPanes = [](std::map>& panes) { panes.clear(); }; + panes_.write(clearPanes); - - layouts_.write([](auto& layouts) { - layouts.clear(); - }); - - activePaneId_.write([](std::string& activeId) { - activeId = ""; - }); + + layouts_.write([](auto& layouts) { layouts.clear(); }); + + activePaneId_.write([](std::string& activeId) { activeId = ""; }); } // Private methods @@ -595,13 +527,10 @@ void SplitViewManager::updateLayout(const std::string& modifiedPaneId) { calculatePanePositions(); } -EditorPane::PanePosition SplitViewManager::calculateSplitPosition( - const EditorPane::PanePosition& sourcePosition, - SplitDirection direction, - float splitRatio) { - +EditorPane::PanePosition SplitViewManager::calculateSplitPosition(const EditorPane::PanePosition& sourcePosition, + SplitDirection direction, float splitRatio) { EditorPane::PanePosition newPosition = sourcePosition; - + if (direction == SplitDirection::Horizontal) { int splitWidth = static_cast(sourcePosition.width * splitRatio); newPosition.x = sourcePosition.x + splitWidth; @@ -611,15 +540,13 @@ EditorPane::PanePosition SplitViewManager::calculateSplitPosition( newPosition.y = sourcePosition.y + splitHeight; newPosition.height = sourcePosition.height - splitHeight; } - + enforceSizeConstraints(newPosition); return newPosition; } std::string SplitViewManager::generatePaneId() { - return nextPaneId_.write([](int& nextId) -> std::string { - return "pane_" + std::to_string(nextId++); - }); + return nextPaneId_.write([](int& nextId) -> std::string { return "pane_" + std::to_string(nextId++); }); } void SplitViewManager::notifyPaneOperation(PaneOperation op, const std::string& paneId) { @@ -629,20 +556,14 @@ void SplitViewManager::notifyPaneOperation(PaneOperation op, const std::string& } bool SplitViewManager::isValidPaneId(const std::string& paneId) const { - return withPanes([&](const auto& panes) -> bool { - return panes.find(paneId) != panes.end(); - }); + return withPanes([&](const auto& panes) -> bool { return panes.find(paneId) != panes.end(); }); } void SplitViewManager::removePaneFromLayout(const std::string& paneId) { layouts_.write([&](auto& layouts) { - layouts.erase( - std::remove_if(layouts.begin(), layouts.end(), - [&paneId](const SplitLayout& layout) { - return layout.paneId == paneId; - }), - layouts.end() - ); + layouts.erase(std::remove_if(layouts.begin(), layouts.end(), + [&paneId](const SplitLayout& layout) { return layout.paneId == paneId; }), + layouts.end()); }); } @@ -669,14 +590,16 @@ void SplitViewManager::enforceSizeConstraints(EditorPane::PanePosition& position } // Template method implementations -template -auto SplitViewManager::withPanes(Func&& func) const -> decltype(func(std::declval>&>())) { +template +auto SplitViewManager::withPanes(Func&& func) const + -> decltype(func(std::declval>&>())) { return panes_.read(std::forward(func)); } -template -auto SplitViewManager::withPanes(Func&& func) -> decltype(func(std::declval>&>())) { +template +auto SplitViewManager::withPanes(Func&& func) + -> decltype(func(std::declval>&>())) { return panes_.write(std::forward(func)); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/syntax_highlighter.cpp b/src/bolt/editor/syntax_highlighter.cpp index da68379e..e0b6cafe 100644 --- a/src/bolt/editor/syntax_highlighter.cpp +++ b/src/bolt/editor/syntax_highlighter.cpp @@ -1,35 +1,21 @@ #include "bolt/editor/syntax_highlighter.hpp" + #include +#include +#include #include +#include namespace bolt { -SyntaxHighlighter& SyntaxHighlighter::getInstance() { - static SyntaxHighlighter instance; - return instance; -} - -void SyntaxHighlighter::addLanguageRules(const std::string& language, - const std::vector>& patterns) { - std::vector> compiledRules; - for (const auto& pattern : patterns) { - compiledRules.emplace_back(std::regex(pattern.first), pattern.second); - } - - rules_.write([&](auto& rulesMap) { - rulesMap[language] = compiledRules; - }); -} +namespace { -std::vector SyntaxHighlighter::highlight(const std::string& code, const std::string& language) { +// Splits code into tokens using the first rule that matches at each position; unmatched characters become +// single-character "text" tokens. +std::vector tokenizeWithRules(const std::string& code, + const std::vector>& rules) { std::vector tokens; - - auto rules = rules_.read([&](const auto& rulesMap) { - auto it = rulesMap.find(language); - return it != rulesMap.end() ? it->second : std::vector>(); - }); - size_t pos = 0; std::string remaining = code; @@ -65,22 +51,45 @@ std::vector SyntaxHighlighter::highlight(const std::string& code, const s return tokens; } -} // namespace bolt -#include "bolt/editor/syntax_highlighter.hpp" -#include -#include -#include +} // namespace + +SyntaxHighlighter& SyntaxHighlighter::getInstance() { + static SyntaxHighlighter instance; + return instance; +} + +void SyntaxHighlighter::addLanguageRules(const std::string& language, + const std::vector>& patterns) { + std::vector> compiledRules; + for (const auto& pattern : patterns) { + compiledRules.emplace_back(std::regex(pattern.first), pattern.second); + } + + rules_.write([&](auto& rulesMap) { rulesMap[language] = compiledRules; }); +} + +std::vector SyntaxHighlighter::highlight(const std::string& code, const std::string& language) { + auto rules = rules_.read([&](const auto& rulesMap) { + auto it = rulesMap.find(language); + return it != rulesMap.end() ? it->second : std::vector>(); + }); + + return tokenizeWithRules(code, rules); +} + +} // namespace bolt namespace bolt { class SyntaxHighlighter { -private: + private: std::map>> languageRules; bool enabled = true; -public: + public: void addLanguageRule(const std::string& language, const std::string& pattern, const std::string& tokenType) { - if (!enabled) return; + if (!enabled) + return; languageRules[language].emplace_back(std::regex(pattern), tokenType); } @@ -91,58 +100,23 @@ class SyntaxHighlighter { return tokens; } - const auto& rules = languageRules[language]; - size_t pos = 0; - std::string remaining = code; - - while (!remaining.empty()) { - bool matched = false; - size_t bestMatch = remaining.length(); - std::string bestType; - std::string matchedText; - - for (const auto& rule : rules) { - std::smatch match; - if (std::regex_search(remaining, match, rule.first, std::regex_constants::match_continuous)) { - if (match.position(0) < bestMatch) { - bestMatch = match.position(0); - bestType = rule.second; - matchedText = match.str(0); - matched = true; - } - } - } - - if (matched) { - tokens.push_back({matchedText, bestType, pos}); - pos += matchedText.length(); - remaining = remaining.substr(matchedText.length()); - } else { - tokens.push_back({remaining.substr(0, 1), "text", pos}); - pos += 1; - remaining = remaining.substr(1); - } - } - - return tokens; + return tokenizeWithRules(code, languageRules[language]); } - void setEnabled(bool enable) { - enabled = enable; - } + void setEnabled(bool enable) { enabled = enable; } - bool isEnabled() const { - return enabled; - } + bool isEnabled() const { return enabled; } - void clearRules() { - languageRules.clear(); - } + void clearRules() { languageRules.clear(); } void loadDefaultRules() { // C++ syntax rules - addLanguageRule("cpp", R"(\b(int|char|bool|float|double|void|auto|class|struct|enum|namespace|template|typename|const|static|virtual|override|public|private|protected)\b)", "keyword"); - addLanguageRule("cpp", R"(\b(if|else|while|for|do|switch|case|break|continue|return|try|catch|throw)\b)", "control"); + addLanguageRule( + "cpp", + R"(\b(int|char|bool|float|double|void|auto|class|struct|enum|namespace|template|typename|const|static|virtual|override|public|private|protected)\b)", + "keyword"); + addLanguageRule("cpp", R"(\b(if|else|while|for|do|switch|case|break|continue|return|try|catch|throw)\b)", + "control"); addLanguageRule("cpp", R"(\b(new|delete|nullptr|true|false)\b)", "literal"); addLanguageRule("cpp", R"(//[^\n]*)", "comment"); addLanguageRule("cpp", R"(/\*(?:[^*]|\*[^/])*\*/)", "comment"); @@ -154,4 +128,4 @@ class SyntaxHighlighter { } }; -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/tab_bar.cpp b/src/bolt/editor/tab_bar.cpp index d1452070..5d32a3ac 100644 --- a/src/bolt/editor/tab_bar.cpp +++ b/src/bolt/editor/tab_bar.cpp @@ -1,8 +1,26 @@ #include "bolt/editor/tab_bar.hpp" + #include namespace bolt { +namespace { + +// Returns an iterator to the tab with the given id, or tabs.end() if there is none. +template +auto findTabById(Tabs& tabs, size_t tabId) { + return std::find_if(tabs.begin(), tabs.end(), [tabId](const EditorTab& tab) { return tab.id == tabId; }); +} + +// Returns an iterator to the first tab showing the given file, or tabs.end() if there is none. +template +auto findTabByPath(Tabs& tabs, const std::string& filePath) { + return std::find_if(tabs.begin(), tabs.end(), + [&filePath](const EditorTab& tab) { return tab.filePath == filePath; }); +} + +} // namespace + size_t TabBar::addTab(const std::string& filePath) { // Check if tab already exists for this file size_t existingTabId = findTabIdByPath(filePath); @@ -11,20 +29,16 @@ size_t TabBar::addTab(const std::string& filePath) { activateTab(existingTabId); return existingTabId; } - + // Create new tab size_t newTabId = nextTabId_++; EditorTab newTab(filePath, newTabId); - - tabs_.write([&](auto& tabs) { - tabs.push_back(newTab); - }); - + + tabs_.write([&](auto& tabs) { tabs.push_back(newTab); }); + // Activate the new tab - activeTabId_.write([&](auto& activeId) { - activeId = newTabId; - }); - + activeTabId_.write([&](auto& activeId) { activeId = newTabId; }); + // Notify listeners if (onTabAdded_) { onTabAdded_(newTabId); @@ -32,57 +46,51 @@ size_t TabBar::addTab(const std::string& filePath) { if (onTabActivated_) { onTabActivated_(newTabId); } - + return newTabId; } bool TabBar::closeTab(size_t tabId) { bool closed = false; - + tabs_.write([&](auto& tabs) { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end()) { // Don't close pinned tabs if (it->isPinned) { return; } - + bool wasActive = false; - activeTabId_.read([&](const auto& activeId) { - wasActive = activeId.has_value() && activeId.value() == tabId; - }); - + activeTabId_.read( + [&](const auto& activeId) { wasActive = activeId.has_value() && activeId.value() == tabId; }); + // Remove the tab size_t removedIndex = std::distance(tabs.begin(), it); tabs.erase(it); closed = true; - + // If we closed the active tab, activate another one if (wasActive && !tabs.empty()) { // Activate the tab to the left, or the first tab if we removed the first size_t newActiveIndex = (removedIndex > 0) ? removedIndex - 1 : 0; if (newActiveIndex < tabs.size()) { - activeTabId_.write([&](auto& activeId) { - activeId = tabs[newActiveIndex].id; - }); + activeTabId_.write([&](auto& activeId) { activeId = tabs[newActiveIndex].id; }); if (onTabActivated_) { onTabActivated_(tabs[newActiveIndex].id); } } } else if (tabs.empty()) { - activeTabId_.write([](auto& activeId) { - activeId = std::nullopt; - }); + activeTabId_.write([](auto& activeId) { activeId = std::nullopt; }); } } }); - + if (closed && onTabClosed_) { onTabClosed_(tabId); } - + return closed; } @@ -96,7 +104,7 @@ bool TabBar::closeTabByPath(const std::string& filePath) { void TabBar::closeOtherTabs(size_t exceptTabId) { std::vector tabsToClose; - + tabs_.read([&](const auto& tabs) { for (const auto& tab : tabs) { if (tab.id != exceptTabId && !tab.isPinned) { @@ -104,7 +112,7 @@ void TabBar::closeOtherTabs(size_t exceptTabId) { } } }); - + for (size_t tabId : tabsToClose) { closeTab(tabId); } @@ -112,7 +120,7 @@ void TabBar::closeOtherTabs(size_t exceptTabId) { void TabBar::closeAllTabs() { std::vector tabsToClose; - + tabs_.read([&](const auto& tabs) { for (const auto& tab : tabs) { if (!tab.isPinned) { @@ -120,7 +128,7 @@ void TabBar::closeAllTabs() { } } }); - + for (size_t tabId : tabsToClose) { closeTab(tabId); } @@ -128,26 +136,23 @@ void TabBar::closeAllTabs() { bool TabBar::activateTab(size_t tabId) { bool found = false; - + tabs_.read([&](const auto& tabs) { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end()) { found = true; } }); - + if (found) { - activeTabId_.write([&](auto& activeId) { - activeId = tabId; - }); - + activeTabId_.write([&](auto& activeId) { activeId = tabId; }); + if (onTabActivated_) { onTabActivated_(tabId); } } - + return found; } @@ -160,41 +165,18 @@ bool TabBar::activateTabByPath(const std::string& filePath) { } void TabBar::activateNextTab() { - tabs_.read([&](const auto& tabs) { - if (tabs.empty()) return; - - activeTabId_.write([&](auto& activeId) { - if (!activeId.has_value()) { - activeId = tabs[0].id; - if (onTabActivated_) { - onTabActivated_(tabs[0].id); - } - return; - } - - // Find current tab index - auto it = std::find_if(tabs.begin(), tabs.end(), - [&activeId](const EditorTab& tab) { return tab.id == activeId.value(); }); - - if (it != tabs.end()) { - // Move to next tab (wrap around) - ++it; - if (it == tabs.end()) { - it = tabs.begin(); - } - activeId = it->id; - if (onTabActivated_) { - onTabActivated_(it->id); - } - } - }); - }); + activateAdjacentTab(true); } void TabBar::activatePreviousTab() { + activateAdjacentTab(false); +} + +void TabBar::activateAdjacentTab(bool forward) { tabs_.read([&](const auto& tabs) { - if (tabs.empty()) return; - + if (tabs.empty()) + return; + activeTabId_.write([&](auto& activeId) { if (!activeId.has_value()) { activeId = tabs[0].id; @@ -203,17 +185,24 @@ void TabBar::activatePreviousTab() { } return; } - + // Find current tab index - auto it = std::find_if(tabs.begin(), tabs.end(), - [&activeId](const EditorTab& tab) { return tab.id == activeId.value(); }); - + auto it = findTabById(tabs, activeId.value()); + if (it != tabs.end()) { - // Move to previous tab (wrap around) - if (it == tabs.begin()) { - it = tabs.end(); + if (forward) { + // Move to next tab (wrap around) + ++it; + if (it == tabs.end()) { + it = tabs.begin(); + } + } else { + // Move to previous tab (wrap around) + if (it == tabs.begin()) { + it = tabs.end(); + } + --it; } - --it; activeId = it->id; if (onTabActivated_) { onTabActivated_(it->id); @@ -225,21 +214,20 @@ void TabBar::activatePreviousTab() { std::optional TabBar::getActiveTab() const { std::optional result; - + activeTabId_.read([&](const auto& activeId) { if (activeId.has_value()) { result = getTab(activeId.value()); } }); - + return result; } std::optional TabBar::getTab(size_t tabId) const { return tabs_.read([&](const auto& tabs) -> std::optional { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end()) { return *it; // Return copy } @@ -249,9 +237,8 @@ std::optional TabBar::getTab(size_t tabId) const { std::optional TabBar::getTabByPath(const std::string& filePath) const { return tabs_.read([&](const auto& tabs) -> std::optional { - auto it = std::find_if(tabs.begin(), tabs.end(), - [&filePath](const EditorTab& tab) { return tab.filePath == filePath; }); - + auto it = findTabByPath(tabs, filePath); + if (it != tabs.end()) { return *it; // Return copy } @@ -260,15 +247,11 @@ std::optional TabBar::getTabByPath(const std::string& filePath) const } std::vector TabBar::getAllTabs() const { - return tabs_.read([](const auto& tabs) { - return tabs; - }); + return tabs_.read([](const auto& tabs) { return tabs; }); } size_t TabBar::getTabCount() const { - return tabs_.read([](const auto& tabs) { - return tabs.size(); - }); + return tabs_.read([](const auto& tabs) { return tabs.size(); }); } bool TabBar::hasTabs() const { @@ -277,14 +260,13 @@ bool TabBar::hasTabs() const { void TabBar::setTabDirty(size_t tabId, bool isDirty) { tabs_.write([&](auto& tabs) { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end()) { it->isDirty = isDirty; } }); - + if (onTabDirtyChanged_) { onTabDirtyChanged_(isDirty); } @@ -299,9 +281,8 @@ void TabBar::setTabDirtyByPath(const std::string& filePath, bool isDirty) { void TabBar::setTabPinned(size_t tabId, bool isPinned) { tabs_.write([&](auto& tabs) { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end()) { it->isPinned = isPinned; } @@ -310,9 +291,8 @@ void TabBar::setTabPinned(size_t tabId, bool isPinned) { void TabBar::moveTab(size_t tabId, size_t newIndex) { tabs_.write([&](auto& tabs) { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end() && newIndex < tabs.size()) { EditorTab tab = *it; tabs.erase(it); @@ -323,18 +303,16 @@ void TabBar::moveTab(size_t tabId, size_t newIndex) { size_t TabBar::findTabIdByPath(const std::string& filePath) const { return tabs_.read([&](const auto& tabs) { - auto it = std::find_if(tabs.begin(), tabs.end(), - [&filePath](const EditorTab& tab) { return tab.filePath == filePath; }); - + auto it = findTabByPath(tabs, filePath); + return (it != tabs.end()) ? it->id : 0; }); } std::optional TabBar::findTabIndexById(size_t tabId) const { return tabs_.read([&](const auto& tabs) -> std::optional { - auto it = std::find_if(tabs.begin(), tabs.end(), - [tabId](const EditorTab& tab) { return tab.id == tabId; }); - + auto it = findTabById(tabs, tabId); + if (it != tabs.end()) { return std::distance(tabs.begin(), it); } @@ -344,9 +322,8 @@ std::optional TabBar::findTabIndexById(size_t tabId) const { std::optional TabBar::findTabIndexByPath(const std::string& filePath) const { return tabs_.read([&](const auto& tabs) -> std::optional { - auto it = std::find_if(tabs.begin(), tabs.end(), - [&filePath](const EditorTab& tab) { return tab.filePath == filePath; }); - + auto it = findTabByPath(tabs, filePath); + if (it != tabs.end()) { return std::distance(tabs.begin(), it); } @@ -354,4 +331,4 @@ std::optional TabBar::findTabIndexByPath(const std::string& filePath) co }); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/lsp/lsp_client.cpp b/src/bolt/lsp/lsp_client.cpp index 4ac84e27..da878743 100644 --- a/src/bolt/lsp/lsp_client.cpp +++ b/src/bolt/lsp/lsp_client.cpp @@ -1,15 +1,40 @@ #include "bolt/lsp/lsp_client.hpp" + +#include + #include #include -#include namespace bolt { namespace lsp { -LSPClient::LSPClient(const std::string& server_command) - : server_command_(server_command), initialized_(false), next_request_id_(1) { +namespace { + +// Builds the TextDocumentPositionParams object shared by the position-based requests. +Json::Value makePositionParams(const std::string& uri, int line, int character) { + Json::Value params; + params["textDocument"]["uri"] = uri; + params["position"]["line"] = line; + params["position"]["character"] = character; + return params; +} + +// Parses an LSP Location ({uri, range}) from its JSON form. +Location parseLocation(const Json::Value& locationJson) { + Location location; + location.uri = locationJson["uri"].asString(); + location.range.start.line = locationJson["range"]["start"]["line"].asInt(); + location.range.start.character = locationJson["range"]["start"]["character"].asInt(); + location.range.end.line = locationJson["range"]["end"]["line"].asInt(); + location.range.end.character = locationJson["range"]["end"]["character"].asInt(); + return location; } +} // namespace + +LSPClient::LSPClient(const std::string& server_command) + : server_command_(server_command), initialized_(false), next_request_id_(1) {} + LSPClient::~LSPClient() { shutdown(); } @@ -18,28 +43,28 @@ bool LSPClient::initialize(const std::string& root_uri) { if (initialized_) { return true; } - + // Start LSP server process if (!startServer()) { std::cerr << "Failed to start LSP server" << std::endl; return false; } - + // Send initialize request Json::Value params; params["processId"] = static_cast(getpid()); params["rootUri"] = root_uri; params["capabilities"] = buildClientCapabilities(); - + auto response = sendRequest("initialize", params); if (response.isNull()) { std::cerr << "Initialize request failed" << std::endl; return false; } - + // Send initialized notification sendNotification("initialized", Json::Value()); - + initialized_ = true; return true; } @@ -48,16 +73,16 @@ void LSPClient::shutdown() { if (!initialized_) { return; } - + // Send shutdown request sendRequest("shutdown", Json::Value()); - + // Send exit notification sendNotification("exit", Json::Value()); - + // Stop server process stopServer(); - + initialized_ = false; } @@ -67,15 +92,16 @@ void LSPClient::didOpen(const std::string& uri, const std::string& language_id, params["textDocument"]["languageId"] = language_id; params["textDocument"]["version"] = 1; params["textDocument"]["text"] = text; - + sendNotification("textDocument/didOpen", params); } -void LSPClient::didChange(const std::string& uri, int version, const std::vector& changes) { +void LSPClient::didChange(const std::string& uri, int version, + const std::vector& changes) { Json::Value params; params["textDocument"]["uri"] = uri; params["textDocument"]["version"] = version; - + Json::Value changesArray(Json::arrayValue); for (const auto& change : changes) { Json::Value changeJson; @@ -90,30 +116,27 @@ void LSPClient::didChange(const std::string& uri, int version, const std::vector changesArray.append(changeJson); } params["contentChanges"] = changesArray; - + sendNotification("textDocument/didChange", params); } void LSPClient::didClose(const std::string& uri) { Json::Value params; params["textDocument"]["uri"] = uri; - + sendNotification("textDocument/didClose", params); } std::vector LSPClient::completion(const std::string& uri, int line, int character) { - Json::Value params; - params["textDocument"]["uri"] = uri; - params["position"]["line"] = line; - params["position"]["character"] = character; - + Json::Value params = makePositionParams(uri, line, character); + auto response = sendRequest("textDocument/completion", params); - + std::vector items; if (response.isNull()) { return items; } - + // Parse completion items Json::Value itemsArray = response.isArray() ? response : response["items"]; for (const auto& item : itemsArray) { @@ -125,76 +148,55 @@ std::vector LSPClient::completion(const std::string& uri, int li completion.insertText = item.get("insertText", completion.label).asString(); items.push_back(completion); } - + return items; } std::optional LSPClient::gotoDefinition(const std::string& uri, int line, int character) { - Json::Value params; - params["textDocument"]["uri"] = uri; - params["position"]["line"] = line; - params["position"]["character"] = character; - + Json::Value params = makePositionParams(uri, line, character); + auto response = sendRequest("textDocument/definition", params); - + if (response.isNull()) { return std::nullopt; } - + // Handle both single location and array of locations Json::Value locationJson = response.isArray() ? response[0] : response; - - Location location; - location.uri = locationJson["uri"].asString(); - location.range.start.line = locationJson["range"]["start"]["line"].asInt(); - location.range.start.character = locationJson["range"]["start"]["character"].asInt(); - location.range.end.line = locationJson["range"]["end"]["line"].asInt(); - location.range.end.character = locationJson["range"]["end"]["character"].asInt(); - - return location; + + return parseLocation(locationJson); } -std::vector LSPClient::findReferences(const std::string& uri, int line, int character, bool include_declaration) { - Json::Value params; - params["textDocument"]["uri"] = uri; - params["position"]["line"] = line; - params["position"]["character"] = character; +std::vector LSPClient::findReferences(const std::string& uri, int line, int character, + bool include_declaration) { + Json::Value params = makePositionParams(uri, line, character); params["context"]["includeDeclaration"] = include_declaration; - + auto response = sendRequest("textDocument/references", params); - + std::vector locations; if (response.isNull() || !response.isArray()) { return locations; } - + for (const auto& locationJson : response) { - Location location; - location.uri = locationJson["uri"].asString(); - location.range.start.line = locationJson["range"]["start"]["line"].asInt(); - location.range.start.character = locationJson["range"]["start"]["character"].asInt(); - location.range.end.line = locationJson["range"]["end"]["line"].asInt(); - location.range.end.character = locationJson["range"]["end"]["character"].asInt(); - locations.push_back(location); + locations.push_back(parseLocation(locationJson)); } - + return locations; } std::optional LSPClient::hover(const std::string& uri, int line, int character) { - Json::Value params; - params["textDocument"]["uri"] = uri; - params["position"]["line"] = line; - params["position"]["character"] = character; - + Json::Value params = makePositionParams(uri, line, character); + auto response = sendRequest("textDocument/hover", params); - + if (response.isNull()) { return std::nullopt; } - + Hover hover; - + // Parse contents Json::Value contents = response["contents"]; if (contents.isString()) { @@ -204,7 +206,7 @@ std::optional LSPClient::hover(const std::string& uri, int line, int char } else if (contents.isArray() && contents.size() > 0) { hover.contents = contents[0].asString(); } - + // Parse range if present if (response.isMember("range")) { Range range; @@ -214,7 +216,7 @@ std::optional LSPClient::hover(const std::string& uri, int line, int char range.end.character = response["range"]["end"]["character"].asInt(); hover.range = range; } - + return hover; } @@ -229,19 +231,19 @@ std::vector LSPClient::getDiagnostics(const std::string& uri) { Json::Value LSPClient::sendRequest(const std::string& method, const Json::Value& params) { int request_id = next_request_id_++; - + Json::Value request; request["jsonrpc"] = "2.0"; request["id"] = request_id; request["method"] = method; request["params"] = params; - + std::string message = jsonToString(request); - + if (!sendMessage(message)) { return Json::Value(); } - + // Wait for response return waitForResponse(request_id); } @@ -251,7 +253,7 @@ void LSPClient::sendNotification(const std::string& method, const Json::Value& p notification["jsonrpc"] = "2.0"; notification["method"] = method; notification["params"] = params; - + std::string message = jsonToString(notification); sendMessage(message); } @@ -261,12 +263,12 @@ bool LSPClient::startServer() { // 1. Fork and exec the LSP server process // 2. Set up pipes for stdin/stdout communication // 3. Start reader thread for server responses - + std::cout << "Starting LSP server: " << server_command_ << std::endl; - + // Placeholder: would use fork/exec or platform-specific process creation // For now, just indicate success - + return true; } @@ -275,7 +277,7 @@ void LSPClient::stopServer() { // 1. Close pipes // 2. Wait for server process to exit // 3. Kill server if it doesn't exit gracefully - + std::cout << "Stopping LSP server" << std::endl; } @@ -283,11 +285,11 @@ bool LSPClient::sendMessage(const std::string& message) { // Format: Content-Length: \r\n\r\n std::string header = "Content-Length: " + std::to_string(message.length()) + "\r\n\r\n"; std::string full_message = header + message; - + // In a real implementation, write to server's stdin // For now, just log std::cout << "Sending LSP message: " << method << std::endl; - + return true; } @@ -296,14 +298,14 @@ Json::Value LSPClient::waitForResponse(int request_id) { // 1. Wait for response with matching ID // 2. Handle timeout // 3. Return parsed response - + // Placeholder: return empty response return Json::Value(); } void LSPClient::handleNotification(const Json::Value& notification) { std::string method = notification["method"].asString(); - + if (method == "textDocument/publishDiagnostics") { handleDiagnostics(notification["params"]); } @@ -312,7 +314,7 @@ void LSPClient::handleNotification(const Json::Value& notification) { void LSPClient::handleDiagnostics(const Json::Value& params) { std::string uri = params["uri"].asString(); - + std::vector diagnostics; for (const auto& diagJson : params["diagnostics"]) { Diagnostic diag; @@ -325,14 +327,14 @@ void LSPClient::handleDiagnostics(const Json::Value& params) { diag.source = diagJson.get("source", "").asString(); diagnostics.push_back(diag); } - + std::lock_guard lock(diagnostics_mutex_); diagnostics_[uri] = diagnostics; } Json::Value LSPClient::buildClientCapabilities() { Json::Value capabilities; - + // Text document capabilities capabilities["textDocument"]["completion"]["completionItem"]["snippetSupport"] = true; capabilities["textDocument"]["completion"]["completionItem"]["commitCharactersSupport"] = true; @@ -342,7 +344,7 @@ Json::Value LSPClient::buildClientCapabilities() { capabilities["textDocument"]["synchronization"]["dynamicRegistration"] = true; capabilities["textDocument"]["synchronization"]["willSave"] = true; capabilities["textDocument"]["synchronization"]["didSave"] = true; - + return capabilities; } @@ -352,5 +354,5 @@ std::string LSPClient::jsonToString(const Json::Value& json) { return Json::writeString(builder, json); } -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt From dd5f4e57d063f4361f95d400f8c8c3d546c3bed1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 15:30:40 +0000 Subject: [PATCH 2/2] LspEditorBridge: fix self-deadlock when accepting a result acceptCompletion, acceptDefinition, acceptReference and acceptSymbol each locked their mutex and then called the matching dismiss function, which locks the same non-recursive mutex. Accepting a completion, a definition, a reference or a symbol therefore hung the calling thread. Release the lock before calling the dismiss function. The selected value is copied while the lock is held, as before. Found while refactoring this file; no test covered these paths. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71 --- src/bolt/editor/lsp_editor_bridge.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/bolt/editor/lsp_editor_bridge.cpp b/src/bolt/editor/lsp_editor_bridge.cpp index bf35d06d..6bc47ca7 100644 --- a/src/bolt/editor/lsp_editor_bridge.cpp +++ b/src/bolt/editor/lsp_editor_bridge.cpp @@ -347,13 +347,15 @@ void LspEditorBridge::requestCompletion(const std::string& filePath, size_t line } std::string LspEditorBridge::acceptCompletion() { - std::lock_guard lock(completionMutex_); + std::unique_lock lock(completionMutex_); if (!completionState_.isVisible || completionState_.items.empty()) { return ""; } std::string insertText = completionState_.items[completionState_.selectedIndex].insertText; + // dismissCompletion() takes the same mutex, so release it first. + lock.unlock(); dismissCompletion(); return insertText; } @@ -662,13 +664,15 @@ void LspEditorBridge::requestDefinition(const std::string& filePath, size_t line } std::optional LspEditorBridge::acceptDefinition() { - std::lock_guard lock(definitionMutex_); + std::unique_lock lock(definitionMutex_); if (!definitionState_.isVisible || definitionState_.locations.empty()) { return std::nullopt; } EditorLocation result = definitionState_.locations[definitionState_.selectedIndex]; + // dismissDefinition() takes the same mutex, so release it first. + lock.unlock(); dismissDefinition(); return result; } @@ -715,13 +719,15 @@ void LspEditorBridge::requestReferences(const std::string& filePath, size_t line } std::optional LspEditorBridge::acceptReference() { - std::lock_guard lock(referencesMutex_); + std::unique_lock lock(referencesMutex_); if (!referencesState_.isVisible || referencesState_.locations.empty()) { return std::nullopt; } EditorLocation result = referencesState_.locations[referencesState_.selectedIndex]; + // dismissReferences() takes the same mutex, so release it first. + lock.unlock(); dismissReferences(); return result; } @@ -830,7 +836,7 @@ void LspEditorBridge::requestDocumentSymbols(const std::string& filePath) { } std::optional LspEditorBridge::acceptSymbol() { - std::lock_guard lock(symbolsMutex_); + std::unique_lock lock(symbolsMutex_); if (!symbolOutlineState_.isVisible || symbolOutlineState_.symbols.empty()) { return std::nullopt; @@ -844,6 +850,8 @@ std::optional LspEditorBridge::acceptSymbol() { result.endLine = sym.endLine; result.endColumn = sym.endColumn; + // dismissSymbolOutline() takes the same mutex, so release it first. + lock.unlock(); dismissSymbolOutline(); return result; }