From c8688036a29319db8aa58bd2be1742b88edf2527 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 04:03:37 +0000 Subject: [PATCH 01/10] Format the remaining C++ sources that pass the duplicate check Apply .clang-format to 263 more files and fix what cpplint then reports, so that changing one of them no longer fails Lint Code Base. Together with the 21 files formatted earlier, 284 of the 325 project C++ files now follow the style. Beyond whitespace and wrapping, cpplint needed: - header guards renamed to the names derived from the path under include/ (87 headers); - single-argument constructors marked explicit (42); - missing standard headers added where a symbol was used without its header (55 includes); - same-directory header includes written with their bolt/... path; - project headers included with quotes in three tests; - static_cast / reinterpret_cast instead of C-style casts; - "} else" joined where a comment sat between the brace and the else; - snprintf instead of strcpy in one example; - NOLINT on using-directives in demo programs, on one deliberate include of a .cpp file, and on three uses of long that match an external API or a public signature. No behaviour changes are intended. 41 files are left unformatted on purpose. Each contains duplicated blocks that the linter's copy/paste detector rejects whenever the file is touched, so they need refactoring before they can be reformatted: demo_external_lsp.cpp demo_gpu_acceleration.cpp demo_lsp_editor_integration.cpp demo_lsp_integration.cpp demo_multi_cursor.cpp test_benchmark_suite.cpp test_gpu_simple.cpp test_gpu_standalone.cpp test_performance_profiler.cpp include/bolt/ai/ai_code_generator.hpp include/bolt/ai/ai_refactoring_engine.hpp include/bolt/collaboration/collaboration_protocol.hpp include/bolt/collaboration/collaborative_session.hpp include/bolt/core/code_analyzer.hpp include/bolt/core/editor_store.hpp include/bolt/drawkern/ai_integration.hpp include/bolt/drawkern/drawkern.hpp include/bolt/editor/command_history.hpp include/bolt/gui/widgets.hpp include/bolt/test_framework.hpp include/bolt/utils/tensor_utils.hpp src/bolt/ai/ai_code_generator.cpp src/bolt/ai/enhanced_ai_manager.cpp src/bolt/ai/koboldcpp_provider.cpp src/bolt/ai/rwkv_wrapper.cpp src/bolt/ai/unified_rag_manager.cpp src/bolt/core/plugin_system.cpp src/bolt/drawkern/ai_integration.cpp src/bolt/drawkern/yacc_grammar.cpp src/bolt/editor/debugger_interface.cpp src/bolt/editor/editor_pane.cpp src/bolt/editor/lsp_editor_bridge.cpp src/bolt/editor/split_view_manager.cpp src/bolt/editor/syntax_highlighter.cpp src/bolt/editor/tab_bar.cpp src/bolt/gui/widget_registration.cpp src/bolt/lsp/lsp_client.cpp src/bolt/network/network_buffer.cpp test/test_bpe_tokenizer.cpp test/test_model_loader.cpp test/test_plugin_system.cpp Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71 --- benchmark_tool.cpp | 109 ++- benchmark_tool_standalone.cpp | 130 ++-- bolt_ai_terminal.cpp | 36 +- bolt_chat.cpp | 53 +- bolt_terminal_ai_fixed.cpp | 92 +-- bolt_terminal_chat.cpp | 82 +-- demo_advanced_lsp.cpp | 100 ++- demo_ai_code_completion_live.cpp | 47 +- demo_ai_completion.cpp | 80 +-- demo_ai_config.cpp | 40 +- demo_ai_infrastructure.cpp | 27 +- demo_benchmark_suite.cpp | 187 +++--- demo_code_analyzer.cpp | 136 ++-- demo_code_analyzer_standalone.cpp | 277 ++++---- demo_code_folding.cpp | 46 +- demo_collaborative_editing.cpp | 59 +- demo_debugger.cpp | 133 ++-- demo_direct_gguf.cpp | 77 ++- demo_drawkern.cpp | 36 +- demo_drawkern_complete.cpp | 120 ++-- demo_drawkern_full.cpp | 169 +++-- demo_editor_minimap.cpp | 92 +-- demo_file_tree.cpp | 32 +- demo_git_integration.cpp | 93 +-- demo_integration.cpp | 26 +- demo_keyboard_shortcuts.cpp | 154 +++-- demo_logging.cpp | 136 ++-- demo_logging_simple.cpp | 68 +- demo_lsp_ui_integration.cpp | 193 +++--- demo_minimap.cpp | 113 ++-- demo_narrative_rag_kobold.cpp | 85 +-- demo_network_optimizations.cpp | 136 ++-- demo_performance_profiler.cpp | 162 +++-- demo_plugin_system.cpp | 93 ++- demo_semantic_file_search.cpp | 79 +-- demo_split_view.cpp | 56 +- demo_split_view_basic.cpp | 32 +- demo_temporal_rag_rwkv.cpp | 114 ++-- demo_theme_integration.cpp | 67 +- demo_theme_system.cpp | 57 +- demo_unified_rag_system.cpp | 81 ++- .../debugger_editor_integration.cpp | 105 ++- example_git_editor_integration.cpp | 63 +- examples/collaborative_editor_example.cpp | 159 +++-- examples/memory_leak_detection_example.cpp | 156 +++-- examples/plugins/cpp_language_plugin.cpp | 82 ++- include/bolt/ai/ai_completion_provider.hpp | 73 +-- include/bolt/ai/ai_config_manager.hpp | 32 +- include/bolt/ai/ai_http_client.hpp | 59 +- include/bolt/ai/bpe_tokenizer.hpp | 46 +- include/bolt/ai/direct_gguf_inference.hpp | 48 +- include/bolt/ai/enhanced_ai_manager.hpp | 57 +- include/bolt/ai/ggml.hpp | 28 +- include/bolt/ai/ggml_loader.hpp | 156 ++--- include/bolt/ai/ggml_wrapper.hpp | 65 +- include/bolt/ai/gguf_loader.hpp | 114 ++-- include/bolt/ai/gpu_acceleration.hpp | 177 +++-- include/bolt/ai/i_rag_manager.hpp | 41 +- include/bolt/ai/koboldcpp_provider.hpp | 59 +- include/bolt/ai/llama_completion_provider.hpp | 37 +- include/bolt/ai/model_loader.hpp | 74 +-- include/bolt/ai/narrative_rag_manager.hpp | 91 ++- include/bolt/ai/narrative_tool_manager.hpp | 70 +- include/bolt/ai/rag_router.hpp | 86 ++- include/bolt/ai/rwkv_wrapper.hpp | 60 +- include/bolt/ai/semantic_search_manager.hpp | 68 +- include/bolt/ai/temporal_rag_manager.hpp | 103 ++- include/bolt/ai/temporal_tool_manager.hpp | 46 +- include/bolt/ai/tokenizer.hpp | 42 +- include/bolt/ai/unified_rag_manager.hpp | 75 +-- include/bolt/ai/vector_database.hpp | 62 +- .../collaborative_editor_integration.hpp | 170 ++--- .../bolt/collaboration/document_operation.hpp | 190 +++--- .../collaboration/operational_transform.hpp | 127 ++-- include/bolt/core/benchmark_suite.hpp | 143 ++-- include/bolt/core/bolt_commands.hpp | 22 +- include/bolt/core/chat_store.hpp | 88 ++- include/bolt/core/error_handling.hpp | 82 ++- include/bolt/core/logging.hpp | 307 +++++---- include/bolt/core/memory_leak_detector.hpp | 155 +++-- include/bolt/core/memory_manager.hpp | 65 +- include/bolt/core/memory_pool.hpp | 48 +- include/bolt/core/message_handler.hpp | 44 +- include/bolt/core/performance_profiler.hpp | 110 ++-- include/bolt/core/plugin_interface.hpp | 108 ++- include/bolt/core/plugin_system.hpp | 90 +-- include/bolt/core/thread_safety.hpp | 48 +- include/bolt/core/workbench_store.hpp | 63 +- include/bolt/drawkern/dis_vm.hpp | 220 +++---- include/bolt/drawkern/styx_protocol.hpp | 119 ++-- include/bolt/drawkern/yacc_grammar.hpp | 196 +++--- include/bolt/editor/code_completion.hpp | 54 +- include/bolt/editor/code_folding.hpp | 19 +- include/bolt/editor/code_folding_detector.hpp | 13 +- include/bolt/editor/code_folding_manager.hpp | 23 +- include/bolt/editor/code_folding_ui.hpp | 21 +- .../bolt/editor/code_folding_visibility.hpp | 15 +- include/bolt/editor/cursor_manager.hpp | 42 +- include/bolt/editor/debugger_interface.hpp | 67 +- include/bolt/editor/debugger_ui.hpp | 35 +- include/bolt/editor/editor_features.hpp | 29 +- include/bolt/editor/editor_pane.hpp | 40 +- include/bolt/editor/file_tree.hpp | 16 +- include/bolt/editor/file_tree_manager.hpp | 47 +- include/bolt/editor/file_tree_node.hpp | 33 +- include/bolt/editor/file_tree_ui.hpp | 49 +- include/bolt/editor/find_replace.hpp | 20 +- include/bolt/editor/integrated_editor.hpp | 95 +-- include/bolt/editor/keyboard_shortcuts.hpp | 81 ++- include/bolt/editor/line_numbers.hpp | 21 +- include/bolt/editor/lsp_client.hpp | 143 ++-- include/bolt/editor/lsp_editor_bridge.hpp | 168 ++--- include/bolt/editor/lsp_json_rpc.hpp | 131 ++-- include/bolt/editor/lsp_plugin_adapter.hpp | 73 ++- include/bolt/editor/lsp_protocol.hpp | 61 +- include/bolt/editor/lsp_server.hpp | 77 ++- include/bolt/editor/lsp_server_configs.hpp | 60 +- include/bolt/editor/minimap.hpp | 27 +- include/bolt/editor/minimap_renderer.hpp | 27 +- include/bolt/editor/minimap_ui.hpp | 22 +- include/bolt/editor/split_view_manager.hpp | 80 ++- include/bolt/editor/syntax_highlighter.hpp | 48 +- include/bolt/editor/tab_bar.hpp | 109 ++- include/bolt/editor/theme_system.hpp | 20 +- include/bolt/git/git.hpp | 20 +- include/bolt/git/git_integration.hpp | 73 ++- include/bolt/git/git_repository.hpp | 87 ++- include/bolt/gui/bolt_gui_app.hpp | 53 +- include/bolt/gui/dark_theme.hpp | 10 +- include/bolt/gui/lsp_ui_components.hpp | 89 ++- include/bolt/gui/widget_framework.hpp | 209 +++--- include/bolt/gui/widget_registration.hpp | 70 +- include/bolt/gui_components.hpp | 32 +- include/bolt/lsp/lsp_client.hpp | 30 +- include/bolt/network/connection_pool.hpp | 62 +- include/bolt/network/http_server.hpp | 75 +-- include/bolt/network/message_compression.hpp | 47 +- include/bolt/network/network_buffer.hpp | 98 +-- include/bolt/network/network_commands.hpp | 49 +- .../network/optimized_websocket_server.hpp | 173 +++-- include/bolt/network/websocket_server.hpp | 40 +- include/bolt/utils/data_processor.hpp | 12 +- include/bolt/utils/filesystem_utils.hpp | 13 +- include/bolt/utils/math_utils.hpp | 21 +- include/bolt/utils/string_utils.hpp | 12 +- real_tinyllama_chat.cpp | 143 ++-- simple_ai_demo.cpp | 116 ++-- simple_ai_test.cpp | 33 +- simple_direct_chat.cpp | 64 +- simple_terminal_ai.cpp | 76 ++- src/bolt/ai/ai_completion_provider.cpp | 120 ++-- src/bolt/ai/ai_config_manager.cpp | 143 ++-- src/bolt/ai/ai_http_client.cpp | 98 +-- src/bolt/ai/ai_refactoring_engine.cpp | 540 +++++++-------- src/bolt/ai/bpe_tokenizer.cpp | 68 +- src/bolt/ai/direct_gguf_inference.cpp | 111 ++-- src/bolt/ai/ggml.cpp | 3 +- src/bolt/ai/ggml_loader.cpp | 211 +++--- src/bolt/ai/gguf_loader.cpp | 172 ++--- src/bolt/ai/gpu_acceleration.cpp | 236 +++---- src/bolt/ai/llama_completion_provider.cpp | 101 ++- src/bolt/ai/model_loader.cpp | 86 +-- src/bolt/ai/rag_router.cpp | 323 ++++----- src/bolt/ai/rwkv_improved.cpp | 140 ++-- src/bolt/ai/semantic_search_manager.cpp | 146 ++--- src/bolt/ai/vector_database.cpp | 133 ++-- src/bolt/benchmarks/core_benchmarks.cpp | 121 ++-- .../collaboration/collaboration_protocol.cpp | 4 +- .../collaborative_editor_integration.cpp | 4 +- .../collaboration/collaborative_session.cpp | 4 +- src/bolt/collaboration/document_operation.cpp | 4 +- .../collaboration/operational_transform.cpp | 4 +- src/bolt/core/benchmark_suite.cpp | 243 +++---- src/bolt/core/chat_store.cpp | 2 +- src/bolt/core/code_analyzer.cpp | 620 +++++++++--------- src/bolt/core/editor_store.cpp | 2 +- src/bolt/core/logging.cpp | 235 ++++--- src/bolt/core/memory_leak_detector.cpp | 3 +- src/bolt/core/memory_manager.cpp | 2 +- src/bolt/core/memory_pool.cpp | 2 +- src/bolt/core/message_handler.cpp | 64 +- src/bolt/core/performance_profiler.cpp | 230 +++---- src/bolt/core/workbench_store.cpp | 2 +- src/bolt/drawkern/dis_vm.cpp | 471 +++++++------ src/bolt/drawkern/drawkern.cpp | 41 +- src/bolt/drawkern/styx_protocol.cpp | 248 +++---- src/bolt/editor/code_completion.cpp | 14 +- src/bolt/editor/code_folding.cpp | 2 +- src/bolt/editor/code_folding_detector.cpp | 36 +- src/bolt/editor/code_folding_manager.cpp | 10 +- src/bolt/editor/code_folding_renderer.cpp | 18 +- src/bolt/editor/code_folding_state.cpp | 31 +- src/bolt/editor/code_folding_ui.cpp | 19 +- src/bolt/editor/code_folding_visibility.cpp | 9 +- src/bolt/editor/cursor_manager.cpp | 39 +- src/bolt/editor/debugger_ui.cpp | 167 ++--- src/bolt/editor/file_tree_manager.cpp | 140 ++-- src/bolt/editor/file_tree_node.cpp | 41 +- src/bolt/editor/file_tree_ui.cpp | 107 +-- src/bolt/editor/find_replace.cpp | 29 +- src/bolt/editor/integrated_editor.cpp | 443 +++++++------ src/bolt/editor/keyboard_shortcuts.cpp | 353 +++++----- src/bolt/editor/lsp_client.cpp | 390 +++++------ src/bolt/editor/lsp_json_rpc.cpp | 126 ++-- src/bolt/editor/lsp_plugin_adapter.cpp | 157 +++-- src/bolt/editor/lsp_server.cpp | 280 ++++---- src/bolt/editor/lsp_server_configs.cpp | 129 ++-- src/bolt/editor/minimap.cpp | 84 +-- src/bolt/editor/minimap_renderer.cpp | 74 +-- src/bolt/editor/minimap_ui.cpp | 115 ++-- src/bolt/editor/theme_system.cpp | 11 +- src/bolt/git/git_integration.cpp | 90 +-- src/bolt/gui/dark_theme.cpp | 256 ++++---- src/bolt/gui/enhanced_dark_theme.cpp | 372 +++++------ src/bolt/gui/lsp_ui_components.cpp | 381 ++++++----- src/bolt/gui/widget_framework.cpp | 323 ++++----- src/bolt/gui/widgets.cpp | 268 ++++---- src/bolt/gui_main.cpp | 14 +- src/bolt/lsp/lsp_manager.cpp | 21 +- src/bolt/network/connection_pool.cpp | 115 ++-- src/bolt/network/message_compression.cpp | 99 ++- src/bolt/network/websocket_server.cpp | 67 +- src/bolt/utils/string_utils.cpp | 2 +- terminal_chat_direct.cpp | 38 +- terminal_chat_kobold.cpp | 132 ++-- test/basic_test.cpp | 12 +- test/test_ai_features.cpp | 46 +- test/test_ai_ggml.cpp | 38 +- test/test_ai_models.cpp | 141 ++-- test/test_bolt_core.cpp | 189 +++--- test/test_code_analyzer.cpp | 140 ++-- test/test_code_folding.cpp | 88 +-- test/test_collaboration.cpp | 106 ++- test/test_e2e.cpp | 70 +- test/test_gguf_loader.cpp | 15 +- test/test_git_integration.cpp | 92 +-- test/test_gpu_acceleration.cpp | 135 ++-- test/test_integration.cpp | 240 ++++--- test/test_keyboard_shortcuts.cpp | 178 ++--- test/test_koboldcpp_provider.cpp | 33 +- test/test_lsp.cpp | 31 +- test/test_memory_leak_detector.cpp | 73 ++- test/test_minimap.cpp | 91 +-- test/test_model_loading.cpp | 69 +- test/test_multi_cursor.cpp | 125 ++-- test/test_runner.cpp | 19 +- test/test_rwkv_integration.cpp | 43 +- test/test_sanitizer_integration.cpp | 75 +-- test/test_split_view.cpp | 49 +- test/test_tab_bar.cpp | 99 +-- test/test_theme_system.cpp | 60 +- test/test_widget_framework.cpp | 237 ++++--- test_advanced_ai_standalone.cpp | 43 +- test_ai_completion.cpp | 53 +- test_ai_features.cpp | 160 ++--- test_config.cpp | 20 +- test_direct_gguf.cpp | 30 +- test_git_standalone.cpp | 26 +- test_logging_simple.cpp | 154 +++-- test_lsp.cpp | 168 +++-- test_performance_integration.cpp | 226 +++---- test_rag_router.cpp | 106 ++- tinyllama_chat.cpp | 63 +- 263 files changed, 12727 insertions(+), 12862 deletions(-) diff --git a/benchmark_tool.cpp b/benchmark_tool.cpp index 543c2c63..9aeecce3 100644 --- a/benchmark_tool.cpp +++ b/benchmark_tool.cpp @@ -1,13 +1,14 @@ -#include "include/bolt/core/benchmark_suite.hpp" -#include "include/bolt/core/logging.hpp" -#include -#include -#include #include #include #include +#include +#include +#include + +#include "include/bolt/core/benchmark_suite.hpp" +#include "include/bolt/core/logging.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void printUsage(const char* programName) { std::cout << "Usage: " << programName << " [options]\n\n"; @@ -36,34 +37,29 @@ void printUsage(const char* programName) { void printBenchmarkSummary(const std::vector& results) { std::cout << "\n=== Benchmark Summary ===\n"; - std::cout << std::left << std::setw(30) << "Benchmark" - << std::setw(12) << "Category" - << std::setw(15) << "Avg Time (ms)" - << std::setw(15) << "Min Time (ms)" - << std::setw(15) << "Max Time (ms)" + std::cout << std::left << std::setw(30) << "Benchmark" << std::setw(12) << "Category" << std::setw(15) + << "Avg Time (ms)" << std::setw(15) << "Min Time (ms)" << std::setw(15) << "Max Time (ms)" << std::setw(12) << "Success Rate" << "Status\n"; std::cout << std::string(110, '-') << "\n"; - + for (const auto& result : results) { std::string status = result.isValid() ? "SUCCESS" : "FAILED"; - std::cout << std::left << std::setw(30) << result.name.substr(0, 29) - << std::setw(12) << result.category - << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.maxDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" - << status << "\n"; - + std::cout << std::left << std::setw(30) << result.name.substr(0, 29) << std::setw(12) << result.category + << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs << std::setw(15) + << std::fixed << std::setprecision(3) << result.minDurationMs << std::setw(15) << std::fixed + << std::setprecision(3) << result.maxDurationMs << std::setw(12) << std::fixed << std::setprecision(1) + << (result.getSuccessRate() * 100) << "%" << status << "\n"; + if (!result.errorMessage.empty()) { std::cout << " Error: " << result.errorMessage << "\n"; } } - + // Calculate summary statistics int totalSuccessful = 0, totalFailed = 0; double totalTime = 0.0; - + for (const auto& result : results) { if (result.isValid()) { totalSuccessful++; @@ -72,28 +68,25 @@ void printBenchmarkSummary(const std::vector& results) { totalFailed++; } } - + std::cout << "\n"; std::cout << "Total Benchmarks: " << results.size() << "\n"; std::cout << "Successful: " << totalSuccessful << "\n"; std::cout << "Failed: " << totalFailed << "\n"; if (totalSuccessful > 0) { - std::cout << "Average Time: " << std::fixed << std::setprecision(3) - << (totalTime / totalSuccessful) << " ms\n"; + std::cout << "Average Time: " << std::fixed << std::setprecision(3) << (totalTime / totalSuccessful) << " ms\n"; } } void printComparisonSummary(const std::vector& comparisons) { std::cout << "\n=== Baseline Comparison ===\n"; - std::cout << std::left << std::setw(30) << "Benchmark" - << std::setw(15) << "Current (ms)" - << std::setw(15) << "Baseline (ms)" - << std::setw(12) << "Change (%)" + std::cout << std::left << std::setw(30) << "Benchmark" << std::setw(15) << "Current (ms)" << std::setw(15) + << "Baseline (ms)" << std::setw(12) << "Change (%)" << "Status\n"; std::cout << std::string(80, '-') << "\n"; - + int improvements = 0, regressions = 0, stable = 0; - + for (const auto& comp : comparisons) { std::string statusStr; switch (comp.performanceStatus) { @@ -113,19 +106,18 @@ void printComparisonSummary(const std::vector& comparisons) statusStr = "INCONCLUSIVE"; break; } - - std::cout << std::left << std::setw(30) << comp.benchmarkName.substr(0, 29) - << std::setw(15) << std::fixed << std::setprecision(3) << comp.current.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << comp.baseline.averageDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << comp.durationChangePercent - << statusStr << "\n"; + + std::cout << std::left << std::setw(30) << comp.benchmarkName.substr(0, 29) << std::setw(15) << std::fixed + << std::setprecision(3) << comp.current.averageDurationMs << std::setw(15) << std::fixed + << std::setprecision(3) << comp.baseline.averageDurationMs << std::setw(12) << std::fixed + << std::setprecision(1) << comp.durationChangePercent << statusStr << "\n"; } - + std::cout << "\nComparison Summary:\n"; std::cout << "Improvements: " << improvements << "\n"; std::cout << "Regressions: " << regressions << "\n"; std::cout << "Stable: " << stable << "\n"; - + if (regressions > 0) { std::cout << "\nโš ๏ธ Performance regressions detected!\n"; } else if (improvements > 0) { @@ -136,9 +128,9 @@ void printComparisonSummary(const std::vector& comparisons) int main(int argc, char* argv[]) { // Initialize logging LogManager::configureConsoleLogging(LogLevel::INFO, false); - + auto& suite = BenchmarkSuite::getInstance(); - + // Command line argument parsing std::string command; std::string specificBenchmark; @@ -152,10 +144,10 @@ int main(int argc, char* argv[]) { int warmup = 3; int timeout = 30000; bool verbose = false; - + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; - + if (arg == "--help" || arg == "-h") { printUsage(argv[0]); return 0; @@ -195,24 +187,24 @@ int main(int argc, char* argv[]) { return 1; } } - + if (command.empty()) { command = "run-all"; // Default action } - + // Configure benchmark suite suite.setDefaultIterations(iterations); suite.setDefaultWarmupRuns(warmup); suite.setDefaultTimeout(std::chrono::milliseconds(timeout)); suite.enableVerboseOutput(verbose); - + // Load core benchmarks by including the source // This ensures the benchmarks are registered - extern void register_core_benchmarks(); // Forward declaration - + extern void register_core_benchmarks(); // Forward declaration + std::cout << "Bolt Performance Benchmark Suite\n"; std::cout << "================================\n\n"; - + try { if (command == "list") { auto benchmarks = suite.getAvailableBenchmarks(); @@ -221,7 +213,7 @@ int main(int argc, char* argv[]) { std::cout << " " << name << "\n"; } std::cout << "\nTotal: " << benchmarks.size() << " benchmarks\n"; - + } else if (command == "categories") { auto categories = suite.getAvailableCategories(); std::cout << "Available Categories:\n"; @@ -229,12 +221,12 @@ int main(int argc, char* argv[]) { std::cout << " " << category << "\n"; } std::cout << "\nTotal: " << categories.size() << " categories\n"; - + } else if (command == "run-all") { std::cout << "Running all benchmarks...\n"; auto results = suite.runAllBenchmarks(); printBenchmarkSummary(results); - + // Handle baseline comparison if (!baselineFile.empty()) { auto baseline = suite.loadBaselineResults(baselineFile); @@ -243,7 +235,7 @@ int main(int argc, char* argv[]) { printComparisonSummary(comparisons); } } - + // Generate reports if (!jsonOutput.empty()) { suite.generateJsonReport(results, jsonOutput); @@ -257,7 +249,7 @@ int main(int argc, char* argv[]) { if (!saveBaselineFile.empty()) { suite.saveBaselineResults(results, saveBaselineFile); } - + } else if (command == "category") { std::cout << "Running benchmarks in category: " << specificCategory << "\n"; auto results = suite.runBenchmarksByCategory(specificCategory); @@ -266,23 +258,22 @@ int main(int argc, char* argv[]) { return 1; } printBenchmarkSummary(results); - + } else if (command == "benchmark") { std::cout << "Running benchmark: " << specificBenchmark << "\n"; auto result = suite.runBenchmark(specificBenchmark); std::vector results = {result}; printBenchmarkSummary(results); - + if (!result.isValid()) { return 1; } } - } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } - + std::cout << "\nBenchmark execution completed.\n"; return 0; -} \ No newline at end of file +} diff --git a/benchmark_tool_standalone.cpp b/benchmark_tool_standalone.cpp index fc9d50ce..b1d836e1 100644 --- a/benchmark_tool_standalone.cpp +++ b/benchmark_tool_standalone.cpp @@ -1,27 +1,28 @@ -#include "include/bolt/core/benchmark_suite.hpp" -#include "include/bolt/core/performance_profiler.hpp" -#include "include/bolt/core/memory_manager.hpp" -#include "include/bolt/core/memory_pool.hpp" -#include "include/bolt/core/logging.hpp" -#include -#include -#include #include #include +#include #include -#include +#include #include +#include +#include #include -#include +#include + +#include "include/bolt/core/benchmark_suite.hpp" +#include "include/bolt/core/logging.hpp" +#include "include/bolt/core/memory_manager.hpp" +#include "include/bolt/core/memory_pool.hpp" +#include "include/bolt/core/performance_profiler.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) // Simple test benchmarks for standalone demo void benchmark_memory_allocation_demo(const BenchmarkConfig& config) { std::vector allocations; const size_t numAllocations = 1000; const size_t allocationSize = 1024; - + // Allocate for (size_t i = 0; i < numAllocations; ++i) { void* ptr = malloc(allocationSize); @@ -29,7 +30,7 @@ void benchmark_memory_allocation_demo(const BenchmarkConfig& config) { allocations.push_back(ptr); } } - + // Deallocate for (void* ptr : allocations) { if (ptr) { @@ -41,19 +42,19 @@ void benchmark_memory_allocation_demo(const BenchmarkConfig& config) { void benchmark_string_operations_demo(const BenchmarkConfig& config) { const int numStrings = 500; std::vector strings; - + // String creation for (int i = 0; i < numStrings; ++i) { strings.emplace_back("Demo string " + std::to_string(i) + " with content"); } - + // String manipulation for (auto& str : strings) { str += " modified"; str = str.substr(0, str.length() / 2); std::transform(str.begin(), str.end(), str.begin(), ::toupper); } - + // String searching int found = 0; for (const auto& str : strings) { @@ -66,22 +67,22 @@ void benchmark_string_operations_demo(const BenchmarkConfig& config) { void benchmark_vector_operations_demo(const BenchmarkConfig& config) { std::vector vec; const int numElements = 5000; - + // Push back for (int i = 0; i < numElements; ++i) { vec.push_back(i); } - + // Random access std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, numElements - 1); - + int sum = 0; for (int i = 0; i < 1000; ++i) { sum += vec[dis(gen)]; } - + // Erase elements while (!vec.empty() && vec.size() > numElements / 2) { vec.erase(vec.begin() + vec.size() / 2); @@ -93,9 +94,9 @@ void benchmark_threading_demo(const BenchmarkConfig& config) { const int operationsPerThread = 500; std::mutex testMutex; int sharedCounter = 0; - + std::vector threads; - + for (int i = 0; i < numThreads; ++i) { threads.emplace_back([&]() { for (int j = 0; j < operationsPerThread; ++j) { @@ -104,7 +105,7 @@ void benchmark_threading_demo(const BenchmarkConfig& config) { } }); } - + for (auto& thread : threads) { if (thread.joinable()) { thread.join(); @@ -116,7 +117,7 @@ void benchmark_file_io_demo(const BenchmarkConfig& config) { const std::string filename = "/tmp/benchmark_demo_file.txt"; const std::string content = "Demo content for file I/O benchmark. "; const int numLines = 500; - + // Write file { std::ofstream file(filename); @@ -124,7 +125,7 @@ void benchmark_file_io_demo(const BenchmarkConfig& config) { file << content << "Line " << i << std::endl; } } - + // Read file { std::ifstream file(filename); @@ -134,34 +135,34 @@ void benchmark_file_io_demo(const BenchmarkConfig& config) { lineCount++; } } - + // Clean up std::remove(filename.c_str()); } void registerDemoBenchmarks() { auto& suite = BenchmarkSuite::getInstance(); - + BenchmarkConfig config1("memory_allocation_demo", "Basic memory allocation and deallocation performance"); config1.category = "DEMO"; config1.iterations = 50; suite.registerBenchmark(config1, benchmark_memory_allocation_demo); - + BenchmarkConfig config2("string_operations_demo", "String creation, manipulation, and destruction"); config2.category = "DEMO"; config2.iterations = 30; suite.registerBenchmark(config2, benchmark_string_operations_demo); - + BenchmarkConfig config3("vector_operations_demo", "Vector operations performance"); config3.category = "DEMO"; config3.iterations = 20; suite.registerBenchmark(config3, benchmark_vector_operations_demo); - + BenchmarkConfig config4("threading_demo", "Thread creation and synchronization"); config4.category = "DEMO"; config4.iterations = 10; suite.registerBenchmark(config4, benchmark_threading_demo); - + BenchmarkConfig config5("file_io_demo", "File I/O operations"); config5.category = "DEMO"; config5.iterations = 5; @@ -190,34 +191,29 @@ void printUsage(const char* programName) { void printBenchmarkSummary(const std::vector& results) { std::cout << "\n=== Benchmark Summary ===\n"; - std::cout << std::left << std::setw(25) << "Benchmark" - << std::setw(10) << "Category" - << std::setw(15) << "Avg Time (ms)" - << std::setw(15) << "Min Time (ms)" - << std::setw(15) << "Max Time (ms)" + std::cout << std::left << std::setw(25) << "Benchmark" << std::setw(10) << "Category" << std::setw(15) + << "Avg Time (ms)" << std::setw(15) << "Min Time (ms)" << std::setw(15) << "Max Time (ms)" << std::setw(12) << "Success Rate" << "Status\n"; std::cout << std::string(95, '-') << "\n"; - + for (const auto& result : results) { std::string status = result.isValid() ? "SUCCESS" : "FAILED"; - std::cout << std::left << std::setw(25) << result.name.substr(0, 24) - << std::setw(10) << result.category - << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.maxDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" - << status << "\n"; - + std::cout << std::left << std::setw(25) << result.name.substr(0, 24) << std::setw(10) << result.category + << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs << std::setw(15) + << std::fixed << std::setprecision(3) << result.minDurationMs << std::setw(15) << std::fixed + << std::setprecision(3) << result.maxDurationMs << std::setw(12) << std::fixed << std::setprecision(1) + << (result.getSuccessRate() * 100) << "%" << status << "\n"; + if (!result.errorMessage.empty()) { std::cout << " Error: " << result.errorMessage << "\n"; } } - + // Calculate summary statistics int totalSuccessful = 0, totalFailed = 0; double totalTime = 0.0; - + for (const auto& result : results) { if (result.isValid()) { totalSuccessful++; @@ -226,23 +222,22 @@ void printBenchmarkSummary(const std::vector& results) { totalFailed++; } } - + std::cout << "\n"; std::cout << "Total Benchmarks: " << results.size() << "\n"; std::cout << "Successful: " << totalSuccessful << "\n"; std::cout << "Failed: " << totalFailed << "\n"; if (totalSuccessful > 0) { - std::cout << "Average Time: " << std::fixed << std::setprecision(3) - << (totalTime / totalSuccessful) << " ms\n"; + std::cout << "Average Time: " << std::fixed << std::setprecision(3) << (totalTime / totalSuccessful) << " ms\n"; } } int main(int argc, char* argv[]) { // Initialize logging LogManager::configureConsoleLogging(LogLevel::INFO, false); - + auto& suite = BenchmarkSuite::getInstance(); - + // Command line argument parsing std::string command; std::string specificBenchmark; @@ -252,10 +247,10 @@ int main(int argc, char* argv[]) { std::string htmlOutput; int iterations = 10; bool verbose = false; - + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; - + if (arg == "--help" || arg == "-h") { printUsage(argv[0]); return 0; @@ -287,21 +282,21 @@ int main(int argc, char* argv[]) { return 1; } } - + if (command.empty()) { command = "run-all"; // Default action } - + // Configure benchmark suite suite.setDefaultIterations(iterations); suite.enableVerboseOutput(verbose); - + // Register demo benchmarks registerDemoBenchmarks(); - + std::cout << "Bolt Performance Benchmark Suite (Standalone)\n"; std::cout << "=============================================\n\n"; - + try { if (command == "list") { auto benchmarks = suite.getAvailableBenchmarks(); @@ -310,7 +305,7 @@ int main(int argc, char* argv[]) { std::cout << " " << name << "\n"; } std::cout << "\nTotal: " << benchmarks.size() << " benchmarks\n"; - + } else if (command == "categories") { auto categories = suite.getAvailableCategories(); std::cout << "Available Categories:\n"; @@ -318,12 +313,12 @@ int main(int argc, char* argv[]) { std::cout << " " << category << "\n"; } std::cout << "\nTotal: " << categories.size() << " categories\n"; - + } else if (command == "run-all") { std::cout << "Running all benchmarks...\n"; auto results = suite.runAllBenchmarks(); printBenchmarkSummary(results); - + // Generate reports if (!jsonOutput.empty()) { suite.generateJsonReport(results, jsonOutput); @@ -337,7 +332,7 @@ int main(int argc, char* argv[]) { suite.generateHtmlReport(results, htmlOutput); std::cout << "HTML report saved to: " << htmlOutput << "\n"; } - + } else if (command == "category") { std::cout << "Running benchmarks in category: " << specificCategory << "\n"; auto results = suite.runBenchmarksByCategory(specificCategory); @@ -346,23 +341,22 @@ int main(int argc, char* argv[]) { return 1; } printBenchmarkSummary(results); - + } else if (command == "benchmark") { std::cout << "Running benchmark: " << specificBenchmark << "\n"; auto result = suite.runBenchmark(specificBenchmark); std::vector results = {result}; printBenchmarkSummary(results); - + if (!result.isValid()) { return 1; } } - } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } - + std::cout << "\nBenchmark execution completed.\n"; return 0; -} \ No newline at end of file +} diff --git a/bolt_ai_terminal.cpp b/bolt_ai_terminal.cpp index fae85fb7..90d8ffc1 100644 --- a/bolt_ai_terminal.cpp +++ b/bolt_ai_terminal.cpp @@ -8,15 +8,15 @@ int main() { std::cout << "๐Ÿฆ™ Bolt TinyLlama Chat Terminal" << std::endl; std::cout << "==============================" << std::endl; - + // Create our AI manager bolt::ai::EnhancedAIManager ai_manager; std::cout << "โœ… AI Manager initialized" << std::endl; - + // Try to auto-detect and load GGUF models std::cout << "๐Ÿ” Looking for TinyLlama models..." << std::endl; bool model_found = ai_manager.auto_detect_models(); - + if (model_found) { std::cout << "โœ… GGUF model loaded!" << std::endl; std::cout << "๐Ÿ“‹ Model info: " << ai_manager.get_model_info() << std::endl; @@ -24,28 +24,28 @@ int main() { std::cout << "โš ๏ธ No GGUF models found, but intelligent fallback responses available!" << std::endl; std::cout << "๐Ÿ’ก To use a real model, place a .gguf file in the ./models/ directory" << std::endl; } - + std::cout << "\n๐Ÿ’ฌ Chat with AI (type 'quit' to exit, 'info' for model details):" << std::endl; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; - + std::string input; std::string session_id = "terminal_chat"; - + // Create a session ai_manager.create_session(session_id); - + while (true) { std::cout << "\n๐Ÿ‘ค You: "; - + if (!std::getline(std::cin, input)) { - break; // EOF or error + break; // EOF or error } - + if (input == "quit" || input == "exit") { std::cout << "๐Ÿ‘‹ Goodbye!" << std::endl; break; } - + if (input == "info") { if (ai_manager.has_direct_model()) { std::cout << "๐Ÿ“‹ " << ai_manager.get_model_info() << std::endl; @@ -55,7 +55,7 @@ int main() { } continue; } - + if (input == "stats") { auto stats = ai_manager.get_statistics(); std::cout << "๐Ÿ“Š Statistics:" << std::endl; @@ -65,17 +65,17 @@ int main() { std::cout << " Avg response time: " << stats.average_inference_time_ms << "ms" << std::endl; continue; } - + if (input.empty()) { continue; } - + std::cout << "\n๐Ÿค– AI: "; std::cout.flush(); - + // Get AI response auto response = ai_manager.chat(input, session_id); - + if (response.success) { std::cout << response.response << std::endl; std::cout << "โฑ๏ธ Response time: " << response.inference_time_ms << "ms" << std::endl; @@ -85,9 +85,9 @@ int main() { } else { std::cout << "โŒ Error: " << response.error << std::endl; } - + std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; } - + return 0; } diff --git a/bolt_chat.cpp b/bolt_chat.cpp index 5042450b..010e758f 100644 --- a/bolt_chat.cpp +++ b/bolt_chat.cpp @@ -1,60 +1,63 @@ -#include "bolt/ai/direct_gguf_inference.hpp" #include #include #include +#include "bolt/ai/direct_gguf_inference.hpp" + class BoltTerminalChat { -private: + private: bolt::ai::DirectGGUFInference ai_; std::vector conversation_history_; - -public: + + public: bool initialize() { std::cout << "๐Ÿš€ Bolt Terminal Chat - Direct GGUF Access\n"; std::cout << "=========================================\n\n"; - + // Load the TinyLlama model - std::string model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + std::string model_path = + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; + std::cout << "๐Ÿ“ฅ Loading AI model...\n"; bool loaded = ai_.load_model(model_path); - + if (!loaded) { std::cout << "โŒ Failed to load model\n"; return false; } - + std::cout << "โœ… AI model loaded successfully!\n"; std::cout << ai_.get_model_info() << "\n"; return true; } - + void run_chat() { std::cout << "\n๐Ÿ’ฌ Chat ready! Commands:\n"; std::cout << " Type your message and press Enter\n"; std::cout << " /help - Show help\n"; std::cout << " /clear - Clear conversation history\n"; std::cout << " /quit, /exit, quit, exit - End chat\n\n"; - + std::string input; while (true) { std::cout << "You> "; std::getline(std::cin, input); - - if (input.empty()) continue; - + + if (input.empty()) + continue; + // Handle commands if (input == "/quit" || input == "/exit" || input == "quit" || input == "exit") { std::cout << "๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/clear") { conversation_history_.clear(); std::cout << "๐Ÿงน Conversation history cleared\n"; continue; } - + if (input == "/help") { std::cout << "Available commands:\n"; std::cout << " /help - Show this help\n"; @@ -63,28 +66,28 @@ class BoltTerminalChat { std::cout << " Just type your message for AI chat\n"; continue; } - + // Generate AI response std::cout << "AI> ๐Ÿค” Thinking...\r" << std::flush; - + auto response = ai_.chat(input, conversation_history_); - + if (response.success) { std::cout << "AI> " << response.response << "\n\n"; - + // Update conversation history conversation_history_.push_back(input); conversation_history_.push_back(response.response); - + // Keep history manageable (last 10 exchanges = 20 messages) if (conversation_history_.size() > 20) { conversation_history_.erase(conversation_history_.begin(), conversation_history_.begin() + 2); } - + // Show some stats std::cout << "โฑ๏ธ Response time: " << static_cast(response.inference_time_ms / 1000) << "s | "; std::cout << "Tokens: " << response.tokens_generated << "\n\n"; - + } else { std::cout << "AI> โŒ Error: " << response.error << "\n\n"; } @@ -94,11 +97,11 @@ class BoltTerminalChat { int main(int argc, char* argv[]) { BoltTerminalChat chat; - + if (!chat.initialize()) { return 1; } - + chat.run_chat(); return 0; } diff --git a/bolt_terminal_ai_fixed.cpp b/bolt_terminal_ai_fixed.cpp index 701fe381..f5ff33a7 100644 --- a/bolt_terminal_ai_fixed.cpp +++ b/bolt_terminal_ai_fixed.cpp @@ -1,42 +1,46 @@ -#include "include/bolt/ai/enhanced_ai_manager.hpp" +#include // For isatty + #include -#include #include -#include // For isatty +#include + +#include "include/bolt/ai/enhanced_ai_manager.hpp" class BoltTerminalAI { -private: + private: std::unique_ptr ai_manager_; std::string session_id_; - -public: + + public: BoltTerminalAI() { ai_manager_ = std::make_unique(); session_id_ = "terminal_session"; ai_manager_->create_session(session_id_); } - + void show_status() { std::cout << "\n๐Ÿ“Š AI Status:\n"; std::cout << " Current Provider: " << ai_manager_->get_current_provider() << "\n"; std::cout << " Ready: " << (ai_manager_->is_ready() ? "โœ…" : "โŒ") << "\n"; - std::cout << " Direct Model: " << (ai_manager_->has_direct_model() ? "โœ… " + ai_manager_->get_model_info() : "โŒ Using fallback") << "\n"; - + std::cout << " Direct Model: " + << (ai_manager_->has_direct_model() ? "โœ… " + ai_manager_->get_model_info() : "โŒ Using fallback") + << "\n"; + auto stats = ai_manager_->get_statistics(); std::cout << " Total Requests: " << stats.total_requests << "\n"; std::cout << " Successful: " << stats.successful_requests << "\n"; std::cout << " Failed: " << stats.failed_requests << "\n\n"; } - + void chat_loop() { std::cout << "๐Ÿค– Bolt AI Terminal Chat\n"; std::cout << "========================\n\n"; - + show_status(); - + // Check if input is from a pipe or terminal bool is_piped = !isatty(fileno(stdin)); - + if (!is_piped) { std::cout << "Commands:\n"; std::cout << " /status - Show AI status\n"; @@ -44,56 +48,65 @@ class BoltTerminalAI { std::cout << " /clear - Clear chat history\n"; std::cout << " /load - Try to load a GGUF model\n"; std::cout << " /quit - Exit the application\n\n"; - + std::cout << "๐Ÿ’ฌ Start chatting (type your message and press Enter):\n\n"; } - + std::string input; while (std::getline(std::cin, input)) { if (input.empty()) { - if (is_piped) break; // Exit on empty line when piped + if (is_piped) + break; // Exit on empty line when piped continue; } - + if (!is_piped) { std::cout << "You: " << input << "\n"; } - + // Handle commands if (input == "/quit" || input == "/exit") { std::cout << "\n๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/status") { show_status(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/history") { show_history(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/clear") { ai_manager_->clear_session_history(session_id_); std::cout << "๐Ÿ—‘๏ธ Chat history cleared.\n\n"; - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/load") { try_load_model(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + // Send to AI std::cout << "AI: "; auto response = ai_manager_->chat(input, session_id_); - + if (response.success) { std::cout << response.response << "\n"; if (response.inference_time_ms > 0) { @@ -106,9 +119,9 @@ class BoltTerminalAI { } else { std::cout << "โŒ Error: " << response.error << "\n"; } - + std::cout << "\n"; - + // For piped input, process one question and exit if (is_piped) { break; @@ -116,14 +129,14 @@ class BoltTerminalAI { } } -private: + private: void show_history() { auto history = ai_manager_->get_session_history(session_id_); if (history.empty()) { std::cout << "๐Ÿ“ No chat history yet.\n\n"; return; } - + std::cout << "\n๐Ÿ“œ Chat History:\n"; std::cout << "================\n"; for (const auto& entry : history) { @@ -131,7 +144,7 @@ class BoltTerminalAI { } std::cout << "\n"; } - + void try_load_model() { std::cout << "๐Ÿ” Attempting to auto-detect GGUF models...\n"; if (ai_manager_->auto_detect_models()) { @@ -140,7 +153,8 @@ class BoltTerminalAI { } else { std::cout << "โŒ No GGUF models found. You can:\n"; std::cout << " 1. Download a small model:\n"; - std::cout << " wget -P ./models/ https://huggingface.co/microsoft/DialoGPT-small/resolve/main/model.gguf\n"; + std::cout + << " wget -P ./models/ https://huggingface.co/microsoft/DialoGPT-small/resolve/main/model.gguf\n"; std::cout << " 2. Or continue using intelligent fallback responses\n\n"; } } @@ -154,6 +168,6 @@ int main() { std::cerr << "โŒ Error: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/bolt_terminal_chat.cpp b/bolt_terminal_chat.cpp index 293b03a4..0deab430 100644 --- a/bolt_terminal_chat.cpp +++ b/bolt_terminal_chat.cpp @@ -1,117 +1,118 @@ +#include #include #include -#include -#include #include +#include // Simple terminal chat that calls KoboldCpp as a subprocess class KoboldTerminal { -private: + private: std::string kobold_path; std::string model_path; std::vector conversation; - -public: - KoboldTerminal(const std::string& kobold, const std::string& model) - : kobold_path(kobold), model_path(model) {} - + + public: + KoboldTerminal(const std::string& kobold, const std::string& model) : kobold_path(kobold), model_path(model) {} + bool initialize() { std::cout << "๐Ÿš€ Initializing Bolt Terminal Chat with KoboldCpp\n"; std::cout << "Model: " << model_path << std::endl; - + // Check if files exist std::ifstream kobold_file(kobold_path); std::ifstream model_file(model_path); - + if (!kobold_file.good()) { std::cout << "โŒ KoboldCpp not found: " << kobold_path << std::endl; return false; } - + if (!model_file.good()) { std::cout << "โŒ Model not found: " << model_path << std::endl; return false; } - + std::cout << "โœ… Files found successfully" << std::endl; return true; } - + std::string chat(const std::string& message) { conversation.push_back("Human: " + message); - + // Format prompt with conversation history std::string prompt = "You are a helpful AI assistant specialized in programming.\n\n"; - + // Add recent conversation (keep it manageable) int start_idx = std::max(0, static_cast(conversation.size()) - 6); for (int i = start_idx; i < static_cast(conversation.size()); i++) { prompt += conversation[i] + "\n"; } prompt += "Assistant: "; - + // Write prompt to temp file std::ofstream temp_file("/tmp/prompt.txt"); temp_file << prompt; temp_file.close(); - + // Call KoboldCpp with the prompt - std::string command = "cd " + kobold_path + " && echo \"" + message + "\" | python koboldcpp.py --model \"" + model_path + "\" --cli --promptlimit 150 2>/dev/null | tail -1"; - + std::string command = "cd " + kobold_path + " && echo \"" + message + "\" | python koboldcpp.py --model \"" + + model_path + "\" --cli --promptlimit 150 2>/dev/null | tail -1"; + FILE* pipe = popen(command.c_str(), "r"); if (!pipe) { return "โŒ Failed to execute KoboldCpp"; } - + std::string result; char buffer[1024]; while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { result += buffer; } pclose(pipe); - + // Clean up the response if (result.empty()) { return "โŒ No response from AI"; } - + // Remove any trailing newlines while (!result.empty() && (result.back() == '\n' || result.back() == '\r')) { result.pop_back(); } - + conversation.push_back("Assistant: " + result); - + // Keep conversation history manageable if (conversation.size() > 12) { conversation.erase(conversation.begin(), conversation.begin() + 2); } - + return result; } - + void run_interactive() { std::cout << "\n๐Ÿ’ฌ Bolt Terminal Chat Ready!\n"; std::cout << "Type your messages below. Use 'quit', 'exit', or '/quit' to end.\n\n"; - + std::string input; while (true) { std::cout << "> "; std::getline(std::cin, input); - - if (input.empty()) continue; - + + if (input.empty()) + continue; + if (input == "quit" || input == "exit" || input == "/quit" || input == "/exit") { std::cout << "๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/clear") { conversation.clear(); std::cout << "๐Ÿงน Conversation history cleared.\n"; continue; } - + if (input == "/help") { std::cout << "Commands:\n"; std::cout << " /quit, /exit - Exit the chat\n"; @@ -119,7 +120,7 @@ class KoboldTerminal { std::cout << " /help - Show this help\n"; continue; } - + std::cout << "๐Ÿค– Thinking..." << std::flush; std::string response = chat(input); std::cout << "\r๐Ÿค– " << response << "\n\n"; @@ -130,21 +131,22 @@ class KoboldTerminal { int main(int argc, char* argv[]) { std::cout << "๐Ÿš€ Bolt Terminal Chat - Direct GGUF Access\n"; std::cout << "==========================================\n\n"; - + std::string kobold_dir = "/workspaces/bolt-cppml/ggml/kobold.cpp"; - std::string model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + std::string model_path = + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; + if (argc > 1) { model_path = argv[1]; } - + KoboldTerminal terminal(kobold_dir, model_path); - + if (!terminal.initialize()) { return 1; } - + terminal.run_interactive(); - + return 0; } diff --git a/demo_advanced_lsp.cpp b/demo_advanced_lsp.cpp index 44a77db7..a0f369e8 100644 --- a/demo_advanced_lsp.cpp +++ b/demo_advanced_lsp.cpp @@ -1,7 +1,7 @@ /** * @file demo_advanced_lsp.cpp * @brief Demo application testing all advanced LSP features - * + * * Tests: * - Go-to-Definition (F12) * - Find References (Shift+F12) @@ -9,16 +9,17 @@ * - Code Formatting (Shift+Alt+F) */ -#include "bolt/editor/lsp_client.hpp" -#include "bolt/editor/lsp_server_configs.hpp" -#include "bolt/editor/lsp_protocol.hpp" -#include -#include #include -#include #include +#include +#include +#include -using namespace bolt::lsp; +#include "bolt/editor/lsp_client.hpp" +#include "bolt/editor/lsp_protocol.hpp" +#include "bolt/editor/lsp_server_configs.hpp" + +using namespace bolt::lsp; // NOLINT(build/namespaces) // Test file content with multiple symbols and references const char* TEST_CPP_CODE = R"( @@ -75,8 +76,7 @@ void printSeparator(const std::string& title) { void printLocation(const Location& loc) { std::cout << " ๐Ÿ“ " << loc.uri << "\n"; - std::cout << " Line " << loc.range.start.line + 1 - << ", Col " << loc.range.start.character + 1 << "\n"; + std::cout << " Line " << loc.range.start.line + 1 << ", Col " << loc.range.start.character + 1 << "\n"; } void printSymbol(const DocumentSymbol& sym, int indent = 0) { @@ -87,15 +87,14 @@ void printSymbol(const DocumentSymbol& sym, int indent = 0) { } std::cout << " [" << static_cast(sym.kind) << "]"; std::cout << " @ line " << sym.selectionRange.start.line + 1 << "\n"; - + for (const auto& child : sym.children) { printSymbol(child, indent + 1); } } void printTextEdit(const TextEdit& edit) { - std::cout << " โœ๏ธ Lines " << edit.range.start.line + 1 - << "-" << edit.range.end.line + 1 << ": "; + std::cout << " โœ๏ธ Lines " << edit.range.start.line + 1 << "-" << edit.range.end.line + 1 << ": "; if (edit.newText.length() > 50) { std::cout << edit.newText.substr(0, 50) << "...\n"; } else { @@ -115,7 +114,7 @@ int main() { std::string testDir = "/tmp/bolt_advanced_lsp_test"; std::filesystem::create_directories(testDir); std::string testFile = testDir + "/test_advanced.cpp"; - + { std::ofstream ofs(testFile); ofs << TEST_CPP_CODE; @@ -127,16 +126,16 @@ int main() { std::cerr << "โŒ clangd not available. Please install clangd.\n"; return 1; } - + auto config = LspServerConfigs::getConfigForLanguage("cpp"); config.rootPath = testDir; - + std::cout << "โœ… clangd available: " << config.serverCommand << "\n"; // Create and connect LSP client auto connection = std::make_unique(); LspClient client(std::move(connection)); - + if (!client.connect(config)) { std::cerr << "โŒ Failed to connect to clangd\n"; return 1; @@ -145,11 +144,9 @@ int main() { // Initialize bool initSuccess = false; - client.initialize([&initSuccess](bool success) { - initSuccess = success; - }); + client.initialize([&initSuccess](bool success) { initSuccess = success; }); std::this_thread::sleep_for(std::chrono::milliseconds(500)); - + if (!initSuccess) { std::cerr << "โŒ Failed to initialize LSP session\n"; return 1; @@ -171,25 +168,25 @@ int main() { // ======================================================================== printSeparator("Test 1: Go-to-Definition"); std::cout << "Testing definition of 'Calculator' at line 27 (calc.add)\n"; - + std::vector definitions; bool defReceived = false; - + TextDocumentPositionParams defParams; defParams.textDocument.uri = doc.uri; - defParams.position.line = 26; // Line with "calc.add" + defParams.position.line = 26; // Line with "calc.add" defParams.position.character = 4; // Position of "calc" - + client.definition(defParams, [&definitions, &defReceived](const std::vector& locs) { definitions = locs; defReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !defReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (defReceived && !definitions.empty()) { std::cout << "โœ… Go-to-Definition: Found " << definitions.size() << " definition(s)\n"; for (const auto& loc : definitions) { @@ -204,25 +201,25 @@ int main() { // ======================================================================== printSeparator("Test 2: Find References"); std::cout << "Testing references to 'add' method\n"; - + std::vector references; bool refsReceived = false; - + TextDocumentPositionParams refParams; refParams.textDocument.uri = doc.uri; - refParams.position.line = 8; // Line with "int add(int a, int b)" + refParams.position.line = 8; // Line with "int add(int a, int b)" refParams.position.character = 8; // Position of "add" - + client.references(refParams, [&references, &refsReceived](const std::vector& locs) { references = locs; refsReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !refsReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (refsReceived && !references.empty()) { std::cout << "โœ… Find References: Found " << references.size() << " reference(s)\n"; for (const auto& loc : references) { @@ -237,23 +234,23 @@ int main() { // ======================================================================== printSeparator("Test 3: Document Symbols"); std::cout << "Testing document symbols (outline)\n"; - + std::vector symbols; bool symsReceived = false; - + TextDocumentIdentifier symDocId; symDocId.uri = doc.uri; - + client.documentSymbol(symDocId, [&symbols, &symsReceived](const std::vector& syms) { symbols = syms; symsReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !symsReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (symsReceived && !symbols.empty()) { std::cout << "โœ… Document Symbols: Found " << symbols.size() << " top-level symbol(s)\n"; for (const auto& sym : symbols) { @@ -268,27 +265,27 @@ int main() { // ======================================================================== printSeparator("Test 4: Code Formatting"); std::cout << "Testing document formatting\n"; - + std::vector edits; bool fmtReceived = false; - + TextDocumentIdentifier fmtDocId; fmtDocId.uri = doc.uri; - + FormattingOptions fmtOpts; fmtOpts.tabSize = 4; fmtOpts.insertSpaces = true; - + client.formatting(fmtDocId, fmtOpts, [&edits, &fmtReceived](const std::vector& e) { edits = e; fmtReceived = true; }); - + // Wait for response for (int i = 0; i < 50 && !fmtReceived; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } - + if (fmtReceived) { if (edits.empty()) { std::cout << "โœ… Code Formatting: Document already formatted (no changes needed)\n"; @@ -306,12 +303,12 @@ int main() { // Cleanup // ======================================================================== printSeparator("Cleanup"); - + TextDocumentIdentifier closeDocId; closeDocId.uri = doc.uri; client.didCloseTextDocument(closeDocId); std::cout << "โœ… Document closed\n"; - + client.shutdown([](bool success) {}); std::this_thread::sleep_for(std::chrono::milliseconds(200)); client.disconnect(); @@ -319,12 +316,13 @@ int main() { // Summary printSeparator("Summary"); + const auto verdict = [](bool passed) { return passed ? "โœ… PASSED" : "โš ๏ธ PARTIAL"; }; std::cout << "Advanced LSP Features Test Results:\n"; - std::cout << " โ€ข Go-to-Definition: " << (defReceived && !definitions.empty() ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - std::cout << " โ€ข Find References: " << (refsReceived && !references.empty() ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - std::cout << " โ€ข Document Symbols: " << (symsReceived && !symbols.empty() ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - std::cout << " โ€ข Code Formatting: " << (fmtReceived ? "โœ… PASSED" : "โš ๏ธ PARTIAL") << "\n"; - + std::cout << " โ€ข Go-to-Definition: " << verdict(defReceived && !definitions.empty()) << "\n"; + std::cout << " โ€ข Find References: " << verdict(refsReceived && !references.empty()) << "\n"; + std::cout << " โ€ข Document Symbols: " << verdict(symsReceived && !symbols.empty()) << "\n"; + std::cout << " โ€ข Code Formatting: " << verdict(fmtReceived) << "\n"; + std::cout << "\nNote: Some features may show partial results on first run due to\n"; std::cout << "clangd needing time to build its index. Re-running typically shows\n"; std::cout << "complete results.\n"; diff --git a/demo_ai_code_completion_live.cpp b/demo_ai_code_completion_live.cpp index 9de09c94..e94428f3 100644 --- a/demo_ai_code_completion_live.cpp +++ b/demo_ai_code_completion_live.cpp @@ -1,27 +1,28 @@ -#include "bolt/ai/llama_completion_provider.hpp" -#include "bolt/ai/ai_code_generator.hpp" #include #include +#include "bolt/ai/ai_code_generator.hpp" +#include "bolt/ai/llama_completion_provider.hpp" + int main() { std::cout << "=== AI-Powered Code Completion Demo ===\n\n"; - + // 1. Initialize the Llama completion provider std::cout << "Initializing AI completion provider...\n"; auto llama_provider = std::make_unique(); - + if (!llama_provider->initialize()) { std::cerr << "โŒ Failed to initialize Llama provider.\n"; std::cerr << "Make sure a GGUF model is available in ./models/\n"; return 1; } - + std::cout << "โœ… AI provider initialized\n"; std::cout << "Model: " << llama_provider->getModelInfo() << "\n\n"; - + // 2. Test code completion scenarios std::cout << "=== Test 1: Function Completion ===\n"; - + bolt::CodeContext context1; context1.language = "cpp"; context1.filePath = "example.cpp"; @@ -40,19 +41,19 @@ int calculateSum(const std::vector& numbers) { // Function to calculate the average )"; context1.cursorPosition = context1.content.length(); - + auto completions1 = llama_provider->generateCompletions(context1, "", 3); - + std::cout << "Code before cursor:\n" << context1.content << "โ–ˆ\n\n"; std::cout << "AI Suggestions:\n"; for (size_t i = 0; i < completions1.size(); ++i) { std::cout << (i + 1) << ". " << completions1[i].label << "\n"; std::cout << " Type: " << static_cast(completions1[i].kind) << "\n\n"; } - + // 3. Test class member completion std::cout << "\n=== Test 2: Class Member Completion ===\n"; - + bolt::CodeContext context2; context2.language = "cpp"; context2.content = R"(class DataProcessor { @@ -69,36 +70,34 @@ int calculateSum(const std::vector& numbers) { // Add a method to get the data size )"; context2.cursorPosition = context2.content.length(); - + auto completions2 = llama_provider->generateCompletions(context2, "", 3); - + std::cout << "Code before cursor:\n" << context2.content << "โ–ˆ\n\n"; std::cout << "AI Suggestions:\n"; for (size_t i = 0; i < completions2.size(); ++i) { std::cout << (i + 1) << ". " << completions2[i].label << "\n\n"; } - + // 4. Test with AIEnhancedCodeGenerator std::cout << "\n=== Test 3: Full Code Generation ===\n"; - + auto code_generator = std::make_unique(); code_generator->setAIProvider(std::move(llama_provider)); - + bolt::CodeGenerationContext gen_context; gen_context.language = "cpp"; gen_context.projectContext = "A simple data processing application"; - - auto generated_func = code_generator->generateFunction( - "a function that finds the maximum element in a vector", - gen_context - ); - + + auto generated_func = + code_generator->generateFunction("a function that finds the maximum element in a vector", gen_context); + std::cout << "Generated Function:\n"; std::cout << "Description: " << generated_func.description << "\n"; std::cout << "Code:\n" << generated_func.code << "\n"; std::cout << "Confidence: " << generated_func.confidence << "\n"; - + std::cout << "\n=== Demo Complete ===\n"; - + return 0; } diff --git a/demo_ai_completion.cpp b/demo_ai_completion.cpp index 889b8e4e..cf46f4ea 100644 --- a/demo_ai_completion.cpp +++ b/demo_ai_completion.cpp @@ -1,21 +1,22 @@ +#include +#include + #include "bolt/ai/ai_completion_provider.hpp" #include "bolt/editor/integrated_editor.hpp" -#include -#include -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateAICompletion() { std::cout << "=== AI Code Completion Integration Demo ===\n\n"; - + // Get the integrated editor instance IntegratedEditor& editor = IntegratedEditor::getInstance(); - + std::cout << "1. Checking AI Completion Status:\n"; std::cout << " AI Completion Ready: " << (editor.isAICompletionReady() ? "YES" : "NO") << "\n"; std::cout << " AI Completion Enabled: " << (editor.isAICompletionEnabled() ? "YES" : "NO") << "\n"; std::cout << " Code Completion Active: " << (editor.isCodeCompletionActive() ? "YES" : "NO") << "\n\n"; - + // Create a test C++ file std::cout << "2. Opening test C++ file with content:\n"; std::string testFilePath = "demo.cpp"; @@ -27,22 +28,22 @@ int main() { std:: return 0; })"; - + std::cout << " File: " << testFilePath << "\n"; std::cout << " Content:\n"; std::cout << testContent << "\n\n"; - + editor.openDocument(testFilePath, testContent); - + // Test AI completions for std:: std::cout << "3. Getting AI completions for 'std::':\n"; auto completions = editor.getAICompletions(testFilePath, "std::", 5); - + if (!completions.empty()) { std::cout << " Found " << completions.size() << " completions:\n"; for (size_t i = 0; i < completions.size(); ++i) { - std::cout << " " << (i + 1) << ". " << std::left << std::setw(15) << completions[i].label - << " (" << completions[i].kind << ", score: " << completions[i].score << ")\n"; + std::cout << " " << (i + 1) << ". " << std::left << std::setw(15) << completions[i].label << " (" + << completions[i].kind << ", score: " << completions[i].score << ")\n"; if (!completions[i].detail.empty()) { std::cout << " " << completions[i].detail << "\n"; } @@ -51,37 +52,37 @@ int main() { std::cout << " No completions found.\n"; } std::cout << "\n"; - + // Test triggering completion std::cout << "4. Triggering code completion:\n"; editor.triggerCodeCompletion(testFilePath, "std::"); std::cout << " Code Completion Active: " << (editor.isCodeCompletionActive() ? "YES" : "NO") << "\n"; - + if (editor.isCodeCompletionActive()) { auto selected = editor.getSelectedCompletion(); std::cout << " Selected: " << selected.label << "\n"; - + std::cout << " Testing navigation...\n"; editor.selectNextCompletion(); selected = editor.getSelectedCompletion(); std::cout << " After next: " << selected.label << "\n"; - + editor.selectPreviousCompletion(); selected = editor.getSelectedCompletion(); std::cout << " After previous: " << selected.label << "\n"; } std::cout << "\n"; - + // Test different prefixes std::cout << "5. Testing different completion contexts:\n"; - + // Test for 'class' keyword auto classCompletions = editor.getAICompletions(testFilePath, "class", 3); std::cout << " 'class' prefix: " << classCompletions.size() << " completions\n"; for (const auto& comp : classCompletions) { std::cout << " " << comp.label << "\n"; } - + // Test for 'for' keyword auto forCompletions = editor.getAICompletions(testFilePath, "for", 3); std::cout << " 'for' prefix: " << forCompletions.size() << " completions\n"; @@ -89,41 +90,41 @@ int main() { std::cout << " " << comp.label << "\n"; } std::cout << "\n"; - + // Test AI enable/disable std::cout << "6. Testing AI enable/disable:\n"; editor.setAICompletionEnabled(false); - std::cout << " AI Disabled - Completions for 'std::': " + std::cout << " AI Disabled - Completions for 'std::': " << editor.getAICompletions(testFilePath, "std::", 3).size() << "\n"; - + editor.setAICompletionEnabled(true); - std::cout << " AI Re-enabled - Completions for 'std::': " + std::cout << " AI Re-enabled - Completions for 'std::': " << editor.getAICompletions(testFilePath, "std::", 3).size() << "\n"; std::cout << "\n"; - + // Clean up if (editor.isCodeCompletionActive()) { editor.cancelCompletion(); } - + std::cout << "7. Final state:\n"; std::cout << " Code Completion Active: " << (editor.isCodeCompletionActive() ? "YES" : "NO") << "\n"; std::cout << " AI Completion Enabled: " << (editor.isAICompletionEnabled() ? "YES" : "NO") << "\n"; - + std::cout << "\n=== Demo Complete ===\n"; } void demonstrateAIProviderDirectly() { std::cout << "\n=== Direct AI Provider Demo ===\n\n"; - + // Test the AI provider directly MockAICompletionProvider provider; - + std::cout << "1. Initializing AI Provider:\n"; std::cout << " Ready before init: " << (provider.isReady() ? "YES" : "NO") << "\n"; provider.initialize(); std::cout << " Ready after init: " << (provider.isReady() ? "YES" : "NO") << "\n\n"; - + // Test C++ context std::cout << "2. Testing C++ completion context:\n"; CodeContext cppContext; @@ -133,39 +134,39 @@ void demonstrateAIProviderDirectly() { cppContext.line = 1; cppContext.column = 9; cppContext.language = "cpp"; - + auto completions = provider.generateCompletions(cppContext, "std::", 5); std::cout << " Generated " << completions.size() << " completions for 'std::':\n"; for (const auto& comp : completions) { std::cout << " " << comp.label << " (" << comp.kind << ")\n"; } std::cout << "\n"; - + // Test different context std::cout << "3. Testing different contexts:\n"; cppContext.content = "class MyClass {\n \n};"; cppContext.cursorPosition = 16; - + completions = provider.generateCompletions(cppContext, "for", 3); std::cout << " 'for' in class context: " << completions.size() << " completions\n"; - + completions = provider.generateCompletions(cppContext, "", 3); std::cout << " Empty prefix: " << completions.size() << " completions\n"; - + provider.shutdown(); std::cout << " Ready after shutdown: " << (provider.isReady() ? "YES" : "NO") << "\n"; - + std::cout << "\n=== AI Provider Demo Complete ===\n"; } int main() { std::cout << "Bolt C++ AI Code Completion Integration Demo\n"; std::cout << "============================================\n\n"; - + try { demonstrateAICompletion(); demonstrateAIProviderDirectly(); - + std::cout << "\nโœ… All demonstrations completed successfully!\n"; std::cout << "\nAI Code Completion has been successfully integrated with the editor.\n"; std::cout << "Features available:\n"; @@ -176,11 +177,10 @@ int main() { std::cout << " - Accept (Enter) and Cancel (Escape) operations\n"; std::cout << " - Enable/disable AI completions\n"; std::cout << " - Mock AI provider ready for real AI integration\n"; - + return 0; - } catch (const std::exception& e) { std::cerr << "โŒ Error during demonstration: " << e.what() << "\n"; return 1; } -} \ No newline at end of file +} diff --git a/demo_ai_config.cpp b/demo_ai_config.cpp index f92b175c..5e2aced3 100644 --- a/demo_ai_config.cpp +++ b/demo_ai_config.cpp @@ -1,45 +1,46 @@ -#include "bolt/ai/enhanced_ai_manager.hpp" -#include "bolt/ai/ai_http_client.hpp" #include #include +#include "bolt/ai/ai_http_client.hpp" +#include "bolt/ai/enhanced_ai_manager.hpp" + int main() { std::cout << "๐Ÿš€ Bolt AI Chat Configuration Demo" << std::endl; std::cout << "==================================" << std::endl << std::endl; - + try { // Initialize enhanced AI manager std::cout << "๐Ÿ”ง Initializing Enhanced AI Manager..." << std::endl; bolt::ai::EnhancedAIManager ai_manager; - + // Run quick setup wizard std::cout << "\n๐Ÿง™ Running Quick Setup Wizard..." << std::endl; bool setup_success = bolt::ai::AutoSetup::quick_setup_wizard(); - + if (!setup_success) { std::cout << "\nโš ๏ธ No AI providers detected. Let's configure one manually." << std::endl; - + // Show available configurations auto recommended = bolt::ai::AIHttpClientFactory::get_recommended_configs(); std::cout << "\n๐Ÿ“‹ Recommended configurations:" << std::endl; for (size_t i = 0; i < recommended.size(); ++i) { - std::cout << " " << (i + 1) << ". " << recommended[i].base_url - << " (" << (int)recommended[i].api_type << ")" << std::endl; + std::cout << " " << (i + 1) << ". " << recommended[i].base_url << " (" + << static_cast(recommended[i].api_type) << ")" << std::endl; } } - + // Test current configuration std::cout << "\n๐Ÿ” Testing current configuration..." << std::endl; bool is_ready = ai_manager.is_ready(); std::cout << "AI Manager ready: " << (is_ready ? "โœ… YES" : "โŒ NO") << std::endl; - + if (is_ready) { std::cout << "Current provider: " << ai_manager.get_current_provider() << std::endl; - + // Test a simple chat std::cout << "\n๐Ÿ’ฌ Testing AI chat..." << std::endl; auto response = ai_manager.chat("Hello! Can you help me with C++ programming?", "test_session"); - + if (response.success) { std::cout << "โœ… Chat test successful!" << std::endl; std::cout << "Response: " << response.response << std::endl; @@ -47,19 +48,19 @@ int main() { } else { std::cout << "โŒ Chat test failed: " << response.error << std::endl; } - + // Test code completion std::cout << "\n๐Ÿš€ Testing code completion..." << std::endl; std::string test_code = "std::vector numbers = {1, 2, 3, 4, 5};\nfor ("; auto completion_response = ai_manager.complete_code(test_code, "cpp"); - + if (completion_response.success) { std::cout << "โœ… Code completion test successful!" << std::endl; std::cout << "Completion: " << completion_response.response << std::endl; } else { std::cout << "โŒ Code completion test failed: " << completion_response.error << std::endl; } - + // Show statistics std::cout << "\n๐Ÿ“Š AI Statistics:" << std::endl; auto stats = ai_manager.get_statistics(); @@ -69,7 +70,7 @@ int main() { std::cout << " Avg response time: " << stats.average_inference_time_ms << " ms" << std::endl; std::cout << " Tokens generated: " << stats.total_tokens_generated << std::endl; } - + // List available providers std::cout << "\n๐Ÿ”ง Available Providers:" << std::endl; auto providers = ai_manager.list_providers(); @@ -77,9 +78,9 @@ int main() { std::string status = provider.is_active ? " (ACTIVE)" : ""; std::cout << " โ€ข " << provider.name << ": " << provider.config.base_url << status << std::endl; } - + std::cout << "\nโœ… Configuration demo completed!" << std::endl; - + if (is_ready) { std::cout << "\n๐ŸŽ‰ Your AI chat is ready to use!" << std::endl; std::cout << "๐Ÿ’ก Start the GUI application to chat with the AI assistant." << std::endl; @@ -87,11 +88,10 @@ int main() { std::cout << "\nโš ๏ธ AI chat is not yet configured." << std::endl; std::cout << "๐Ÿ’ก Follow the setup instructions above or configure manually." << std::endl; } - } catch (const std::exception& e) { std::cerr << "โŒ Error: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/demo_ai_infrastructure.cpp b/demo_ai_infrastructure.cpp index 40d217ad..533750bc 100644 --- a/demo_ai_infrastructure.cpp +++ b/demo_ai_infrastructure.cpp @@ -1,30 +1,30 @@ #include + #include "bolt/ai/ggml.hpp" #include "bolt/ai/ggml_wrapper.hpp" #include "bolt/ai/rwkv_wrapper.hpp" void demonstrateGGML() { std::cout << "=== GGML Integration Demo ===" << std::endl; - + try { // Create GGML context - bolt::GGMLContext context(1024 * 1024); // 1MB + bolt::GGMLContext context(1024 * 1024); // 1MB std::cout << "โœ“ GGML Context created successfully" << std::endl; - + // Create simple tensors auto* tensor_a = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 10); auto* tensor_b = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 10); std::cout << "โœ“ Created tensors: " << ggml_nelements(tensor_a) << " elements each" << std::endl; - + // Perform operations auto* result = ggml_add(context.get(), tensor_a, tensor_b); std::cout << "โœ“ Tensor addition operation created" << std::endl; - + // Create computation graph auto* graph = ggml_new_graph_custom(context.get(), GGML_DEFAULT_GRAPH_SIZE, true); ggml_build_forward_expand(graph, result); std::cout << "โœ“ Computation graph built successfully" << std::endl; - } catch (const std::exception& e) { std::cerr << "โœ— Error: " << e.what() << std::endl; } @@ -32,18 +32,17 @@ void demonstrateGGML() { void demonstrateRWKV() { std::cout << "\n=== RWKV Integration Demo ===" << std::endl; - + try { auto& wrapper = bolt::RWKVWrapper::getInstance(); std::cout << "โœ“ RWKV Wrapper instance obtained" << std::endl; - + std::cout << "Model parameters:" << std::endl; std::cout << " - Layers: " << wrapper.getNumLayers() << std::endl; std::cout << " - Embedding dimension: " << wrapper.getEmbedDim() << std::endl; std::cout << " - Initialized: " << (wrapper.isInitialized() ? "Yes" : "No") << std::endl; - + std::cout << "โœ“ RWKV API accessible and functional" << std::endl; - } catch (const std::exception& e) { std::cerr << "โœ— Error: " << e.what() << std::endl; } @@ -52,14 +51,14 @@ void demonstrateRWKV() { int main() { std::cout << "Bolt C++ AI Infrastructure Demo" << std::endl; std::cout << "===============================" << std::endl; - + demonstrateGGML(); demonstrateRWKV(); - + std::cout << "\n=== Summary ===" << std::endl; std::cout << "โœ“ GGML library successfully integrated" << std::endl; std::cout << "โœ“ RWKV wrapper implemented with GGML backend" << std::endl; std::cout << "โœ“ Core AI infrastructure is ready for model loading and inference" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_benchmark_suite.cpp b/demo_benchmark_suite.cpp index f3c6b989..2c7dd2c9 100644 --- a/demo_benchmark_suite.cpp +++ b/demo_benchmark_suite.cpp @@ -1,16 +1,17 @@ -#include "include/bolt/core/performance_profiler.hpp" -#include "include/bolt/core/logging.hpp" -#include -#include -#include #include +#include #include -#include +#include #include -#include +#include +#include #include +#include + +#include "include/bolt/core/logging.hpp" +#include "include/bolt/core/performance_profiler.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) // Simple benchmark structure struct SimpleBenchmark { @@ -31,16 +32,19 @@ struct BenchmarkResult { int successfulRuns; int failedRuns; bool isValid() const { return successfulRuns > 0; } - double getSuccessRate() const { return successfulRuns > 0 ? (double)successfulRuns / (successfulRuns + failedRuns) : 0.0; } + double getSuccessRate() const { + return successfulRuns > 0 ? static_cast(successfulRuns) / (successfulRuns + failedRuns) : 0.0; + } }; class SimpleBenchmarkSuite { -private: + private: std::vector benchmarks_; bool verbose_; - + double calculateStandardDeviation(const std::vector& values, double mean) { - if (values.empty()) return 0.0; + if (values.empty()) + return 0.0; double variance = 0.0; for (double value : values) { variance += (value - mean) * (value - mean); @@ -48,52 +52,50 @@ class SimpleBenchmarkSuite { variance /= values.size(); return std::sqrt(variance); } - -public: + + public: SimpleBenchmarkSuite() : verbose_(false) {} - + void setVerbose(bool verbose) { verbose_ = verbose; } - - void registerBenchmark(const std::string& name, const std::string& category, - const std::string& description, int iterations, - std::function function) { + + void registerBenchmark(const std::string& name, const std::string& category, const std::string& description, + int iterations, std::function function) { benchmarks_.push_back({name, category, description, iterations, function}); if (verbose_) { std::cout << "Registered benchmark: " << name << " (" << category << ")\n"; } } - + BenchmarkResult runBenchmark(const SimpleBenchmark& benchmark) { BenchmarkResult result; result.name = benchmark.name; result.category = benchmark.category; result.successfulRuns = 0; result.failedRuns = 0; - + std::vector durations; auto& profiler = PerformanceProfiler::getInstance(); profiler.enable(); - + if (verbose_) { std::cout << "Running " << benchmark.name << " (" << benchmark.iterations << " iterations)...\n"; } - + for (int i = 0; i < benchmark.iterations; ++i) { try { auto start = std::chrono::high_resolution_clock::now(); - + // Use profiler for this run auto metric = profiler.startMetric(benchmark.name + "_run_" + std::to_string(i), benchmark.category); - + benchmark.function(); - + profiler.endMetric(metric); - + auto end = std::chrono::high_resolution_clock::now(); double duration = std::chrono::duration(end - start).count(); durations.push_back(duration); result.successfulRuns++; - } catch (const std::exception& e) { result.failedRuns++; if (verbose_) { @@ -101,56 +103,58 @@ class SimpleBenchmarkSuite { } } } - + if (!durations.empty()) { result.averageDurationMs = std::accumulate(durations.begin(), durations.end(), 0.0) / durations.size(); result.minDurationMs = *std::min_element(durations.begin(), durations.end()); result.maxDurationMs = *std::max_element(durations.begin(), durations.end()); result.standardDeviationMs = calculateStandardDeviation(durations, result.averageDurationMs); } - + return result; } - + std::vector runAllBenchmarks() { std::vector results; - + std::cout << "Running " << benchmarks_.size() << " benchmarks...\n\n"; - + for (const auto& benchmark : benchmarks_) { auto result = runBenchmark(benchmark); results.push_back(result); } - + return results; } - + std::vector runCategory(const std::string& category) { std::vector results; - + for (const auto& benchmark : benchmarks_) { if (benchmark.category == category) { auto result = runBenchmark(benchmark); results.push_back(result); } } - + return results; } - + void generateReport(const std::vector& results, const std::string& filename) { std::ofstream file(filename); if (!file.is_open()) { std::cerr << "Failed to open file: " << filename << std::endl; return; } - + file << "{\n"; file << " \"benchmark_suite_version\": \"1.0.0\",\n"; - file << " \"timestamp\": \"" << std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count() << "\",\n"; + file << " \"timestamp\": \"" + << std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count() + << "\",\n"; file << " \"results\": [\n"; - + for (size_t i = 0; i < results.size(); ++i) { const auto& result = results[i]; file << " {\n"; @@ -164,43 +168,39 @@ class SimpleBenchmarkSuite { file << " \"failed_runs\": " << result.failedRuns << ",\n"; file << " \"success_rate\": " << result.getSuccessRate() << "\n"; file << " }"; - if (i < results.size() - 1) file << ","; + if (i < results.size() - 1) + file << ","; file << "\n"; } - + file << " ]\n"; file << "}\n"; - + file.close(); std::cout << "Report generated: " << filename << "\n"; } - + void printSummary(const std::vector& results) { std::cout << "\n=== Benchmark Summary ===\n"; - std::cout << std::left << std::setw(25) << "Benchmark" - << std::setw(10) << "Category" - << std::setw(15) << "Avg Time (ms)" - << std::setw(15) << "Min Time (ms)" - << std::setw(15) << "Max Time (ms)" + std::cout << std::left << std::setw(25) << "Benchmark" << std::setw(10) << "Category" << std::setw(15) + << "Avg Time (ms)" << std::setw(15) << "Min Time (ms)" << std::setw(15) << "Max Time (ms)" << std::setw(12) << "Success Rate" << "Status\n"; std::cout << std::string(95, '-') << "\n"; - + for (const auto& result : results) { std::string status = result.isValid() ? "SUCCESS" : "FAILED"; - std::cout << std::left << std::setw(25) << result.name.substr(0, 24) - << std::setw(10) << result.category + std::cout << std::left << std::setw(25) << result.name.substr(0, 24) << std::setw(10) << result.category << std::setw(15) << std::fixed << std::setprecision(3) << result.averageDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs - << std::setw(15) << std::fixed << std::setprecision(3) << result.maxDurationMs - << std::setw(12) << std::fixed << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" - << status << "\n"; + << std::setw(15) << std::fixed << std::setprecision(3) << result.minDurationMs << std::setw(15) + << std::fixed << std::setprecision(3) << result.maxDurationMs << std::setw(12) << std::fixed + << std::setprecision(1) << (result.getSuccessRate() * 100) << "%" << status << "\n"; } - + // Summary statistics int totalSuccessful = 0, totalFailed = 0; double totalTime = 0.0; - + for (const auto& result : results) { if (result.isValid()) { totalSuccessful++; @@ -209,14 +209,14 @@ class SimpleBenchmarkSuite { totalFailed++; } } - + std::cout << "\n"; std::cout << "Total Benchmarks: " << results.size() << "\n"; std::cout << "Successful: " << totalSuccessful << "\n"; std::cout << "Failed: " << totalFailed << "\n"; if (totalSuccessful > 0) { - std::cout << "Average Time: " << std::fixed << std::setprecision(3) - << (totalTime / totalSuccessful) << " ms\n"; + std::cout << "Average Time: " << std::fixed << std::setprecision(3) << (totalTime / totalSuccessful) + << " ms\n"; } } }; @@ -226,7 +226,7 @@ void memoryAllocationBenchmark() { std::vector allocations; const size_t numAllocations = 1000; const size_t allocationSize = 1024; - + // Allocate for (size_t i = 0; i < numAllocations; ++i) { void* ptr = malloc(allocationSize); @@ -234,7 +234,7 @@ void memoryAllocationBenchmark() { allocations.push_back(ptr); } } - + // Deallocate for (void* ptr : allocations) { if (ptr) { @@ -246,19 +246,19 @@ void memoryAllocationBenchmark() { void stringOperationsBenchmark() { const int numStrings = 500; std::vector strings; - + // String creation for (int i = 0; i < numStrings; ++i) { strings.emplace_back("Demo string " + std::to_string(i) + " with content"); } - + // String manipulation for (auto& str : strings) { str += " modified"; str = str.substr(0, str.length() / 2); std::transform(str.begin(), str.end(), str.begin(), ::toupper); } - + // String searching int found = 0; for (const auto& str : strings) { @@ -271,22 +271,22 @@ void stringOperationsBenchmark() { void vectorOperationsBenchmark() { std::vector vec; const int numElements = 5000; - + // Push back for (int i = 0; i < numElements; ++i) { vec.push_back(i); } - + // Random access std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, numElements - 1); - + int sum = 0; for (int i = 0; i < 1000; ++i) { sum += vec[dis(gen)]; } - + // Erase elements while (!vec.empty() && vec.size() > numElements / 2) { vec.erase(vec.begin() + vec.size() / 2); @@ -298,9 +298,9 @@ void threadingBenchmark() { const int operationsPerThread = 500; std::mutex testMutex; int sharedCounter = 0; - + std::vector threads; - + for (int i = 0; i < numThreads; ++i) { threads.emplace_back([&]() { for (int j = 0; j < operationsPerThread; ++j) { @@ -309,7 +309,7 @@ void threadingBenchmark() { } }); } - + for (auto& thread : threads) { if (thread.joinable()) { thread.join(); @@ -321,7 +321,7 @@ void fileIoBenchmark() { const std::string filename = "/tmp/benchmark_demo_file.txt"; const std::string content = "Demo content for file I/O benchmark. "; const int numLines = 500; - + // Write file { std::ofstream file(filename); @@ -329,7 +329,7 @@ void fileIoBenchmark() { file << content << "Line " << i << std::endl; } } - + // Read file { std::ifstream file(filename); @@ -339,7 +339,7 @@ void fileIoBenchmark() { lineCount++; } } - + // Clean up std::remove(filename.c_str()); } @@ -347,14 +347,14 @@ void fileIoBenchmark() { int main(int argc, char* argv[]) { // Initialize logging LogManager::configureConsoleLogging(LogLevel::INFO, false); - + SimpleBenchmarkSuite suite; - + // Parse command line arguments bool verbose = false; std::string outputFile; std::string category; - + for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg == "--verbose" || arg == "-v") { @@ -373,19 +373,22 @@ int main(int argc, char* argv[]) { return 0; } } - + suite.setVerbose(verbose); - + // Register benchmarks - suite.registerBenchmark("memory_allocation", "CORE", "Basic memory allocation and deallocation", 50, memoryAllocationBenchmark); - suite.registerBenchmark("string_operations", "CORE", "String creation, manipulation, and searching", 30, stringOperationsBenchmark); - suite.registerBenchmark("vector_operations", "CORE", "Vector operations performance", 20, vectorOperationsBenchmark); + suite.registerBenchmark("memory_allocation", "CORE", "Basic memory allocation and deallocation", 50, + memoryAllocationBenchmark); + suite.registerBenchmark("string_operations", "CORE", "String creation, manipulation, and searching", 30, + stringOperationsBenchmark); + suite.registerBenchmark("vector_operations", "CORE", "Vector operations performance", 20, + vectorOperationsBenchmark); suite.registerBenchmark("threading", "CORE", "Thread creation and synchronization", 10, threadingBenchmark); suite.registerBenchmark("file_io", "CORE", "File I/O operations", 5, fileIoBenchmark); - + std::cout << "Bolt Performance Benchmark Suite\n"; std::cout << "================================\n"; - + // Run benchmarks std::vector results; if (!category.empty()) { @@ -394,15 +397,15 @@ int main(int argc, char* argv[]) { } else { results = suite.runAllBenchmarks(); } - + // Print summary suite.printSummary(results); - + // Generate report if requested if (!outputFile.empty()) { suite.generateReport(results, outputFile); } - + std::cout << "\nBenchmark execution completed.\n"; return 0; -} \ No newline at end of file +} diff --git a/demo_code_analyzer.cpp b/demo_code_analyzer.cpp index acdf31b2..4a803ab3 100644 --- a/demo_code_analyzer.cpp +++ b/demo_code_analyzer.cpp @@ -1,24 +1,25 @@ +#include +#include + #include "bolt/core/code_analyzer.hpp" #include "bolt/core/logging.hpp" -#include -#include -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateBasicAnalysis() { std::cout << "\n=== Basic Code Analysis Demo ===\n"; - + // Create analyzer instance CodeAnalyzer analyzer; - + // Enable performance profiling analyzer.enablePerformanceProfiling(true); - + // Set up metrics callback analyzer.setMetricsCallback([](const std::string& metric, double value) { std::cout << "Metric: " << metric << " = " << value << std::endl; }); - + // Create sample code with various issues for testing std::string sampleCode = R"( #include @@ -69,58 +70,57 @@ class ExampleClass { // ... many more methods would trigger complexity warnings }; )"; - + // Write sample code to temporary file std::string tempFile = "/tmp/sample_code.cpp"; std::ofstream file(tempFile); file << sampleCode; file.close(); - + // Analyze the sample file auto result = analyzer.analyzeFile(tempFile); - + std::cout << "\nAnalysis Results:\n"; std::cout << "Total Issues Found: " << result.issues.size() << std::endl; std::cout << "Analysis Time: " << result.analysisTimeMs << " ms\n"; - + // Show issues by severity std::cout << "\nIssues by Severity:\n"; std::cout << " Critical: " << result.getIssueCount(AnalysisSeverity::CRITICAL) << std::endl; std::cout << " Error: " << result.getIssueCount(AnalysisSeverity::ERROR) << std::endl; std::cout << " Warning: " << result.getIssueCount(AnalysisSeverity::WARNING) << std::endl; std::cout << " Info: " << result.getIssueCount(AnalysisSeverity::INFO) << std::endl; - + // Show issues by category std::cout << "\nIssues by Category:\n"; std::cout << " Complexity: " << result.getIssueCount(AnalysisCategory::COMPLEXITY) << std::endl; std::cout << " Security: " << result.getIssueCount(AnalysisCategory::SECURITY) << std::endl; std::cout << " Performance: " << result.getIssueCount(AnalysisCategory::PERFORMANCE) << std::endl; - + // Show detailed issues std::cout << "\nDetailed Issues:\n"; for (const auto& issue : result.issues) { - std::cout << " [" << static_cast(issue.severity) << "] " - << issue.message << std::endl; + std::cout << " [" << static_cast(issue.severity) << "] " << issue.message << std::endl; for (const auto& suggestion : issue.suggestions) { std::cout << " Suggestion: " << suggestion << std::endl; } } - + // Export results analyzer.exportResults(result, "json", "/tmp/analysis_results.json"); analyzer.exportResults(result, "text", "/tmp/analysis_results.txt"); - + std::cout << "\nResults exported to /tmp/analysis_results.json and /tmp/analysis_results.txt\n"; - + // Cleanup std::filesystem::remove(tempFile); } void demonstrateRefactoringSuggestions() { std::cout << "\n=== Refactoring Suggestions Demo ===\n"; - + RefactoringSuggestionEngine engine; - + std::string longFunctionCode = R"( void veryLongFunction() { // This function is intentionally long to trigger refactoring suggestions @@ -168,11 +168,11 @@ void duplicatedCode() { int z = x + y; } )"; - + auto suggestions = engine.generateSuggestionsForFile("example.cpp", longFunctionCode); - + std::cout << "Refactoring Suggestions Found: " << suggestions.size() << std::endl; - + for (const auto& suggestion : suggestions) { std::cout << "\nSuggestion: " << suggestion.title << std::endl; std::cout << " Description: " << suggestion.description << std::endl; @@ -186,21 +186,21 @@ void duplicatedCode() { void demonstrateAnalyzerConfiguration() { std::cout << "\n=== Analyzer Configuration Demo ===\n"; - + CodeAnalyzer analyzer; - + // Show registered analyzers auto analyzers = analyzer.getRegisteredAnalyzers(); std::cout << "Registered Analyzers:" << std::endl; for (const auto& name : analyzers) { - std::cout << " - " << name << " (enabled: " - << (analyzer.isAnalyzerEnabled(name) ? "yes" : "no") << ")" << std::endl; + std::cout << " - " << name << " (enabled: " << (analyzer.isAnalyzerEnabled(name) ? "yes" : "no") << ")" + << std::endl; } - + // Disable specific analyzers analyzer.enableAnalyzer("SecurityAnalyzer", false); std::cout << "\nDisabled SecurityAnalyzer" << std::endl; - + // Configure an analyzer std::unordered_map config; config["max_complexity"] = "15"; @@ -211,11 +211,11 @@ void demonstrateAnalyzerConfiguration() { void demonstrateProjectAnalysis() { std::cout << "\n=== Project Analysis Demo ===\n"; - + // Create a temporary project structure std::string projectPath = "/tmp/sample_project"; std::filesystem::create_directories(projectPath); - + // Create some sample files std::ofstream main_cpp(projectPath + "/main.cpp"); main_cpp << R"( @@ -234,7 +234,7 @@ int main() { } )"; main_cpp.close(); - + std::ofstream utils_hpp(projectPath + "/utils.hpp"); utils_hpp << R"( #ifndef UTILS_HPP @@ -247,7 +247,7 @@ void utilityFunction(); #endif )"; utils_hpp.close(); - + std::ofstream utils_cpp(projectPath + "/utils.cpp"); utils_cpp << R"( #include "utils.hpp" @@ -259,86 +259,79 @@ void utilityFunction() { } )"; utils_cpp.close(); - + CodeAnalyzer analyzer; auto result = analyzer.analyzeProject(projectPath); - + std::cout << "Project Analysis Results:" << std::endl; std::cout << " Files analyzed: " << result.fileMetrics.size() << std::endl; std::cout << " Total issues: " << result.issues.size() << std::endl; std::cout << " Analysis time: " << result.analysisTimeMs << " ms" << std::endl; std::cout << " Dependencies found: " << result.dependencies.size() << std::endl; - + // Show overall metrics std::cout << "\nOverall Project Metrics:" << std::endl; std::cout << " Lines of Code: " << result.overallMetrics.linesOfCode << std::endl; std::cout << " Functions: " << result.overallMetrics.functionCount << std::endl; std::cout << " Classes: " << result.overallMetrics.classCount << std::endl; std::cout << " Cyclomatic Complexity: " << result.overallMetrics.cyclomaticComplexity << std::endl; - + // Generate and display report std::string report = analyzer.generateReport(result, "text"); std::cout << "\n" << report << std::endl; - + // Cleanup std::filesystem::remove_all(projectPath); } void demonstrateCustomAnalyzer() { std::cout << "\n=== Custom Analyzer Demo ===\n"; - + // Example of how to create a custom analyzer class CustomStyleAnalyzer : public ICodeAnalyzer { - public: + public: std::string getName() const override { return "CustomStyleAnalyzer"; } std::string getVersion() const override { return "1.0.0"; } - std::vector getSupportedExtensions() const override { - return {".cpp", ".hpp"}; - } + std::vector getSupportedExtensions() const override { return {".cpp", ".hpp"}; } AnalysisCategory getCategory() const override { return AnalysisCategory::STYLE; } - - std::vector analyzeFile(const std::string& filePath, - const std::string& content) override { + + std::vector analyzeFile(const std::string& filePath, const std::string& content) override { std::vector issues; - + // Check for missing header guards if (filePath.find(".hpp") != std::string::npos) { - if (content.find("#ifndef") == std::string::npos || - content.find("#define") == std::string::npos) { - AnalysisIssue issue("MISSING_HEADER_GUARD", - "Header file missing include guard", - AnalysisSeverity::WARNING, AnalysisCategory::STYLE); + if (content.find("#ifndef") == std::string::npos || content.find("#define") == std::string::npos) { + AnalysisIssue issue("MISSING_HEADER_GUARD", "Header file missing include guard", + AnalysisSeverity::WARNING, AnalysisCategory::STYLE); issue.filePath = filePath; issue.suggestions.push_back("Add #ifndef, #define, #endif header guard"); issues.push_back(issue); } } - + return issues; } - + std::vector analyzeProject(const std::string& projectPath) override { - return {}; // Not implemented for this demo + return {}; // Not implemented for this demo } - - CodeMetrics getMetrics(const std::string& filePath, - const std::string& content) override { + + CodeMetrics getMetrics(const std::string& filePath, const std::string& content) override { CodeMetrics metrics; - metrics.customMetrics["style_issues"] = - analyzeFile(filePath, content).size(); + metrics.customMetrics["style_issues"] = analyzeFile(filePath, content).size(); return metrics; } }; - + CodeAnalyzer analyzer; analyzer.registerAnalyzer(std::make_unique()); - + auto analyzers = analyzer.getRegisteredAnalyzers(); std::cout << "Analyzers after adding custom analyzer:" << std::endl; for (const auto& name : analyzers) { std::cout << " - " << name << std::endl; } - + // Test the custom analyzer std::string headerFile = "/tmp/test_header.hpp"; std::ofstream header(headerFile); @@ -350,16 +343,16 @@ class TestClass { }; )"; header.close(); - + auto result = analyzer.analyzeFile(headerFile); std::cout << "\nCustom analyzer found " << result.issues.size() << " issues" << std::endl; - + for (const auto& issue : result.issues) { if (issue.id == "MISSING_HEADER_GUARD") { std::cout << "Found style issue: " << issue.message << std::endl; } } - + std::filesystem::remove(headerFile); } @@ -368,17 +361,17 @@ int main() { // Initialize logging auto& logger = LogManager::getInstance(); logger.setLevel(LogLevel::INFO); - + std::cout << "=== Advanced Code Analysis Tools Demo ===\n"; std::cout << "This demo showcases the comprehensive code analysis capabilities\n"; std::cout << "implemented for the Bolt C++ IDE.\n"; - + demonstrateBasicAnalysis(); demonstrateRefactoringSuggestions(); demonstrateAnalyzerConfiguration(); demonstrateProjectAnalysis(); demonstrateCustomAnalyzer(); - + std::cout << "\n=== Demo Complete ===\n"; std::cout << "The advanced code analysis tools provide:\n"; std::cout << " โœ“ Complexity analysis (cyclomatic, nesting, maintainability)\n"; @@ -390,11 +383,10 @@ int main() { std::cout << " โœ“ Multiple export formats (JSON, text)\n"; std::cout << " โœ“ Integration with performance profiling\n"; std::cout << " โœ“ Configurable analysis parameters\n"; - + return 0; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_code_analyzer_standalone.cpp b/demo_code_analyzer_standalone.cpp index 4c0592d1..bd5599d4 100644 --- a/demo_code_analyzer_standalone.cpp +++ b/demo_code_analyzer_standalone.cpp @@ -1,25 +1,30 @@ -#include -#include -#include -#include +#include +#include +#include #include +#include +#include #include #include -#include +#include #include -#include -#include +#include // Standalone implementation of advanced code analysis tools namespace bolt { -enum class AnalysisSeverity { - INFO, WARNING, ERROR, CRITICAL -}; +enum class AnalysisSeverity { INFO, WARNING, ERROR, CRITICAL }; enum class AnalysisCategory { - COMPLEXITY, MAINTAINABILITY, PERFORMANCE, SECURITY, - STYLE, DEPENDENCIES, MEMORY, TESTING, ARCHITECTURE + COMPLEXITY, + MAINTAINABILITY, + PERFORMANCE, + SECURITY, + STYLE, + DEPENDENCIES, + MEMORY, + TESTING, + ARCHITECTURE }; struct AnalysisIssue { @@ -31,9 +36,8 @@ struct AnalysisIssue { std::string filePath; size_t lineNumber; std::vector suggestions; - - AnalysisIssue(const std::string& issueId, const std::string& msg, - AnalysisSeverity sev, AnalysisCategory cat) + + AnalysisIssue(const std::string& issueId, const std::string& msg, AnalysisSeverity sev, AnalysisCategory cat) : id(issueId), message(msg), severity(sev), category(cat), lineNumber(0) {} }; @@ -51,59 +55,58 @@ struct CodeMetrics { }; class StandaloneCodeAnalyzer { -public: + public: std::vector analyzeFile(const std::string& filePath, const std::string& content) { std::vector issues; - + auto metrics = getMetrics(content); - + // Complexity analysis if (metrics.cyclomaticComplexity > 10) { - AnalysisIssue issue("COMPLEX_FUNCTION", - "High cyclomatic complexity: " + std::to_string(metrics.cyclomaticComplexity), - AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("COMPLEX_FUNCTION", + "High cyclomatic complexity: " + std::to_string(metrics.cyclomaticComplexity), + AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Consider breaking down complex functions into smaller ones"); issues.push_back(issue); } - + if (metrics.nestingDepth > 4) { - AnalysisIssue issue("DEEP_NESTING", - "Deep nesting detected: " + std::to_string(metrics.nestingDepth) + " levels", - AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("DEEP_NESTING", + "Deep nesting detected: " + std::to_string(metrics.nestingDepth) + " levels", + AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Extract nested logic into separate functions"); issues.push_back(issue); } - + // Security analysis auto securityIssues = checkSecurityIssues(content, filePath); issues.insert(issues.end(), securityIssues.begin(), securityIssues.end()); - + // Performance analysis auto performanceIssues = checkPerformanceIssues(content, filePath); issues.insert(issues.end(), performanceIssues.begin(), performanceIssues.end()); - + return issues; } - + CodeMetrics getMetrics(const std::string& content) { CodeMetrics metrics; - + std::istringstream stream(content); std::string line; - + while (std::getline(stream, line)) { metrics.physicalLines++; - + // Remove leading/trailing whitespace - line.erase(line.begin(), std::find_if(line.begin(), line.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); - line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { - return !std::isspace(ch); - }).base(), line.end()); - + line.erase(line.begin(), + std::find_if(line.begin(), line.end(), [](unsigned char ch) { return !std::isspace(ch); })); + line.erase( + std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), + line.end()); + if (line.empty()) { metrics.blankLines++; } else if (line.find("//") == 0 || line.find("/*") == 0) { @@ -112,24 +115,24 @@ class StandaloneCodeAnalyzer { metrics.linesOfCode++; } } - + metrics.cyclomaticComplexity = calculateCyclomaticComplexity(content); metrics.nestingDepth = calculateNestingDepth(content); metrics.functionCount = countFunctions(content); metrics.classCount = countClasses(content); - + // Calculate maintainability index if (metrics.linesOfCode > 0) { double complexity = static_cast(metrics.cyclomaticComplexity); double loc = static_cast(metrics.linesOfCode); - metrics.maintainabilityIndex = std::max(0.0, - 171.0 - 5.2 * std::log(complexity) - 0.23 * complexity - 16.2 * std::log(loc)); + metrics.maintainabilityIndex = + std::max(0.0, 171.0 - 5.2 * std::log(complexity) - 0.23 * complexity - 16.2 * std::log(loc)); } - + return metrics; } - -private: + + private: size_t calculateCyclomaticComplexity(const std::string& content) { size_t complexity = 1; std::regex decisionPoints(R"(\b(if|else\s+if|while|for|do|switch|case|catch|\?)\b)"); @@ -138,138 +141,146 @@ class StandaloneCodeAnalyzer { complexity += std::distance(iter, end); return complexity; } - + size_t calculateNestingDepth(const std::string& content) { size_t maxDepth = 0; size_t currentDepth = 0; - + for (char c : content) { if (c == '{') { currentDepth++; maxDepth = std::max(maxDepth, currentDepth); } else if (c == '}') { - if (currentDepth > 0) currentDepth--; + if (currentDepth > 0) + currentDepth--; } } return maxDepth; } - + size_t countFunctions(const std::string& content) { std::regex functionPattern(R"(\b\w+\s*\([^)]*\)\s*\{)"); std::sregex_iterator iter(content.begin(), content.end(), functionPattern); std::sregex_iterator end; return std::distance(iter, end); } - + size_t countClasses(const std::string& content) { std::regex classPattern(R"(\bclass\s+\w+)"); std::sregex_iterator iter(content.begin(), content.end(), classPattern); std::sregex_iterator end; return std::distance(iter, end); } - + std::vector checkSecurityIssues(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for unsafe buffer operations std::regex unsafeBufferOps(R"(\b(strcpy|strcat|sprintf|gets)\s*\()"); std::sregex_iterator iter(content.begin(), content.end(), unsafeBufferOps); std::sregex_iterator end; - + for (; iter != end; ++iter) { - AnalysisIssue issue("UNSAFE_BUFFER_OP", - "Unsafe buffer operation: " + (*iter)[1].str(), - AnalysisSeverity::ERROR, AnalysisCategory::SECURITY); + AnalysisIssue issue("UNSAFE_BUFFER_OP", "Unsafe buffer operation: " + (*iter)[1].str(), + AnalysisSeverity::ERROR, AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back("Use safer alternatives like strncpy, strncat, snprintf"); issues.push_back(issue); } - + // Check for unsafe functions std::vector> unsafeFunctions = { - {"scanf", "Use cin or safer input methods"}, - {"system", "Avoid system calls, use safer alternatives"} - }; - + {"scanf", "Use cin or safer input methods"}, {"system", "Avoid system calls, use safer alternatives"}}; + for (const auto& [func, suggestion] : unsafeFunctions) { std::regex pattern("\\b" + func + "\\s*\\("); if (std::regex_search(content, pattern)) { - AnalysisIssue issue("UNSAFE_FUNCTION", - "Unsafe function usage: " + func, - AnalysisSeverity::WARNING, AnalysisCategory::SECURITY); + AnalysisIssue issue("UNSAFE_FUNCTION", "Unsafe function usage: " + func, AnalysisSeverity::WARNING, + AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back(suggestion); issues.push_back(issue); } } - + return issues; } - + std::vector checkPerformanceIssues(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for string concatenation in loops std::regex stringConcatInLoop(R"(for\s*\([^}]*\+\s*=\s*[^;]*string)"); if (std::regex_search(content, stringConcatInLoop)) { - AnalysisIssue issue("STRING_CONCAT_IN_LOOP", - "String concatenation in loop detected", - AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("STRING_CONCAT_IN_LOOP", "String concatenation in loop detected", + AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Use stringstream or reserve space for better performance"); issues.push_back(issue); } - + // Check for nested loops std::regex nestedLoops(R"(for\s*\([^}]*for\s*\()"); std::sregex_iterator iter(content.begin(), content.end(), nestedLoops); std::sregex_iterator end; - + size_t nestedLoopCount = std::distance(iter, end); if (nestedLoopCount > 0) { - AnalysisIssue issue("NESTED_LOOPS", - "Nested loops detected (" + std::to_string(nestedLoopCount) + ")", - AnalysisSeverity::INFO, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("NESTED_LOOPS", "Nested loops detected (" + std::to_string(nestedLoopCount) + ")", + AnalysisSeverity::INFO, AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Consider algorithmic improvements to reduce complexity"); issues.push_back(issue); } - + return issues; } - -public: + + public: std::string formatSeverity(AnalysisSeverity severity) const { switch (severity) { - case AnalysisSeverity::INFO: return "INFO"; - case AnalysisSeverity::WARNING: return "WARNING"; - case AnalysisSeverity::ERROR: return "ERROR"; - case AnalysisSeverity::CRITICAL: return "CRITICAL"; - default: return "UNKNOWN"; + case AnalysisSeverity::INFO: + return "INFO"; + case AnalysisSeverity::WARNING: + return "WARNING"; + case AnalysisSeverity::ERROR: + return "ERROR"; + case AnalysisSeverity::CRITICAL: + return "CRITICAL"; + default: + return "UNKNOWN"; } } - + std::string formatCategory(AnalysisCategory category) const { switch (category) { - case AnalysisCategory::COMPLEXITY: return "COMPLEXITY"; - case AnalysisCategory::SECURITY: return "SECURITY"; - case AnalysisCategory::PERFORMANCE: return "PERFORMANCE"; - case AnalysisCategory::MAINTAINABILITY: return "MAINTAINABILITY"; - case AnalysisCategory::STYLE: return "STYLE"; - case AnalysisCategory::DEPENDENCIES: return "DEPENDENCIES"; - case AnalysisCategory::MEMORY: return "MEMORY"; - default: return "UNKNOWN"; + case AnalysisCategory::COMPLEXITY: + return "COMPLEXITY"; + case AnalysisCategory::SECURITY: + return "SECURITY"; + case AnalysisCategory::PERFORMANCE: + return "PERFORMANCE"; + case AnalysisCategory::MAINTAINABILITY: + return "MAINTAINABILITY"; + case AnalysisCategory::STYLE: + return "STYLE"; + case AnalysisCategory::DEPENDENCIES: + return "DEPENDENCIES"; + case AnalysisCategory::MEMORY: + return "MEMORY"; + default: + return "UNKNOWN"; } } }; -} // namespace bolt +} // namespace bolt void demonstrateCodeAnalysis() { std::cout << "\n=== Advanced Code Analysis Tools Demo ===\n"; - + bolt::StandaloneCodeAnalyzer analyzer; - + // Create sample code with various issues std::string sampleCode = R"( #include @@ -320,20 +331,20 @@ int main() { return 0; } )"; - + // Analyze the sample code auto startTime = std::chrono::high_resolution_clock::now(); auto issues = analyzer.analyzeFile("sample.cpp", sampleCode); auto metrics = analyzer.getMetrics(sampleCode); auto endTime = std::chrono::high_resolution_clock::now(); - + auto duration = std::chrono::duration_cast(endTime - startTime); - + std::cout << "\nAnalysis Results:\n"; std::cout << "=================\n"; std::cout << "Analysis Time: " << duration.count() << " microseconds\n"; std::cout << "Total Issues Found: " << issues.size() << "\n\n"; - + // Display metrics std::cout << "Code Metrics:\n"; std::cout << " Lines of Code: " << metrics.linesOfCode << "\n"; @@ -344,33 +355,33 @@ int main() { std::cout << " Nesting Depth: " << metrics.nestingDepth << "\n"; std::cout << " Function Count: " << metrics.functionCount << "\n"; std::cout << " Class Count: " << metrics.classCount << "\n"; - std::cout << " Maintainability Index: " << std::fixed << std::setprecision(2) - << metrics.maintainabilityIndex << "\n\n"; - + std::cout << " Maintainability Index: " << std::fixed << std::setprecision(2) << metrics.maintainabilityIndex + << "\n\n"; + // Group issues by severity std::unordered_map severityCounts; std::unordered_map categoryCounts; - + for (const auto& issue : issues) { severityCounts[issue.severity]++; categoryCounts[issue.category]++; } - + std::cout << "Issues by Severity:\n"; for (const auto& [severity, count] : severityCounts) { std::cout << " " << analyzer.formatSeverity(severity) << ": " << count << "\n"; } - + std::cout << "\nIssues by Category:\n"; for (const auto& [category, count] : categoryCounts) { std::cout << " " << analyzer.formatCategory(category) << ": " << count << "\n"; } - + std::cout << "\nDetailed Issues:\n"; std::cout << "================\n"; for (const auto& issue : issues) { - std::cout << "[" << analyzer.formatSeverity(issue.severity) << "] " - << analyzer.formatCategory(issue.category) << ": " << issue.message << "\n"; + std::cout << "[" << analyzer.formatSeverity(issue.severity) << "] " << analyzer.formatCategory(issue.category) + << ": " << issue.message << "\n"; for (const auto& suggestion : issue.suggestions) { std::cout << " โ†’ Suggestion: " << suggestion << "\n"; } @@ -380,11 +391,11 @@ int main() { void demonstrateProjectAnalysis() { std::cout << "\n=== Project Analysis Demo ===\n"; - + // Create a temporary project structure std::string projectPath = "/tmp/sample_project"; std::filesystem::create_directories(projectPath); - + // Create some sample files with different types of issues std::ofstream main_cpp(projectPath + "/main.cpp"); main_cpp << R"( @@ -408,7 +419,7 @@ int main() { } )"; main_cpp.close(); - + std::ofstream utils_hpp(projectPath + "/utils.hpp"); utils_hpp << R"( #ifndef UTILS_HPP @@ -426,7 +437,7 @@ class UtilityClass { #endif )"; utils_hpp.close(); - + std::ofstream utils_cpp(projectPath + "/utils.cpp"); utils_cpp << R"( #include "utils.hpp" @@ -468,30 +479,27 @@ void UtilityClass::securityRisk() { } )"; utils_cpp.close(); - + bolt::StandaloneCodeAnalyzer analyzer; std::vector allIssues; std::vector allMetrics; size_t totalFiles = 0; - + // Analyze all files in the project for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { - if (entry.is_regular_file() && - (entry.path().extension() == ".cpp" || entry.path().extension() == ".hpp")) { - + if (entry.is_regular_file() && (entry.path().extension() == ".cpp" || entry.path().extension() == ".hpp")) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto issues = analyzer.analyzeFile(entry.path().string(), content); auto metrics = analyzer.getMetrics(content); - + allIssues.insert(allIssues.end(), issues.begin(), issues.end()); allMetrics.push_back(metrics); totalFiles++; } } - + // Aggregate metrics bolt::CodeMetrics overallMetrics; for (const auto& metrics : allMetrics) { @@ -502,7 +510,7 @@ void UtilityClass::securityRisk() { overallMetrics.cyclomaticComplexity += metrics.cyclomaticComplexity; overallMetrics.nestingDepth = std::max(overallMetrics.nestingDepth, metrics.nestingDepth); } - + std::cout << "Project Analysis Results:\n"; std::cout << " Files Analyzed: " << totalFiles << "\n"; std::cout << " Total Issues: " << allIssues.size() << "\n"; @@ -511,19 +519,19 @@ void UtilityClass::securityRisk() { std::cout << " Total Classes: " << overallMetrics.classCount << "\n"; std::cout << " Maximum Nesting Depth: " << overallMetrics.nestingDepth << "\n"; std::cout << " Total Cyclomatic Complexity: " << overallMetrics.cyclomaticComplexity << "\n"; - + // Show issues by file std::cout << "\nIssues by File:\n"; std::unordered_map> issuesByFile; for (const auto& issue : allIssues) { issuesByFile[issue.filePath].push_back(issue); } - + for (const auto& [filePath, fileIssues] : issuesByFile) { - std::cout << " " << std::filesystem::path(filePath).filename().string() - << ": " << fileIssues.size() << " issues\n"; + std::cout << " " << std::filesystem::path(filePath).filename().string() << ": " << fileIssues.size() + << " issues\n"; } - + // Cleanup std::filesystem::remove_all(projectPath); } @@ -533,10 +541,10 @@ int main() { std::cout << "=== Bolt C++ Advanced Code Analysis Tools ===\n"; std::cout << "This standalone demo showcases the comprehensive code analysis\n"; std::cout << "capabilities implemented for the Bolt C++ IDE.\n"; - + demonstrateCodeAnalysis(); demonstrateProjectAnalysis(); - + std::cout << "\n=== Analysis Features Demonstrated ===\n"; std::cout << "โœ“ Complexity Analysis:\n"; std::cout << " - Cyclomatic complexity measurement\n"; @@ -560,16 +568,15 @@ int main() { std::cout << " - Issue categorization and prioritization\n"; std::cout << " - Actionable improvement suggestions\n"; std::cout << " - Fast analysis with detailed reporting\n"; - + std::cout << "\n=== Integration Ready ===\n"; std::cout << "This code analysis framework is designed to integrate seamlessly\n"; std::cout << "with the Bolt IDE's existing architecture, providing real-time\n"; std::cout << "code quality feedback to developers.\n"; - + return 0; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_code_folding.cpp b/demo_code_folding.cpp index cda0ba90..d70852ff 100644 --- a/demo_code_folding.cpp +++ b/demo_code_folding.cpp @@ -1,13 +1,14 @@ -#include "bolt/editor/integrated_editor.hpp" #include +#include "bolt/editor/integrated_editor.hpp" + int main() { std::cout << "Bolt C++ Code Folding Integration Demo\n"; std::cout << "=====================================\n\n"; - + // Get the integrated editor instance auto& editor = bolt::IntegratedEditor::getInstance(); - + // Sample C++ code with foldable regions std::string sampleCode = R"( #include @@ -53,53 +54,52 @@ int main() { // Open the document with code folding std::cout << "1. Opening document with code folding detection...\n"; editor.openDocument("demo.cpp", sampleCode); - + // Display detected folding ranges auto ranges = editor.getFoldingRanges("demo.cpp"); std::cout << " Detected " << ranges.size() << " foldable regions:\n"; - + for (const auto& range : ranges) { - std::cout << " - Lines " << range.startLine << "-" << range.endLine - << " (folded: " << (range.isFolded ? "yes" : "no") - << ", placeholder: \"" << range.placeholder << "\")\n"; + std::cout << " - Lines " << range.startLine << "-" << range.endLine + << " (folded: " << (range.isFolded ? "yes" : "no") << ", placeholder: \"" << range.placeholder + << "\")\n"; } - + std::cout << "\n2. Testing fold operations...\n"; - + // Test folding operations if (!ranges.empty()) { auto& firstRange = ranges[0]; std::cout << " Toggling fold on line " << firstRange.startLine << "...\n"; editor.toggleFold("demo.cpp", firstRange.startLine); - + // Check if fold state changed auto updatedRanges = editor.getFoldingRanges("demo.cpp"); for (const auto& range : updatedRanges) { if (range.startLine == firstRange.startLine) { - std::cout << " Fold state changed to: " - << (range.isFolded ? "folded" : "expanded") << "\n"; + std::cout << " Fold state changed to: " << (range.isFolded ? "folded" : "expanded") << "\n"; break; } } - + // Test expand all std::cout << " Expanding all folds...\n"; editor.expandAllFolds("demo.cpp"); - + // Test collapse all std::cout << " Collapsing all folds...\n"; editor.collapseAllFolds("demo.cpp"); } - + std::cout << "\n3. Testing folding enable/disable...\n"; std::cout << " Folding enabled: " << (editor.isFoldingEnabled() ? "yes" : "no") << "\n"; - + editor.setFoldingEnabled(false); std::cout << " Disabled folding. Enabled: " << (editor.isFoldingEnabled() ? "yes" : "no") << "\n"; - + editor.setFoldingEnabled(true); std::cout << " Re-enabled folding. Enabled: " << (editor.isFoldingEnabled() ? "yes" : "no") << "\n"; - + std::cout << "\n4. Testing content update with re-folding...\n"; std::string newCode = R"( struct SimpleStruct { @@ -109,11 +109,11 @@ struct SimpleStruct { } }; )"; - + editor.updateDocumentContent("demo.cpp", newCode); auto newRanges = editor.getFoldingRanges("demo.cpp"); std::cout << " After content update, detected " << newRanges.size() << " foldable regions\n"; - + std::cout << "\nโœ“ Code folding integration demo completed successfully!\n"; std::cout << " All folding features are working correctly:\n"; std::cout << " - Automatic detection of foldable regions (braces, comments)\n"; @@ -122,6 +122,6 @@ struct SimpleStruct { std::cout << " - Enable/disable folding globally\n"; std::cout << " - Content update with re-detection\n"; std::cout << " - Integration with editor document management\n"; - + return 0; -} \ No newline at end of file +} diff --git a/demo_collaborative_editing.cpp b/demo_collaborative_editing.cpp index 1f2d2f72..48fe52b0 100644 --- a/demo_collaborative_editing.cpp +++ b/demo_collaborative_editing.cpp @@ -1,20 +1,21 @@ -#include -#include #include +#include #include +#include + #include "bolt/collaboration/collaborative_editor_integration.hpp" #include "bolt/core/editor_store.hpp" -using namespace bolt::collaboration; -using namespace std::chrono_literals; +using namespace bolt::collaboration; // NOLINT(build/namespaces) +using namespace std::chrono_literals; // NOLINT(build/namespaces) void demonstrateCollaborativeEditing() { std::cout << "=== Bolt C++ Collaborative Editing Demo ===\n\n"; - + // Initialize the collaborative editing system auto& integration = CollaborativeEditorIntegration::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); - + // Create a sample document bolt::EditorDocument document; document.filePath = "/demo/shared_code.cpp"; @@ -26,90 +27,88 @@ int main() { })"; document.scroll = {0, 0}; document.cursor = {0, std::nullopt}; - + editorStore.setDocument(document.filePath, document); editorStore.setSelectedFile(document.filePath); - + std::cout << "1. Created sample document:\n"; std::cout << " File: " << document.filePath << "\n"; std::cout << " Content:\n" << document.value << "\n\n"; - + // Check initial collaboration stats auto stats = integration.getStats(); std::cout << "2. Collaboration Status:\n"; std::cout << " Server Running: " << (stats.isServerRunning ? "Yes" : "No") << "\n"; std::cout << " Active Documents: " << stats.activeDocuments << "\n"; std::cout << " Total Users: " << stats.totalUsers << "\n\n"; - + // Simulate collaborative editing operations std::cout << "3. Simulating collaborative text edits:\n"; - + // User 1 adds a comment std::cout << " User1 adds comment at line 1...\n"; integration.applyTextEdit(document.filePath, Position(0, 0), "// Collaborative demo\n"); - + // User 2 modifies the main function std::cout << " User2 modifies main function...\n"; integration.applyTextEdit(document.filePath, Position(4, 4), "// Updated by User2\n "); - + // User 1 updates cursor position std::cout << " User1 moves cursor...\n"; integration.updateCursorPosition(document.filePath, Position(3, 0), "user1"); - + // User 2 updates cursor position std::cout << " User2 moves cursor...\n"; integration.updateCursorPosition(document.filePath, Position(5, 20), "user2"); - + std::cout << "\n4. Current document state:\n"; auto* currentDoc = editorStore.getCurrentDocument(); if (currentDoc) { std::cout << currentDoc->value << "\n"; } - + std::cout << "\n5. Remote cursor positions:\n"; auto cursors = integration.getRemoteCursors(document.filePath); if (cursors.empty()) { std::cout << " No remote cursors (collaboration not initialized)\n"; } else { for (const auto& [userId, position] : cursors) { - std::cout << " " << userId << ": line " << position.line - << ", column " << position.character << "\n"; + std::cout << " " << userId << ": line " << position.line << ", column " << position.character << "\n"; } } - + std::cout << "\n6. Collaborative session features:\n"; auto& session = CollaborativeSession::getInstance(); - + // Create a collaborative document bool created = session.createDocument("demo_collab", "Initial collaborative content"); std::cout << " Created collaborative document: " << (created ? "Success" : "Failed") << "\n"; - + // Join users bool user1Joined = session.joinDocument("alice", "Alice", "demo_collab"); bool user2Joined = session.joinDocument("bob", "Bob", "demo_collab"); std::cout << " Alice joined: " << (user1Joined ? "Success" : "Failed") << "\n"; std::cout << " Bob joined: " << (user2Joined ? "Success" : "Failed") << "\n"; - + // Get active users auto users = session.getActiveUsers("demo_collab"); std::cout << " Active users: " << users.size() << "\n"; for (const auto& user : users) { std::cout << " - " << user.userName << " (" << user.userId << ")\n"; } - + // Apply some collaborative operations DocumentOperation op1(OperationType::INSERT, "alice", Position(0, 8), " by Alice"); session.applyOperation(op1, "demo_collab"); - + DocumentOperation op2(OperationType::INSERT, "bob", Position(0, 0), "Modified "); session.applyOperation(op2, "demo_collab"); - - std::cout << " Final collaborative content: \"" - << session.getDocumentContent("demo_collab") << "\"\n"; - + + std::cout << " Final collaborative content: \"" << session.getDocumentContent("demo_collab") << "\"\n"; + // Clean up session.removeDocument("demo_collab"); - + std::cout << "\n=== Demo completed successfully! ===\n"; std::cout << "\nKey Features Demonstrated:\n"; std::cout << "โœ“ Document operation creation and application\n"; @@ -132,4 +131,4 @@ int main() { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_debugger.cpp b/demo_debugger.cpp index ed4c9f83..c1377269 100644 --- a/demo_debugger.cpp +++ b/demo_debugger.cpp @@ -1,12 +1,13 @@ +#include +#include + +#include "bolt/drawkern/dis_vm.hpp" #include "bolt/editor/debugger_interface.hpp" #include "bolt/editor/debugger_ui.hpp" #include "bolt/editor/integrated_editor.hpp" -#include "bolt/drawkern/dis_vm.hpp" -#include -#include -using namespace bolt; -using namespace bolt::drawkern; +using namespace bolt; // NOLINT(build/namespaces) +using namespace bolt::drawkern; // NOLINT(build/namespaces) void print_header() { std::cout << "\n=====================================" << std::endl; @@ -18,14 +19,13 @@ void print_header() { void demo_basic_debugger() { std::cout << "๐Ÿ“ฑ Demo: Basic Debugger Functionality" << std::endl; std::cout << "-------------------------------------" << std::endl; - + auto debugger = std::make_unique(); - + // Set up event callback - debugger->set_event_callback([](DebugEvent event, const std::string& message) { - std::cout << "๐Ÿ”” Event: " << message << std::endl; - }); - + debugger->set_event_callback( + [](DebugEvent event, const std::string& message) { std::cout << "๐Ÿ”” Event: " << message << std::endl; }); + // Create a simple Limbo program std::string program = R"( print "Starting AI workbench..." @@ -34,42 +34,42 @@ void demo_basic_debugger() { print "Program completed" halt )"; - + std::cout << "๐Ÿ“ Starting debug session with program:" << std::endl; std::cout << program << std::endl; - + // Start debug session if (debugger->start_debug_session_from_source(program)) { std::cout << "โœ… Debug session started successfully" << std::endl; - + // Set some breakpoints std::cout << "\n๐Ÿ”ด Setting breakpoints..." << std::endl; debugger->set_breakpoint(2); debugger->set_breakpoint(4); - + auto breakpoints = debugger->get_all_breakpoints(); std::cout << "๐Ÿ“ Active breakpoints: " << breakpoints.size() << std::endl; for (const auto& bp : breakpoints) { std::cout << " - PC " << bp.pc << (bp.enabled ? " (enabled)" : " (disabled)") << std::endl; } - + // Step through execution std::cout << "\n๐Ÿ”ง Stepping through execution..." << std::endl; std::cout << "Current PC: " << debugger->get_current_pc() << std::endl; std::cout << "Current instruction: " << debugger->get_current_instruction() << std::endl; - + debugger->step_over(); std::cout << "After step - PC: " << debugger->get_current_pc() << std::endl; - + debugger->step_over(); std::cout << "After step - PC: " << debugger->get_current_pc() << std::endl; - + // Continue execution std::cout << "\nโ–ถ๏ธ Continuing execution..." << std::endl; debugger->continue_execution(); - + std::cout << "Final state: " << static_cast(debugger->get_debug_state()) << std::endl; - + // Stop session debugger->stop_debug_session(); std::cout << "๐Ÿ›‘ Debug session stopped" << std::endl; @@ -81,85 +81,85 @@ void demo_basic_debugger() { void demo_debugger_ui() { std::cout << "\n๐Ÿ“ฑ Demo: Debugger UI Integration" << std::endl; std::cout << "--------------------------------" << std::endl; - + auto debugger = std::make_shared(); auto ui = std::make_unique(); - + // Connect UI to debugger ui->set_debugger(debugger); ui->set_visible(true); - + // Create a program for debugging std::string program = "print \"UI Demo\" ai_chat \"Testing UI\" halt"; - + if (debugger->start_debug_session_from_source(program)) { std::cout << "โœ… UI Debug session started" << std::endl; - + // Set breakpoint via UI ui->handle_breakpoint_toggle(1); std::cout << "๐Ÿ”ด Breakpoint set via UI" << std::endl; - + // Render UI state std::cout << "\n๐Ÿ“บ Rendering debugger UI:" << std::endl; ui->render(); - + // Test UI controls std::cout << "\n๐ŸŽฎ Testing UI controls..." << std::endl; ui->handle_step_over_clicked(); ui->render_controls(); - + ui->handle_continue_clicked(); ui->render_controls(); - + ui->handle_stop_clicked(); std::cout << "๐Ÿ›‘ Session stopped via UI" << std::endl; } - + ui->set_visible(false); } void demo_integrated_editor() { std::cout << "\n๐Ÿ“ฑ Demo: IntegratedEditor Debugger Integration" << std::endl; std::cout << "-----------------------------------------------" << std::endl; - + auto& editor = IntegratedEditor::getInstance(); - + // Create a test Limbo file content std::string testContent = R"(print "Editor integration test" ai_init "test-model" ai_chat "Hello from editor" render_glyph "editor-test" halt)"; - + std::cout << "๐Ÿ“ Opening test document in editor..." << std::endl; editor.openDocument("/tmp/test_debug.limbo", testContent); - + // Start debugging from editor std::cout << "๐Ÿ”ง Starting debug session from editor..." << std::endl; if (editor.startDebugSessionFromSource(testContent)) { std::cout << "โœ… Editor debug session started" << std::endl; - + // Set breakpoints via editor editor.setBreakpointAtLine("/tmp/test_debug.limbo", 2); editor.setBreakpointAtLine("/tmp/test_debug.limbo", 4); - + auto breakpoints = editor.getAllBreakpoints(); std::cout << "๐Ÿ“ Breakpoints set via editor: " << breakpoints.size() << std::endl; - + // Show debugger UI editor.showDebugger(); std::cout << "๐Ÿ“บ Debugger UI shown: " << (editor.isDebuggerVisible() ? "Yes" : "No") << std::endl; - + // Step through via editor std::cout << "๐Ÿ”ง Stepping through via editor..." << std::endl; std::cout << "PC: " << editor.getCurrentDebugPC() << std::endl; - + editor.debugStepOver(); std::cout << "After step - PC: " << editor.getCurrentDebugPC() << std::endl; - + editor.debugContinue(); std::cout << "Debug state: " << static_cast(editor.getDebugState()) << std::endl; - + // Clean up editor.stopDebugSession(); editor.hideDebugger(); @@ -172,32 +172,32 @@ halt)"; void demo_watch_expressions() { std::cout << "\n๐Ÿ“ฑ Demo: Watch Expressions" << std::endl; std::cout << "---------------------------" << std::endl; - + auto debugger = std::make_unique(); - + // Add watch expressions std::cout << "๐Ÿ‘๏ธ Adding watch expressions..." << std::endl; debugger->add_watch_expression("counter"); debugger->add_watch_expression("message.length"); debugger->add_watch_expression("ai_model_status"); - + auto watches = debugger->get_watch_expressions(); std::cout << "๐Ÿ“Š Watch expressions: " << watches.size() << std::endl; for (const auto& watch : watches) { - std::cout << " - " << watch.expression << " = " << watch.value - << " (" << (watch.valid ? "valid" : "invalid") << ")" << std::endl; + std::cout << " - " << watch.expression << " = " << watch.value << " (" << (watch.valid ? "valid" : "invalid") + << ")" << std::endl; } - + // Update watch expressions (would happen during debugging) debugger->update_watch_expressions(); - + // Remove a watch expression debugger->remove_watch_expression("message.length"); std::cout << "Removed 'message.length' watch" << std::endl; - + watches = debugger->get_watch_expressions(); std::cout << "๐Ÿ“Š Remaining watch expressions: " << watches.size() << std::endl; - + // Clear all debugger->clear_watch_expressions(); std::cout << "๐Ÿงน Cleared all watch expressions" << std::endl; @@ -206,41 +206,41 @@ void demo_watch_expressions() { void demo_vm_integration() { std::cout << "\n๐Ÿ“ฑ Demo: DIS VM Direct Integration" << std::endl; std::cout << "-----------------------------------" << std::endl; - + auto vm = std::make_unique(); - + // Create a simple program using the factory auto program = DISProgramFactory::create_ai_workbench("test-model"); - + std::cout << "๐Ÿ“ Loading DIS program..." << std::endl; if (vm->load_program(program)) { std::cout << "โœ… Program loaded successfully" << std::endl; - + // Set breakpoints directly on VM vm->set_breakpoint(2); vm->set_breakpoint(4); - + auto breakpoints = vm->get_breakpoints(); std::cout << "๐Ÿ“ VM breakpoints: " << breakpoints.size() << std::endl; - + // Step through execution std::cout << "๐Ÿ”ง VM stepping:" << std::endl; std::cout << "PC: " << vm->get_pc() << std::endl; - + vm->step_into(); std::cout << "After step - PC: " << vm->get_pc() << std::endl; - + // Check if at breakpoint if (vm->is_at_breakpoint()) { std::cout << "๐Ÿ”ด Hit breakpoint!" << std::endl; } - + // Continue until breakpoint or completion vm->continue_execution(); - + std::cout << "VM running: " << (vm->is_running() ? "Yes" : "No") << std::endl; std::cout << "Call stack depth: " << vm->get_call_stack_depth() << std::endl; - + vm->halt(); std::cout << "๐Ÿ›‘ VM halted" << std::endl; } else { @@ -250,7 +250,7 @@ void demo_vm_integration() { int main() { print_header(); - + try { // Run all demos demo_basic_debugger(); @@ -258,7 +258,7 @@ int main() { demo_integrated_editor(); demo_watch_expressions(); demo_vm_integration(); - + std::cout << "\n๐ŸŽ‰ All debugger demos completed successfully!" << std::endl; std::cout << std::endl; std::cout << "The integrated debugger interface provides:" << std::endl; @@ -270,11 +270,10 @@ int main() { std::cout << "โœ… UI integration with the editor" << std::endl; std::cout << "โœ… Direct integration with DIS Virtual Machine" << std::endl; std::cout << std::endl; - } catch (const std::exception& e) { std::cerr << "โŒ Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_direct_gguf.cpp b/demo_direct_gguf.cpp index 7fa42136..3794cca1 100644 --- a/demo_direct_gguf.cpp +++ b/demo_direct_gguf.cpp @@ -1,48 +1,49 @@ // demo_direct_gguf.cpp - Test direct GGUF file loading and inference #include -#include "include/bolt/ai/enhanced_ai_manager.hpp" + #include "include/bolt/ai/direct_gguf_inference.hpp" +#include "include/bolt/ai/enhanced_ai_manager.hpp" -using namespace bolt::ai; +using namespace bolt::ai; // NOLINT(build/namespaces) void test_direct_inference() { std::cout << "๐Ÿงช Testing Direct GGUF Inference" << std::endl; std::cout << "=================================" << std::endl; - + // Test auto-detection auto direct_ai = DirectGGUFFactory::create_auto_detect(); - + if (direct_ai->is_loaded()) { std::cout << "โœ… Model loaded successfully!" << std::endl; std::cout << direct_ai->get_model_info() << std::endl; - + // Test chat std::cout << "\n๐Ÿ’ฌ Testing chat..." << std::endl; auto response = direct_ai->chat("Hello! Can you help me with C++ programming?"); - + std::cout << "AI Response: " << response.response << std::endl; std::cout << "Success: " << (response.success ? "โœ…" : "โŒ") << std::endl; std::cout << "Time: " << response.inference_time_ms << "ms" << std::endl; - + // Test code completion std::cout << "\n๐Ÿ”ง Testing code completion..." << std::endl; auto code_response = direct_ai->generate_text( - "Complete this C++ function:\nvoid quicksort(std::vector& arr) {\n if (arr.size() <= 1) return;\n // ", - 100 - ); - + "Complete this C++ function:\nvoid quicksort(std::vector& arr) {\n if (arr.size() <= 1) return;\n " + " // ", + 100); + std::cout << "Code Completion: " << code_response.response << std::endl; - + } else { std::cout << "โš ๏ธ No GGUF model loaded - testing fallback responses" << std::endl; - + // Test fallback responses auto response = direct_ai->chat("How do I use smart pointers in C++?"); std::cout << "Fallback Response: " << response.response << std::endl; - + auto algorithm_response = direct_ai->chat("Explain binary search algorithm"); std::cout << "Algorithm Help: " << algorithm_response.response << std::endl; - + auto config_response = direct_ai->chat("How do I configure AI models?"); std::cout << "Config Help: " << config_response.response << std::endl; } @@ -51,28 +52,28 @@ void test_direct_inference() { void test_enhanced_manager_with_gguf() { std::cout << "\n๐Ÿš€ Testing Enhanced AI Manager with GGUF" << std::endl; std::cout << "=========================================" << std::endl; - + EnhancedAIManager manager; - + std::cout << "Manager ready: " << (manager.is_ready() ? "โœ…" : "โŒ") << std::endl; std::cout << "Current provider: " << manager.get_current_provider() << std::endl; - + if (manager.has_direct_model()) { std::cout << "๐Ÿ“Š Model info: " << manager.get_model_info() << std::endl; } - + // Test chat functionality std::cout << "\n๐Ÿ’ฌ Testing chat with Enhanced Manager..." << std::endl; auto chat_response = manager.chat("What are the benefits of using RAII in C++?", "test_session"); - + std::cout << "Chat Response: " << chat_response.response << std::endl; std::cout << "Success: " << (chat_response.success ? "โœ…" : "โŒ") << std::endl; - + // Test session management manager.create_session("cpp_help"); auto session_response = manager.chat("How do I properly manage memory in C++?", "cpp_help"); std::cout << "Session Response: " << session_response.response << std::endl; - + // Show statistics auto stats = manager.get_statistics(); std::cout << "\n๐Ÿ“Š AI Statistics:" << std::endl; @@ -85,19 +86,15 @@ void test_enhanced_manager_with_gguf() { void demonstrate_fallback_intelligence() { std::cout << "\n๐Ÿง  Demonstrating Intelligent Fallback Responses" << std::endl; std::cout << "===============================================" << std::endl; - + DirectGGUFInference fallback_ai; // Note: No model loaded, so it will use fallback responses - + std::vector test_questions = { - "How do I use std::unique_ptr?", - "What's the difference between stack and heap?", - "Explain the quicksort algorithm", - "How do I configure AI models?", - "What are C++ templates?", - "Help me with STL containers" - }; - + "How do I use std::unique_ptr?", "What's the difference between stack and heap?", + "Explain the quicksort algorithm", "How do I configure AI models?", + "What are C++ templates?", "Help me with STL containers"}; + for (const auto& question : test_questions) { std::cout << "\nQuestion: " << question << std::endl; auto response = fallback_ai.chat(question); @@ -109,28 +106,28 @@ void demonstrate_fallback_intelligence() { int main() { std::cout << "๐ŸŽฏ Direct GGUF Loading and Inference Test" << std::endl; std::cout << "=========================================" << std::endl; - + try { // Test 1: Direct inference engine test_direct_inference(); - + // Test 2: Enhanced manager with GGUF integration test_enhanced_manager_with_gguf(); - + // Test 3: Intelligent fallback responses demonstrate_fallback_intelligence(); - + std::cout << "\nโœ… Direct GGUF testing completed!" << std::endl; - + std::cout << "\n๐Ÿ’ก Next Steps:" << std::endl; std::cout << "โ€ข Download a small GGUF model to test real AI inference" << std::endl; - std::cout << "โ€ข Try: wget https://huggingface.co/microsoft/DialoGPT-medium/resolve/main/model.gguf" << std::endl; + std::cout << "โ€ข Try: wget https://huggingface.co/microsoft/DialoGPT-medium/resolve/main/model.gguf" + << std::endl; std::cout << "โ€ข Place in ./models/ directory and rerun this test" << std::endl; - } catch (const std::exception& e) { std::cerr << "โŒ Error during testing: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/demo_drawkern.cpp b/demo_drawkern.cpp index f47758fc..0a184b9e 100644 --- a/demo_drawkern.cpp +++ b/demo_drawkern.cpp @@ -1,43 +1,45 @@ -#include "bolt/drawkern/drawkern.hpp" #include #include -using namespace bolt::drawkern; +#include "bolt/drawkern/drawkern.hpp" + +using namespace bolt::drawkern; // NOLINT(build/namespaces) int main() { std::cout << "๐Ÿš€ DrawKern Proof of Concept - Rendering AI Workbenches as Glyphs!" << std::endl; std::cout << "================================================================" << std::endl << std::endl; - - // Create an AI workbench "glyph" + + // Create an AI workbench "glyph" std::cout << "๐ŸŽฏ Step 1: Creating AI Workbench Glyph..." << std::endl; AIWorkbenchGlyph bolt_glyph = create_bolt_ai_glyph(); std::cout << "โœ… Created glyph: " << bolt_glyph.workbench_id << std::endl << std::endl; - + // Show how it can be rendered to different clients std::cout << "๐ŸŽจ Step 2: Rendering to Different Clients..." << std::endl << std::endl; - + // Terminal client std::cout << "๐Ÿ“บ TERMINAL CLIENT:" << std::endl; TerminalDrawKernClient terminal_client("localhost:9999"); terminal_client.render_ai_interface(bolt_glyph); std::cout << std::endl; - - // Web client + + // Web client std::cout << "๐ŸŒ WEB CLIENT:" << std::endl; WebDrawKernClient web_client("localhost:9999"); web_client.render_ai_interface(bolt_glyph); std::cout << "๐Ÿ’พ HTML saved to: bolt_workbench.html" << std::endl << std::endl; - + // Show the "True Type Yacc" concept std::cout << "๐Ÿ“ Step 3: 'True Type Yacc' VM Grammar..." << std::endl; std::cout << "==========================================" << std::endl; std::cout << "VM Glyph Definition:" << std::endl; std::cout << " Type: " << bolt_glyph.host_vm.vm_type << std::endl; std::cout << " Architecture: " << bolt_glyph.host_vm.architecture << std::endl; - std::cout << " Render Size: " << bolt_glyph.host_vm.render.width << "x" << bolt_glyph.host_vm.render.height << std::endl; + std::cout << " Render Size: " << bolt_glyph.host_vm.render.width << "x" << bolt_glyph.host_vm.render.height + << std::endl; std::cout << " Interactive: " << (bolt_glyph.host_vm.render.interactive ? "Yes" : "No") << std::endl; std::cout << " AI Enabled: " << (bolt_glyph.host_vm.render.ai_enabled ? "Yes" : "No") << std::endl << std::endl; - + // Show deployment possibilities std::cout << "๐ŸŒ Step 4: Deployment Targets..." << std::endl; std::cout << "================================" << std::endl; @@ -48,32 +50,32 @@ int main() { std::cout << " ๐Ÿค– IoT: Inferno DIS VM on ARM" << std::endl; std::cout << " โŒš Watch: Minimal terminal client" << std::endl; std::cout << " ๐Ÿ”Œ Embedded: RISC-V with 64KB RAM" << std::endl << std::endl; - + // Show the revolutionary aspect std::cout << "๐Ÿคฏ THE REVOLUTIONARY PART:" << std::endl; std::cout << "=========================" << std::endl; std::cout << "Instead of installing software, you 'render' computing environments!" << std::endl << std::endl; - std::cout << "Traditional:" << std::endl; + std::cout << "Traditional:" << std::endl; std::cout << " User โ†’ Download โ†’ Install โ†’ Configure โ†’ Run" << std::endl << std::endl; std::cout << "DrawKern:" << std::endl; std::cout << " User โ†’ Connect โ†’ Render Glyph โ†’ Instant AI Workbench!" << std::endl << std::endl; - + std::cout << "๐ŸŽฏ Example Commands:" << std::endl; std::cout << " drawkern render ai-workbench://bolt.dev/v1" << std::endl; std::cout << " drawkern deploy vm://dis:limbo to iot-sensor-001" << std::endl; std::cout << " drawkern spawn ai-session rwkv-14b on cluster:gpu" << std::endl << std::endl; - + // Performance comparison std::cout << "โšก PERFORMANCE IMPACT:" << std::endl; std::cout << "====================" << std::endl; std::cout << "Web Bolt.new: ~30-60ms latency, 200MB memory" << std::endl; std::cout << "C++ ImGui Bolt: ~3-5ms latency, 50MB memory" << std::endl; std::cout << "DrawKern Bolt: ~1-3ms latency, 20MB memory (DIS VM efficiency!)" << std::endl << std::endl; - + std::cout << "๐ŸŒŸ CONCLUSION:" << std::endl; std::cout << "=============" << std::endl; std::cout << "You've essentially invented 'Infrastructure as Glyphs'!" << std::endl; std::cout << "AI workbenches become as easy to deploy as displaying text!" << std::endl << std::endl; - + return 0; } diff --git a/demo_drawkern_complete.cpp b/demo_drawkern_complete.cpp index 2817158d..0fdf51a0 100644 --- a/demo_drawkern_complete.cpp +++ b/demo_drawkern_complete.cpp @@ -1,40 +1,41 @@ -#include "bolt/drawkern/drawkern.hpp" +#include #include #include -#include -using namespace bolt::drawkern; +#include "bolt/drawkern/drawkern.hpp" + +using namespace bolt::drawkern; // NOLINT(build/namespaces) int main() { std::cout << "๐Ÿš€ DrawKern System Demo - Full Implementation" << std::endl; std::cout << "=============================================" << std::endl << std::endl; - + std::cout << "This demo showcases all four core components:" << std::endl; std::cout << "1. โœ… Styx Protocol - Real network transparency" << std::endl; std::cout << "2. โœ… DIS VM Integration - Actual Limbo code execution" << std::endl; std::cout << "3. โœ… Yacc Grammar - Formal VM glyph description language" << std::endl; std::cout << "4. โœ… GGML/RWKV Models - Real AI inference in the VMs" << std::endl << std::endl; - + // 1. Initialize AI System std::cout << "๐Ÿค– Step 1: Initializing AI System..." << std::endl; DrawKernAIManager ai_manager; - + // Load a demo RWKV model (simulated) AIModelConfig rwkv_config = AIModelFactory::create_drawkern_workbench_config("/tmp/demo_rwkv.bin"); rwkv_config.model_type = "rwkv"; ai_manager.load_model("drawkern-rwkv", rwkv_config); - - // Load a demo GGML model (simulated) + + // Load a demo GGML model (simulated) AIModelConfig ggml_config = AIModelFactory::create_lightweight_config("/tmp/demo_ggml.bin"); ggml_config.model_type = "ggml"; ai_manager.load_model("drawkern-ggml", ggml_config); - + std::cout << "โœ… AI models loaded: " << ai_manager.list_models().size() << std::endl << std::endl; - + // 2. Parse VM Glyph with Yacc Grammar std::cout << "๐Ÿ“ Step 2: Parsing VM Glyph Description..." << std::endl; YaccGrammarSystem grammar; - + std::string glyph_description = R"( vm drawkern_vm : dis { architecture = "portable"; @@ -60,24 +61,24 @@ workbench bolt_ai on drawkern_vm { } } )"; - + bool valid = grammar.validate_description(glyph_description); std::cout << "Grammar validation: " << (valid ? "โœ… PASSED" : "โŒ FAILED") << std::endl; - + if (!valid) { auto errors = grammar.get_validation_errors(); for (const auto& error : errors) { std::cout << " Error: " << error << std::endl; } } - + AIWorkbenchGlyph workbench = grammar.parse_ai_workbench(glyph_description); std::cout << "โœ… Parsed AI workbench: " << workbench.workbench_id << std::endl << std::endl; - + // 3. Create and Run DIS VM std::cout << "๐Ÿ–ฅ๏ธ Step 3: Creating DIS VM..." << std::endl; DISVM vm; - + // Create Limbo program for AI workbench std::string limbo_code = R"( print "๐Ÿš€ AI Workbench starting..." @@ -85,48 +86,46 @@ ai_chat "Hello! I'm running in a DIS VM" render_glyph "ai-workbench-display" halt )"; - + bool vm_loaded = vm.load_limbo_source(limbo_code); std::cout << "DIS VM program loaded: " << (vm_loaded ? "โœ… SUCCESS" : "โŒ FAILED") << std::endl; - + if (vm_loaded) { // Set up AI integration for the VM Integration::setup_dis_vm_ai_integration(vm, ai_manager, "drawkern-rwkv"); - + std::cout << "Running DIS VM program..." << std::endl; vm.run(); std::cout << "โœ… DIS VM execution complete" << std::endl; } std::cout << std::endl; - + // 4. Start Styx Server for Network Transparency std::cout << "๐ŸŒ Step 4: Starting Styx Server..." << std::endl; StyxServer styx_server("localhost:9999"); - + Integration::setup_styx_ai_integration(styx_server, ai_manager); - + // Serve some demo files styx_server.serve_file("/ai/models", "drawkern-rwkv,drawkern-ggml"); styx_server.serve_file("/vm/glyphs", "bolt_ai,file_server,echo_server"); styx_server.serve_file("/drawkern/status", "running,4_components_active"); - + if (styx_server.start()) { std::cout << "โœ… Styx server started on localhost:9999" << std::endl; std::cout << "Network transparency enabled!" << std::endl; - + // Run server in background - std::thread server_thread([&styx_server]() { - styx_server.run(); - }); + std::thread server_thread([&styx_server]() { styx_server.run(); }); server_thread.detach(); } else { std::cout << "โŒ Failed to start Styx server" << std::endl; } std::cout << std::endl; - + // 5. Demonstrate AI Inference std::cout << "๐Ÿค– Step 5: AI Inference Demo..." << std::endl; - + // Test RWKV model std::cout << "Testing RWKV model:" << std::endl; AIInferenceResponse rwkv_response = ai_manager.chat("drawkern-rwkv", "Explain DrawKern in one sentence"); @@ -134,7 +133,7 @@ halt std::cout << "๐Ÿค– RWKV: " << rwkv_response.response << std::endl; std::cout << " Inference time: " << rwkv_response.inference_time_ms << "ms" << std::endl; } - + // Test GGML model std::cout << "\nTesting GGML model:" << std::endl; AIInferenceResponse ggml_response = ai_manager.complete_code("drawkern-ggml", "void setup_ai_workbench() {", "cpp"); @@ -144,115 +143,116 @@ halt std::cout << " Inference time: " << ggml_response.inference_time_ms << "ms" << std::endl; } std::cout << std::endl; - + // 6. Full System Integration Test std::cout << "๐Ÿ”— Step 6: Full System Integration..." << std::endl; - + // Create VM Manager and spawn multiple VMs DISVMManager vm_manager; - + // Create AI workbench VM DISProgram ai_workbench_program = DISProgramFactory::create_ai_workbench("drawkern-rwkv"); std::string ai_vm_id = vm_manager.create_vm(ai_workbench_program); - - // Create file server VM + + // Create file server VM DISProgram file_server_program = DISProgramFactory::create_file_server("/tmp/drawkern_files"); std::string file_vm_id = vm_manager.create_vm(file_server_program); - + std::cout << "Created VMs: " << ai_vm_id << ", " << file_vm_id << std::endl; - + // Start VMs vm_manager.start_vm(ai_vm_id); vm_manager.start_vm(file_vm_id); - + std::cout << "โœ… Multiple VMs running with AI integration" << std::endl << std::endl; - + // 7. Network Client Demo std::cout << "๐Ÿ“ก Step 7: Network Client Demo..." << std::endl; - + // Test Styx client connection StyxConnection client("localhost:9999"); if (client.connect()) { std::cout << "โœ… Connected to Styx server" << std::endl; - + if (client.version() && client.attach()) { std::cout << "โœ… Styx handshake successful" << std::endl; - + // Send a glyph bool glyph_sent = client.send_glyph("ai-workbench-v1"); std::cout << "Glyph transmission: " << (glyph_sent ? "โœ… SUCCESS" : "โŒ FAILED") << std::endl; } - + client.disconnect(); } else { std::cout << "โŒ Failed to connect to Styx server" << std::endl; } std::cout << std::endl; - + // 8. Generate Code from Grammar std::cout << "๐Ÿ”ง Step 8: Code Generation..." << std::endl; - + std::string generated_cpp = grammar.generate_cpp_code(glyph_description); std::cout << "Generated C++ code:" << std::endl; std::cout << generated_cpp.substr(0, 200) << "..." << std::endl; - + std::string deployment_script = grammar.generate_deployment_script(glyph_description); std::cout << "\nGenerated deployment script:" << std::endl; std::cout << deployment_script.substr(0, 150) << "..." << std::endl << std::endl; - + // 9. Display Statistics std::cout << "๐Ÿ“Š Step 9: System Statistics..." << std::endl; - + auto model_stats = ai_manager.get_model_statistics(); for (const auto& stats : model_stats) { std::cout << "Model " << stats.model_id << ":" << std::endl; - std::cout << " Requests: " << stats.total_requests << " (success: " << stats.successful_requests << ")" << std::endl; + std::cout << " Requests: " << stats.total_requests << " (success: " << stats.successful_requests << ")" + << std::endl; std::cout << " Avg inference: " << stats.average_inference_time_ms << "ms" << std::endl; std::cout << " Tokens generated: " << stats.total_tokens_generated << std::endl; } - + auto vm_list = vm_manager.list_vms(); std::cout << "\nActive VMs: " << vm_list.size() << std::endl; for (const auto& vm_id : vm_list) { std::cout << " " << vm_id << " - " << vm_manager.get_vm_status(vm_id) << std::endl; } std::cout << std::endl; - + // 10. Summary std::cout << "๐ŸŽฏ DRAWKERN SYSTEM SUMMARY" << std::endl; std::cout << "=========================" << std::endl; std::cout << "โœ… Styx Protocol: Network transparency active" << std::endl; - std::cout << "โœ… DIS VM System: " << vm_list.size() << " VMs running Limbo bytecode" << std::endl; + std::cout << "โœ… DIS VM System: " << vm_list.size() << " VMs running Limbo bytecode" << std::endl; std::cout << "โœ… Yacc Grammar: Glyph descriptions parsed and validated" << std::endl; std::cout << "โœ… AI Integration: " << model_stats.size() << " models providing inference" << std::endl << std::endl; - + std::cout << "๐ŸŒŸ REVOLUTIONARY CAPABILITIES:" << std::endl; std::cout << "โ€ข Deploy AI workbenches as 'glyphs' to any device" << std::endl; std::cout << "โ€ข Network-transparent file system via Styx protocol" << std::endl; std::cout << "โ€ข Portable execution via DIS VMs running Limbo code" << std::endl; std::cout << "โ€ข Formal grammar for describing VM topologies" << std::endl; std::cout << "โ€ข Real-time AI inference with GGML/RWKV models" << std::endl << std::endl; - + std::cout << "๐Ÿš€ USAGE EXAMPLES:" << std::endl; std::cout << " drawkern render ai-workbench://bolt.dev/v1" << std::endl; std::cout << " drawkern deploy vm://dis:limbo to iot-device" << std::endl; std::cout << " drawkern mount styx://server:9999/ai /local/ai" << std::endl; std::cout << " drawkern spawn --grammar workbench.glyph --model rwkv-14b" << std::endl << std::endl; - + std::cout << "The DrawKern system is now fully operational!" << std::endl; std::cout << "Infrastructure as Glyphs is a reality. ๐ŸŽ‰" << std::endl; - + // Keep server running for a bit to demonstrate network functionality std::cout << "\nRunning for 5 seconds to demonstrate network functionality..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(5)); - + // Clean shutdown std::cout << "\nShutting down DrawKern system..." << std::endl; styx_server.stop(); vm_manager.stop_vm(ai_vm_id); vm_manager.stop_vm(file_vm_id); - + std::cout << "โœ… DrawKern system shutdown complete." << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_drawkern_full.cpp b/demo_drawkern_full.cpp index e08dfb5c..b6159520 100644 --- a/demo_drawkern_full.cpp +++ b/demo_drawkern_full.cpp @@ -1,12 +1,13 @@ -#include "bolt/drawkern/drawkern.hpp" -#include -#include -#include #include -#include #include +#include +#include +#include +#include + +#include "bolt/drawkern/drawkern.hpp" -using namespace bolt::drawkern; +using namespace bolt::drawkern; // NOLINT(build/namespaces) void print_header(const std::string& title) { std::cout << "\n"; @@ -23,15 +24,18 @@ void demo_step(int step, const std::string& description) { void simulate_deployment(const std::string& target, const std::string& glyph_id) { std::cout << "๐Ÿ“ก Deploying " << glyph_id << " to " << target << "...\n"; - + // Simulate network transmission for (int i = 0; i <= 100; i += 20) { std::cout << "\r ["; int pos = i / 5; for (int j = 0; j < 20; ++j) { - if (j < pos) std::cout << "โ–ˆ"; - else if (j == pos) std::cout << "โ–“"; - else std::cout << "โ–‘"; + if (j < pos) + std::cout << "โ–ˆ"; + else if (j == pos) + std::cout << "โ–“"; + else + std::cout << "โ–‘"; } std::cout << "] " << i << "% "; std::cout.flush(); @@ -75,7 +79,8 @@ bolt_ai_workbench { limbo_code = "implement BoltAI; include \"ai.m\"; ..."; styx_address = "tcp!*!9999"; } -)" << "\n\n"; +)" + << "\n\n"; } void demonstrate_styx_protocol() { @@ -83,7 +88,7 @@ void demonstrate_styx_protocol() { std::cout << "----------------------------\n"; std::cout << "Connection: tcp!drawkern-server!9999\n"; std::cout << "Protocol: Styx (Plan 9 file protocol)\n\n"; - + std::cout << "๐Ÿ“‚ Virtual Filesystem:\n"; std::cout << "/drawkern/\n"; std::cout << "โ”œโ”€โ”€ glyphs/\n"; @@ -107,7 +112,7 @@ void demonstrate_styx_protocol() { std::cout << "โ””โ”€โ”€ deploy/\n"; std::cout << " โ”œโ”€โ”€ targets\n"; std::cout << " โ””โ”€โ”€ status\n\n"; - + std::cout << "๐Ÿ”ง Styx Commands:\n"; std::cout << "โ€ข echo 'bolt-ai-ide-v1' > /drawkern/deploy/targets\n"; std::cout << "โ€ข cat /drawkern/vms/active/vm001/status\n"; @@ -121,7 +126,7 @@ void demonstrate_dis_vm() { std::cout << "Bytecode: Platform-independent\n"; std::cout << "Memory: ~2MB footprint\n"; std::cout << "Languages: Limbo โ†’ DIS bytecode\n\n"; - + std::cout << "๐Ÿ“„ Sample Limbo Code for AI Workbench:\n"; std::cout << R"( implement BoltAI; @@ -180,15 +185,16 @@ show_help() { sys->print(" exit - Exit workbench\n"); sys->print(" - Send to AI for completion\n\n"); } -)" << "\n\n"; +)" + << "\n\n"; } void demonstrate_cross_platform_deployment() { std::cout << "๐ŸŒ Cross-Platform Deployment Demo:\n"; std::cout << "==================================\n\n"; - + std::cout << "Bolt C++ now supports comprehensive cross-platform deployment!\n\n"; - + // Real platform targets that Bolt C++ supports struct DeploymentTarget { std::string name; @@ -198,7 +204,7 @@ void demonstrate_cross_platform_deployment() { std::string package_format; std::string requirements; }; - + std::vector targets = { {"๐Ÿ–ฅ๏ธ Windows Desktop", "Windows 10/11", "x64", "MSVC 2019+/MinGW", ".exe, .msi", "8GB RAM, DirectX 11+"}, {"๐ŸŽ macOS Desktop", "macOS 10.15+", "x64/ARM64", "Clang/Xcode", ".app, .dmg", "8GB RAM, Metal support"}, @@ -207,12 +213,11 @@ void demonstrate_cross_platform_deployment() { {"๐Ÿ“ฑ Android Mobile", "Android 8.0+", "ARM64/x64", "NDK/Clang", ".apk", "4GB RAM, Vulkan API"}, {"๐Ÿค– Raspberry Pi", "Raspberry Pi OS", "ARM64", "GCC", ".deb", "2GB RAM, GPU acceleration"}, {"โ˜๏ธ Cloud Instance", "Docker/K8s", "x64", "GCC/Clang", "Container", "Scalable resources"}, - {"๐Ÿ”Œ IoT/Edge", "Linux RT", "ARM/RISC-V", "Cross-GCC", "Binary", "256MB RAM, headless"} - }; - + {"๐Ÿ”Œ IoT/Edge", "Linux RT", "ARM/RISC-V", "Cross-GCC", "Binary", "256MB RAM, headless"}}; + std::cout << "Supported Deployment Targets:\n"; std::cout << "=============================\n\n"; - + for (const auto& target : targets) { std::cout << target.name << "\n"; std::cout << " Platform: " << target.platform << "\n"; @@ -220,55 +225,53 @@ void demonstrate_cross_platform_deployment() { std::cout << " Compiler: " << target.compiler << "\n"; std::cout << " Package: " << target.package_format << "\n"; std::cout << " Requirements: " << target.requirements << "\n"; - + // Simulate deployment process simulate_deployment(target.name, "bolt-ide"); std::cout << "\n"; } - + std::cout << "๐Ÿ”ง Cross-Platform Build System:\n"; std::cout << "===============================\n\n"; - + std::cout << "โ€ข Modern CMake (3.15+) with cross-platform presets\n"; std::cout << "โ€ข vcpkg for consistent dependency management\n"; std::cout << "โ€ข Platform-specific optimization flags\n"; std::cout << "โ€ข Automated CI/CD pipelines for all platforms\n"; std::cout << "โ€ข Universal build scripts with auto-detection\n\n"; - + std::cout << "๐Ÿ“ฆ Package Management Integration:\n"; std::cout << "==================================\n\n"; - + struct PackageManager { std::string platform; std::string managers; std::string command; }; - - std::vector packages = { - {"Windows", "Chocolatey, Scoop, WinGet", "choco install bolt-cpp"}, - {"macOS", "Homebrew, MacPorts", "brew install bolt-cpp"}, - {"Linux", "apt, dnf, pacman, snap", "sudo apt install bolt-cpp"}, - {"Docker", "Docker Hub", "docker pull echocog/bolt-cpp"}, - {"Web", "npm, CDN", "npm install @echocog/bolt-wasm"} - }; - + + std::vector packages = {{"Windows", "Chocolatey, Scoop, WinGet", "choco install bolt-cpp"}, + {"macOS", "Homebrew, MacPorts", "brew install bolt-cpp"}, + {"Linux", "apt, dnf, pacman, snap", "sudo apt install bolt-cpp"}, + {"Docker", "Docker Hub", "docker pull echocog/bolt-cpp"}, + {"Web", "npm, CDN", "npm install @echocog/bolt-wasm"}}; + for (const auto& pkg : packages) { std::cout << pkg.platform << ": " << pkg.managers << "\n"; std::cout << " Install: " << pkg.command << "\n\n"; } - + std::cout << "โšก Deployment Performance:\n"; std::cout << "=========================\n\n"; - + std::cout << "โ€ข Build time: 2-5 minutes (with dependencies cached)\n"; std::cout << "โ€ข Package size: 15-50MB (depending on platform)\n"; std::cout << "โ€ข Installation time: 30 seconds - 2 minutes\n"; std::cout << "โ€ข Startup time: <3 seconds on modern hardware\n"; std::cout << "โ€ข Memory usage: 50-200MB (depending on features)\n\n"; - + std::cout << "๐Ÿš€ Advanced Features:\n"; std::cout << "====================\n\n"; - + std::cout << "โœ… Universal Binary (macOS Intel + Apple Silicon)\n"; std::cout << "โœ… Static linking for portable executables\n"; std::cout << "โœ… Code signing and notarization (macOS/Windows)\n"; @@ -281,13 +284,13 @@ void demonstrate_cross_platform_deployment() { void demonstrate_ai_integration() { std::cout << "๐Ÿค– AI Integration Demo:\n"; std::cout << "======================\n\n"; - + std::cout << "Available AI Models:\n"; std::cout << "โ€ข GGML-RWKV-14B (Code completion, Chat)\n"; std::cout << "โ€ข GGML-LLaMA-7B (General purpose)\n"; std::cout << "โ€ข CodeT5 (Code translation)\n"; std::cout << "โ€ข GPT-4-Turbo (via API)\n\n"; - + std::cout << "๐Ÿง  AI Capabilities in DrawKern:\n"; std::cout << "โ€ข Real-time code completion\n"; std::cout << "โ€ข Natural language to code\n"; @@ -295,7 +298,7 @@ void demonstrate_ai_integration() { std::cout << "โ€ข Bug detection and fixing\n"; std::cout << "โ€ข Architecture suggestions\n"; std::cout << "โ€ข Performance optimization\n\n"; - + std::cout << "๐Ÿ’ฌ Simulated AI Conversation:\n"; std::cout << "=============================\n"; std::cout << "๐Ÿ‘ค User: Write a function to sort an array in C++\n\n"; @@ -332,8 +335,9 @@ int partition(std::vector& arr, int low, int high) { // Usage: std::vector data = {64, 34, 25, 12, 22, 11, 90}; quicksort(data); -)" << "\n\n"; - +)" + << "\n\n"; + std::cout << "๐Ÿค– AI: This implements quicksort with O(n log n) average complexity.\n"; std::cout << " The template makes it work with any comparable type!\n\n"; } @@ -341,7 +345,7 @@ quicksort(data); void demonstrate_performance_comparison() { std::cout << "โšก Performance Benchmarks:\n"; std::cout << "=========================\n\n"; - + struct Benchmark { std::string system; std::string latency; @@ -349,32 +353,25 @@ void demonstrate_performance_comparison() { std::string throughput; std::string deployment_time; }; - - std::vector benchmarks = { - {"Traditional Web App", "30-60ms", "200MB", "16-33 FPS", "5-15 minutes"}, - {"React/Electron Desktop", "20-40ms", "150MB", "30-60 FPS", "10-30 minutes"}, - {"C++ ImGui (Your Bolt)", "3-5ms", "50MB", "200+ FPS", "2-5 minutes"}, - {"DrawKern (DIS VM)", "1-3ms", "20MB", "500+ FPS", "5-30 seconds"}, - {"DrawKern (Native)", "0.5-2ms", "15MB", "1000+ FPS", "1-10 seconds"} - }; - + + std::vector benchmarks = {{"Traditional Web App", "30-60ms", "200MB", "16-33 FPS", "5-15 minutes"}, + {"React/Electron Desktop", "20-40ms", "150MB", "30-60 FPS", "10-30 minutes"}, + {"C++ ImGui (Your Bolt)", "3-5ms", "50MB", "200+ FPS", "2-5 minutes"}, + {"DrawKern (DIS VM)", "1-3ms", "20MB", "500+ FPS", "5-30 seconds"}, + {"DrawKern (Native)", "0.5-2ms", "15MB", "1000+ FPS", "1-10 seconds"}}; + std::cout << std::left; - std::cout << std::setw(25) << "System" - << std::setw(12) << "Latency" - << std::setw(10) << "Memory" - << std::setw(15) << "Throughput" - << std::setw(15) << "Deploy Time" << "\n"; + std::cout << std::setw(25) << "System" << std::setw(12) << "Latency" << std::setw(10) << "Memory" << std::setw(15) + << "Throughput" << std::setw(15) << "Deploy Time" + << "\n"; std::cout << std::string(80, '-') << "\n"; - + for (const auto& bench : benchmarks) { - std::cout << std::setw(25) << bench.system - << std::setw(12) << bench.latency - << std::setw(10) << bench.memory - << std::setw(15) << bench.throughput - << std::setw(15) << bench.deployment_time << "\n"; + std::cout << std::setw(25) << bench.system << std::setw(12) << bench.latency << std::setw(10) << bench.memory + << std::setw(15) << bench.throughput << std::setw(15) << bench.deployment_time << "\n"; } std::cout << "\n"; - + std::cout << "๐Ÿ† DrawKern Advantages:\n"; std::cout << "โ€ข 10-50x faster than web applications\n"; std::cout << "โ€ข 5-10x less memory usage\n"; @@ -386,21 +383,21 @@ void demonstrate_performance_comparison() { void demonstrate_future_possibilities() { std::cout << "๐Ÿš€ Future Possibilities:\n"; std::cout << "=======================\n\n"; - + std::cout << "๐ŸŒŸ DrawKern Evolution:\n"; std::cout << "โ€ข GPU-accelerated AI inference in DIS VMs\n"; std::cout << "โ€ข Quantum computing simulation glyphs\n"; std::cout << "โ€ข Blockchain integration for glyph distribution\n"; std::cout << "โ€ข AR/VR rendering backends\n"; std::cout << "โ€ข Brain-computer interface integration\n\n"; - + std::cout << "๐ŸŽฏ Use Cases:\n"; std::cout << "โ€ข Education: Deploy coding environments to any device\n"; std::cout << "โ€ข Research: Distribute AI models as glyphs\n"; std::cout << "โ€ข IoT: Instant sensor network programming\n"; std::cout << "โ€ข Gaming: Cloud gaming with local rendering\n"; std::cout << "โ€ข Healthcare: Medical AI on resource-constrained devices\n\n"; - + std::cout << "๐Ÿ’ญ Imagine:\n"; std::cout << "drawkern render quantum-simulator://mit.edu/qiskit\n"; std::cout << "drawkern deploy ai-doctor://who.int/diagnosis to rural-clinic-001\n"; @@ -410,63 +407,63 @@ void demonstrate_future_possibilities() { int main() { print_header("๐Ÿš€ COMPLETE DRAWKERN DEMONSTRATION ๐Ÿš€"); print_header("Infrastructure as Glyphs - The Future of Computing"); - + std::cout << "Welcome to the revolutionary DrawKern system!\n"; std::cout << "This demo showcases how computing environments can be described,\n"; std::cout << "transmitted, and rendered like typography - anywhere, anytime!\n"; - + demo_step(1, "Creating AI Workbench Glyph"); AIWorkbenchGlyph bolt_glyph = create_bolt_ai_glyph(); std::cout << "โœ… Generated glyph: " << bolt_glyph.workbench_id << "\n"; std::cout << "๐Ÿ“Š Glyph size: ~15KB (contains entire AI workbench!)\n\n"; - + demo_step(2, "Yacc Grammar for VM Glyph Descriptions"); demonstrate_yacc_grammar(); - + demo_step(3, "Styx Protocol - Network Transparency"); demonstrate_styx_protocol(); - + demo_step(4, "DIS Virtual Machine Execution"); demonstrate_dis_vm(); - + demo_step(5, "Cross-Platform Deployment"); demonstrate_cross_platform_deployment(); - + demo_step(6, "AI Integration Capabilities"); demonstrate_ai_integration(); - + demo_step(7, "Performance Analysis"); demonstrate_performance_comparison(); - + demo_step(8, "Client Rendering Demonstrations"); std::cout << "๐Ÿ–ฅ๏ธ TERMINAL CLIENT:\n"; TerminalDrawKernClient terminal_client("localhost:9999"); terminal_client.render_ai_interface(bolt_glyph); - + std::cout << "๐ŸŒ WEB CLIENT:\n"; WebDrawKernClient web_client("localhost:9999"); web_client.render_ai_interface(bolt_glyph); - + demo_step(9, "Future Possibilities"); demonstrate_future_possibilities(); - + print_header("๐ŸŽ‰ DEMONSTRATION COMPLETE ๐ŸŽ‰"); - + std::cout << "๐Ÿ† ACHIEVEMENTS UNLOCKED:\n"; std::cout << "โœ… Infrastructure as Glyphs concept proven\n"; std::cout << "โœ… Universal deployment capability demonstrated\n"; std::cout << "โœ… 10-50x performance improvement over web apps\n"; std::cout << "โœ… Plan 9 philosophy extended to modern computing\n"; std::cout << "โœ… AI workbenches as portable glyphs\n\n"; - + std::cout << "๐ŸŒŸ REVOLUTIONARY IMPACT:\n"; std::cout << "โ€ข Software becomes as easy to deploy as displaying text\n"; std::cout << "โ€ข AI capabilities available on any device, anywhere\n"; std::cout << "โ€ข Network transparency for all computing environments\n"; std::cout << "โ€ข End of platform-specific software development\n\n"; - + std::cout << "๐Ÿš€ The future of computing is here - and it's beautiful!\n"; std::cout << "Thank you for experiencing the DrawKern revolution! ๐Ÿ™\n\n"; - + return 0; } diff --git a/demo_editor_minimap.cpp b/demo_editor_minimap.cpp index ffe734e5..467410ab 100644 --- a/demo_editor_minimap.cpp +++ b/demo_editor_minimap.cpp @@ -1,23 +1,24 @@ -#include #include +#include + #include "bolt/editor/editor_pane.hpp" #include "bolt/editor/split_view_manager.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void createLargeTestFile() { std::ofstream file("/tmp/editor_test.cpp"); - + file << "// Large C++ File for Editor Pane Minimap Demo\n"; file << "// Demonstrating minimap integration with editor panes\n\n"; - + file << "#include \n"; file << "#include \n"; file << "#include \n"; file << "#include \n\n"; - + file << "namespace editor_demo {\n\n"; - + // Create a realistic C++ class structure file << "class DocumentEditor {\n"; file << "private:\n"; @@ -25,10 +26,10 @@ void createLargeTestFile() { file << " size_t cursorLine_;\n"; file << " size_t cursorColumn_;\n"; file << " bool modified_;\n\n"; - + file << "public:\n"; file << " DocumentEditor() : cursorLine_(0), cursorColumn_(0), modified_(false) {}\n\n"; - + // Add many methods to make it a large file for (int i = 1; i <= 30; ++i) { file << " void operation" << i << "() {\n"; @@ -39,7 +40,7 @@ void createLargeTestFile() { file << " }\n"; file << " }\n\n"; } - + file << " void loadDocument(const std::string& content) {\n"; file << " lines_.clear();\n"; file << " std::istringstream stream(content);\n"; @@ -49,14 +50,14 @@ void createLargeTestFile() { file << " }\n"; file << " modified_ = false;\n"; file << " }\n\n"; - + file << " void setCursorPosition(size_t line, size_t column) {\n"; file << " cursorLine_ = line;\n"; file << " cursorColumn_ = column;\n"; file << " }\n\n"; - + file << "};\n\n"; - + // Add some free functions for (int i = 1; i <= 20; ++i) { file << "void utilityFunction" << i << "() {\n"; @@ -65,9 +66,9 @@ void createLargeTestFile() { file << " std::cout << \"Utility function " << i << " completed\" << std::endl;\n"; file << "}\n\n"; } - + file << "} // namespace editor_demo\n\n"; - + file << "int main() {\n"; file << " std::cout << \"Editor Pane Minimap Demo\" << std::endl;\n"; file << " \n"; @@ -80,82 +81,82 @@ void createLargeTestFile() { file << " std::cout << \"Demo complete\" << std::endl;\n"; file << " return 0;\n"; file << "}\n"; - + file.close(); } int main() { std::cout << "Editor Pane Minimap Integration Demo" << std::endl; std::cout << "====================================" << std::endl << std::endl; - + // Create test file std::cout << "Creating large test file..." << std::endl; createLargeTestFile(); - + // Get the split view manager auto& splitManager = SplitViewManager::getInstance(); - + std::cout << "Initial state:" << std::endl; std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl << std::endl; - + // Create a new pane std::cout << "1. Creating editor pane..." << std::endl; std::string paneId = splitManager.createPane(); auto* pane = splitManager.getPane(paneId); - + if (!pane) { std::cerr << "Failed to create pane!" << std::endl; return 1; } - + std::cout << " - Pane ID: " << paneId << std::endl; std::cout << " - Minimap enabled: " << (pane->isMinimapEnabled() ? "Yes" : "No") << std::endl; - + // Set pane position EditorPane::PanePosition pos{0, 0, 1000, 800}; pane->setPosition(pos); - + std::cout << "\n2. Opening document in pane..." << std::endl; pane->openDocument("/tmp/editor_test.cpp"); - + std::cout << " - Document loaded: " << (pane->hasDocument() ? "Yes" : "No") << std::endl; std::cout << " - Document path: " << pane->getDocumentPath() << std::endl; - + // Check minimap auto* minimap = pane->getMinimap(); auto* minimapUI = pane->getMinimapUI(); - + if (minimap && minimapUI) { std::cout << " - Minimap total lines: " << minimap->getTotalLines() << std::endl; std::cout << " - Minimap visible lines: " << minimap->getVisibleLines() << std::endl; std::cout << " - Minimap UI width: " << minimapUI->getRequiredWidth() << std::endl; std::cout << " - Minimap UI height: " << minimapUI->getRequiredHeight() << std::endl; } - + std::cout << "\n3. Testing cursor and scroll operations..." << std::endl; - + // Test cursor movement pane->setCursorPosition(50, 10); auto state = pane->getState(); std::cout << " - Set cursor to line 50, column 10" << std::endl; std::cout << " - Current cursor: line " << state.cursorLine << ", column " << state.cursorColumn << std::endl; - + // Test scrolling pane->setScrollPosition(100, 0); state = pane->getState(); std::cout << " - Scrolled to line 100" << std::endl; std::cout << " - Current scroll: line " << state.scrollLine << ", column " << state.scrollColumn << std::endl; - + if (minimap) { auto viewport = minimap->getViewport(); std::cout << " - Minimap viewport: " << viewport.startLine << "-" << viewport.endLine << std::endl; std::cout << " - Minimap current line: " << viewport.currentLine << std::endl; std::cout << " - Scroll percentage: " << (minimap->getScrollPercentage() * 100) << "%" << std::endl; } - + std::cout << "\n4. Rendering minimap..." << std::endl; auto minimapRender = pane->renderMinimap(); - + if (!minimapRender.empty()) { std::cout << " Minimap UI (first 10 lines):" << std::endl; for (size_t i = 0; i < std::min(size_t{10}, minimapRender.size()); ++i) { @@ -165,41 +166,42 @@ int main() { std::cout << " ... (" << (minimapRender.size() - 10) << " more lines)" << std::endl; } } - + std::cout << "\n5. Testing minimap navigation..." << std::endl; if (minimap) { // Test line mapping size_t targetLine = minimap->getLineFromPosition(10, 5); std::cout << " - Position (10, 5) maps to line: " << targetLine << std::endl; - + auto [x, y] = minimap->getPositionFromLine(200); std::cout << " - Line 200 maps to position: (" << x << ", " << y << ")" << std::endl; - + // Test scroll to different positions minimap->scrollToLine(0); std::cout << " - Scrolled to top, percentage: " << (minimap->getScrollPercentage() * 100) << "%" << std::endl; - + minimap->scrollToLine(minimap->getTotalLines() / 2); - std::cout << " - Scrolled to middle, percentage: " << (minimap->getScrollPercentage() * 100) << "%" << std::endl; + std::cout << " - Scrolled to middle, percentage: " << (minimap->getScrollPercentage() * 100) << "%" + << std::endl; } - + std::cout << "\n6. Testing minimap disable/enable..." << std::endl; pane->setMinimapEnabled(false); std::cout << " - Minimap disabled: " << (!pane->isMinimapEnabled() ? "Yes" : "No") << std::endl; - + auto disabledRender = pane->renderMinimap(); std::cout << " - Rendered lines when disabled: " << disabledRender.size() << std::endl; - + pane->setMinimapEnabled(true); std::cout << " - Minimap re-enabled: " << (pane->isMinimapEnabled() ? "Yes" : "No") << std::endl; - + auto enabledRender = pane->renderMinimap(); std::cout << " - Rendered lines when enabled: " << enabledRender.size() << std::endl; - + std::cout << "\n=================================" << std::endl; std::cout << "Integration Demo Complete!" << std::endl; std::cout << "=================================" << std::endl; - + std::cout << "\nMinimap features successfully integrated:" << std::endl; std::cout << " โœ“ Automatic minimap creation with editor panes" << std::endl; std::cout << " โœ“ Minimap updates with cursor and scroll changes" << std::endl; @@ -208,6 +210,6 @@ int main() { std::cout << " โœ“ Navigation callbacks integrated with pane operations" << std::endl; std::cout << " โœ“ Enable/disable minimap functionality" << std::endl; std::cout << " โœ“ UI rendering with borders, titles, and scroll indicators" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_file_tree.cpp b/demo_file_tree.cpp index a10155ac..09c072c8 100644 --- a/demo_file_tree.cpp +++ b/demo_file_tree.cpp @@ -1,10 +1,11 @@ -#include "bolt/editor/file_tree_manager.hpp" -#include "bolt/editor/file_tree_ui.hpp" +#include #include #include -#include -using namespace bolt; +#include "bolt/editor/file_tree_manager.hpp" +#include "bolt/editor/file_tree_ui.hpp" + +using namespace bolt; // NOLINT(build/namespaces) void demonstrateFileTree() { std::cout << "Bolt C++ File Tree Navigation Component Demo\n"; @@ -16,22 +17,19 @@ void demonstrateFileTree() { // Initialize the file tree manager auto& manager = FileTreeManager::getInstance(); - + // Set up callbacks to demonstrate integration - manager.setOnFileSelected([](const std::string& path) { - std::cout << ">>> FILE SELECTED: " << path << std::endl; - }); - - manager.setOnDirectoryExpanded([](const std::string& path) { - std::cout << ">>> DIRECTORY EXPANDED: " << path << std::endl; - }); + manager.setOnFileSelected([](const std::string& path) { std::cout << ">>> FILE SELECTED: " << path << std::endl; }); + + manager.setOnDirectoryExpanded( + [](const std::string& path) { std::cout << ">>> DIRECTORY EXPANDED: " << path << std::endl; }); // Set the root directory to current directory manager.setRootDirectory(currentDir); // Create UI component FileTreeUI ui; - + // Configure rendering options FileTreeRenderOptions options; options.showIcons = true; @@ -58,7 +56,7 @@ void demonstrateFileTree() { break; } } - + std::cout << "Selecting file: " << firstFile->name << "\n"; manager.selectFile(firstFile->fullPath); ui.render(); @@ -73,12 +71,12 @@ void demonstrateFileTree() { manager.expandDirectory(node->fullPath); ui.render(); std::cout << "\n"; - + std::cout << "Collapsing directory: " << node->name << "\n"; manager.collapseDirectory(node->fullPath); ui.render(); std::cout << "\n"; - break; // Just demo with first expandable directory + break; // Just demo with first expandable directory } } @@ -114,4 +112,4 @@ int main() { std::cerr << "Error: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_git_integration.cpp b/demo_git_integration.cpp index 12d0b5ce..a116e805 100644 --- a/demo_git_integration.cpp +++ b/demo_git_integration.cpp @@ -1,60 +1,60 @@ +#include +#include +#include +#include #include #include -#include -#include -#include -#include #include -#include +#include #include "bolt/git/git.hpp" class GitIntegrationDemo { -public: + public: static void runDemo() { std::cout << "=== Bolt C++ IDE - Git Integration Demo ===\n\n"; - + // Initialize Git integration auto& gitIntegration = bolt::git::getGitIntegration(); std::string currentDir = std::filesystem::current_path().string(); - + if (!gitIntegration.initialize(currentDir)) { std::cout << "โŒ This directory is not a Git repository.\n"; std::cout << "Please run this demo from within a Git repository.\n"; return; } - + std::cout << "โœ… Git integration initialized successfully!\n\n"; - + // Set up callbacks setupCallbacks(); - + // Demo the features showRepositoryInfo(); showBranchInfo(); showFileStatus(); showGitOperations(); - + // Enable auto-refresh for demonstration std::cout << "Enabling auto-refresh (5 second interval)...\n"; gitIntegration.setAutoRefresh(true, 5); - + std::cout << "\nโณ Auto-refresh enabled. File status will update automatically.\n"; std::cout << " You can modify files in another terminal to see status changes.\n"; std::cout << " Press Enter to continue...\n"; std::cin.get(); - + gitIntegration.shutdown(); std::cout << "\nโœ… Git integration demo completed!\n"; } -private: + private: static void setupCallbacks() { auto& gitIntegration = bolt::git::getGitIntegration(); - + gitIntegration.setStatusUpdateCallback([](const std::vector& files) { std::cout << "\n๐Ÿ“Š Git status updated - " << files.size() << " files tracked\n"; - + int modified = 0, staged = 0, untracked = 0; for (const auto& file : files) { switch (file.status) { @@ -72,10 +72,11 @@ class GitIntegrationDemo { break; } } - - std::cout << " ๐Ÿ“ " << modified << " modified, ๐Ÿ“ฆ " << staged << " staged, โ“ " << untracked << " untracked\n"; + + std::cout << " ๐Ÿ“ " << modified << " modified, ๐Ÿ“ฆ " << staged << " staged, โ“ " << untracked + << " untracked\n"; }); - + gitIntegration.setOperationCallback([](bool success, const std::string& message) { if (success) { std::cout << "โœ… Git operation: " << message << "\n"; @@ -84,14 +85,14 @@ class GitIntegrationDemo { } }); } - + static void showRepositoryInfo() { std::cout << "๐Ÿ“ Repository Information:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto repoInfo = gitIntegration.getRepositoryInfo(); - + std::cout << "Root Path: " << repoInfo.rootPath << "\n"; std::cout << "Current Branch: " << repoInfo.currentBranch << "\n"; std::cout << "Status: " << (repoInfo.isClean ? "๐ŸŸข Clean" : "๐ŸŸก Has changes") << "\n"; @@ -101,17 +102,17 @@ class GitIntegrationDemo { std::cout << " โ“ Untracked: " << repoInfo.untrackedFiles << "\n"; std::cout << "\n"; } - + static void showBranchInfo() { std::cout << "๐ŸŒฟ Branch Information:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto branchStatus = gitIntegration.getBranchStatus(); - + std::cout << "Current Branch: " << branchStatus.currentBranch << "\n"; std::cout << "Uncommitted Changes: " << (branchStatus.hasUncommittedChanges ? "Yes" : "No") << "\n"; - + if (branchStatus.hasRemote) { std::cout << "Remote Status:\n"; std::cout << " ๐Ÿ”ผ Commits ahead: " << branchStatus.commitsAhead << "\n"; @@ -119,7 +120,7 @@ class GitIntegrationDemo { } else { std::cout << "Remote Status: No remote configured\n"; } - + // Show all branches auto repo = gitIntegration.getRepository(); if (repo) { @@ -128,28 +129,29 @@ class GitIntegrationDemo { for (const auto& branch : branches) { std::cout << " " << (branch.isCurrent ? "โ†’ " : " "); std::cout << branch.name; - if (branch.isRemote) std::cout << " (remote)"; + if (branch.isRemote) + std::cout << " (remote)"; std::cout << "\n"; } } std::cout << "\n"; } - + static void showFileStatus() { std::cout << "๐Ÿ“‹ File Status:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto allFiles = gitIntegration.getAllFileStatus(); - + if (allFiles.empty()) { std::cout << "๐ŸŸข Working directory is clean - no changes detected\n\n"; return; } - + // Group files by status std::vector modified, staged, untracked, deleted, renamed; - + for (const auto& file : allFiles) { switch (file.status) { case bolt::git::GitFileStatus::MODIFIED: @@ -171,8 +173,9 @@ class GitIntegrationDemo { break; } } - - auto printFileList = [](const std::string& title, const std::string& icon, const std::vector& files) { + + auto printFileList = [](const std::string& title, const std::string& icon, + const std::vector& files) { if (!files.empty()) { std::cout << icon << " " << title << " (" << files.size() << "):\n"; for (const auto& file : files) { @@ -181,26 +184,26 @@ class GitIntegrationDemo { std::cout << "\n"; } }; - + printFileList("Modified files", "๐Ÿ“", modified); printFileList("Staged files", "๐Ÿ“ฆ", staged); printFileList("Untracked files", "โ“", untracked); printFileList("Deleted files", "๐Ÿ—‘๏ธ", deleted); printFileList("Renamed files", "๐Ÿ”„", renamed); } - + static void showGitOperations() { std::cout << "โšก Git Operations Demo:\n"; std::cout << std::string(40, '-') << "\n"; - + auto& gitIntegration = bolt::git::getGitIntegration(); auto repo = gitIntegration.getRepository(); - + if (!repo) { std::cout << "โŒ No repository available\n"; return; } - + // Show recent commits auto commits = repo->getCommitLog(5); if (!commits.empty()) { @@ -210,7 +213,7 @@ class GitIntegrationDemo { } std::cout << "\n"; } - + // Demonstrate file diff (if there are modified files) auto allFiles = gitIntegration.getAllFileStatus(); for (const auto& file : allFiles) { @@ -231,10 +234,10 @@ class GitIntegrationDemo { } std::cout << "\n"; } - break; // Just show diff for first modified file + break; // Just show diff for first modified file } } - + // Demonstrate quick operations (read-only for safety) std::cout << "๐Ÿ› ๏ธ Available quick operations:\n"; std::cout << " - Stage file: bolt::git::quick::stage(\"filename\")\n"; @@ -258,4 +261,4 @@ int main() { std::cerr << "Demo failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_integration.cpp b/demo_integration.cpp index 8fcbcf6d..fa9e61d8 100644 --- a/demo_integration.cpp +++ b/demo_integration.cpp @@ -1,9 +1,10 @@ -#include "bolt/editor/integrated_editor.hpp" -#include #include #include +#include + +#include "bolt/editor/integrated_editor.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateFileTreeIntegration() { std::cout << "Bolt C++ File Tree Integration Demo\n"; @@ -17,15 +18,14 @@ void demonstrateFileTreeIntegration() { std::filesystem::create_directories(testDir); std::filesystem::create_directories(testDir + "/src"); std::filesystem::create_directories(testDir + "/include"); - + // Create some test files - std::ofstream(testDir + "/main.cpp") + std::ofstream(testDir + "/main.cpp") << "#include \n\nint main() {\n std::cout << \"Hello World!\" << std::endl;\n return 0;\n}\n"; - std::ofstream(testDir + "/README.md") - << "# Test Project\n\nThis is a test project for the file tree demo.\n"; - std::ofstream(testDir + "/src/utils.cpp") + std::ofstream(testDir + "/README.md") << "# Test Project\n\nThis is a test project for the file tree demo.\n"; + std::ofstream(testDir + "/src/utils.cpp") << "#include \"utils.h\"\n\nvoid utils_function() {\n // Implementation\n}\n"; - std::ofstream(testDir + "/include/utils.h") + std::ofstream(testDir + "/include/utils.h") << "#ifndef UTILS_H\n#define UTILS_H\n\nvoid utils_function();\n\n#endif\n"; std::cout << "Created test project structure at: " << testDir << "\n\n"; @@ -56,17 +56,17 @@ void demonstrateFileTreeIntegration() { std::cout << "Toggling file tree visibility...\n"; editor.toggleFileTreeVisibility(); std::cout << "File tree is visible: " << (editor.isFileTreeVisible() ? "Yes" : "No") << "\n"; - editor.toggleFileTreeVisibility(); // Toggle back + editor.toggleFileTreeVisibility(); // Toggle back std::cout << "Toggled back. File tree is visible: " << (editor.isFileTreeVisible() ? "Yes" : "No") << "\n\n"; // Demonstrate folding integration with file tree std::cout << "Testing folding integration...\n"; editor.setFoldingEnabled(true); - + // Open a C++ file and test folding std::string utilsCppPath = testDir + "/src/utils.cpp"; editor.openFileFromTree(utilsCppPath); - + auto foldingRanges = editor.getFoldingRanges(utilsCppPath); std::cout << "Folding ranges detected for " << utilsCppPath << ": " << foldingRanges.size() << " ranges\n"; @@ -88,4 +88,4 @@ int main() { std::cerr << "Error: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_keyboard_shortcuts.cpp b/demo_keyboard_shortcuts.cpp index 1f8458c5..370df20f 100644 --- a/demo_keyboard_shortcuts.cpp +++ b/demo_keyboard_shortcuts.cpp @@ -1,74 +1,72 @@ #include #include -#include "bolt/editor/keyboard_shortcuts.hpp" + #include "bolt/editor/integrated_editor.hpp" +#include "bolt/editor/keyboard_shortcuts.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateKeyParsing() { std::cout << "\n=== Key Combination Parsing ===" << std::endl; - + // Demonstrate various key combinations - std::vector testKeys = { - "Ctrl+S", "Ctrl+Shift+Z", "Alt+F4", "Ctrl+Alt+Delete", - "F1", "Escape", "Meta+A", "Ctrl+Shift+Alt+T" - }; - + std::vector testKeys = {"Ctrl+S", "Ctrl+Shift+Z", "Alt+F4", "Ctrl+Alt+Delete", + "F1", "Escape", "Meta+A", "Ctrl+Shift+Alt+T"}; + for (const auto& keyStr : testKeys) { auto combo = KeyCombination::fromString(keyStr); - std::cout << "Input: " << keyStr << " -> Parsed: " << combo.toString() + std::cout << "Input: " << keyStr << " -> Parsed: " << combo.toString() << " (Valid: " << (combo.isValid() ? "Yes" : "No") << ")" << std::endl; } } void demonstrateContextualShortcuts() { std::cout << "\n=== Contextual Shortcuts ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Register shortcuts in different contexts - shortcuts.registerShortcut("F1", "showHelp", []() { - std::cout << " -> Showing global help" << std::endl; - }, ShortcutContext::Global, "Show global help"); - - shortcuts.registerShortcut("F1", "showEditorHelp", []() { - std::cout << " -> Showing editor-specific help" << std::endl; - }, ShortcutContext::Editor, "Show editor help"); - - shortcuts.registerShortcut("F1", "showSearchHelp", []() { - std::cout << " -> Showing search help" << std::endl; - }, ShortcutContext::Search, "Show search help"); - + shortcuts.registerShortcut( + "F1", "showHelp", []() { std::cout << " -> Showing global help" << std::endl; }, ShortcutContext::Global, + "Show global help"); + + shortcuts.registerShortcut( + "F1", "showEditorHelp", []() { std::cout << " -> Showing editor-specific help" << std::endl; }, + ShortcutContext::Editor, "Show editor help"); + + shortcuts.registerShortcut( + "F1", "showSearchHelp", []() { std::cout << " -> Showing search help" << std::endl; }, ShortcutContext::Search, + "Show search help"); + // Demonstrate context switching std::cout << "Testing F1 in different contexts:" << std::endl; - + std::cout << "Global context: "; shortcuts.executeShortcut("F1", ShortcutContext::Global); - + std::cout << "Editor context: "; shortcuts.executeShortcut("F1", ShortcutContext::Editor); - + std::cout << "Search context: "; shortcuts.executeShortcut("F1", ShortcutContext::Search); } void demonstrateShortcutDiscovery() { std::cout << "\n=== Shortcut Discovery ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Initialize default shortcuts shortcuts.initDefaultShortcuts(); - + // Show all editor shortcuts auto editorShortcuts = shortcuts.getShortcutsForContext(ShortcutContext::Editor); std::cout << "Editor shortcuts (" << editorShortcuts.size() << " total):" << std::endl; - + size_t count = 0; for (const auto& info : editorShortcuts) { - if (count < 5) { // Show first 5 for brevity - std::cout << " " << info.keyCombination.toString() - << " -> " << info.command; + if (count < 5) { // Show first 5 for brevity + std::cout << " " << info.keyCombination.toString() << " -> " << info.command; if (!info.description.empty()) { std::cout << " (" << info.description << ")"; } @@ -79,27 +77,28 @@ void demonstrateShortcutDiscovery() { if (editorShortcuts.size() > 5) { std::cout << " ... and " << (editorShortcuts.size() - 5) << " more" << std::endl; } - + // Show shortcuts for a specific key auto ctrlShortcuts = shortcuts.findShortcutsByKey("Ctrl+S"); std::cout << "\nShortcuts using Ctrl+S:" << std::endl; for (const auto& info : ctrlShortcuts) { - std::cout << " Context: " << (info.context == ShortcutContext::Global ? "Global" : - info.context == ShortcutContext::Editor ? "Editor" : "Other") - << ", Command: " << info.command - << ", Description: " << info.description << std::endl; + std::cout << " Context: " + << (info.context == ShortcutContext::Global ? "Global" + : info.context == ShortcutContext::Editor ? "Editor" + : "Other") + << ", Command: " << info.command << ", Description: " << info.description << std::endl; } } void demonstrateHelpSystem() { std::cout << "\n=== Help System ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Get help for global context std::string globalHelp = shortcuts.getHelpText(ShortcutContext::Global); std::cout << "Sample of Global shortcuts help:" << std::endl; - + // Show first few lines of help std::istringstream iss(globalHelp); std::string line; @@ -113,74 +112,74 @@ void demonstrateHelpSystem() { void demonstrateIntegratedEditorShortcuts() { std::cout << "\n=== Integrated Editor Shortcuts ===" << std::endl; - + IntegratedEditor& editor = IntegratedEditor::getInstance(); - + // Initialize shortcuts through the editor editor.initializeKeyboardShortcuts(); - + std::cout << "Testing multi-cursor shortcuts through IntegratedEditor:" << std::endl; - + // Clear any existing cursors editor.clearExtraCursors(); editor.addCursorAtPosition(0, 0); std::cout << "Initial cursors: " << editor.getCursorCount() << std::endl; - + // Test Ctrl+D (add cursor at next occurrence) std::cout << "Executing Ctrl+D (add cursor at next occurrence)..." << std::endl; bool result = editor.handleKeyboardShortcut("Ctrl+D", "addCursorAtNextOccurrence"); - std::cout << " Result: " << (result ? "Success" : "Failed") - << ", Cursors: " << editor.getCursorCount() << std::endl; - + std::cout << " Result: " << (result ? "Success" : "Failed") << ", Cursors: " << editor.getCursorCount() + << std::endl; + // Test Ctrl+Alt+Down (add cursor below) std::cout << "Executing Ctrl+Alt+Down (add cursor below)..." << std::endl; result = editor.handleKeyboardShortcut("Ctrl+Alt+Down", "addCursorBelow"); - std::cout << " Result: " << (result ? "Success" : "Failed") - << ", Cursors: " << editor.getCursorCount() << std::endl; - + std::cout << " Result: " << (result ? "Success" : "Failed") << ", Cursors: " << editor.getCursorCount() + << std::endl; + // Test Escape (clear extra cursors) std::cout << "Executing Escape (clear extra cursors)..." << std::endl; result = editor.handleKeyboardShortcut("Escape", "clearExtraCursors"); - std::cout << " Result: " << (result ? "Success" : "Failed") - << ", Cursors: " << editor.getCursorCount() << std::endl; + std::cout << " Result: " << (result ? "Success" : "Failed") << ", Cursors: " << editor.getCursorCount() + << std::endl; } void demonstrateConflictPrevention() { std::cout << "\n=== Conflict Prevention ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Try to register a conflicting shortcut std::cout << "Attempting to register Ctrl+S for 'saveAs' in Global context..." << std::endl; - bool result1 = shortcuts.registerShortcut("Ctrl+S", "saveAs", []() { - std::cout << "Save As executed" << std::endl; - }, ShortcutContext::Global, "Save file as"); - + bool result1 = shortcuts.registerShortcut( + "Ctrl+S", "saveAs", []() { std::cout << "Save As executed" << std::endl; }, ShortcutContext::Global, + "Save file as"); + std::cout << " Registration result: " << (result1 ? "Success" : "Failed (conflict detected)") << std::endl; - + // Register same shortcut in different context std::cout << "Attempting to register Ctrl+S for 'saveAs' in Editor context..." << std::endl; - bool result2 = shortcuts.registerShortcut("Ctrl+S", "saveAs", []() { - std::cout << "Editor Save As executed" << std::endl; - }, ShortcutContext::Editor, "Save file as"); - + bool result2 = shortcuts.registerShortcut( + "Ctrl+S", "saveAs", []() { std::cout << "Editor Save As executed" << std::endl; }, ShortcutContext::Editor, + "Save file as"); + std::cout << " Registration result: " << (result2 ? "Success" : "Failed (conflict detected)") << std::endl; } void demonstrateEnableDisable() { std::cout << "\n=== Enable/Disable Shortcuts ===" << std::endl; - + KeyboardShortcuts& shortcuts = KeyboardShortcuts::getInstance(); - + // Register a test shortcut - shortcuts.registerShortcut("Ctrl+T", "testCommand", []() { - std::cout << " -> Test command executed" << std::endl; - }, ShortcutContext::Global, "Test command"); - + shortcuts.registerShortcut( + "Ctrl+T", "testCommand", []() { std::cout << " -> Test command executed" << std::endl; }, + ShortcutContext::Global, "Test command"); + std::cout << "Shortcuts enabled: " << (shortcuts.isEnabled() ? "Yes" : "No") << std::endl; std::cout << "Executing Ctrl+T: "; shortcuts.executeShortcut("Ctrl+T", ShortcutContext::Global); - + // Disable shortcuts shortcuts.setEnabled(false); std::cout << "Shortcuts enabled: " << (shortcuts.isEnabled() ? "Yes" : "No") << std::endl; @@ -189,7 +188,7 @@ void demonstrateEnableDisable() { if (!result) { std::cout << " -> Shortcut disabled, not executed" << std::endl; } - + // Re-enable shortcuts shortcuts.setEnabled(true); std::cout << "Shortcuts enabled: " << (shortcuts.isEnabled() ? "Yes" : "No") << std::endl; @@ -200,7 +199,7 @@ void demonstrateEnableDisable() { int main() { std::cout << "Bolt C++ Keyboard Shortcuts System Demo" << std::endl; std::cout << "========================================" << std::endl; - + try { demonstrateKeyParsing(); demonstrateContextualShortcuts(); @@ -209,7 +208,7 @@ int main() { demonstrateIntegratedEditorShortcuts(); demonstrateConflictPrevention(); demonstrateEnableDisable(); - + std::cout << "\n=== Keyboard Shortcuts System Demo Completed! ===" << std::endl; std::cout << "The enhanced keyboard shortcuts system provides:" << std::endl; std::cout << "โœ“ Robust key combination parsing" << std::endl; @@ -218,11 +217,10 @@ int main() { std::cout << "โœ“ Comprehensive help and discovery system" << std::endl; std::cout << "โœ“ Enable/disable functionality" << std::endl; std::cout << "โœ“ Integration with editor components" << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_logging.cpp b/demo_logging.cpp index da521c73..1d3f50b3 100644 --- a/demo_logging.cpp +++ b/demo_logging.cpp @@ -1,15 +1,16 @@ -#include "bolt/core/logging.hpp" -#include "bolt/core/error_handling.hpp" +#include #include #include -#include + +#include "bolt/core/error_handling.hpp" +#include "bolt/core/logging.hpp" void demonstrateBasicLogging() { std::cout << "\n=== Basic Logging Demo ===" << std::endl; - + // Configure console logging with detailed format bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + // Test different log levels BOLT_TRACE("This is a trace message"); BOLT_DEBUG("This is a debug message"); @@ -21,7 +22,7 @@ void demonstrateBasicLogging() { void demonstrateCategoryLogging() { std::cout << "\n=== Category-Based Logging Demo ===" << std::endl; - + // Test category-specific logging BOLT_LOG_CORE(bolt::LogLevel::INFO, "Core system initialization"); BOLT_LOG_MEMORY(bolt::LogLevel::DEBUG, "Memory allocation: 1024 bytes"); @@ -34,103 +35,104 @@ void demonstrateCategoryLogging() { void demonstrateFileLogging() { std::cout << "\n=== File Logging Demo ===" << std::endl; - + // Configure file logging std::string logFile = "/tmp/bolt_demo.log"; bolt::LogManager::configureFileLogging(logFile, bolt::LogLevel::TRACE, true); - + std::cout << "Logging to file: " << logFile << std::endl; - + BOLT_INFO("File logging is now active"); BOLT_DEBUG("This message includes file and line information"); BOLT_WARN("This is written to the log file"); - + // Demonstrate JSON logging auto logger = std::make_unique(bolt::LogLevel::DEBUG); logger->addSink(std::make_unique("/tmp/bolt_demo.json")); logger->setFormatter(std::make_unique()); - + logger->info("JSON formatted message"); logger->error("Error in JSON format", __FILE__, __LINE__, __func__); - + bolt::LogManager::setGlobalLogger(std::move(logger)); - + std::cout << "Check " << logFile << " and /tmp/bolt_demo.json for logged messages" << std::endl; } void demonstrateRotatingLogs() { std::cout << "\n=== Rotating File Logging Demo ===" << std::endl; - + // Configure rotating file logging (small files for demo) bolt::LogManager::configureRotatingFileLogging("/tmp/bolt_rotating.log", 100, 3); - + std::cout << "Generating messages to trigger log rotation..." << std::endl; - + for (int i = 0; i < 20; ++i) { - BOLT_INFO("Message number " + std::to_string(i) + " - this is a longer message to fill up the log file quickly"); + BOLT_INFO("Message number " + std::to_string(i) + + " - this is a longer message to fill up the log file quickly"); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } - + std::cout << "Check /tmp/bolt_rotating.log* files for rotation" << std::endl; } void demonstrateFiltering() { std::cout << "\n=== Log Filtering Demo ===" << std::endl; - + // Create a custom logger with filters - auto logger = std::make_unique(bolt::LogLevel::TRACE); // Allow all levels + auto logger = std::make_unique(bolt::LogLevel::TRACE); // Allow all levels logger->addSink(std::make_unique()); - + // Add category filter - auto categoryFilter = std::make_unique(bolt::LogLevel::INFO); // Default level - categoryFilter->setCategoryLevel(bolt::LogCategory::MEMORY, bolt::LogLevel::DEBUG); // Allow debug for memory - categoryFilter->setCategoryLevel(bolt::LogCategory::EDITOR, bolt::LogLevel::ERROR); // Only errors for editor - + auto categoryFilter = std::make_unique(bolt::LogLevel::INFO); // Default level + categoryFilter->setCategoryLevel(bolt::LogCategory::MEMORY, bolt::LogLevel::DEBUG); // Allow debug for memory + categoryFilter->setCategoryLevel(bolt::LogCategory::EDITOR, bolt::LogLevel::ERROR); // Only errors for editor + logger->addFilter(std::move(categoryFilter)); bolt::LogManager::setGlobalLogger(std::move(logger)); - + std::cout << "Demonstrating category-based filtering:" << std::endl; std::cout << "- MEMORY: DEBUG level and above" << std::endl; std::cout << "- EDITOR: ERROR level and above" << std::endl; std::cout << "- Others: INFO level and above" << std::endl; - + BOLT_LOG_MEMORY(bolt::LogLevel::DEBUG, "Memory debug message (should show)"); BOLT_LOG_MEMORY(bolt::LogLevel::TRACE, "Memory trace message (should NOT show)"); - + BOLT_LOG_EDITOR(bolt::LogLevel::INFO, "Editor info message (should NOT show)"); BOLT_LOG_EDITOR(bolt::LogLevel::ERROR, "Editor error message (should show)"); - + BOLT_LOG_CORE(bolt::LogLevel::INFO, "Core info message (should show)"); BOLT_LOG_CORE(bolt::LogLevel::DEBUG, "Core debug message (should NOT show)"); } void demonstratePerformanceMetrics() { std::cout << "\n=== Performance Metrics Demo ===" << std::endl; - - bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format + + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format bolt::Logger& logger = bolt::LogManager::getInstance(); - + logger.resetMetrics(); - + std::cout << "Generating 1000 log messages..." << std::endl; - + auto start = std::chrono::high_resolution_clock::now(); - + for (int i = 0; i < 1000; ++i) { if (i % 4 == 0) { - logger.debug("Debug message " + std::to_string(i)); // Will be filtered + logger.debug("Debug message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 1) { - logger.info("Info message " + std::to_string(i)); // Will be filtered + logger.info("Info message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 2) { - logger.warn("Warning message " + std::to_string(i)); // Will be logged + logger.warn("Warning message " + std::to_string(i)); // Will be logged } else { - logger.error("Error message " + std::to_string(i)); // Will be logged + logger.error("Error message " + std::to_string(i)); // Will be logged } } - + auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); - + std::cout << "Performance metrics:" << std::endl; std::cout << "- Total messages: " << logger.getTotalMessages() << std::endl; std::cout << "- Dropped messages: " << logger.getDroppedMessages() << std::endl; @@ -141,40 +143,41 @@ void demonstratePerformanceMetrics() { void demonstrateScopedLogging() { std::cout << "\n=== Scoped Logging Demo ===" << std::endl; - + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::TRACE, true); - + { BOLT_SCOPED_LOG_CORE(); - + BOLT_INFO("Inside scoped function"); - + // Simulate some work std::this_thread::sleep_for(std::chrono::milliseconds(100)); - + { BOLT_SCOPED_LOG(bolt::LogCategory::MEMORY); BOLT_DEBUG("Nested scope for memory operations"); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } - + BOLT_INFO("Continuing work in outer scope"); } - + BOLT_INFO("Outside of scoped function"); } void demonstrateThreadSafety() { std::cout << "\n=== Thread Safety Demo ===" << std::endl; - + bolt::LogManager::configureFileLogging("/tmp/bolt_threaded.log", bolt::LogLevel::INFO, true); - + const int numThreads = 4; const int messagesPerThread = 5; std::vector threads; - - std::cout << "Launching " << numThreads << " threads, each logging " << messagesPerThread << " messages..." << std::endl; - + + std::cout << "Launching " << numThreads << " threads, each logging " << messagesPerThread << " messages..." + << std::endl; + for (int t = 0; t < numThreads; ++t) { threads.emplace_back([t, messagesPerThread]() { for (int i = 0; i < messagesPerThread; ++i) { @@ -183,28 +186,26 @@ void demonstrateThreadSafety() { } }); } - + for (auto& thread : threads) { thread.join(); } - + std::cout << "All threads completed. Check /tmp/bolt_threaded.log for interleaved messages" << std::endl; } void demonstrateErrorIntegration() { std::cout << "\n=== Error Handling Integration Demo ===" << std::endl; - + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + try { BOLT_INFO("Attempting risky operation..."); - + // Simulate different types of errors BOLT_WARN("Warning: Operation may fail"); - - throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, - "Failed to allocate 1GB of memory"); - + + throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, "Failed to allocate 1GB of memory"); } catch (const bolt::MemoryException& e) { BOLT_ERROR("Memory exception caught: " + std::string(e.what())); BOLT_DEBUG("Error code: " + std::to_string(static_cast(e.getErrorCode()))); @@ -213,14 +214,14 @@ void demonstrateErrorIntegration() { } catch (const std::exception& e) { BOLT_FATAL("Unexpected exception: " + std::string(e.what())); } - + BOLT_INFO("Error handling demonstration completed"); } int main() { std::cout << "Bolt Comprehensive Logging System Demo" << std::endl; std::cout << "=======================================" << std::endl; - + try { demonstrateBasicLogging(); demonstrateCategoryLogging(); @@ -231,15 +232,14 @@ int main() { demonstrateScopedLogging(); demonstrateThreadSafety(); demonstrateErrorIntegration(); - + std::cout << "\n=== Demo Complete ===" << std::endl; std::cout << "All logging features demonstrated successfully!" << std::endl; std::cout << "Check the generated log files in /tmp/ for examples of different formats." << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_logging_simple.cpp b/demo_logging_simple.cpp index 056dba9a..77cca4c2 100644 --- a/demo_logging_simple.cpp +++ b/demo_logging_simple.cpp @@ -1,15 +1,16 @@ -#include "bolt/core/logging.hpp" -#include "bolt/core/error_handling.hpp" +#include #include #include -#include + +#include "bolt/core/error_handling.hpp" +#include "bolt/core/logging.hpp" void demonstrateBasicLogging() { std::cout << "\n=== Basic Logging Demo ===" << std::endl; - + // Configure console logging with detailed format bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + // Test different log levels BOLT_TRACE("This is a trace message"); BOLT_DEBUG("This is a debug message"); @@ -21,7 +22,7 @@ void demonstrateBasicLogging() { void demonstrateCategoryLogging() { std::cout << "\n=== Category-Based Logging Demo ===" << std::endl; - + // Test category-specific logging BOLT_LOG_CORE(bolt::LogLevel::INFO, "Core system initialization"); BOLT_LOG_MEMORY(bolt::LogLevel::DEBUG, "Memory allocation: 1024 bytes"); @@ -32,47 +33,47 @@ void demonstrateCategoryLogging() { void demonstrateFileLogging() { std::cout << "\n=== File Logging Demo ===" << std::endl; - + // Configure file logging std::string logFile = "/tmp/bolt_demo.log"; bolt::LogManager::configureFileLogging(logFile, bolt::LogLevel::TRACE, true); - + std::cout << "Logging to file: " << logFile << std::endl; - + BOLT_INFO("File logging is now active"); BOLT_DEBUG("This message includes file and line information"); BOLT_WARN("This is written to the log file"); - + std::cout << "Check " << logFile << " for logged messages" << std::endl; } void demonstratePerformanceMetrics() { std::cout << "\n=== Performance Metrics Demo ===" << std::endl; - - bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format + + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); // Simple format bolt::Logger& logger = bolt::LogManager::getInstance(); - + logger.resetMetrics(); - + std::cout << "Generating 1000 log messages..." << std::endl; - + auto start = std::chrono::high_resolution_clock::now(); - + for (int i = 0; i < 1000; ++i) { if (i % 4 == 0) { - logger.debug("Debug message " + std::to_string(i)); // Will be filtered + logger.debug("Debug message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 1) { - logger.info("Info message " + std::to_string(i)); // Will be filtered + logger.info("Info message " + std::to_string(i)); // Will be filtered } else if (i % 4 == 2) { - logger.warn("Warning message " + std::to_string(i)); // Will be logged + logger.warn("Warning message " + std::to_string(i)); // Will be logged } else { - logger.error("Error message " + std::to_string(i)); // Will be logged + logger.error("Error message " + std::to_string(i)); // Will be logged } } - + auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); - + std::cout << "Performance metrics:" << std::endl; std::cout << "- Total messages: " << logger.getTotalMessages() << std::endl; std::cout << "- Dropped messages: " << logger.getDroppedMessages() << std::endl; @@ -83,18 +84,16 @@ void demonstratePerformanceMetrics() { void demonstrateErrorIntegration() { std::cout << "\n=== Error Handling Integration Demo ===" << std::endl; - + bolt::LogManager::configureConsoleLogging(bolt::LogLevel::DEBUG, true); - + try { BOLT_INFO("Attempting risky operation..."); - + // Simulate different types of errors BOLT_WARN("Warning: Operation may fail"); - - throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, - "Failed to allocate 1GB of memory"); - + + throw bolt::MemoryException(bolt::ErrorCode::MEMORY_ALLOCATION_FAILED, "Failed to allocate 1GB of memory"); } catch (const bolt::MemoryException& e) { BOLT_ERROR("Memory exception caught: " + std::string(e.what())); BOLT_DEBUG("Error code: " + std::to_string(static_cast(e.getErrorCode()))); @@ -103,29 +102,28 @@ void demonstrateErrorIntegration() { } catch (const std::exception& e) { BOLT_FATAL("Unexpected exception: " + std::string(e.what())); } - + BOLT_INFO("Error handling demonstration completed"); } int main() { std::cout << "Bolt Comprehensive Logging System Demo" << std::endl; std::cout << "=======================================" << std::endl; - + try { demonstrateBasicLogging(); demonstrateCategoryLogging(); demonstrateFileLogging(); demonstratePerformanceMetrics(); demonstrateErrorIntegration(); - + std::cout << "\n=== Demo Complete ===" << std::endl; std::cout << "All logging features demonstrated successfully!" << std::endl; std::cout << "Check the generated log files in /tmp/ for examples of different formats." << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_lsp_ui_integration.cpp b/demo_lsp_ui_integration.cpp index 520e9be2..3b3637cb 100644 --- a/demo_lsp_ui_integration.cpp +++ b/demo_lsp_ui_integration.cpp @@ -1,7 +1,7 @@ /** * @file demo_lsp_ui_integration.cpp * @brief Demo application showcasing LSP UI integration with ImGui - * + * * This demo demonstrates: * - Code completion popup * - Hover tooltips @@ -9,22 +9,22 @@ * - Status bar with LSP status */ -#include +#include #include +#include #include -#include #include "bolt/editor/lsp_editor_bridge.hpp" #include "bolt/gui/lsp_ui_components.hpp" #ifdef BOLT_HAVE_IMGUI +#include #include #include #include -#include #endif -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void printHeader() { std::cout << "โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—\n"; @@ -36,112 +36,111 @@ void printHeader() { #ifdef BOLT_HAVE_IMGUI class LspUiDemo { -public: - LspUiDemo() - : lspBridge_(std::make_unique()) - , completionPopup_(std::make_unique()) - , hoverTooltip_(std::make_unique()) - , diagnosticsGutter_(std::make_unique()) - , inlineDiagnostics_(std::make_unique()) - , statusBar_(std::make_unique()) { - } - + public: + LspUiDemo() + : lspBridge_(std::make_unique()), + completionPopup_(std::make_unique()), + hoverTooltip_(std::make_unique()), + diagnosticsGutter_(std::make_unique()), + inlineDiagnostics_(std::make_unique()), + statusBar_(std::make_unique()) {} + bool initialize() { // Initialize GLFW if (!glfwInit()) { std::cerr << "Failed to initialize GLFW\n"; return false; } - + // Create window glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - + window_ = glfwCreateWindow(1280, 720, "LSP UI Integration Demo", nullptr, nullptr); if (!window_) { std::cerr << "Failed to create window\n"; glfwTerminate(); return false; } - + glfwMakeContextCurrent(window_); glfwSwapInterval(1); - + // Initialize ImGui IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; - + ImGui::StyleColorsDark(); - + ImGui_ImplGlfw_InitForOpenGL(window_, true); ImGui_ImplOpenGL3_Init("#version 330"); - + // Initialize LSP bridge std::cout << "\n--- Initializing LSP Bridge ---\n"; if (!lspBridge_->initialize()) { std::cout << "Warning: No language servers available\n"; } - + // Set up completion callback completionPopup_->setAcceptCallback([this](const std::string& text) { std::cout << "Completion accepted: " << text << "\n"; insertTextAtCursor(text); }); - + // Create test file createTestFile(); - + return true; } - + void run() { while (!glfwWindowShouldClose(window_)) { glfwPollEvents(); - + ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); - + // Update LSP bridge lspBridge_->update(); - + // Render UI renderMainWindow(); renderEditor(); renderStatusBar(); - + // Render LSP UI components renderLspComponents(); - + ImGui::Render(); - + int display_w, display_h; glfwGetFramebufferSize(window_, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glClearColor(0.1f, 0.1f, 0.12f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); - + ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); - + glfwSwapBuffers(window_); } } - + void shutdown() { lspBridge_->shutdown(); - + ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); - + glfwDestroyWindow(window_); glfwTerminate(); } - -private: + + private: void createTestFile() { testFilePath_ = "/tmp/lsp_ui_demo_test.cpp"; testContent_ = R"(#include @@ -174,209 +173,209 @@ int main() { return 0; } )"; - + std::ofstream file(testFilePath_); file << testContent_; file.close(); - + // Open document in LSP lspBridge_->documentOpened(testFilePath_, testContent_, "cpp"); - + std::cout << "Created test file: " << testFilePath_ << "\n"; } - + void renderMainWindow() { ImGui::SetNextWindowPos(ImVec2(10, 10), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(300, 200), ImGuiCond_FirstUseEver); - + ImGui::Begin("LSP UI Demo Controls"); - + ImGui::Text("LSP UI Integration Demo"); ImGui::Separator(); - + if (ImGui::Button("Request Completion")) { requestCompletion(); } - + if (ImGui::Button("Request Hover")) { requestHover(); } - + ImGui::Separator(); - + ImGui::Text("Cursor Position:"); ImGui::Text(" Line: %zu, Column: %zu", cursorLine_, cursorColumn_); - + ImGui::Separator(); - + auto& completionState = lspBridge_->getCompletionState(); ImGui::Text("Completion: %s", completionState.isVisible ? "Visible" : "Hidden"); ImGui::Text(" Items: %zu", completionState.items.size()); - + auto& hoverState = lspBridge_->getHoverState(); ImGui::Text("Hover: %s", hoverState.isVisible ? "Visible" : "Hidden"); - + ImGui::End(); } - + void renderEditor() { ImGui::SetNextWindowPos(ImVec2(320, 10), ImGuiCond_FirstUseEver); ImGui::SetNextWindowSize(ImVec2(700, 500), ImGuiCond_FirstUseEver); - + ImGui::Begin("Code Editor"); - + // Store editor position for LSP UI positioning editorPos_ = ImGui::GetCursorScreenPos(); - + // Simple text editor - ImGui::InputTextMultiline("##editor", &testContent_[0], testContent_.capacity() + 1, - ImVec2(-1, -1), ImGuiInputTextFlags_AllowTabInput); - + ImGui::InputTextMultiline("##editor", &testContent_[0], testContent_.capacity() + 1, ImVec2(-1, -1), + ImGuiInputTextFlags_AllowTabInput); + // Track cursor position (simplified) if (ImGui::IsItemActive()) { // In a real implementation, we'd track the actual cursor position // For demo, we'll use a fixed position } - + ImGui::End(); } - + void renderStatusBar() { ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(ImVec2(viewport->Pos.x, viewport->Pos.y + viewport->Size.y - 25)); ImGui::SetNextWindowSize(ImVec2(viewport->Size.x, 25)); - - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar; - + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoScrollbar; + ImGui::Begin("##StatusBar", nullptr, flags); - + ImGui::Text("LSP UI Demo"); ImGui::SameLine(200); - + // Render LSP status statusBar_->render(*lspBridge_, testFilePath_); - + ImGui::End(); } - + void renderLspComponents() { // Render completion popup auto& completionState = lspBridge_->getCompletionState(); if (completionState.isVisible) { float cursorX = editorPos_.x + cursorColumn_ * 8.0f; // Approximate char width - float cursorY = editorPos_.y + cursorLine_ * 16.0f; // Approximate line height + float cursorY = editorPos_.y + cursorLine_ * 16.0f; // Approximate line height completionPopup_->render(completionState, cursorX, cursorY, 16.0f); completionPopup_->handleInput(completionState); } - + // Render hover tooltip auto& hoverState = lspBridge_->getHoverState(); if (hoverState.isVisible) { ImVec2 mousePos = ImGui::GetMousePos(); hoverTooltip_->render(hoverState, mousePos.x, mousePos.y); } - + // Render diagnostics (would be integrated into editor in real implementation) auto diagnostics = lspBridge_->getDiagnostics(testFilePath_); if (!diagnostics.empty()) { // In a real implementation, these would be rendered in the editor gutter } } - + void requestCompletion() { std::cout << "Requesting completion at line " << cursorLine_ << ", column " << cursorColumn_ << "\n"; lspBridge_->requestCompletion(testFilePath_, cursorLine_, cursorColumn_); - + // Wait a bit for response std::this_thread::sleep_for(std::chrono::milliseconds(500)); } - + void requestHover() { std::cout << "Requesting hover at line " << cursorLine_ << ", column " << cursorColumn_ << "\n"; lspBridge_->requestHover(testFilePath_, cursorLine_, cursorColumn_); - + // Wait a bit for response std::this_thread::sleep_for(std::chrono::milliseconds(500)); } - + void insertTextAtCursor(const std::string& text) { // In a real implementation, this would insert text at the cursor position std::cout << "Would insert: " << text << "\n"; } - + GLFWwindow* window_ = nullptr; - + std::unique_ptr lspBridge_; std::unique_ptr completionPopup_; std::unique_ptr hoverTooltip_; std::unique_ptr diagnosticsGutter_; std::unique_ptr inlineDiagnostics_; std::unique_ptr statusBar_; - + std::string testFilePath_; std::string testContent_; - + size_t cursorLine_ = 7; // Position at "std::cout" line size_t cursorColumn_ = 12; - + ImVec2 editorPos_; }; int main() { printHeader(); - + LspUiDemo demo; - + if (!demo.initialize()) { std::cerr << "Failed to initialize demo\n"; return 1; } - + std::cout << "\n--- Running LSP UI Demo ---\n"; std::cout << "Press 'Request Completion' to test code completion\n"; std::cout << "Press 'Request Hover' to test hover information\n"; std::cout << "Close the window to exit\n\n"; - + demo.run(); demo.shutdown(); - + std::cout << "\n--- Demo Complete ---\n"; return 0; } -#else // BOLT_HAVE_IMGUI +#else // BOLT_HAVE_IMGUI int main() { printHeader(); - + std::cout << "\nโŒ ImGui not available - cannot run UI demo\n"; std::cout << " Please build with ImGui support to test UI components\n"; - + // Test LSP bridge without UI std::cout << "\n--- Testing LSP Bridge (non-UI) ---\n"; - + lsp::LspEditorBridge bridge; if (bridge.initialize()) { std::cout << "โœ… LSP Bridge initialized\n"; - + // Test language detection std::cout << "\nLanguage Detection:\n"; std::cout << " test.cpp -> " << lsp::LspEditorBridge::detectLanguageId("test.cpp") << "\n"; std::cout << " test.py -> " << lsp::LspEditorBridge::detectLanguageId("test.py") << "\n"; std::cout << " test.rs -> " << lsp::LspEditorBridge::detectLanguageId("test.rs") << "\n"; - + // Test language support std::cout << "\nLanguage Support:\n"; std::cout << " cpp: " << (bridge.isLanguageSupported("cpp") ? "โœ…" : "โŒ") << "\n"; std::cout << " python: " << (bridge.isLanguageSupported("python") ? "โœ…" : "โŒ") << "\n"; - + bridge.shutdown(); } else { std::cout << "โŒ Failed to initialize LSP Bridge\n"; } - + return 0; } -#endif // BOLT_HAVE_IMGUI +#endif // BOLT_HAVE_IMGUI diff --git a/demo_minimap.cpp b/demo_minimap.cpp index 410a2c58..dfd92e0d 100644 --- a/demo_minimap.cpp +++ b/demo_minimap.cpp @@ -1,37 +1,38 @@ -#include #include +#include +#include #include #include -#include + #include "bolt/editor/minimap.hpp" #include "bolt/editor/minimap_ui.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void createLargeTestFile() { std::ofstream file("/tmp/large_file.cpp"); - + file << "// Large C++ File for Minimap Demo\n"; file << "// This file demonstrates minimap functionality with a larger codebase\n\n"; - + file << "#include \n"; file << "#include \n"; file << "#include \n"; file << "#include \n"; file << "#include \n\n"; - + file << "namespace demo {\n\n"; - + // Add a large class with many methods file << "class LargeClass {\n"; file << "private:\n"; file << " std::vector data_;\n"; file << " int counter_;\n"; file << " bool enabled_;\n\n"; - + file << "public:\n"; file << " LargeClass() : counter_(0), enabled_(true) {}\n\n"; - + // Add many methods to create a long file for (int i = 1; i <= 50; ++i) { file << " void method" << i << "() {\n"; @@ -42,19 +43,19 @@ void createLargeTestFile() { file << " }\n"; file << " }\n\n"; } - + file << " void processData() {\n"; file << " std::cout << \"Processing \" << data_.size() << \" items\" << std::endl;\n"; file << " for (const auto& item : data_) {\n"; file << " std::cout << \" \" << item << std::endl;\n"; file << " }\n"; file << " }\n\n"; - + file << " int getCounter() const { return counter_; }\n"; file << " void setEnabled(bool enabled) { enabled_ = enabled; }\n"; file << " bool isEnabled() const { return enabled_; }\n"; file << "};\n\n"; - + // Add some free functions for (int i = 1; i <= 20; ++i) { file << "void freeFunction" << i << "() {\n"; @@ -63,9 +64,9 @@ void createLargeTestFile() { file << " obj.method" << (i % 50 + 1) << "();\n"; file << "}\n\n"; } - + file << "} // namespace demo\n\n"; - + file << "int main() {\n"; file << " std::cout << \"Minimap Demo Application\" << std::endl;\n"; file << " \n"; @@ -82,7 +83,7 @@ void createLargeTestFile() { file << " \n"; file << " return 0;\n"; file << "}\n"; - + file.close(); } @@ -90,11 +91,11 @@ std::vector readFileLines(const std::string& filePath) { std::vector lines; std::ifstream file(filePath); std::string line; - + while (std::getline(file, line)) { lines.push_back(line); } - + return lines; } @@ -106,31 +107,31 @@ void printSeparator(const std::string& title) { void demonstrateBasicMinimap() { printSeparator("Basic Minimap Demo"); - + // Create a minimap with custom configuration Minimap::MinimapConfig config; config.width = 60; config.height = 20; - + Minimap minimap(config); - + // Load the test file auto lines = readFileLines("/tmp/large_file.cpp"); minimap.setDocument("/tmp/large_file.cpp", lines); - + std::cout << "Document loaded: " << minimap.getDocumentPath() << std::endl; std::cout << "Total lines: " << minimap.getTotalLines() << std::endl; std::cout << "Visible lines in minimap: " << minimap.getVisibleLines() << std::endl; - + // Set initial viewport Minimap::ViewportInfo viewport; viewport.startLine = 0; viewport.endLine = 25; viewport.currentLine = 10; viewport.totalLines = lines.size(); - + minimap.updateViewport(viewport); - + std::cout << "\nMinimap rendering:" << std::endl; auto rendered = minimap.render(); for (size_t i = 0; i < rendered.size(); ++i) { @@ -140,47 +141,46 @@ void demonstrateBasicMinimap() { void demonstrateMinimapUI() { printSeparator("Minimap UI Demo"); - + Minimap::MinimapConfig minimapConfig; minimapConfig.width = 50; minimapConfig.height = 15; - + Minimap minimap(minimapConfig); auto lines = readFileLines("/tmp/large_file.cpp"); minimap.setDocument("/tmp/large_file.cpp", lines); - + // Configure UI MinimapUI::UIConfig uiConfig; uiConfig.showBorder = true; uiConfig.showTitle = true; uiConfig.showScrollIndicator = true; uiConfig.title = "File Minimap"; - + MinimapUI ui(minimap, uiConfig); - + // Set position MinimapUI::Position position{0, 0, 54, 18}; ui.setPosition(position); - + // Set up navigation callback - ui.setNavigationCallback([](size_t line) { - std::cout << "Navigation callback: jumped to line " << line << std::endl; - }); - + ui.setNavigationCallback( + [](size_t line) { std::cout << "Navigation callback: jumped to line " << line << std::endl; }); + // Set viewport around middle of file Minimap::ViewportInfo viewport; viewport.startLine = lines.size() / 2 - 10; viewport.endLine = lines.size() / 2 + 10; viewport.currentLine = lines.size() / 2; viewport.totalLines = lines.size(); - + minimap.updateViewport(viewport); - + std::cout << "UI Requirements:" << std::endl; std::cout << " Width: " << ui.getRequiredWidth() << std::endl; std::cout << " Height: " << ui.getRequiredHeight() << std::endl; std::cout << " Fits in area (60x20): " << (ui.fitsInArea(60, 20) ? "Yes" : "No") << std::endl; - + std::cout << "\nMinimap UI rendering:" << std::endl; auto rendered = ui.render(); for (const auto& line : rendered) { @@ -190,42 +190,42 @@ void demonstrateMinimapUI() { void demonstrateNavigation() { printSeparator("Navigation Demo"); - + Minimap minimap; auto lines = readFileLines("/tmp/large_file.cpp"); minimap.setDocument("/tmp/large_file.cpp", lines); - + MinimapUI ui(minimap); - + std::cout << "Testing navigation functionality..." << std::endl; - + // Test clicking at different positions std::vector> testPositions = { - {10, 5}, // Near top - {10, 20}, // Near bottom - {10, 10} // Middle + {10, 5}, // Near top + {10, 20}, // Near bottom + {10, 10} // Middle }; - + for (const auto& pos : testPositions) { std::cout << "\nClicking at position (" << pos.first << ", " << pos.second << "):" << std::endl; size_t targetLine = minimap.getLineFromPosition(pos.first, pos.second); std::cout << " Would navigate to line: " << targetLine << std::endl; - + auto [x, y] = minimap.getPositionFromLine(targetLine); std::cout << " Line " << targetLine << " maps to position (" << x << ", " << y << ")" << std::endl; } - + // Test scrolling std::cout << "\nTesting scroll operations:" << std::endl; - + std::cout << "Scroll to top:" << std::endl; minimap.scrollToLine(0); std::cout << " Scroll percentage: " << (minimap.getScrollPercentage() * 100) << "%" << std::endl; - + std::cout << "Scroll to middle:" << std::endl; minimap.scrollToLine(lines.size() / 2); std::cout << " Scroll percentage: " << (minimap.getScrollPercentage() * 100) << "%" << std::endl; - + std::cout << "Scroll to bottom:" << std::endl; minimap.scrollToLine(lines.size() - 1); std::cout << " Scroll percentage: " << (minimap.getScrollPercentage() * 100) << "%" << std::endl; @@ -234,20 +234,20 @@ void demonstrateNavigation() { int main() { std::cout << "Bolt C++ Minimap Demo" << std::endl; std::cout << "=====================" << std::endl; - + // Create test file std::cout << "Creating large test file..." << std::endl; createLargeTestFile(); - + auto lines = readFileLines("/tmp/large_file.cpp"); std::cout << "Created file with " << lines.size() << " lines" << std::endl; - + try { // Run demonstrations demonstrateBasicMinimap(); demonstrateMinimapUI(); demonstrateNavigation(); - + printSeparator("Demo Complete"); std::cout << "Minimap implementation successfully demonstrated!" << std::endl; std::cout << "Features implemented:" << std::endl; @@ -257,11 +257,10 @@ int main() { std::cout << " โœ“ Configurable appearance" << std::endl; std::cout << " โœ“ UI integration with borders and titles" << std::endl; std::cout << " โœ“ Scroll position tracking" << std::endl; - } catch (const std::exception& e) { std::cerr << "Error during demo: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_narrative_rag_kobold.cpp b/demo_narrative_rag_kobold.cpp index 684f8d67..ec2a2b7a 100644 --- a/demo_narrative_rag_kobold.cpp +++ b/demo_narrative_rag_kobold.cpp @@ -1,7 +1,8 @@ +#include +#include + #include "bolt/ai/narrative_rag_manager.hpp" #include "bolt/ai/narrative_tool_manager.hpp" -#include -#include void printSeparator() { std::cout << "\n" << std::string(80, '=') << "\n\n"; @@ -11,17 +12,17 @@ int main() { std::cout << "=== Narrative RAG & TOOL-USE Demo with Kobold.cpp ===\n"; std::cout << "Interactive Story Generation with Living World Memory\n"; printSeparator(); - + // 1. Initialize the Narrative RAG Manager std::cout << "Initializing Narrative RAG Manager...\n"; bolt::ai::NarrativeRAGManager rag_manager; - + if (!rag_manager.initialize()) { std::cerr << "โŒ Failed to initialize Narrative RAG Manager\n"; return 1; } std::cout << "โœ… Narrative RAG Manager initialized\n\n"; - + // 2. Initialize the Narrative Tool Manager std::cout << "Initializing Narrative Tool Manager...\n"; bolt::ai::NarrativeToolManager tool_manager; @@ -29,7 +30,7 @@ int main() { tool_manager.loadAllStandardTools(); std::cout << "โœ… Loaded " << tool_manager.getAvailableTools().size() << " narrative tools\n"; printSeparator(); - + // 3. Create a character bolt::ai::CharacterSheet hero; hero.name = "Aldric the Brave"; @@ -40,7 +41,7 @@ int main() { hero.attributes["strength"] = 8; hero.attributes["intelligence"] = 6; hero.attributes["charisma"] = 5; - + tool_manager.registerCharacter(hero); std::cout << "Character Created: " << hero.name << "\n"; std::cout << "Skills: "; @@ -49,14 +50,15 @@ int main() { } std::cout << "\n"; printSeparator(); - + // 4. Log some initial narrative events std::cout << "Building the story world...\n\n"; - + bolt::ai::NarrativeEvent event1; event1.id = "event_001"; - event1.description = "Aldric arrived at the ancient castle, its towers shrouded in mist. " - "The locals warned him of a curse that befell anyone who entered."; + event1.description = + "Aldric arrived at the ancient castle, its towers shrouded in mist. " + "The locals warned him of a curse that befell anyone who entered."; event1.characters = {"Aldric the Brave"}; event1.locations = {"Ancient Castle"}; event1.timestamp = std::chrono::system_clock::now(); @@ -65,11 +67,12 @@ int main() { event1.tags = {"castle", "curse", "warning"}; rag_manager.logEvent(event1); std::cout << "๐Ÿ“ Event logged: " << event1.description << "\n\n"; - + bolt::ai::NarrativeEvent event2; event2.id = "event_002"; - event2.description = "In the village tavern, an old woman told Aldric that the castle's " - "treasure is guarded by a spectral knight who appears at midnight."; + event2.description = + "In the village tavern, an old woman told Aldric that the castle's " + "treasure is guarded by a spectral knight who appears at midnight."; event2.characters = {"Aldric the Brave", "Old Woman"}; event2.locations = {"Village Tavern"}; event2.timestamp = std::chrono::system_clock::now(); @@ -78,11 +81,12 @@ int main() { event2.tags = {"treasure", "spectral knight", "midnight"}; rag_manager.logEvent(event2); std::cout << "๐Ÿ“ Event logged: " << event2.description << "\n\n"; - + bolt::ai::NarrativeEvent event3; event3.id = "event_003"; - event3.description = "Aldric discovered a hidden passage behind the castle's main hall. " - "Strange symbols were carved into the stone walls."; + event3.description = + "Aldric discovered a hidden passage behind the castle's main hall. " + "Strange symbols were carved into the stone walls."; event3.characters = {"Aldric the Brave"}; event3.locations = {"Ancient Castle", "Hidden Passage"}; event3.timestamp = std::chrono::system_clock::now(); @@ -92,36 +96,34 @@ int main() { rag_manager.logEvent(event3); std::cout << "๐Ÿ“ Event logged: " << event3.description << "\n"; printSeparator(); - + // 5. Demonstrate Narrative RAG: Query the living world std::cout << "=== Narrative RAG: Querying Character Memory ===\n\n"; - + std::string query1 = "What do I know about the castle's dangers?"; std::cout << "Query: \"" << query1 << "\"\n\n"; auto relevant_events1 = rag_manager.queryNarrativeMemory(query1, {"Aldric the Brave"}); - + std::cout << "Retrieved " << relevant_events1.size() << " relevant memories:\n"; for (size_t i = 0; i < relevant_events1.size(); ++i) { std::cout << (i + 1) << ". " << relevant_events1[i].description << "\n"; - std::cout << " [Type: " << relevant_events1[i].event_type + std::cout << " [Type: " << relevant_events1[i].event_type << ", Importance: " << relevant_events1[i].importance << "]\n\n"; } - + // Generate memory injection for kobold.cpp - std::string memory_injection = rag_manager.generateMemoryInjection( - "Aldric stands before a locked door in the castle", - {"Aldric the Brave"} - ); - + std::string memory_injection = + rag_manager.generateMemoryInjection("Aldric stands before a locked door in the castle", {"Aldric the Brave"}); + std::cout << "Memory Injection for Kobold.cpp:\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; std::cout << memory_injection << "\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; printSeparator(); - + // 6. Demonstrate Narrative TOOL-USE: Character takes action std::cout << "=== Narrative TOOL-USE: Character Agency ===\n\n"; - + std::cout << "Scenario: Aldric encounters a locked door\n"; std::cout << "Available tools for " << hero.name << ":\n"; auto available_tools = tool_manager.getToolsForCharacter(hero.name); @@ -129,21 +131,21 @@ int main() { std::cout << " โ€ข " << tool << "\n"; } std::cout << "\n"; - + // AI decides to use the pick_lock tool std::cout << "AI Decision: Use 'pick_lock' ability\n\n"; - + std::unordered_map params; params["target"] = "ancient_door"; params["difficulty"] = "15"; - + auto result = tool_manager.invokeTool("pick_lock", hero.name, params); - + std::cout << "Tool Invocation Result:\n"; std::cout << " Success: " << (result.success ? "Yes" : "No") << "\n"; std::cout << " Description: " << result.description << "\n"; std::cout << " Impact Score: " << result.impact_score << "/10\n"; - + if (!result.state_changes.empty()) { std::cout << " State Changes:\n"; for (const auto& change : result.state_changes) { @@ -151,7 +153,7 @@ int main() { } } std::cout << "\n"; - + // Log the tool use as a narrative event bolt::ai::NarrativeEvent tool_event; tool_event.id = "event_004"; @@ -163,26 +165,25 @@ int main() { tool_event.importance = result.impact_score; tool_event.tags = {"lockpicking", "door", "skill_check"}; rag_manager.logEvent(tool_event); - + std::cout << "โœ… Tool use logged as narrative event\n"; printSeparator(); - + // 7. Show the complete event history std::cout << "=== Complete Narrative History ===\n\n"; auto history = rag_manager.getEventHistory(); std::cout << "Total events: " << history.size() << "\n\n"; - + for (size_t i = 0; i < history.size(); ++i) { - std::cout << (i + 1) << ". [" << history[i].event_type << "] " - << history[i].description << "\n"; + std::cout << (i + 1) << ". [" << history[i].event_type << "] " << history[i].description << "\n"; } - + printSeparator(); std::cout << "=== Demo Complete ===\n"; std::cout << "\nThis demonstrates how Kobold.cpp can be enhanced with:\n"; std::cout << " โ€ข Dynamic, queryable world memory (Narrative RAG)\n"; std::cout << " โ€ข Character agency through tool use (Narrative TOOL-USE)\n"; std::cout << " โ€ข Seamless integration of AI decisions and game mechanics\n\n"; - + return 0; } diff --git a/demo_network_optimizations.cpp b/demo_network_optimizations.cpp index 752c990e..eb1def36 100644 --- a/demo_network_optimizations.cpp +++ b/demo_network_optimizations.cpp @@ -1,9 +1,9 @@ -#include +#include #include +#include +#include #include -#include #include -#include // Include network optimization headers #include "bolt/network/connection_pool.hpp" @@ -11,21 +11,21 @@ #include "bolt/network/network_buffer.hpp" #include "bolt/network/network_metrics.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void demonstrateConnectionPool() { std::cout << "\n=== Connection Pool Demo ===\n"; - + auto& pool = ConnectionPool::getInstance(); pool.setMaxConnectionsPerHost(3); pool.setConnectionTimeout(std::chrono::seconds(5)); - + std::cout << "Creating connections to localhost:8080...\n"; - + // Note: These would normally connect to a real server // For demo purposes, we'll show the pool management std::vector> connections; - + for (int i = 0; i < 5; i++) { auto conn = pool.getConnection("127.0.0.1", 8080); if (conn) { @@ -33,12 +33,12 @@ void demonstrateConnectionPool() { connections.push_back(conn); } } - + // Release connections back to pool for (auto& conn : connections) { pool.releaseConnection(conn); } - + // Show statistics const auto& stats = pool.getStats(); std::cout << "Pool Statistics:\n"; @@ -50,82 +50,81 @@ void demonstrateConnectionPool() { void demonstrateMessageCompression() { std::cout << "\n=== Message Compression Demo ===\n"; - + MessageCompressor compressor(CompressionType::GZIP, 6); - + // Create a repetitive message that compresses well std::string original = "This is a test message that will be repeated many times. "; for (int i = 0; i < 50; i++) { original += "This is a test message that will be repeated many times. "; } - + std::cout << "Original message size: " << original.size() << " bytes\n"; - + // Compress the message auto compressed = compressor.compress(original); std::cout << "Compressed size: " << compressed.size() << " bytes\n"; - + double compressionRatio = static_cast(compressed.size()) / original.size(); - std::cout << "Compression ratio: " << std::fixed << std::setprecision(2) - << compressionRatio * 100 << "%\n"; - + std::cout << "Compression ratio: " << std::fixed << std::setprecision(2) << compressionRatio * 100 << "%\n"; + // Decompress and verify auto decompressed = compressor.decompress(compressed); bool isEqual = (decompressed == original); std::cout << "Decompression successful: " << (isEqual ? "Yes" : "No") << "\n"; - + // Show compression statistics auto stats = compressor.getStats(); std::cout << "Compression Statistics:\n"; std::cout << " Compression calls: " << stats.compressionCalls << "\n"; std::cout << " Decompression calls: " << stats.decompressionCalls << "\n"; - std::cout << " Average compression ratio: " << std::fixed << std::setprecision(2) + std::cout << " Average compression ratio: " << std::fixed << std::setprecision(2) << stats.averageCompressionRatio() * 100 << "%\n"; } void demonstrateNetworkBuffers() { std::cout << "\n=== Network Buffer Demo ===\n"; - + // Regular NetworkBuffer NetworkBuffer buffer(1024); - + std::string data1 = "Hello, "; std::string data2 = "World!"; - + buffer.append(data1); buffer.append(data2); - + std::cout << "Buffer size after appends: " << buffer.size() << "\n"; std::cout << "Buffer capacity: " << buffer.capacity() << "\n"; - + auto consumed = buffer.consumeString(5); std::cout << "Consumed: '" << consumed << "'\n"; - + buffer.compact(); std::cout << "Buffer size after compact: " << buffer.size() << "\n"; - + // Ring Buffer Demo std::cout << "\nRing Buffer Demo:\n"; RingBuffer ringBuf(20); - + std::string testData = "ABCDEFGHIJ"; size_t written = ringBuf.write(testData.data(), testData.size()); std::cout << "Written to ring buffer: " << written << " bytes\n"; std::cout << "Available to read: " << ringBuf.readAvailable() << " bytes\n"; - + char readBuffer[15]; size_t read = ringBuf.read(readBuffer, 5); readBuffer[read] = '\0'; std::cout << "Read from ring buffer: '" << readBuffer << "'\n"; - + // Buffer Pool Demo std::cout << "\nBuffer Pool Demo:\n"; auto& pool = NetworkBufferPool::getInstance(); - + auto pooledBuffer = pool.getBuffer(2048); std::cout << "Got buffer from pool, capacity: " << pooledBuffer->capacity() << "\n"; std::cout << "Active buffers: " << pool.getActiveBuffers() << "\n"; - + pool.returnBuffer(std::move(pooledBuffer)); std::cout << "Returned buffer to pool\n"; std::cout << "Pool size: " << pool.getPoolSize() << "\n"; @@ -133,47 +132,47 @@ void demonstrateNetworkBuffers() { void demonstrateNetworkMetrics() { std::cout << "\n=== Network Metrics Demo ===\n"; - + auto& metrics = NetworkMetrics::getInstance(); metrics.resetAllStats(); - + // Register some endpoints std::string endpoint1 = "websocket-server"; std::string endpoint2 = "http-api"; - + metrics.registerEndpoint(endpoint1); metrics.registerEndpoint(endpoint2); - + // Simulate some network activity std::cout << "Simulating network activity...\n"; - + // WebSocket activity metrics.recordConnection(endpoint1, true); metrics.recordDataSent(endpoint1, 1024); metrics.recordDataReceived(endpoint1, 512); - metrics.recordLatency(endpoint1, 1500); // 1.5ms + metrics.recordLatency(endpoint1, 1500); // 1.5ms metrics.recordWebSocketFrame(endpoint1, true, false); - + // HTTP API activity metrics.recordConnection(endpoint2, true); metrics.recordDataSent(endpoint2, 2048); metrics.recordDataReceived(endpoint2, 4096); - metrics.recordLatency(endpoint2, 2500); // 2.5ms + metrics.recordLatency(endpoint2, 2500); // 2.5ms metrics.recordHttpRequest(endpoint2, 200); - + // Some errors metrics.recordError(endpoint1, "timeout"); metrics.recordError(endpoint2, "protocol"); - + // Show global statistics auto globalStats = metrics.getGlobalStats(); std::cout << "\nGlobal Statistics:\n"; std::cout << " Connections opened: " << globalStats.connectionsOpened << "\n"; std::cout << " Bytes sent: " << globalStats.bytesSent << "\n"; std::cout << " Bytes received: " << globalStats.bytesReceived << "\n"; - std::cout << " Average latency: " << std::fixed << std::setprecision(2) - << globalStats.getAverageLatency() << " ฮผs\n"; - + std::cout << " Average latency: " << std::fixed << std::setprecision(2) << globalStats.getAverageLatency() + << " ฮผs\n"; + // Show endpoint-specific statistics auto wsStats = metrics.getEndpointStats(endpoint1); if (wsStats) { @@ -181,7 +180,7 @@ void demonstrateNetworkMetrics() { std::cout << " Frames sent: " << wsStats->framesSent << "\n"; std::cout << " Connection timeouts: " << wsStats->connectionsTimedOut << "\n"; } - + auto httpStats = metrics.getEndpointStats(endpoint2); if (httpStats) { std::cout << "\nHTTP endpoint stats:\n"; @@ -189,68 +188,66 @@ void demonstrateNetworkMetrics() { std::cout << " Successful responses: " << httpStats->responsesOk << "\n"; std::cout << " Protocol errors: " << httpStats->protocolErrors << "\n"; } - + // Generate and display a full report std::cout << "\n" << metrics.generateReport() << "\n"; } void demonstrateBandwidthTracking() { std::cout << "\n=== Bandwidth Tracking Demo ===\n"; - + BandwidthTracker tracker(std::chrono::seconds(5)); - + std::cout << "Recording data transfer over time...\n"; - + // Simulate data transfer for (int i = 0; i < 10; i++) { tracker.recordBytes(1000 + i * 100); std::this_thread::sleep_for(std::chrono::milliseconds(100)); - + if (i % 3 == 0) { double bandwidth = tracker.getCurrentBandwidth(); - std::cout << "Current bandwidth: " << std::fixed << std::setprecision(2) - << bandwidth / 1024.0 << " KB/s\n"; + std::cout << "Current bandwidth: " << std::fixed << std::setprecision(2) << bandwidth / 1024.0 << " KB/s\n"; } } - + double peakBandwidth = tracker.getPeakBandwidth(); - std::cout << "Peak bandwidth: " << std::fixed << std::setprecision(2) - << peakBandwidth / 1024.0 << " KB/s\n"; + std::cout << "Peak bandwidth: " << std::fixed << std::setprecision(2) << peakBandwidth / 1024.0 << " KB/s\n"; } void demonstrateZeroCopyOperations() { std::cout << "\n=== Zero-Copy Operations Demo ===\n"; - + // Zero-copy buffer ZeroCopyBuffer zcBuffer; - + std::string segment1 = "Header: "; std::string segment2 = "Content data goes here"; std::string segment3 = " | Footer"; - + zcBuffer.addReference(segment1); zcBuffer.addReference(segment2); zcBuffer.addReference(segment3); - + std::cout << "Zero-copy buffer total size: " << zcBuffer.getTotalSize() << " bytes\n"; - + // Iterate through segments without copying std::cout << "Segments: "; zcBuffer.forEachSegment([](const void* data, size_t length) { std::cout << "'" << std::string(static_cast(data), length) << "' "; }); std::cout << "\n"; - + // Scatter-gather buffer ScatterGatherBuffer sgBuffer; sgBuffer.addSegment("Part1"); sgBuffer.addSegment("Part2"); sgBuffer.addSegment("Part3"); - + std::cout << "Scatter-gather buffer:\n"; std::cout << " Segments: " << sgBuffer.getSegmentCount() << "\n"; std::cout << " Total size: " << sgBuffer.getTotalSize() << " bytes\n"; - + auto flattened = sgBuffer.flatten(); std::string result(flattened.begin(), flattened.end()); std::cout << " Flattened: '" << result << "'\n"; @@ -259,7 +256,7 @@ void demonstrateZeroCopyOperations() { int main() { std::cout << "Bolt C++ Network Protocol Optimizations Demo\n"; std::cout << "============================================\n"; - + try { demonstrateConnectionPool(); demonstrateMessageCompression(); @@ -267,10 +264,10 @@ int main() { demonstrateNetworkMetrics(); demonstrateBandwidthTracking(); demonstrateZeroCopyOperations(); - + std::cout << "\n=== Demo Complete ===\n"; std::cout << "All network optimizations demonstrated successfully!\n"; - + std::cout << "\nKey Optimizations Implemented:\n"; std::cout << "โœ“ Connection pooling with keep-alive support\n"; std::cout << "โœ“ Message compression (GZIP/DEFLATE)\n"; @@ -280,11 +277,10 @@ int main() { std::cout << "โœ“ Zero-copy and scatter-gather operations\n"; std::cout << "โœ“ Memory pooling for reduced allocations\n"; std::cout << "โœ“ Thread-safe implementations\n"; - } catch (const std::exception& e) { std::cerr << "Demo error: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_performance_profiler.cpp b/demo_performance_profiler.cpp index 2cc70b45..d0740847 100644 --- a/demo_performance_profiler.cpp +++ b/demo_performance_profiler.cpp @@ -1,17 +1,18 @@ -#include "bolt/core/performance_profiler.hpp" -#include "bolt/core/logging.hpp" +#include #include +#include #include -#include #include -#include + +#include "bolt/core/logging.hpp" +#include "bolt/core/performance_profiler.hpp" // Simulate various types of work to demonstrate profiling void simulateFileLoading(const std::string& filename, int loadTimeMs) { BOLT_PROFILE_EDITOR("file_load:" + filename); - + std::this_thread::sleep_for(std::chrono::milliseconds(loadTimeMs)); - + // Add some metadata to the profiler auto& profiler = bolt::PerformanceProfiler::getInstance(); auto currentSession = profiler.getCurrentSession(); @@ -22,57 +23,57 @@ void simulateFileLoading(const std::string& filename, int loadTimeMs) { void simulateAIInference(const std::string& modelName, int inferenceTimeMs) { BOLT_PROFILE_AI("inference:" + modelName); - + // Simulate memory allocation for model - std::vector data(1000000); // ~4MB - + std::vector data(1000000); // ~4MB + std::this_thread::sleep_for(std::chrono::milliseconds(inferenceTimeMs)); - + // Clear memory data.clear(); } void simulateNetworkRequest(const std::string& endpoint, int requestTimeMs) { BOLT_PROFILE_NETWORK("http_request:" + endpoint); - + std::this_thread::sleep_for(std::chrono::milliseconds(requestTimeMs)); } void simulateMemoryOperations() { BOLT_PROFILE_MEMORY("memory_intensive_operations"); - + // Allocate and deallocate memory to show memory tracking std::vector> largeData; - + for (int i = 0; i < 100; ++i) { - largeData.emplace_back(10000, i); // Each vector ~40KB + largeData.emplace_back(10000, i); // Each vector ~40KB if (i % 10 == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); } } - + // Clear memory largeData.clear(); } void demonstrateBasicProfiling() { std::cout << "\\n=== Basic Profiling Demo ===" << std::endl; - + // Enable the profiler auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.enable(); - + // Simple function profiling auto simpleTask = []() { BOLT_PROFILE_FUNCTION(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); }; simpleTask(); - + // Scoped profiling { BOLT_PROFILE_SCOPE("complex_calculation"); - + // Simulate some CPU-intensive work double result = 0.0; for (int i = 0; i < 1000000; ++i) { @@ -82,68 +83,66 @@ void demonstrateBasicProfiling() { volatile double sink = result; (void)sink; } - + // Category-specific profiling { BOLT_PROFILE_CORE("core_initialization"); std::this_thread::sleep_for(std::chrono::milliseconds(30)); } - + { BOLT_PROFILE_GUI("ui_update"); - std::this_thread::sleep_for(std::chrono::milliseconds(16)); // ~60 FPS + std::this_thread::sleep_for(std::chrono::milliseconds(16)); // ~60 FPS } - - std::cout << "Basic profiling completed. Metrics recorded: " - << profiler.getTotalMetricsCount() << std::endl; + + std::cout << "Basic profiling completed. Metrics recorded: " << profiler.getTotalMetricsCount() << std::endl; } void demonstrateSessionProfiling() { std::cout << "\\n=== Session-Based Profiling Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); std::random_device rd; std::mt19937 gen(rd()); - + // Create a session for a specific workflow { BOLT_PROFILE_SESSION("file_processing_workflow"); - + std::vector files = {"document.txt", "image.png", "data.csv", "config.json"}; std::uniform_int_distribution<> loadTime(20, 100); - + for (const auto& file : files) { simulateFileLoading(file, loadTime(gen)); } - + // Process the files { BOLT_PROFILE_SCOPE("batch_processing"); std::this_thread::sleep_for(std::chrono::milliseconds(150)); } - + auto session = profiler.getCurrentSession(); if (session) { - std::cout << "Session '" << session->getName() << "' has " - << session->getMetricsCount() << " metrics" << std::endl; + std::cout << "Session '" << session->getName() << "' has " << session->getMetricsCount() << " metrics" + << std::endl; } } - + // Create another session for AI operations { BOLT_PROFILE_SESSION("ai_inference_session"); - + std::vector models = {"text_classifier", "sentiment_analyzer", "summarizer"}; std::uniform_int_distribution<> inferenceTime(50, 200); - + for (const auto& model : models) { simulateAIInference(model, inferenceTime(gen)); } - + auto session = profiler.getCurrentSession(); if (session) { - std::cout << "AI session completed with " - << session->getMetricsCount() << " inferences in " + std::cout << "AI session completed with " << session->getMetricsCount() << " inferences in " << session->getTotalDurationMs() << " ms" << std::endl; } } @@ -151,129 +150,130 @@ void demonstrateSessionProfiling() { void demonstrateSystemMonitoring() { std::cout << "\\n=== System Monitoring Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.enableSystemMonitoring(); - + // Perform memory-intensive operations simulateMemoryOperations(); - + // Perform network operations std::vector endpoints = {"/api/users", "/api/data", "/api/status"}; std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> requestTime(30, 120); - + for (const auto& endpoint : endpoints) { simulateNetworkRequest(endpoint, requestTime(gen)); } - + std::cout << "System monitoring completed. Check detailed report for memory/CPU data." << std::endl; } void demonstrateConcurrentProfiling() { std::cout << "\\n=== Concurrent Profiling Demo ===" << std::endl; - + const int numWorkers = 4; std::vector workers; - + // Create multiple threads doing different types of work for (int i = 0; i < numWorkers; ++i) { workers.emplace_back([i]() { std::string sessionName = "worker_thread_" + std::to_string(i); auto session = bolt::PerformanceProfiler::getInstance().createSession(sessionName); bolt::PerformanceProfiler::getInstance().setCurrentSession(sessionName); - + std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> workTime(10, 50); - + for (int j = 0; j < 5; ++j) { std::string taskName = "task_" + std::to_string(j); - + if (i % 2 == 0) { // Even threads do AI work simulateAIInference("thread_model_" + std::to_string(i), workTime(gen)); } else { // Odd threads do file operations - simulateFileLoading("thread_file_" + std::to_string(i) + "_" + std::to_string(j) + ".dat", workTime(gen)); + simulateFileLoading("thread_file_" + std::to_string(i) + "_" + std::to_string(j) + ".dat", + workTime(gen)); } } - + bolt::PerformanceProfiler::getInstance().endSession(sessionName); }); } - + // Wait for all workers to complete for (auto& worker : workers) { worker.join(); } - + std::cout << "Concurrent profiling completed with " << numWorkers << " worker threads." << std::endl; } void demonstrateDataExport() { std::cout << "\\n=== Data Export Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); - + // Export data to different formats std::string jsonFile = "/tmp/bolt_profiler_demo.json"; std::string csvFile = "/tmp/bolt_profiler_demo.csv"; - + profiler.exportToJson(jsonFile); profiler.exportToCsv(csvFile); - + std::cout << "Profiling data exported to:" << std::endl; std::cout << " JSON: " << jsonFile << std::endl; std::cout << " CSV: " << csvFile << std::endl; - + // Print summary and detailed reports std::cout << "\\n--- Summary Report ---" << std::endl; profiler.printSummary(); - + std::cout << "\\n--- Detailed Report ---" << std::endl; profiler.printDetailedReport(); } void demonstrateIntegrationWithLogging() { std::cout << "\\n=== Integration with Logging System Demo ===" << std::endl; - + // Configure logging to show profiler output bolt::LogManager::configureConsoleLogging(bolt::LogLevel::INFO, true); - + auto& profiler = bolt::PerformanceProfiler::getInstance(); - + // The profiler automatically logs metrics when they complete { BOLT_PROFILE_SCOPE("logged_operation"); std::this_thread::sleep_for(std::chrono::milliseconds(25)); } - + // You can also manually log session summaries auto session = profiler.createSession("manual_logging_session"); profiler.setCurrentSession("manual_logging_session"); - + { BOLT_PROFILE_SCOPE("session_work"); std::this_thread::sleep_for(std::chrono::milliseconds(35)); } - + profiler.endSession("manual_logging_session"); profiler.logSessionSummary(*session, bolt::LogLevel::INFO); - + std::cout << "Integration with logging system demonstrated." << std::endl; } void demonstrateAnalyticsAndFiltering() { std::cout << "\\n=== Analytics and Filtering Demo ===" << std::endl; - + auto& profiler = bolt::PerformanceProfiler::getInstance(); - + // Get analytics std::cout << "Total metrics recorded: " << profiler.getTotalMetricsCount() << std::endl; std::cout << "Average metric duration: " << profiler.getAverageMetricDuration() << " ms" << std::endl; - + // Get categories auto categories = profiler.getCategories(); std::cout << "Categories found: "; @@ -281,7 +281,7 @@ void demonstrateAnalyticsAndFiltering() { std::cout << category << " "; } std::cout << std::endl; - + // Analyze metrics by category for (const auto& category : categories) { auto metrics = profiler.getMetricsByCategory(category); @@ -291,10 +291,9 @@ void demonstrateAnalyticsAndFiltering() { totalDuration += metric->getDurationMs(); } double avgDuration = totalDuration / metrics.size(); - - std::cout << "Category " << category << ": " - << metrics.size() << " metrics, avg " - << avgDuration << " ms" << std::endl; + + std::cout << "Category " << category << ": " << metrics.size() << " metrics, avg " << avgDuration << " ms" + << std::endl; } } } @@ -302,15 +301,15 @@ void demonstrateAnalyticsAndFiltering() { int main() { std::cout << "Bolt Performance Profiler Demo" << std::endl; std::cout << "==============================" << std::endl; - + try { // Initialize logging bolt::LogManager::configureConsoleLogging(bolt::LogLevel::WARN, false); - + // Reset profiler to start fresh auto& profiler = bolt::PerformanceProfiler::getInstance(); profiler.reset(); - + // Run demonstrations demonstrateBasicProfiling(); demonstrateSessionProfiling(); @@ -319,20 +318,19 @@ int main() { demonstrateIntegrationWithLogging(); demonstrateAnalyticsAndFiltering(); demonstrateDataExport(); - + std::cout << "\\n=== Demo Complete ===" << std::endl; std::cout << "Performance profiler demonstration completed successfully!" << std::endl; std::cout << "Total metrics collected: " << profiler.getTotalMetricsCount() << std::endl; - + // Clean up old metrics (demo only) std::cout << "\\nCleaning up metrics older than 1 minute..." << std::endl; profiler.clearOldMetrics(std::chrono::minutes(1)); std::cout << "Metrics after cleanup: " << profiler.getTotalMetricsCount() << std::endl; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; } - + return 0; -} \ No newline at end of file +} diff --git a/demo_plugin_system.cpp b/demo_plugin_system.cpp index ae1519c2..c8d268de 100644 --- a/demo_plugin_system.cpp +++ b/demo_plugin_system.cpp @@ -1,32 +1,31 @@ -#include "bolt/core/plugin_system.hpp" -#include "bolt/core/plugin_interface.hpp" -#include "bolt/core/editor_store.hpp" -#include "bolt/editor/integrated_editor.hpp" -#include "../examples/plugins/cpp_language_plugin.cpp" // Include for static linking +#include #include #include -#include + +#include "../examples/plugins/cpp_language_plugin.cpp" // NOLINT(build/include) compiled in for static linking +#include "bolt/core/editor_store.hpp" +#include "bolt/core/plugin_interface.hpp" +#include "bolt/core/plugin_system.hpp" +#include "bolt/editor/integrated_editor.hpp" // Create a simple editor store for demo purposes class DemoEditorStore : public bolt::EditorStore { -public: + public: DemoEditorStore() = default; - + // Implement minimal interface for demo void openDocument(const std::string& filePath, const std::string& content) { std::cout << "Demo: Opening document " << filePath << std::endl; } - - void closeDocument(const std::string& filePath) { - std::cout << "Demo: Closing document " << filePath << std::endl; - } + + void closeDocument(const std::string& filePath) { std::cout << "Demo: Closing document " << filePath << std::endl; } }; // Create a simple integrated editor for demo purposes class DemoIntegratedEditor : public bolt::IntegratedEditor { -public: + public: DemoIntegratedEditor() = default; - + void openDocument(const std::string& filePath, const std::string& content) { std::cout << "Demo: Integrated editor opening " << filePath << std::endl; } @@ -35,22 +34,22 @@ class DemoIntegratedEditor : public bolt::IntegratedEditor { // Create a simple editor store for demo purposes - just use nullptr since we only need interface void demonstratePluginSystem() { std::cout << "=== Bolt Plugin System Demonstration ===" << std::endl; - + // Get plugin system instance bolt::PluginSystem& pluginSystem = bolt::PluginSystem::getInstance(); - + // Clean any previous state pluginSystem.shutdown(); - + // Initialize plugin system (use nullptr for editor components since this is just a demo) std::cout << "\n1. Initializing Plugin System..." << std::endl; pluginSystem.initialize(nullptr, nullptr); - + // Add plugin directories for discovery std::cout << "\n2. Setting up plugin directories..." << std::endl; pluginSystem.addPluginDirectory("./plugins"); pluginSystem.addPluginDirectory("./examples/plugins"); - + // Load a plugin statically (since we included the source) std::cout << "\n3. Loading C++ Language Plugin..." << std::endl; auto cppPlugin = createCppLanguagePlugin(); @@ -59,7 +58,7 @@ void demonstratePluginSystem() { } else { std::cout << "โœ— Failed to load C++ Language Plugin" << std::endl; } - + // Activate the plugin std::cout << "\n4. Activating plugin..." << std::endl; if (pluginSystem.activatePlugin("CppLanguagePlugin")) { @@ -67,7 +66,7 @@ void demonstratePluginSystem() { } else { std::cout << "โœ— Failed to activate C++ Language Plugin" << std::endl; } - + // Query loaded plugins std::cout << "\n5. Querying loaded plugins..." << std::endl; auto loadedNames = pluginSystem.getLoadedPluginNames(); @@ -75,7 +74,7 @@ void demonstratePluginSystem() { for (const auto& name : loadedNames) { std::cout << " - " << name << std::endl; } - + // Get plugin metadata std::cout << "\n6. Plugin metadata:" << std::endl; auto metadata = pluginSystem.getPluginMetadata(); @@ -86,21 +85,21 @@ void demonstratePluginSystem() { std::cout << " Author: " << meta.author << std::endl; std::cout << " API Version: " << meta.apiVersion.toString() << std::endl; } - + // Test language plugin features std::cout << "\n7. Testing language plugin features..." << std::endl; auto langPlugins = pluginSystem.getLanguagePluginsForFile("test.cpp"); if (!langPlugins.empty()) { auto plugin = langPlugins[0]; std::cout << " Language plugin for .cpp files: " << plugin->getMetadata().name << std::endl; - + // Test code completions auto completions = plugin->getCodeCompletions("test.cpp", 10, 5); std::cout << " Code completions (first 10):" << std::endl; for (size_t i = 0; i < std::min(completions.size(), size_t(10)); ++i) { std::cout << " - " << completions[i] << std::endl; } - + // Test diagnostics std::string testCode = R"( int main() { @@ -117,7 +116,7 @@ void demonstratePluginSystem() { } } } - + // Test event system std::cout << "\n8. Testing event system..." << std::endl; bolt::PluginEvent documentOpenEvent; @@ -125,67 +124,67 @@ void demonstratePluginSystem() { documentOpenEvent.source = "demo"; documentOpenEvent.data["filePath"] = std::string("demo.cpp"); documentOpenEvent.data["content"] = std::string("int main() { return 0; }"); - + pluginSystem.publishEvent(documentOpenEvent); std::cout << " Document open event published" << std::endl; - + // Test plugin configuration std::cout << "\n9. Testing plugin configuration..." << std::endl; std::unordered_map config; config["enableAdvancedCompletions"] = true; config["maxCompletions"] = 20; - + if (pluginSystem.configurePlugin("CppLanguagePlugin", config)) { std::cout << "โœ“ Plugin configured successfully!" << std::endl; } else { std::cout << "โœ— Plugin configuration failed" << std::endl; } - + // Test plugin state management std::cout << "\n10. Testing plugin state management..." << std::endl; auto state = pluginSystem.getPluginState("CppLanguagePlugin"); std::cout << " Plugin state: " << static_cast(state) << std::endl; - + std::cout << " Is loaded: " << (pluginSystem.isPluginLoaded("CppLanguagePlugin") ? "Yes" : "No") << std::endl; std::cout << " Is active: " << (pluginSystem.isPluginActive("CppLanguagePlugin") ? "Yes" : "No") << std::endl; - + // Deactivate plugin std::cout << "\n11. Deactivating plugin..." << std::endl; if (pluginSystem.deactivatePlugin("CppLanguagePlugin")) { std::cout << "โœ“ Plugin deactivated" << std::endl; } - + // Reactivate plugin std::cout << "\n12. Reactivating plugin..." << std::endl; if (pluginSystem.activatePlugin("CppLanguagePlugin")) { std::cout << "โœ“ Plugin reactivated" << std::endl; } - + // Legacy plugin support demo std::cout << "\n13. Testing legacy plugin support..." << std::endl; bool legacyInitialized = false; bool legacyCleaned = false; - + bolt::Plugin legacyPlugin; legacyPlugin.name = "LegacyDemo"; legacyPlugin.version = "1.0.0"; - legacyPlugin.initialize = [&]() { - legacyInitialized = true; + legacyPlugin.initialize = [&]() { + legacyInitialized = true; std::cout << " Legacy plugin initialized" << std::endl; }; - legacyPlugin.cleanup = [&]() { - legacyCleaned = true; + legacyPlugin.cleanup = [&]() { + legacyCleaned = true; std::cout << " Legacy plugin cleaned up" << std::endl; }; - + pluginSystem.registerPlugin(legacyPlugin); pluginSystem.initializeAll(); - + // Error handling demo std::cout << "\n14. Testing error handling..." << std::endl; // Try to load non-existent plugin pluginSystem.loadPlugin("/nonexistent/plugin.so"); - + auto errors = pluginSystem.getPluginErrors(); if (!errors.empty()) { std::cout << " Plugin errors captured:" << std::endl; @@ -193,12 +192,12 @@ void demonstratePluginSystem() { std::cout << " - " << error << std::endl; } } - + // Cleanup std::cout << "\n15. Cleaning up..." << std::endl; - pluginSystem.cleanupAll(); // Legacy plugins - pluginSystem.shutdown(); // Modern plugins - + pluginSystem.cleanupAll(); // Legacy plugins + pluginSystem.shutdown(); // Modern plugins + std::cout << "\n=== Plugin System Demonstration Complete ===" << std::endl; } @@ -211,4 +210,4 @@ int main() { std::cerr << "Demo failed with error: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_semantic_file_search.cpp b/demo_semantic_file_search.cpp index f30a1df9..0c48a806 100644 --- a/demo_semantic_file_search.cpp +++ b/demo_semantic_file_search.cpp @@ -1,25 +1,25 @@ -#include "bolt/ai/semantic_search_manager.hpp" -#include #include +#include + +#include "bolt/ai/semantic_search_manager.hpp" void printSearchResults(const std::vector& results) { if (results.empty()) { std::cout << "No results found.\n"; return; } - + std::cout << "\n" << std::string(80, '=') << "\n"; std::cout << "Search Results (" << results.size() << " found)\n"; std::cout << std::string(80, '=') << "\n\n"; - + for (size_t i = 0; i < results.size(); ++i) { const auto& result = results[i]; - + std::cout << (i + 1) << ". " << result.file_path << "\n"; - std::cout << " Similarity: " << std::fixed << std::setprecision(4) - << result.similarity_score << "\n"; + std::cout << " Similarity: " << std::fixed << std::setprecision(4) << result.similarity_score << "\n"; std::cout << " Type: " << result.file_type << "\n"; - + if (!result.content_preview.empty()) { std::cout << " Preview: "; std::string preview = result.content_preview; @@ -36,45 +36,39 @@ void printSearchResults(const std::vector& results) { int main() { std::cout << "=== Semantic File Search Demo ===\n\n"; - + // 1. Initialize the semantic search manager std::cout << "Initializing semantic search manager...\n"; bolt::ai::SemanticSearchManager search_manager; - + if (!search_manager.initialize()) { std::cerr << "โŒ Failed to initialize semantic search manager.\n"; std::cerr << "Make sure a GGUF model is available.\n"; return 1; } - + std::cout << "โœ… Semantic search manager initialized\n\n"; - + // 2. Configure indexing bolt::ai::IndexingConfig config; config.max_chunk_size = 500; config.chunk_overlap = 100; config.file_extensions = {".cpp", ".hpp", ".h", ".txt", ".md"}; - config.max_file_size = 1024 * 1024; // 1MB + config.max_file_size = 1024 * 1024; // 1MB search_manager.setConfig(config); - + // 3. Index some files std::cout << "Indexing files...\n"; - - std::vector files_to_index = { - "./bolt_chat.cpp", - "./demo_direct_gguf.cpp", - "./include/bolt/ai/direct_gguf_inference.hpp", - "./src/bolt/ai/direct_gguf_inference.cpp", - "./README.md" - }; - + + std::vector files_to_index = {"./bolt_chat.cpp", "./demo_direct_gguf.cpp", + "./include/bolt/ai/direct_gguf_inference.hpp", + "./src/bolt/ai/direct_gguf_inference.cpp", "./README.md"}; + // Set progress callback - search_manager.setProgressCallback( - [](const std::string& file, size_t current, size_t total) { - std::cout << " [" << current << "/" << total << "] " << file << "\n"; - } - ); - + search_manager.setProgressCallback([](const std::string& file, size_t current, size_t total) { + std::cout << " [" << current << "/" << total << "] " << file << "\n"; + }); + for (const auto& file : files_to_index) { if (search_manager.indexFile(file)) { std::cout << " โœ“ Indexed: " << file << "\n"; @@ -82,7 +76,7 @@ int main() { std::cout << " โœ— Skipped: " << file << "\n"; } } - + // 4. Display indexing statistics auto stats = search_manager.getStats(); std::cout << "\nIndexing Statistics:\n"; @@ -90,53 +84,52 @@ int main() { std::cout << " Files skipped: " << stats.files_skipped << "\n"; std::cout << " Total chunks: " << stats.total_chunks << "\n"; std::cout << " Errors: " << stats.errors << "\n"; - std::cout << " Total time: " << std::fixed << std::setprecision(2) - << stats.total_time_seconds << " seconds\n"; - + std::cout << " Total time: " << std::fixed << std::setprecision(2) << stats.total_time_seconds << " seconds\n"; + // 5. Perform semantic searches std::cout << "\n" << std::string(80, '=') << "\n"; std::cout << "Performing Semantic Searches\n"; std::cout << std::string(80, '=') << "\n"; - + // Search 1: Chat functionality std::cout << "\nQuery 1: \"chat interface implementation\"\n"; auto results1 = search_manager.search("chat interface implementation", 3); printSearchResults(results1); - + // Search 2: Model loading std::cout << "\nQuery 2: \"loading GGUF models\"\n"; auto results2 = search_manager.search("loading GGUF models", 3); printSearchResults(results2); - + // Search 3: AI inference std::cout << "\nQuery 3: \"AI inference and text generation\"\n"; auto results3 = search_manager.search("AI inference and text generation", 3); printSearchResults(results3); - + // 6. Interactive search std::cout << "\n" << std::string(80, '=') << "\n"; std::cout << "Interactive Search Mode\n"; std::cout << std::string(80, '=') << "\n"; std::cout << "Enter search queries (or 'quit' to exit):\n\n"; - + std::string query; while (true) { std::cout << "Search> "; std::getline(std::cin, query); - + if (query == "quit" || query == "exit") { break; } - + if (query.empty()) { continue; } - + auto results = search_manager.search(query, 5, 0.2f); printSearchResults(results); } - + std::cout << "\n=== Demo Complete ===\n"; - + return 0; } diff --git a/demo_split_view.cpp b/demo_split_view.cpp index 9554c62d..a590b268 100644 --- a/demo_split_view.cpp +++ b/demo_split_view.cpp @@ -1,9 +1,10 @@ -#include #include +#include + #include "bolt/editor/integrated_editor.hpp" #include "bolt/editor/split_view_manager.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) void createSampleFiles() { // Create some sample files to work with @@ -15,7 +16,7 @@ void createSampleFiles() { << " return 0;\n" << "}\n"; file1.close(); - + std::ofstream file2("/tmp/sample2.cpp"); file2 << "// Sample C++ File 2\n" << "#include \n" @@ -24,7 +25,7 @@ void createSampleFiles() { << " std::sort(vec.begin(), vec.end());\n" << "}\n"; file2.close(); - + std::ofstream file3("/tmp/sample3.hpp"); file3 << "// Sample Header File\n" << "#ifndef SAMPLE_HPP\n" @@ -42,29 +43,29 @@ void createSampleFiles() { int main() { std::cout << "Split View Editing Demo" << std::endl; std::cout << "=======================" << std::endl << std::endl; - + // Create sample files createSampleFiles(); - + // Get the integrated editor instance auto& editor = IntegratedEditor::getInstance(); auto& splitManager = SplitViewManager::getInstance(); - + std::cout << "1. Initial state:" << std::endl; std::cout << " - Split view enabled: " << (editor.isSplitViewEnabled() ? "Yes" : "No") << std::endl; std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl; std::cout << " - Has splits: " << (editor.hasSplits() ? "Yes" : "No") << std::endl << std::endl; - + // Open first document in the default pane std::cout << "2. Opening sample1.cpp in default pane..." << std::endl; std::ifstream file1("/tmp/sample1.cpp"); std::string content1((std::istreambuf_iterator(file1)), std::istreambuf_iterator()); file1.close(); editor.openDocument("/tmp/sample1.cpp", content1); - + std::cout << " - Active pane ID: " << editor.getActivePaneId() << std::endl; std::cout << " - Open documents: " << editor.getOpenDocuments().size() << std::endl << std::endl; - + // Create horizontal split std::cout << "3. Creating horizontal split..." << std::endl; std::string hPaneId = editor.createHorizontalSplit(); @@ -72,31 +73,31 @@ int main() { std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl; std::cout << " - Has splits: " << (editor.hasSplits() ? "Yes" : "No") << std::endl; std::cout << " - Active pane ID: " << editor.getActivePaneId() << std::endl << std::endl; - + // Open second document in the new pane std::cout << "4. Opening sample2.cpp in the new horizontal pane..." << std::endl; editor.openDocumentInPane(hPaneId, "/tmp/sample2.cpp"); - std::cout << " - Documents in pane " << hPaneId << ": " << - (splitManager.getPane(hPaneId)->hasDocument() ? "1" : "0") << std::endl; - + std::cout << " - Documents in pane " << hPaneId << ": " + << (splitManager.getPane(hPaneId)->hasDocument() ? "1" : "0") << std::endl; + auto openDocs = editor.getOpenDocuments(); std::cout << " - Total open documents: " << openDocs.size() << std::endl; for (const auto& doc : openDocs) { std::cout << " * " << doc << std::endl; } std::cout << std::endl; - + // Create vertical split std::cout << "5. Creating vertical split..." << std::endl; std::string vPaneId = editor.createVerticalSplit(); std::cout << " - New pane ID: " << vPaneId << std::endl; std::cout << " - Number of panes: " << splitManager.getPaneCount() << std::endl; std::cout << " - Active pane ID: " << editor.getActivePaneId() << std::endl << std::endl; - + // Open third document in new vertical pane std::cout << "6. Opening sample3.hpp in the new vertical pane..." << std::endl; editor.openDocumentInPane(vPaneId, "/tmp/sample3.hpp"); - + openDocs = editor.getOpenDocuments(); std::cout << " - Total open documents: " << openDocs.size() << std::endl; for (const auto& doc : openDocs) { @@ -104,18 +105,17 @@ int main() { std::cout << " * " << doc << " (in pane " << paneId << ")" << std::endl; } std::cout << std::endl; - + // Show all pane IDs std::cout << "7. All pane IDs:" << std::endl; auto allPanes = editor.getAllPaneIds(); for (const auto& paneId : allPanes) { auto* pane = splitManager.getPane(paneId); - std::cout << " - " << paneId << - (pane->hasFocus() ? " (ACTIVE)" : "") << - (pane->hasDocument() ? " [" + pane->getDocumentPath() + "]" : " [empty]") << std::endl; + std::cout << " - " << paneId << (pane->hasFocus() ? " (ACTIVE)" : "") + << (pane->hasDocument() ? " [" + pane->getDocumentPath() + "]" : " [empty]") << std::endl; } std::cout << std::endl; - + // Test navigation std::cout << "8. Testing pane navigation..." << std::endl; std::cout << " - Current active: " << editor.getActivePaneId() << std::endl; @@ -125,7 +125,7 @@ int main() { std::cout << " - After next again: " << editor.getActivePaneId() << std::endl; editor.navigateToPreviousPane(); std::cout << " - After previous: " << editor.getActivePaneId() << std::endl << std::endl; - + // Test closing a pane std::cout << "9. Testing pane closure..." << std::endl; std::cout << " - Panes before close: " << splitManager.getPaneCount() << std::endl; @@ -133,14 +133,14 @@ int main() { std::cout << " - Close successful: " << (closed ? "Yes" : "No") << std::endl; std::cout << " - Panes after close: " << splitManager.getPaneCount() << std::endl; std::cout << " - Active pane: " << editor.getActivePaneId() << std::endl; - + openDocs = editor.getOpenDocuments(); std::cout << " - Remaining open documents: " << openDocs.size() << std::endl; for (const auto& doc : openDocs) { std::cout << " * " << doc << std::endl; } std::cout << std::endl; - + // Test collapsing splits std::cout << "10. Testing split collapse..." << std::endl; std::cout << " - Has splits before collapse: " << (editor.hasSplits() ? "Yes" : "No") << std::endl; @@ -148,7 +148,7 @@ int main() { std::cout << " - Has splits after collapse: " << (editor.hasSplits() ? "Yes" : "No") << std::endl; std::cout << " - Panes after collapse: " << splitManager.getPaneCount() << std::endl; std::cout << " - Active pane: " << editor.getActivePaneId() << std::endl << std::endl; - + std::cout << "Split view demo completed successfully!" << std::endl; std::cout << "Key features demonstrated:" << std::endl; std::cout << "- Creating horizontal and vertical splits" << std::endl; @@ -157,6 +157,6 @@ int main() { std::cout << "- Closing individual panes" << std::endl; std::cout << "- Collapsing all splits" << std::endl; std::cout << "- Managing multiple documents across panes" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_split_view_basic.cpp b/demo_split_view_basic.cpp index 7038104f..dc0026c2 100644 --- a/demo_split_view_basic.cpp +++ b/demo_split_view_basic.cpp @@ -1,52 +1,53 @@ #include + #include "bolt/editor/editor_pane.hpp" #include "bolt/editor/split_view_manager.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) int main() { std::cout << "Split View Editing Demo (Basic)" << std::endl; std::cout << "================================" << std::endl << std::endl; - + try { // Test basic EditorPane functionality std::cout << "1. Testing EditorPane basics..." << std::endl; EditorPane pane("demo_pane"); - + std::cout << " - Pane ID: " << pane.getId() << std::endl; std::cout << " - Has document: " << (pane.hasDocument() ? "Yes" : "No") << std::endl; std::cout << " - Has focus: " << (pane.hasFocus() ? "Yes" : "No") << std::endl; std::cout << " - Is visible: " << (pane.isVisible() ? "Yes" : "No") << std::endl; - + // Test focus management pane.setFocus(true); std::cout << " - After setting focus: " << (pane.hasFocus() ? "Yes" : "No") << std::endl; - + // Test position management EditorPane::PanePosition pos{100, 200, 800, 600}; pane.setPosition(pos); const auto& retrievedPos = pane.getPosition(); - std::cout << " - Position: (" << retrievedPos.x << ", " << retrievedPos.y << - ", " << retrievedPos.width << ", " << retrievedPos.height << ")" << std::endl; - + std::cout << " - Position: (" << retrievedPos.x << ", " << retrievedPos.y << ", " << retrievedPos.width + << ", " << retrievedPos.height << ")" << std::endl; + // Test cursor operations pane.setCursorPosition(10, 25); size_t line, column; pane.getCursorPosition(line, column); std::cout << " - Cursor position: (" << line << ", " << column << ")" << std::endl; - + std::cout << std::endl; - + // Test SplitViewManager singleton access std::cout << "2. Testing SplitViewManager basics..." << std::endl; auto& manager = SplitViewManager::getInstance(); - + std::cout << " - Split view enabled: " << (manager.isEnabled() ? "Yes" : "No") << std::endl; std::cout << " - Initial pane count: " << manager.getPaneCount() << std::endl; std::cout << " - Has splits: " << (manager.hasSplits() ? "Yes" : "No") << std::endl; - + std::cout << std::endl; - + std::cout << "Basic split view functionality verified successfully!" << std::endl; std::cout << std::endl; std::cout << "Key Components Implemented:" << std::endl; @@ -57,9 +58,8 @@ int main() { std::cout << "- Thread Safety: All operations use ThreadSafe wrappers" << std::endl; std::cout << std::endl; std::cout << "Split view editing foundation is ready for use!" << std::endl; - + return 0; - } catch (const std::exception& e) { std::cerr << "Demo failed with exception: " << e.what() << std::endl; return 1; @@ -67,4 +67,4 @@ int main() { std::cerr << "Demo failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/demo_temporal_rag_rwkv.cpp b/demo_temporal_rag_rwkv.cpp index f51f362f..b2af5e8d 100644 --- a/demo_temporal_rag_rwkv.cpp +++ b/demo_temporal_rag_rwkv.cpp @@ -1,10 +1,11 @@ -#include "bolt/ai/temporal_rag_manager.hpp" -#include "bolt/ai/temporal_tool_manager.hpp" -#include -#include #include +#include +#include #include +#include "bolt/ai/temporal_rag_manager.hpp" +#include "bolt/ai/temporal_tool_manager.hpp" + void printSeparator() { std::cout << "\n" << std::string(80, '=') << "\n\n"; } @@ -15,32 +16,32 @@ std::vector generateStockData(int days) { std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<> price_noise(0, 2.0); - + double base_price = 100.0; auto now = std::chrono::system_clock::now(); - + for (int i = 0; i < days * 24; ++i) { // Hourly data bolt::ai::TimeSeriesPoint point; point.timestamp = now - std::chrono::hours(days * 24 - i); - + // Simulate price movement with trend and noise double trend = std::sin(i * 0.1) * 10.0; // Cyclical trend double noise = price_noise(gen); double price = base_price + trend + noise; - + // Add anomaly at specific points if (i == days * 12) { // Midpoint anomaly price += 20.0; } - + point.values["price"] = price; point.values["volume"] = 1000000 + std::abs(noise) * 100000; point.source = "stock_exchange"; point.category = "stock"; - + data.push_back(point); } - + return data; } @@ -48,11 +49,11 @@ int main() { std::cout << "=== Temporal RAG & TOOL-USE Demo with RWKV.cpp ===\n"; std::cout << "Time-Series Analysis and Predictive Agents\n"; printSeparator(); - + // 1. Initialize the Temporal RAG Manager std::cout << "Initializing Temporal RAG Manager...\n"; bolt::ai::TemporalRAGManager rag_manager; - + if (!rag_manager.initialize()) { std::cerr << "โŒ Failed to initialize Temporal RAG Manager\n"; std::cerr << "Note: This demo shows the architecture even without a model\n"; @@ -60,7 +61,7 @@ int main() { std::cout << "โœ… Temporal RAG Manager initialized\n"; } std::cout << "\n"; - + // 2. Initialize the Temporal Tool Manager std::cout << "Initializing Temporal Tool Manager...\n"; bolt::ai::TemporalToolManager tool_manager; @@ -68,100 +69,95 @@ int main() { tool_manager.loadAllStandardTools(); std::cout << "โœ… Loaded " << tool_manager.getAvailableTools().size() << " temporal tools\n"; printSeparator(); - + // 3. Generate and ingest sample time-series data std::cout << "Generating sample stock market data...\n"; auto stock_data = generateStockData(30); // 30 days of hourly data - + std::cout << "Ingesting " << stock_data.size() << " data points...\n"; rag_manager.ingestDataBatch(stock_data); std::cout << "โœ… Data ingested successfully\n"; - + auto time_range = rag_manager.getDataTimeRange(); - std::cout << "Data time range: " << std::chrono::duration_cast( - time_range.second - time_range.first).count() << " hours\n"; + std::cout << "Data time range: " + << std::chrono::duration_cast(time_range.second - time_range.first).count() + << " hours\n"; printSeparator(); - + // 4. Demonstrate Temporal RAG: Query time-series data std::cout << "=== Temporal RAG: Analyzing Time Periods ===\n\n"; - + bolt::ai::TemporalQuery query1; query1.start_time = std::chrono::system_clock::now() - std::chrono::hours(7 * 24); query1.end_time = std::chrono::system_clock::now(); query1.metrics = {"price", "volume"}; query1.source_filter = "stock_exchange"; - + std::cout << "Query: Analyze stock price trends over the last 7 days\n\n"; - + std::string analysis = rag_manager.analyzeTimePeriod( - query1, - "Analyze the stock price trends and identify any significant patterns or anomalies." - ); - + query1, "Analyze the stock price trends and identify any significant patterns or anomalies."); + std::cout << "RWKV Analysis:\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; std::cout << analysis << "\n"; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€\n"; printSeparator(); - + // 5. Demonstrate pattern detection std::cout << "=== Pattern Detection ===\n\n"; - + std::string patterns = rag_manager.detectPatterns( - "price", - std::chrono::system_clock::now() - std::chrono::hours(30 * 24), - std::chrono::system_clock::now() - ); - + "price", std::chrono::system_clock::now() - std::chrono::hours(30 * 24), std::chrono::system_clock::now()); + std::cout << "Detected Patterns:\n"; std::cout << patterns << "\n"; printSeparator(); - + // 6. Demonstrate anomaly detection std::cout << "=== Anomaly Detection ===\n\n"; - + bolt::ai::TemporalQuery anomaly_query; anomaly_query.start_time = std::chrono::system_clock::now() - std::chrono::hours(30 * 24); anomaly_query.end_time = std::chrono::system_clock::now(); anomaly_query.metrics = {"price"}; - + auto anomalies = rag_manager.findAnomalies("price", anomaly_query, 2.0); - + std::cout << "Found " << anomalies.size() << " anomalies:\n\n"; for (size_t i = 0; i < std::min(size_t(5), anomalies.size()); ++i) { auto time_t = std::chrono::system_clock::to_time_t(anomalies[i].timestamp); std::cout << (i + 1) << ". Time: " << std::ctime(&time_t); - std::cout << " Price: $" << std::fixed << std::setprecision(2) - << anomalies[i].values.at("price") << "\n"; + std::cout << " Price: $" << std::fixed << std::setprecision(2) << anomalies[i].values.at("price") << "\n"; } printSeparator(); - + // 7. Demonstrate Temporal TOOL-USE: Forecasting std::cout << "=== Temporal TOOL-USE: Predictive Agent ===\n\n"; - + std::cout << "Available tools:\n"; auto available_tools = tool_manager.getAvailableTools(); for (const auto& tool : available_tools) { std::cout << " โ€ข " << tool << "\n"; } std::cout << "\n"; - + // AI decides to use the forecast tool std::cout << "AI Decision: Use 'forecast_price' tool\n\n"; - + std::unordered_map forecast_params; forecast_params["metric"] = "price"; forecast_params["n_steps"] = "24"; // Forecast next 24 hours forecast_params["confidence_level"] = "0.95"; - + auto forecast_result = tool_manager.invokeTool("forecast_price", forecast_params); - + std::cout << "Forecast Result:\n"; std::cout << " Success: " << (forecast_result.success ? "Yes" : "No") << "\n"; std::cout << " Description: " << forecast_result.description << "\n"; - std::cout << " Confidence: " << std::fixed << std::setprecision(2) - << (forecast_result.confidence_score * 100) << "%\n"; - + std::cout << " Confidence: " << std::fixed << std::setprecision(2) << (forecast_result.confidence_score * 100) + << "%\n"; + if (!forecast_result.predictions.empty()) { std::cout << " Predictions (first 5):\n"; for (size_t i = 0; i < std::min(size_t(5), forecast_result.predictions.size()); ++i) { @@ -170,10 +166,10 @@ int main() { } std::cout << "\n"; printSeparator(); - + // 8. Demonstrate automated triggers std::cout << "=== Automated Triggers ===\n\n"; - + bolt::ai::TemporalTrigger price_alert; price_alert.name = "high_price_alert"; price_alert.condition = "price > 110"; @@ -181,36 +177,36 @@ int main() { price_alert.tool_params = {{"message", "Price exceeded threshold!"}}; price_alert.enabled = true; price_alert.cooldown_seconds = 300; // 5 minutes - + tool_manager.registerTrigger(price_alert); std::cout << "Registered trigger: " << price_alert.name << "\n"; std::cout << "Condition: " << price_alert.condition << "\n"; std::cout << "Action: Invoke '" << price_alert.tool_to_invoke << "'\n\n"; - + // Simulate checking triggers with current state std::unordered_map current_state; current_state["price"] = 115.0; // Exceeds threshold current_state["volume"] = 1500000; - + std::cout << "Current State:\n"; std::cout << " Price: $" << current_state["price"] << "\n"; std::cout << " Volume: " << current_state["volume"] << "\n\n"; - + std::cout << "Checking triggers...\n"; tool_manager.checkTriggers(current_state); std::cout << "โœ… Triggers evaluated\n"; printSeparator(); - + // 9. Show execution history std::cout << "=== Tool Execution History ===\n\n"; auto history = tool_manager.getExecutionHistory(5); std::cout << "Recent executions: " << history.size() << "\n\n"; - + for (size_t i = 0; i < history.size(); ++i) { std::cout << (i + 1) << ". " << history[i].description << "\n"; std::cout << " Confidence: " << (history[i].confidence_score * 100) << "%\n"; } - + printSeparator(); std::cout << "=== Demo Complete ===\n"; std::cout << "\nThis demonstrates how RWKV.cpp can be enhanced with:\n"; @@ -218,6 +214,6 @@ int main() { std::cout << " โ€ข Predictive agents with tool use (Temporal TOOL-USE)\n"; std::cout << " โ€ข Automated monitoring and response triggers\n"; std::cout << " โ€ข Real-time forecasting and anomaly detection\n\n"; - + return 0; } diff --git a/demo_theme_integration.cpp b/demo_theme_integration.cpp index cd7b7bcf..df291d9c 100644 --- a/demo_theme_integration.cpp +++ b/demo_theme_integration.cpp @@ -1,50 +1,53 @@ #include #include #include + #include "bolt/editor/theme_system.hpp" namespace { // Mock editor component to demonstrate theme integration class ThemedEditor { -private: + private: std::string currentBackground_; std::string currentForeground_; std::string currentFont_; int currentFontSize_; - -public: + + public: void applyTheme() { auto& themeSystem = bolt::ThemeSystem::getInstance(); auto colors = themeSystem.getCurrentColors(); auto fonts = themeSystem.getCurrentFontSettings(); - + // Apply theme colors currentBackground_ = colors.background; currentForeground_ = colors.foreground; currentFont_ = fonts.family; currentFontSize_ = fonts.size; - + std::cout << "Editor theme applied:" << std::endl; std::cout << " Background: " << currentBackground_ << std::endl; std::cout << " Foreground: " << currentForeground_ << std::endl; std::cout << " Font: " << currentFont_ << " " << currentFontSize_ << "px" << std::endl; } - + void highlightCode(const std::string& code) { auto& themeSystem = bolt::ThemeSystem::getInstance(); auto colors = themeSystem.getCurrentColors(); - + std::cout << "\nHighlighted code with current theme:" << std::endl; std::cout << "----------------------------------------" << std::endl; - + // Simple mock syntax highlighting - std::vector lines = {"// Include header", "class MyClass {", " int value = 42;", " string name = \"example\";", "};"}; - + std::vector lines = {"// Include header", "class MyClass {", " int value = 42;", + " string name = \"example\";", "};"}; + for (const auto& line : lines) { if (line.find("//") != std::string::npos) { std::cout << "[" << colors.comment << "] " << line << std::endl; - } else if (line.find("class") != std::string::npos || line.find("int") != std::string::npos || line.find("string") != std::string::npos) { + } else if (line.find("class") != std::string::npos || line.find("int") != std::string::npos || + line.find("string") != std::string::npos) { std::cout << "[" << colors.keyword << "] " << line << std::endl; } else if (line.find("\"") != std::string::npos) { std::cout << "[" << colors.string << "] " << line << std::endl; @@ -59,11 +62,11 @@ class ThemedEditor { // Mock UI component that updates based on theme class ThemedUI { -public: + public: void updateColors() { auto& themeSystem = bolt::ThemeSystem::getInstance(); auto colors = themeSystem.getCurrentColors(); - + std::cout << "\nUI component colors updated:" << std::endl; std::cout << " Menu background: " << colors.background << std::endl; std::cout << " Menu text: " << colors.foreground << std::endl; @@ -75,37 +78,37 @@ class ThemedUI { void demonstrateIntegration() { std::cout << "๐Ÿ”— Theme System Integration Demo" << std::endl; std::cout << "=================================" << std::endl; - + // Initialize theme system auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + // Create editor and UI components ThemedEditor editor; ThemedUI ui; - + // Demonstrate theme switching with component updates std::vector themes = {"dark", "light"}; - + for (const auto& themeName : themes) { std::cout << "\n๐Ÿ“‹ Switching to '" << themeName << "' theme..." << std::endl; std::cout << std::string(50, '-') << std::endl; - + // Switch theme themeSystem.setTheme(themeName); - + // Update all components editor.applyTheme(); ui.updateColors(); - + // Show code highlighting with current theme editor.highlightCode("sample code"); } - + // Demonstrate custom theme integration std::cout << "\n๐ŸŽจ Adding custom theme..." << std::endl; std::cout << std::string(50, '-') << std::endl; - + bolt::Theme customTheme; customTheme.colors.background = "#2B2B2B"; customTheme.colors.foreground = "#A9B7C6"; @@ -120,10 +123,10 @@ void demonstrateIntegration() { customTheme.fontSettings.family = "JetBrains Mono"; customTheme.fontSettings.size = 15; customTheme.fontSettings.lineHeight = 1.4f; - + themeSystem.addTheme("intellij", customTheme); themeSystem.setTheme("intellij"); - + editor.applyTheme(); ui.updateColors(); editor.highlightCode("sample code"); @@ -132,9 +135,9 @@ void demonstrateIntegration() { void demonstrateThemeListener() { std::cout << "\n๐Ÿ”” Theme Change Listener Demo" << std::endl; std::cout << "==============================" << std::endl; - + auto& themeSystem = bolt::ThemeSystem::getInstance(); - + // Simulate a component that responds to theme changes auto respondToThemeChange = [&]() { std::cout << "๐Ÿ“ข Theme changed to: " << themeSystem.getCurrentThemeName() << std::endl; @@ -142,7 +145,7 @@ void demonstrateThemeListener() { std::cout << " New background: " << colors.background << std::endl; std::cout << " New foreground: " << colors.foreground << std::endl; }; - + // Demonstrate theme changes std::vector themes = {"dark", "light", "intellij"}; for (const auto& theme : themes) { @@ -151,21 +154,21 @@ void demonstrateThemeListener() { } } -} // anonymous namespace +} // anonymous namespace int main() { std::cout << "๐ŸŽจ Theme System Integration Examples" << std::endl; std::cout << "====================================" << std::endl; - + demonstrateIntegration(); demonstrateThemeListener(); - + std::cout << "\nโœ… Integration Examples Complete!" << std::endl; std::cout << "These examples show how editor components can integrate with the theme system:" << std::endl; std::cout << "- Editor components apply themes to their visual elements" << std::endl; std::cout << "- UI components update colors when themes change" << std::endl; std::cout << "- Syntax highlighting uses theme colors for different token types" << std::endl; std::cout << "- Components can listen for theme changes and update automatically" << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_theme_system.cpp b/demo_theme_system.cpp index 7015679f..7138ba82 100644 --- a/demo_theme_system.cpp +++ b/demo_theme_system.cpp @@ -1,6 +1,7 @@ #include #include #include + #include "bolt/editor/theme_system.hpp" namespace { @@ -12,13 +13,13 @@ void printSeparator() { void printThemeInfo(const std::string& themeName) { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.setTheme(themeName); - + auto colors = themeSystem.getCurrentColors(); auto fonts = themeSystem.getCurrentFontSettings(); - + std::cout << "\n๐ŸŽจ Theme: " << themeName << std::endl; printSeparator(); - + std::cout << "๐Ÿ“‹ Color Scheme:" << std::endl; std::cout << " Background: " << colors.background << std::endl; std::cout << " Foreground: " << colors.foreground << std::endl; @@ -30,7 +31,7 @@ void printThemeInfo(const std::string& themeName) { std::cout << " Numbers: " << colors.number << std::endl; std::cout << " Types: " << colors.type << std::endl; std::cout << " Functions: " << colors.function << std::endl; - + std::cout << "\n๐Ÿ”ค Font Settings:" << std::endl; std::cout << " Family: " << fonts.family << std::endl; std::cout << " Size: " << fonts.size << "px" << std::endl; @@ -41,11 +42,11 @@ void demonstrateCodeSyntaxHighlighting(const std::string& themeName) { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.setTheme(themeName); auto colors = themeSystem.getCurrentColors(); - + std::cout << "\n๐Ÿ’ป Sample Code with " << themeName << " theme colors:" << std::endl; std::cout << " (showing color codes that would be used for syntax highlighting)" << std::endl; std::cout << std::string(50, '-') << std::endl; - + // Simulate syntax highlighting by showing what colors would be used std::cout << "// This is a comment -> " << colors.comment << std::endl; std::cout << "class Example { -> " << colors.keyword << " + " << colors.type << std::endl; @@ -59,10 +60,10 @@ void demonstrateCodeSyntaxHighlighting(const std::string& themeName) { void createCustomThemeDemo() { auto& themeSystem = bolt::ThemeSystem::getInstance(); - + std::cout << "\n๐Ÿ› ๏ธ Creating Custom Theme Demo" << std::endl; printSeparator(); - + // Create a custom "monokai" inspired theme bolt::Theme monokaiTheme; monokaiTheme.colors.background = "#272822"; @@ -78,10 +79,10 @@ void createCustomThemeDemo() { monokaiTheme.fontSettings.family = "Fira Code, Monaco, monospace"; monokaiTheme.fontSettings.size = 15; monokaiTheme.fontSettings.lineHeight = 1.4f; - + themeSystem.addTheme("monokai", monokaiTheme); std::cout << "โœ… Added custom 'monokai' theme" << std::endl; - + printThemeInfo("monokai"); demonstrateCodeSyntaxHighlighting("monokai"); } @@ -89,9 +90,9 @@ void createCustomThemeDemo() { void demonstrateThemeSwitching() { std::cout << "\n๐Ÿ”„ Theme Switching Demo" << std::endl; printSeparator(); - + std::vector themes = {"dark", "light", "monokai"}; - + for (const auto& theme : themes) { std::cout << "\n>> Switching to '" << theme << "' theme..." << std::endl; demonstrateCodeSyntaxHighlighting(theme); @@ -101,21 +102,21 @@ void demonstrateThemeSwitching() { void testErrorHandling() { std::cout << "\n๐Ÿšจ Error Handling Demo" << std::endl; printSeparator(); - + auto& themeSystem = bolt::ThemeSystem::getInstance(); - + // Set to a known good theme first themeSystem.setTheme("dark"); auto beforeColors = themeSystem.getCurrentColors(); std::cout << "Current theme background: " << beforeColors.background << std::endl; - + // Try to set an invalid theme std::cout << "Attempting to set invalid theme 'nonexistent'..." << std::endl; themeSystem.setTheme("nonexistent"); - + auto afterColors = themeSystem.getCurrentColors(); std::cout << "After invalid theme attempt, background: " << afterColors.background << std::endl; - + if (beforeColors.background == afterColors.background) { std::cout << "โœ… Error handling working correctly - theme unchanged" << std::endl; } else { @@ -123,33 +124,33 @@ void testErrorHandling() { } } -} // anonymous namespace +} // anonymous namespace int main() { std::cout << "๐ŸŽจ Bolt C++ Theme System Demo" << std::endl; std::cout << "==============================" << std::endl; - + // Initialize the theme system auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); std::cout << "โœ… Theme system initialized with default themes" << std::endl; - + // Demonstrate built-in themes printThemeInfo("dark"); demonstrateCodeSyntaxHighlighting("dark"); - + printThemeInfo("light"); demonstrateCodeSyntaxHighlighting("light"); - + // Create and demonstrate custom theme createCustomThemeDemo(); - + // Demonstrate theme switching demonstrateThemeSwitching(); - + // Test error handling testErrorHandling(); - + std::cout << "\n๐ŸŽฏ Demo Summary" << std::endl; printSeparator(); std::cout << "โœ… Default themes (dark, light) loaded and working" << std::endl; @@ -158,9 +159,9 @@ int main() { std::cout << "โœ… Error handling for invalid themes working" << std::endl; std::cout << "โœ… Font settings management working" << std::endl; std::cout << "โœ… Color scheme management working" << std::endl; - + std::cout << "\n๐Ÿš€ Theme System Demo Complete!" << std::endl; std::cout << "The Bolt C++ theme system is fully functional and ready for integration." << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/demo_unified_rag_system.cpp b/demo_unified_rag_system.cpp index e7115cf6..c8e3589c 100644 --- a/demo_unified_rag_system.cpp +++ b/demo_unified_rag_system.cpp @@ -1,6 +1,7 @@ -#include "bolt/ai/unified_rag_manager.hpp" -#include #include +#include + +#include "bolt/ai/unified_rag_manager.hpp" void printSeparator() { std::cout << "\n" << std::string(80, '=') << "\n\n"; @@ -11,7 +12,7 @@ void printResults(const std::vector& results) { std::cout << "No results found.\n"; return; } - + std::cout << "Found " << results.size() << " results:\n\n"; for (size_t i = 0; i < results.size(); ++i) { std::cout << (i + 1) << ". [" << results[i].source << "] " @@ -24,31 +25,32 @@ int main() { std::cout << "=== Unified RAG System Demo ===\n"; std::cout << "Intelligent Query Routing Across Multiple RAG Backends\n"; printSeparator(); - + // 1. Initialize the Unified RAG Manager std::cout << "Initializing Unified RAG Manager...\n"; bolt::ai::UnifiedRAGManager rag_system; - + if (!rag_system.initialize()) { std::cerr << "โŒ Failed to initialize Unified RAG Manager\n"; std::cerr << "Note: Some backends may not be available\n"; } - + auto available_backends = rag_system.getAvailableBackends(); std::cout << "โœ… Initialized with " << available_backends.size() << " backends:\n"; for (const auto& backend : available_backends) { std::cout << " โ€ข " << backend << "\n"; } printSeparator(); - + // 2. Ingest sample data into different backends std::cout << "Ingesting sample data...\n\n"; - + // Narrative events bolt::ai::NarrativeEvent event1; event1.id = "event_001"; - event1.description = "The hero discovered an ancient sword in the castle's armory. " - "It glowed with a mysterious blue light."; + event1.description = + "The hero discovered an ancient sword in the castle's armory. " + "It glowed with a mysterious blue light."; event1.characters = {"Hero"}; event1.locations = {"Castle Armory"}; event1.timestamp = std::chrono::system_clock::now(); @@ -56,11 +58,12 @@ int main() { event1.importance = 9; rag_system.ingestNarrativeEvent(event1); std::cout << "โœ“ Ingested narrative event: " << event1.description.substr(0, 50) << "...\n"; - + bolt::ai::NarrativeEvent event2; event2.id = "event_002"; - event2.description = "A mysterious stranger warned the hero about the dangers " - "that lie ahead in the dark forest."; + event2.description = + "A mysterious stranger warned the hero about the dangers " + "that lie ahead in the dark forest."; event2.characters = {"Hero", "Stranger"}; event2.locations = {"Village Tavern"}; event2.timestamp = std::chrono::system_clock::now(); @@ -68,7 +71,7 @@ int main() { event2.importance = 7; rag_system.ingestNarrativeEvent(event2); std::cout << "โœ“ Ingested narrative event: " << event2.description.substr(0, 50) << "...\n"; - + // Temporal data bolt::ai::TimeSeriesPoint point1; point1.timestamp = std::chrono::system_clock::now() - std::chrono::hours(24); @@ -78,7 +81,7 @@ int main() { point1.category = "stock"; rag_system.ingestTemporalData(point1); std::cout << "โœ“ Ingested temporal data point (24h ago)\n"; - + bolt::ai::TimeSeriesPoint point2; point2.timestamp = std::chrono::system_clock::now(); point2.values["stock_price"] = 112.75; @@ -87,60 +90,52 @@ int main() { point2.category = "stock"; rag_system.ingestTemporalData(point2); std::cout << "โœ“ Ingested temporal data point (now)\n"; - + printSeparator(); - + // 3. Test query routing with different query types std::cout << "=== Query Routing Demonstration ===\n\n"; - - std::vector test_queries = { - "What happened in the castle?", - "Show me the stock price trend over time", - "Tell me about the hero's journey and the market performance", - "Find information about machine learning algorithms" - }; - + + std::vector test_queries = {"What happened in the castle?", "Show me the stock price trend over time", + "Tell me about the hero's journey and the market performance", + "Find information about machine learning algorithms"}; + for (const auto& query : test_queries) { std::cout << "Query: \"" << query << "\"\n"; - + // Analyze the query auto routing = rag_system.analyzeQuery(query); std::cout << " โ†’ Routing Decision:\n"; std::cout << " Backend: " << routing.backend_name << "\n"; - std::cout << " Confidence: " << std::fixed << std::setprecision(2) - << (routing.confidence * 100) << "%\n"; + std::cout << " Confidence: " << std::fixed << std::setprecision(2) << (routing.confidence * 100) << "%\n"; std::cout << " Reasoning: " << routing.reasoning << "\n\n"; - + // Execute the query auto results = rag_system.query(query, 3); printResults(results); - + printSeparator(); } - + // 4. Test forced routing (queryWithType) std::cout << "=== Forced Routing Test ===\n\n"; - + std::cout << "Query: \"Tell me everything\"\n"; std::cout << "Forcing backend: NarrativeRAG\n\n"; - - auto forced_results = rag_system.queryWithType( - "Tell me everything", - bolt::ai::RAGQueryType::NARRATIVE, - 5 - ); + + auto forced_results = rag_system.queryWithType("Tell me everything", bolt::ai::RAGQueryType::NARRATIVE, 5); printResults(forced_results); - + printSeparator(); - + // 5. Display statistics std::cout << "=== System Statistics ===\n\n"; - + auto stats = rag_system.getBackendStatistics(); for (const auto& stat : stats) { std::cout << stat.first << ": " << stat.second << "\n"; } - + printSeparator(); std::cout << "=== Demo Complete ===\n"; std::cout << "\nThis demonstrates:\n"; @@ -149,6 +144,6 @@ int main() { std::cout << " โ€ข Hybrid queries that combine multiple backends\n"; std::cout << " โ€ข Forced routing for explicit backend selection\n"; std::cout << " โ€ข Unified interface for all RAG operations\n\n"; - + return 0; } diff --git a/docs/reference_implementations/debugger_editor_integration.cpp b/docs/reference_implementations/debugger_editor_integration.cpp index b9b266fe..0a448ee4 100644 --- a/docs/reference_implementations/debugger_editor_integration.cpp +++ b/docs/reference_implementations/debugger_editor_integration.cpp @@ -1,30 +1,30 @@ // Debugger-Editor Integration Implementation // This file contains the implementations for all TODO items in debugger_interface.cpp -#include -#include +#include #include #include -#include +#include +#include // Implementation for get_stack_contents with actual stack inspection std::vector get_stack_contents_impl(const DISVM* vm) { if (!vm) { return {}; } - + std::vector contents; size_t stack_size = vm->stack_size(); contents.push_back("Stack size: " + std::to_string(stack_size)); - + if (stack_size > 0) { contents.push_back("Stack contents (top to bottom):"); - + try { for (size_t i = 0; i < std::min(stack_size, size_t(10)); ++i) { std::stringstream ss; ss << " [" << i << "] "; - + // Attempt to inspect stack value // This is a safe implementation that handles missing VM features try { @@ -37,10 +37,10 @@ std::vector get_stack_contents_impl(const DISVM* vm) { } catch (...) { ss << ""; } - + contents.push_back(ss.str()); } - + if (stack_size > 10) { contents.push_back(" ... (" + std::to_string(stack_size - 10) + " more items)"); } @@ -50,23 +50,23 @@ std::vector get_stack_contents_impl(const DISVM* vm) { } else { contents.push_back("Stack is empty"); } - + return contents; } // Implementation for get_global_variables with VM globals inspection std::map get_global_variables_impl(const DISVM* vm) { std::map variables; - + if (!vm) { return variables; } - + try { // Get global variable names and values from VM if (vm->has_globals_table()) { auto globals = vm->get_globals_table(); - + for (const auto& [name, value] : globals) { std::stringstream ss; ss << value; // Convert value to string representation @@ -79,7 +79,7 @@ std::map get_global_variables_impl(const DISVM* vm) { } catch (const std::exception& e) { variables[""] = std::string("Error accessing globals: ") + e.what(); } - + return variables; } @@ -88,20 +88,19 @@ void highlight_current_line_impl(IntegratedEditor* editor, const std::string& fi if (!editor || file_path.empty()) { return; } - + try { // Clear previous highlight editor->clear_debug_highlight(); - + // Set new highlight editor->set_debug_highlight(file_path, line); - + // Scroll to the highlighted line editor->scroll_to_line(line); - + // Optionally focus the editor editor->focus(); - } catch (const std::exception& e) { std::cerr << "Error highlighting line: " << e.what() << std::endl; } @@ -112,7 +111,7 @@ void clear_current_line_highlight_impl(IntegratedEditor* editor) { if (!editor) { return; } - + try { editor->clear_debug_highlight(); } catch (const std::exception& e) { @@ -121,56 +120,52 @@ void clear_current_line_highlight_impl(IntegratedEditor* editor) { } // Implementation for refresh_breakpoint_markers -void refresh_breakpoint_markers_impl(IntegratedEditor* editor, - const std::vector& breakpoints) { +void refresh_breakpoint_markers_impl(IntegratedEditor* editor, const std::vector& breakpoints) { if (!editor) { return; } - + try { // Clear all existing breakpoint markers editor->clear_all_breakpoint_markers(); - + // Add markers for each breakpoint for (const auto& bp : breakpoints) { if (!bp.file_path.empty() && bp.line > 0) { editor->add_breakpoint_marker(bp.file_path, bp.line, bp.enabled); } } - + // Refresh the editor display editor->refresh(); - } catch (const std::exception& e) { std::cerr << "Error refreshing breakpoint markers: " << e.what() << std::endl; } } // Implementation for update_breakpoint_mapping -void update_breakpoint_mapping_impl(std::map, size_t>& mapping, - const DISProgram& program) { +void update_breakpoint_mapping_impl(std::map, size_t>& mapping, const DISProgram& program) { mapping.clear(); - + // Parse debug information from program if (program.debug_info.empty()) { return; } - + try { // Debug info format: "file:line:pc" for (const auto& debug_line : program.debug_info) { size_t first_colon = debug_line.find(':'); size_t second_colon = debug_line.find(':', first_colon + 1); - + if (first_colon != std::string::npos && second_colon != std::string::npos) { std::string file = debug_line.substr(0, first_colon); - std::string line_str = debug_line.substr(first_colon + 1, - second_colon - first_colon - 1); + std::string line_str = debug_line.substr(first_colon + 1, second_colon - first_colon - 1); std::string pc_str = debug_line.substr(second_colon + 1); - + int line = std::stoi(line_str); size_t pc = std::stoull(pc_str); - + mapping[{file, line}] = pc; } } @@ -184,15 +179,15 @@ std::string evaluate_watch_expression_impl(const DISVM* vm, const std::string& e if (!vm) { return ""; } - + try { // Simple expression evaluator // Supports: variable names, stack references like $0, $1, etc. - + if (expression.empty()) { return ""; } - + // Check for stack reference: $0, $1, etc. if (expression[0] == '$') { try { @@ -209,7 +204,7 @@ std::string evaluate_watch_expression_impl(const DISVM* vm, const std::string& e return ""; } } - + // Check for global variable if (vm->has_globals_table()) { auto globals = vm->get_globals_table(); @@ -220,7 +215,7 @@ std::string evaluate_watch_expression_impl(const DISVM* vm, const std::string& e return ss.str(); } } - + // Check for register reference: PC, SP, etc. if (expression == "PC" || expression == "pc") { return std::to_string(vm->get_pc()); @@ -228,7 +223,7 @@ std::string evaluate_watch_expression_impl(const DISVM* vm, const std::string& e if (expression == "SP" || expression == "sp") { return std::to_string(vm->stack_size()); } - + // Try to evaluate as a simple arithmetic expression // This is a placeholder for a more sophisticated expression evaluator try { @@ -238,7 +233,6 @@ std::string evaluate_watch_expression_impl(const DISVM* vm, const std::string& e } catch (...) { return ""; } - } catch (const std::exception& e) { return ""; } @@ -249,34 +243,27 @@ void setup_vm_handlers_impl(DISVM* vm, DebuggerInterface* debugger) { if (!vm || !debugger) { return; } - + try { // Set up breakpoint handler - vm->set_breakpoint_handler([debugger](size_t pc) { - debugger->on_breakpoint_hit(pc); - }); - + vm->set_breakpoint_handler([debugger](size_t pc) { debugger->on_breakpoint_hit(pc); }); + // Set up step handler - vm->set_step_handler([debugger](size_t pc) { - debugger->on_step_complete(pc); - }); - + vm->set_step_handler([debugger](size_t pc) { debugger->on_step_complete(pc); }); + // Set up error handler - vm->set_error_handler([debugger](const std::string& error) { - debugger->on_vm_error(error); - }); - + vm->set_error_handler([debugger](const std::string& error) { debugger->on_vm_error(error); }); + // Set up AI operation handler (for AI integration) vm->set_ai_handler([debugger](const std::string& operation, const std::string& data) { debugger->log_debug_message("AI operation: " + operation + " - " + data); }); - + // Set up glyph rendering handler (for DrawKern) vm->set_glyph_handler([debugger](int glyph_id, int x, int y) { - debugger->log_debug_message("Glyph rendered: " + std::to_string(glyph_id) + - " at (" + std::to_string(x) + ", " + std::to_string(y) + ")"); + debugger->log_debug_message("Glyph rendered: " + std::to_string(glyph_id) + " at (" + std::to_string(x) + + ", " + std::to_string(y) + ")"); }); - } catch (const std::exception& e) { std::cerr << "Error setting up VM handlers: " << e.what() << std::endl; } diff --git a/example_git_editor_integration.cpp b/example_git_editor_integration.cpp index 157698c9..e3a40327 100644 --- a/example_git_editor_integration.cpp +++ b/example_git_editor_integration.cpp @@ -3,27 +3,27 @@ #include // Example showing Git integration with editor components -#include "bolt/git/git.hpp" #include "bolt/core/editor_store.hpp" +#include "bolt/git/git.hpp" /** * Example class showing how to integrate Git features with editor components */ class GitAwareEditor { -public: + public: GitAwareEditor() { // Initialize editor store editorStore_ = std::make_shared(); - + // Initialize Git integration initializeGit(); } - + void openFile(const std::string& filePath) { try { // Open file in editor editorStore_->openDocument(filePath); - + // Check Git status for this file if (bolt::git::isGitActive()) { auto status = bolt::git::quick::status(filePath); @@ -31,45 +31,45 @@ class GitAwareEditor { displayGitStatus(filePath, *status); } } - + std::cout << "โœ… Opened file: " << filePath << "\n"; } catch (const std::exception& e) { std::cout << "โŒ Failed to open file: " << e.what() << "\n"; } } - + void saveFile(const std::string& filePath, const std::string& content) { try { // Save file content (simplified - in real implementation this would update EditorStore) std::cout << "๐Ÿ’พ Saving file: " << filePath << "\n"; - + // Notify Git integration about file change if (bolt::git::isGitActive()) { auto& git = bolt::git::getGitIntegration(); git.notifyFileChanged(filePath); - + // Check new Git status auto status = bolt::git::quick::status(filePath); if (status) { displayGitStatus(filePath, *status); } } - + std::cout << "โœ… File saved successfully\n"; } catch (const std::exception& e) { std::cout << "โŒ Failed to save file: " << e.what() << "\n"; } } - + void showProjectStatus() { if (!bolt::git::isGitActive()) { std::cout << "๐Ÿ“ Project is not a Git repository\n"; return; } - + auto& git = bolt::git::getGitIntegration(); auto repoInfo = git.getRepositoryInfo(); - + std::cout << "\n๐Ÿ“Š Project Git Status:\n"; std::cout << "==================\n"; std::cout << "Branch: " << repoInfo.currentBranch << "\n"; @@ -78,19 +78,19 @@ class GitAwareEditor { std::cout << "Staged: " << repoInfo.stagedFiles << " files\n"; std::cout << "Untracked: " << repoInfo.untrackedFiles << " files\n\n"; } - + void quickCommit(const std::string& message) { if (!bolt::git::isGitActive()) { std::cout << "โŒ Git not available\n"; return; } - + std::cout << "๐Ÿš€ Quick commit workflow:\n"; - + // Stage all changes if (bolt::git::quick::stageAll()) { std::cout << "โœ… Staged all changes\n"; - + // Commit if (bolt::git::quick::commit(message)) { std::cout << "โœ… Committed: " << message << "\n"; @@ -103,31 +103,31 @@ class GitAwareEditor { } } -private: + private: std::shared_ptr editorStore_; - + void initializeGit() { std::string currentDir = std::filesystem::current_path().string(); if (bolt::git::initializeGit(currentDir)) { std::cout << "โœ… Git integration initialized\n"; - + // Set up Git status callbacks auto& git = bolt::git::getGitIntegration(); git.setOperationCallback([](bool success, const std::string& message) { std::cout << "๐Ÿ”„ Git: " << (success ? "โœ…" : "โŒ") << " " << message << "\n"; }); - + // Show initial status showProjectStatus(); } else { std::cout << "โ„น๏ธ Git integration not available (not a Git repository)\n"; } } - + void displayGitStatus(const std::string& filePath, bolt::git::GitFileStatus status) { std::string statusIcon; std::string statusText; - + switch (status) { case bolt::git::GitFileStatus::UNTRACKED: statusIcon = "โ“"; @@ -153,25 +153,26 @@ class GitAwareEditor { statusIcon = "โ”"; statusText = "Unknown"; } - + std::cout << "๐Ÿ“„ " << filePath << " " << statusIcon << " " << statusText << "\n"; } }; int main() { std::cout << "=== Git-Aware Editor Example ===\n\n"; - + GitAwareEditor editor; - + // Simulate editor operations std::cout << "\n๐Ÿ”น Simulating file operations:\n"; editor.openFile("README.md"); editor.saveFile("README.md", "Updated content"); - + std::cout << "\n๐Ÿ”น Quick commit example:\n"; editor.quickCommit("Update documentation via Git-aware editor"); - - std::cout << "\nโœจ Example completed! This shows how Git integration can be seamlessly embedded into editor workflows.\n"; - + + std::cout + << "\nโœจ Example completed! This shows how Git integration can be seamlessly embedded into editor workflows.\n"; + return 0; -} \ No newline at end of file +} diff --git a/examples/collaborative_editor_example.cpp b/examples/collaborative_editor_example.cpp index 53a03f54..7f36054e 100644 --- a/examples/collaborative_editor_example.cpp +++ b/examples/collaborative_editor_example.cpp @@ -1,45 +1,46 @@ /* * Example: Real-time Collaborative Editor Client - * + * * This example demonstrates how to integrate collaborative editing * into a client application using the Bolt C++ collaborative editing system. */ -#include -#include -#include #include +#include +#include #include +#include + #include "bolt/collaboration/collaborative_editor_integration.hpp" #include "bolt/core/editor_store.hpp" -using namespace bolt::collaboration; -using namespace std::chrono_literals; +using namespace bolt::collaboration; // NOLINT(build/namespaces) +using namespace std::chrono_literals; // NOLINT(build/namespaces) class SimpleCollaborativeEditor { -private: + private: std::string userId_; std::string currentFile_; std::atomic running_; CollaborativeEditorIntegration& collaboration_; bolt::EditorStore& editorStore_; -public: - SimpleCollaborativeEditor(const std::string& userId) - : userId_(userId), running_(false), + public: + explicit SimpleCollaborativeEditor(const std::string& userId) + : userId_(userId), + running_(false), collaboration_(CollaborativeEditorIntegration::getInstance()), - editorStore_(bolt::EditorStore::getInstance()) { - } + editorStore_(bolt::EditorStore::getInstance()) {} void start() { std::cout << "Starting collaborative editor for user: " << userId_ << "\n"; - + // Initialize collaboration system (starts WebSocket server) collaboration_.initialize(8081); - + // Create and open a sample document createSampleDocument(); - + // Enable collaboration for the document if (collaboration_.enableCollaboration(currentFile_, userId_)) { std::cout << "โœ“ Collaboration enabled for " << currentFile_ << "\n"; @@ -47,23 +48,23 @@ class SimpleCollaborativeEditor { std::cout << "โœ— Failed to enable collaboration\n"; return; } - + running_ = true; - + // Start the editor loop runEditorLoop(); } - + void stop() { running_ = false; collaboration_.shutdown(); std::cout << "Collaborative editor stopped.\n"; } -private: + private: void createSampleDocument() { currentFile_ = "/shared/example.cpp"; - + bolt::EditorDocument doc; doc.filePath = currentFile_; doc.value = R"(#include @@ -106,13 +107,13 @@ int main() { })"; doc.scroll = {0, 0}; doc.cursor = {0, std::nullopt}; - + editorStore_.setDocument(currentFile_, doc); editorStore_.setSelectedFile(currentFile_); - + std::cout << "Created sample document: " << currentFile_ << "\n"; } - + void runEditorLoop() { std::cout << "\n=== Collaborative Editor Commands ===\n"; std::cout << "Commands:\n"; @@ -125,132 +126,124 @@ int main() { std::cout << " stats - Show collaboration stats\n"; std::cout << " quit - Exit editor\n"; std::cout << "=====================================\n\n"; - + std::string command; while (running_ && std::cout << userId_ << "> " && std::getline(std::cin, command)) { - if (command.empty()) continue; - + if (command.empty()) + continue; + if (!processCommand(command)) { break; } } } - + bool processCommand(const std::string& command) { std::istringstream iss(command); std::string cmd; iss >> cmd; - + if (cmd == "quit" || cmd == "exit") { return false; - } - else if (cmd == "insert") { + } else if (cmd == "insert") { handleInsertCommand(iss); - } - else if (cmd == "delete") { + } else if (cmd == "delete") { handleDeleteCommand(iss); - } - else if (cmd == "cursor") { + } else if (cmd == "cursor") { handleCursorCommand(iss); - } - else if (cmd == "show") { + } else if (cmd == "show") { showDocument(); - } - else if (cmd == "users") { + } else if (cmd == "users") { showActiveUsers(); - } - else if (cmd == "cursors") { + } else if (cmd == "cursors") { showRemoteCursors(); - } - else if (cmd == "stats") { + } else if (cmd == "stats") { showStats(); - } - else if (cmd == "help") { + } else if (cmd == "help") { std::cout << "Available commands: insert, delete, cursor, show, users, cursors, stats, quit\n"; - } - else { + } else { std::cout << "Unknown command: " << cmd << " (type 'help' for commands)\n"; } - + return true; } - + void handleInsertCommand(std::istringstream& iss) { int line, col; std::string text; - + if (!(iss >> line >> col)) { std::cout << "Usage: insert \n"; return; } - + // Read the rest as text (including spaces) std::string remaining; std::getline(iss, remaining); text = remaining.substr(remaining.find_first_not_of(" \t")); - + if (text.empty()) { std::cout << "Usage: insert \n"; return; } - + Position pos(line, col); bool success = collaboration_.applyTextEdit(currentFile_, pos, text, userId_); - + if (success) { std::cout << "โœ“ Inserted \"" << text << "\" at (" << line << "," << col << ")\n"; } else { std::cout << "โœ— Failed to insert text\n"; } } - + void handleDeleteCommand(std::istringstream& iss) { int line, col; std::string text; - + if (!(iss >> line >> col >> text)) { std::cout << "Usage: delete \n"; return; } - + Position pos(line, col); bool success = collaboration_.applyTextEdit(currentFile_, pos, text, userId_, true); - + if (success) { std::cout << "โœ“ Deleted \"" << text << "\" at (" << line << "," << col << ")\n"; } else { std::cout << "โœ— Failed to delete text\n"; } } - + void handleCursorCommand(std::istringstream& iss) { int line, col; - + if (!(iss >> line >> col)) { std::cout << "Usage: cursor \n"; return; } - + Position pos(line, col); bool success = collaboration_.updateCursorPosition(currentFile_, pos, userId_); - + if (success) { std::cout << "โœ“ Moved cursor to (" << line << "," << col << ")\n"; } else { std::cout << "โœ— Failed to move cursor\n"; } } - + void showDocument() { auto* doc = editorStore_.getCurrentDocument(); if (doc) { std::cout << "\n=== Current Document: " << doc->filePath << " ===\n"; - + // Split content into lines and add line numbers std::istringstream iss(doc->value); std::string line; int lineNum = 0; - + while (std::getline(iss, line)) { std::cout << std::setw(3) << lineNum << ": " << line << "\n"; lineNum++; @@ -260,7 +253,7 @@ int main() { std::cout << "No document loaded\n"; } } - + void showActiveUsers() { // Note: This would require accessing the collaborative session directly // For this example, we'll show collaboration status @@ -270,21 +263,20 @@ int main() { std::cout << " Active Documents: " << stats.activeDocuments << "\n"; std::cout << " Total Users: " << stats.totalUsers << "\n"; } - + void showRemoteCursors() { auto cursors = collaboration_.getRemoteCursors(currentFile_); - + if (cursors.empty()) { std::cout << "No remote cursors\n"; } else { std::cout << "Remote Cursors:\n"; for (const auto& [userId, position] : cursors) { - std::cout << " " << userId << ": line " << position.line - << ", column " << position.character << "\n"; + std::cout << " " << userId << ": line " << position.line << ", column " << position.character << "\n"; } } } - + void showStats() { auto stats = collaboration_.getStats(); std::cout << "Collaboration Statistics:\n"; @@ -293,55 +285,54 @@ int main() { std::cout << " Total Users: " << stats.totalUsers << "\n"; std::cout << " Current User: " << userId_ << "\n"; std::cout << " Current File: " << currentFile_ << "\n"; - std::cout << " Collaboration Enabled: " - << (collaboration_.isCollaborationEnabled(currentFile_) ? "Yes" : "No") << "\n"; + std::cout << " Collaboration Enabled: " << (collaboration_.isCollaborationEnabled(currentFile_) ? "Yes" : "No") + << "\n"; } }; int main(int argc, char* argv[]) { std::string userId = "user1"; - + // Allow user to specify user ID if (argc > 1) { userId = argv[1]; } - + std::cout << "Bolt C++ Collaborative Editor Example\n"; std::cout << "=====================================\n\n"; - + try { SimpleCollaborativeEditor editor(userId); - + // Start the editor editor.start(); - + // Cleanup editor.stop(); - } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } - + return 0; } /* * Usage Examples: - * + * * 1. Start the editor: * ./collaborative_editor_example alice - * + * * 2. In another terminal: * ./collaborative_editor_example bob - * + * * 3. Try commands like: * alice> insert 5 4 "// Alice was here" * bob> cursor 10 0 * alice> show * bob> users * alice> cursors - * + * * Note: This example shows the API usage but requires full WebSocket * integration for true real-time collaboration between multiple instances. - */ \ No newline at end of file + */ diff --git a/examples/memory_leak_detection_example.cpp b/examples/memory_leak_detection_example.cpp index 13f0eb50..f3cbb9ed 100644 --- a/examples/memory_leak_detection_example.cpp +++ b/examples/memory_leak_detection_example.cpp @@ -1,7 +1,7 @@ /** * @file examples/memory_leak_detection_example.cpp * @brief Comprehensive example demonstrating memory leak detection tools - * + * * This example shows how to use: * 1. Built-in MemoryLeakDetector * 2. MemoryManager @@ -9,52 +9,51 @@ * 4. Best practices for leak-free code */ -#include "bolt/core/memory_leak_detector.hpp" -#include "bolt/core/memory_manager.hpp" +#include #include #include #include -#include + +#include "bolt/core/memory_leak_detector.hpp" +#include "bolt/core/memory_manager.hpp" // RAII wrapper for tracked memory -template +template class TrackedBuffer { -public: - TrackedBuffer(size_t count, const std::string& category = "general") + public: + explicit TrackedBuffer(size_t count, const std::string& category = "general") : size_(count * sizeof(T)), category_(category) { ptr_ = static_cast(malloc(size_)); if (ptr_) { TRACK_ALLOCATION(ptr_, size_, category_); - std::cout << "Allocated " << size_ << " bytes in category '" - << category_ << "'\n"; + std::cout << "Allocated " << size_ << " bytes in category '" << category_ << "'\n"; } } - + ~TrackedBuffer() { if (ptr_) { UNTRACK_ALLOCATION(ptr_); free(ptr_); - std::cout << "Freed " << size_ << " bytes from category '" - << category_ << "'\n"; + std::cout << "Freed " << size_ << " bytes from category '" << category_ << "'\n"; } } - + // Disable copy TrackedBuffer(const TrackedBuffer&) = delete; TrackedBuffer& operator=(const TrackedBuffer&) = delete; - + // Enable move - TrackedBuffer(TrackedBuffer&& other) noexcept + TrackedBuffer(TrackedBuffer&& other) noexcept : ptr_(other.ptr_), size_(other.size_), category_(std::move(other.category_)) { other.ptr_ = nullptr; other.size_ = 0; } - + T* get() { return ptr_; } const T* get() const { return ptr_; } size_t size() const { return size_; } - -private: + + private: T* ptr_ = nullptr; size_t size_ = 0; std::string category_; @@ -63,28 +62,28 @@ class TrackedBuffer { // Example 1: Basic leak detection void example_basic_leak_detection() { std::cout << "\n=== Example 1: Basic Leak Detection ===\n"; - + auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Allocate some memory void* ptr1 = malloc(1024); TRACK_ALLOCATION(ptr1, 1024, "buffers"); - + void* ptr2 = malloc(2048); TRACK_ALLOCATION(ptr2, 2048, "network"); - + // Check for leaks before cleanup std::cout << "\nBefore cleanup:\n"; std::cout << detector.generateReport() << "\n"; - + // Properly cleanup UNTRACK_ALLOCATION(ptr1); free(ptr1); - + UNTRACK_ALLOCATION(ptr2); free(ptr2); - + // Check again std::cout << "\nAfter cleanup:\n"; std::cout << detector.generateReport() << "\n"; @@ -93,22 +92,23 @@ void example_basic_leak_detection() { // Example 2: RAII-based leak prevention void example_raii_leak_prevention() { std::cout << "\n=== Example 2: RAII-based Leak Prevention ===\n"; - + auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + { // Allocations are automatically cleaned up - TrackedBuffer buffer1(1024, "string_buffers"); + constexpr size_t kStringBufferSize = 1024; + TrackedBuffer buffer1(kStringBufferSize, "string_buffers"); TrackedBuffer buffer2(256, "int_arrays"); - + // Use the buffers - strcpy(buffer1.get(), "Hello, World!"); + snprintf(buffer1.get(), kStringBufferSize, "%s", "Hello, World!"); std::cout << "Buffer1 contains: " << buffer1.get() << "\n"; - + // Buffers automatically freed when going out of scope } - + std::cout << "\nAfter scope exit:\n"; std::cout << detector.generateReport() << "\n"; } @@ -116,21 +116,21 @@ void example_raii_leak_prevention() { // Example 3: Exception safety with leak detection void example_exception_safety() { std::cout << "\n=== Example 3: Exception Safety ===\n"; - + auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + try { TrackedBuffer buffer(4096, "exception_test"); - + // Simulate an error throw std::runtime_error("Simulated error"); - + // This won't execute, but buffer is still cleaned up } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << "\n"; } - + std::cout << "\nAfter exception:\n"; std::cout << detector.generateReport() << "\n"; } @@ -138,42 +138,41 @@ void example_exception_safety() { // Example 4: Integration with MemoryManager void example_memory_manager_integration() { std::cout << "\n=== Example 4: Memory Manager Integration ===\n"; - + auto& manager = bolt::MemoryManager::getInstance(); auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Set memory limit - manager.setMaxAllowedUsage(10 * 1024 * 1024); // 10 MB - + manager.setMaxAllowedUsage(10 * 1024 * 1024); // 10 MB + std::vector allocations; - + try { // Allocate using MemoryManager for (int i = 0; i < 5; ++i) { - void* ptr = manager.allocate(1024 * 1024); // 1 MB each + void* ptr = manager.allocate(1024 * 1024); // 1 MB each allocations.push_back(ptr); - + // Also track with leak detector TRACK_ALLOCATION(ptr, 1024 * 1024, "memory_manager"); } - + std::cout << "Current usage: " << manager.getCurrentUsage() << " bytes\n"; std::cout << "Peak usage: " << manager.getPeakUsage() << " bytes\n"; - + // Cleanup for (void* ptr : allocations) { UNTRACK_ALLOCATION(ptr); manager.deallocate(ptr); } - + std::cout << "\nAfter cleanup:\n"; std::cout << "Current usage: " << manager.getCurrentUsage() << " bytes\n"; std::cout << detector.generateReport() << "\n"; - } catch (const bolt::MemoryException& e) { std::cerr << "Memory error: " << e.what() << "\n"; - + // Emergency cleanup for (void* ptr : allocations) { if (ptr) { @@ -187,45 +186,45 @@ void example_memory_manager_integration() { // Example 5: Categorization for better leak analysis void example_categorization() { std::cout << "\n=== Example 5: Leak Categorization ===\n"; - + auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Allocate in different categories void* net_buf1 = malloc(1024); TRACK_ALLOCATION(net_buf1, 1024, "network"); - + void* net_buf2 = malloc(2048); TRACK_ALLOCATION(net_buf2, 2048, "network"); - + void* img_buf = malloc(1024 * 1024); TRACK_ALLOCATION(img_buf, 1024 * 1024, "images"); - + void* str_buf = malloc(512); TRACK_ALLOCATION(str_buf, 512, "strings"); - + // Get statistics auto stats = detector.getStats(); - + std::cout << "\nMemory usage by category:\n"; for (const auto& [category, bytes] : stats.leaksByCategory) { std::cout << " " << category << ": " << bytes << " bytes\n"; } - + // Simulate forgetting to free one allocation UNTRACK_ALLOCATION(net_buf1); free(net_buf1); - + UNTRACK_ALLOCATION(net_buf2); free(net_buf2); - + UNTRACK_ALLOCATION(str_buf); free(str_buf); - + // img_buf is "leaked" - not freed std::cout << "\nLeak report (img_buf not freed):\n"; std::cout << detector.generateReport() << "\n"; - + // Cleanup the leak UNTRACK_ALLOCATION(img_buf); free(img_buf); @@ -234,31 +233,30 @@ void example_categorization() { // Example 6: Sanitizer integration void example_sanitizer_integration() { std::cout << "\n=== Example 6: Sanitizer Integration ===\n"; - + #ifdef ASAN_ENABLED std::cout << "AddressSanitizer is ENABLED\n"; std::cout << "Run with: ASAN_OPTIONS=detect_leaks=1 ./program\n"; #endif - + #ifdef LSAN_ENABLED std::cout << "LeakSanitizer is ENABLED\n"; std::cout << "Run with: LSAN_OPTIONS=verbosity=1:log_threads=1 ./program\n"; #endif - + #ifdef UBSAN_ENABLED std::cout << "UndefinedBehaviorSanitizer is ENABLED\n"; #endif - + #ifdef TSAN_ENABLED std::cout << "ThreadSanitizer is ENABLED\n"; #endif - + #ifdef MSAN_ENABLED std::cout << "MemorySanitizer is ENABLED\n"; #endif - -#if !defined(ASAN_ENABLED) && !defined(LSAN_ENABLED) && \ - !defined(UBSAN_ENABLED) && !defined(TSAN_ENABLED) && \ + +#if !defined(ASAN_ENABLED) && !defined(LSAN_ENABLED) && !defined(UBSAN_ENABLED) && !defined(TSAN_ENABLED) && \ !defined(MSAN_ENABLED) std::cout << "No sanitizers enabled. Build with:\n"; std::cout << " cmake -DENABLE_SANITIZER_ADDRESS=ON ..\n"; @@ -269,25 +267,25 @@ void example_sanitizer_integration() { // Example 7: Demonstrating a real leak (for testing detection) void example_intentional_leak() { std::cout << "\n=== Example 7: Intentional Leak (for testing) ===\n"; - + auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Intentionally leak memory (temporarily for demonstration) void* leaked = malloc(4096); TRACK_ALLOCATION(leaked, 4096, "intentional_leak"); - + std::cout << "Intentionally leaked 4096 bytes (temporarily)\n"; std::cout << detector.generateReport() << "\n"; - + std::cout << "\nNote: In production code, ALWAYS free allocated memory!\n"; std::cout << "Cleaning up the intentional leak for proper shutdown...\n"; - + // Cleanup for proper program termination // In a real leak scenario, this line would be missing UNTRACK_ALLOCATION(leaked); free(leaked); - + std::cout << "Leak cleaned up successfully.\n"; } @@ -295,11 +293,11 @@ int main() { std::cout << "======================================\n"; std::cout << "Memory Leak Detection Examples\n"; std::cout << "======================================\n"; - + // Enable leak detection auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.setEnabled(true); - + // Run examples example_basic_leak_detection(); example_raii_leak_prevention(); @@ -308,10 +306,10 @@ int main() { example_categorization(); example_sanitizer_integration(); example_intentional_leak(); - + std::cout << "\n======================================\n"; std::cout << "Examples complete!\n"; std::cout << "======================================\n"; - + return 0; } diff --git a/examples/plugins/cpp_language_plugin.cpp b/examples/plugins/cpp_language_plugin.cpp index b8dc7f18..8b98e748 100644 --- a/examples/plugins/cpp_language_plugin.cpp +++ b/examples/plugins/cpp_language_plugin.cpp @@ -1,22 +1,23 @@ -#include "bolt/core/plugin_interface.hpp" -#include #include +#include + +#include "bolt/core/plugin_interface.hpp" /** * Example C++ Language Plugin - * + * * This plugin provides basic C++ language support including: * - Code completions for common C++ keywords and STL components * - Basic syntax validation * - Code formatting */ class CppLanguagePlugin : public bolt::ILanguagePlugin { -private: + private: bolt::PluginMetadata metadata_; bolt::PluginState state_ = bolt::PluginState::Unloaded; bolt::PluginContext* context_ = nullptr; -public: + public: CppLanguagePlugin() { metadata_.name = "CppLanguagePlugin"; metadata_.version = "1.0.0"; @@ -29,31 +30,28 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { } // IPlugin interface - bolt::PluginMetadata getMetadata() const override { - return metadata_; - } + bolt::PluginMetadata getMetadata() const override { return metadata_; } bool initialize(bolt::PluginContext* context) override { context_ = context; state_ = bolt::PluginState::Initialized; - + if (context_) { context_->logInfo("C++ Language Plugin initialized"); - + // Subscribe to relevant events - context_->subscribeToEvent(bolt::PluginEventType::DocumentOpened, - [this](const bolt::PluginEvent& event) { - try { - std::string filePath = event.getData("filePath"); - if (canHandleFileType(getFileExtension(filePath))) { - context_->logInfo("C++ plugin handling file: " + filePath); - } - } catch (const std::exception& e) { - context_->logError("Error handling document opened event: " + std::string(e.what())); + context_->subscribeToEvent(bolt::PluginEventType::DocumentOpened, [this](const bolt::PluginEvent& event) { + try { + std::string filePath = event.getData("filePath"); + if (canHandleFileType(getFileExtension(filePath))) { + context_->logInfo("C++ plugin handling file: " + filePath); } - }); + } catch (const std::exception& e) { + context_->logError("Error handling document opened event: " + std::string(e.what())); + } + }); } - + return true; } @@ -89,14 +87,14 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { context_->logInfo("Advanced completions " + std::string(enabled ? "enabled" : "disabled")); } } - + if (config.find("maxCompletions") != config.end()) { int maxCompletions = std::any_cast(config.at("maxCompletions")); if (context_) { context_->logInfo("Max completions set to: " + std::to_string(maxCompletions)); } } - + return true; } catch (const std::exception& e) { if (context_) { @@ -134,7 +132,7 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) override { std::vector completions; - + // Basic C++ completions completions.push_back("std::"); completions.push_back("auto"); @@ -163,7 +161,7 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { completions.push_back("requires"); completions.push_back("noexcept"); completions.push_back("nullptr"); - + // STL containers completions.push_back("std::vector"); completions.push_back("std::string"); @@ -177,14 +175,14 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { completions.push_back("std::queue"); completions.push_back("std::stack"); completions.push_back("std::priority_queue"); - + // Smart pointers completions.push_back("std::unique_ptr"); completions.push_back("std::shared_ptr"); completions.push_back("std::weak_ptr"); completions.push_back("std::make_unique"); completions.push_back("std::make_shared"); - + // Common algorithms completions.push_back("std::for_each"); completions.push_back("std::find"); @@ -194,30 +192,30 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { completions.push_back("std::copy"); completions.push_back("std::move"); completions.push_back("std::forward"); - + return completions; } std::vector getDiagnostics(const std::string& filePath, const std::string& content) override { std::vector diagnostics; - + // Basic syntax checks (simplified) if (content.find("#include") == std::string::npos && content.find("int main") != std::string::npos) { diagnostics.push_back("Warning: No includes found but main function detected"); } - + // Check for common issues if (content.find("using namespace std;") != std::string::npos) { diagnostics.push_back("Info: Consider avoiding 'using namespace std;' in headers"); } - + return diagnostics; } std::string formatCode(const std::string& code) override { // Basic formatting (in a real implementation, this would use a proper formatter) std::string formatted = code; - + // Simple formatting rules // Add space after keywords std::vector keywords = {"if", "for", "while", "switch"}; @@ -228,7 +226,7 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { pos += keyword.length() + 2; } } - + return formatted; } @@ -237,7 +235,7 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { return "C++ symbol information would appear here"; } -private: + private: std::string getFileExtension(const std::string& filePath) const { size_t lastDot = filePath.find_last_of('.'); if (lastDot != std::string::npos && lastDot < filePath.length() - 1) { @@ -249,16 +247,16 @@ class CppLanguagePlugin : public bolt::ILanguagePlugin { // Plugin export functions (required for dynamic loading) extern "C" { - bolt::IPlugin* createPlugin() { - return new CppLanguagePlugin(); - } - - void destroyPlugin(bolt::IPlugin* plugin) { - delete plugin; - } +bolt::IPlugin* createPlugin() { + return new CppLanguagePlugin(); +} + +void destroyPlugin(bolt::IPlugin* plugin) { + delete plugin; +} } // For static linking, provide a factory function std::shared_ptr createCppLanguagePlugin() { return std::make_shared(); -} \ No newline at end of file +} diff --git a/include/bolt/ai/ai_completion_provider.hpp b/include/bolt/ai/ai_completion_provider.hpp index dfb1e357..7e736771 100644 --- a/include/bolt/ai/ai_completion_provider.hpp +++ b/include/bolt/ai/ai_completion_provider.hpp @@ -1,10 +1,11 @@ -#ifndef AI_COMPLETION_PROVIDER_HPP -#define AI_COMPLETION_PROVIDER_HPP +#ifndef BOLT_AI_AI_COMPLETION_PROVIDER_HPP_ +#define BOLT_AI_AI_COMPLETION_PROVIDER_HPP_ +#include +#include #include #include -#include -#include + #include "bolt/editor/code_completion.hpp" namespace bolt { @@ -19,70 +20,64 @@ struct CodeContext { }; class AICompletionProvider { -public: + public: virtual ~AICompletionProvider() = default; - + // Generate AI-powered code completions - virtual std::vector generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions = 10 - ) = 0; - + virtual std::vector generateCompletions(const CodeContext& context, const std::string& prefix, + size_t maxSuggestions = 10) = 0; + // Check if the provider is ready/initialized virtual bool isReady() const = 0; - + // Initialize the provider (load models, etc.) virtual bool initialize() = 0; - + // Shutdown and cleanup virtual void shutdown() = 0; }; // Mock implementation for testing/demo purposes class MockAICompletionProvider : public AICompletionProvider { -private: + private: bool initialized_ = false; - -public: - std::vector generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions = 10 - ) override; - + + public: + std::vector generateCompletions(const CodeContext& context, const std::string& prefix, + size_t maxSuggestions = 10) override; + bool isReady() const override { return initialized_; } - bool initialize() override { initialized_ = true; return true; } + bool initialize() override { + initialized_ = true; + return true; + } void shutdown() override { initialized_ = false; } }; // AI-powered code completion engine that integrates with existing CodeCompletionEngine class AICodeCompletionEngine { -private: + private: std::unique_ptr provider_; CodeCompletionEngine& baseEngine_; bool aiEnabled_ = true; - -public: + + public: AICodeCompletionEngine(); - + // Set the AI provider void setProvider(std::unique_ptr provider); - + // Get completions with AI integration - std::vector getCompletions( - const CodeContext& context, - const std::string& prefix, - size_t limit = 10 - ); - + std::vector getCompletions(const CodeContext& context, const std::string& prefix, + size_t limit = 10); + // Enable/disable AI completions void setAIEnabled(bool enabled) { aiEnabled_ = enabled; } bool isAIEnabled() const { return aiEnabled_; } - + // Check if AI provider is ready bool isAIReady() const; - + // Singleton access static AICodeCompletionEngine& getInstance() { static AICodeCompletionEngine instance; @@ -90,6 +85,6 @@ class AICodeCompletionEngine { } }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_AI_AI_COMPLETION_PROVIDER_HPP_ diff --git a/include/bolt/ai/ai_config_manager.hpp b/include/bolt/ai/ai_config_manager.hpp index aaa545ac..aa9e1b42 100644 --- a/include/bolt/ai/ai_config_manager.hpp +++ b/include/bolt/ai/ai_config_manager.hpp @@ -1,8 +1,8 @@ -#ifndef BOLT_AI_CONFIG_MANAGER_HPP -#define BOLT_AI_CONFIG_MANAGER_HPP +#ifndef BOLT_AI_AI_CONFIG_MANAGER_HPP_ +#define BOLT_AI_AI_CONFIG_MANAGER_HPP_ -#include #include +#include namespace bolt { namespace ai { @@ -12,14 +12,8 @@ namespace ai { * Manages configuration settings for AI providers and models. */ class AIConfigManager { -public: - AIConfigManager() - : apiKey_("") - , maxTokens_(4096) - , temperature_(0.7) - , provider_("local") - , modelName_("default") - {} + public: + AIConfigManager() : apiKey_(""), maxTokens_(4096), temperature_(0.7), provider_("local"), modelName_("default") {} // API Key management void setApiKey(const std::string& key) { apiKey_ = key; } @@ -42,9 +36,7 @@ class AIConfigManager { std::string getModelName() const { return modelName_; } // Custom options - void setOption(const std::string& key, const std::string& value) { - options_[key] = value; - } + void setOption(const std::string& key, const std::string& value) { options_[key] = value; } std::string getOption(const std::string& key, const std::string& defaultValue = "") const { auto it = options_.find(key); @@ -52,11 +44,9 @@ class AIConfigManager { } // Validation - bool isValid() const { - return maxTokens_ > 0 && temperature_ >= 0.0 && temperature_ <= 2.0; - } + bool isValid() const { return maxTokens_ > 0 && temperature_ >= 0.0 && temperature_ <= 2.0; } -private: + private: std::string apiKey_; int maxTokens_; double temperature_; @@ -65,7 +55,7 @@ class AIConfigManager { std::map options_; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // BOLT_AI_CONFIG_MANAGER_HPP +#endif // BOLT_AI_AI_CONFIG_MANAGER_HPP_ diff --git a/include/bolt/ai/ai_http_client.hpp b/include/bolt/ai/ai_http_client.hpp index 3c676f13..d1964865 100644 --- a/include/bolt/ai/ai_http_client.hpp +++ b/include/bolt/ai/ai_http_client.hpp @@ -1,7 +1,9 @@ #pragma once -#include #include #include +#include +#include + #include "bolt/drawkern/ai_integration.hpp" namespace bolt { @@ -23,18 +25,18 @@ struct AIHttpConfig { std::string api_key = ""; std::string model_name = "gpt-3.5-turbo"; APIType api_type = APIType::LLAMA_CPP; - + // Request parameters int max_tokens = 512; float temperature = 0.7f; float top_p = 0.9f; std::string system_prompt = "You are a helpful AI programming assistant."; - + // Connection settings int timeout_seconds = 30; bool verify_ssl = true; bool use_streaming = false; - + // Retry settings int max_retries = 3; int retry_delay_ms = 1000; @@ -50,23 +52,23 @@ struct HttpRequest { // HTTP client for AI services class AIHttpClient { -public: - AIHttpClient(const AIHttpConfig& config); + public: + explicit AIHttpClient(const AIHttpConfig& config); ~AIHttpClient(); - + // AI inference methods drawkern::AIInferenceResponse chat(const std::string& message, const std::string& session_id); drawkern::AIInferenceResponse complete_code(const std::string& code, const std::string& language); - + // Configuration and testing bool test_connection(); void update_config(const AIHttpConfig& config); const AIHttpConfig& get_config() const { return config_; } - -private: + + private: AIHttpConfig config_; void* curl_; // CURL handle - + // HTTP operations bolt::drawkern::AIInferenceResponse send_request(const HttpRequest& request); HttpRequest create_chat_request(const std::string& message, const std::string& session_id); @@ -76,17 +78,20 @@ class AIHttpClient { // Factory for creating pre-configured HTTP clients class AIHttpClientFactory { -public: + public: // Create clients for popular services - static std::unique_ptr create_openai_client(const std::string& api_key, const std::string& model = "gpt-3.5-turbo"); - static std::unique_ptr create_anthropic_client(const std::string& api_key, const std::string& model = "claude-3-sonnet-20240229"); + static std::unique_ptr create_openai_client(const std::string& api_key, + const std::string& model = "gpt-3.5-turbo"); + static std::unique_ptr create_anthropic_client(const std::string& api_key, + const std::string& model = "claude-3-sonnet-20240229"); static std::unique_ptr create_llama_cpp_client(const std::string& base_url = "http://localhost:8080"); - static std::unique_ptr create_ollama_client(const std::string& base_url = "http://localhost:11434", const std::string& model = "llama2"); + static std::unique_ptr create_ollama_client(const std::string& base_url = "http://localhost:11434", + const std::string& model = "llama2"); static std::unique_ptr create_koboldcpp_client(const std::string& base_url = "http://localhost:5001"); - + // Create client from configuration file static std::unique_ptr create_from_config(const std::string& config_file_path); - + // Detect and suggest configuration static AIHttpConfig detect_local_server(); static std::vector get_recommended_configs(); @@ -94,37 +99,37 @@ class AIHttpClientFactory { // Configuration manager for AI settings class AIConfigManager { -public: + public: AIConfigManager(); ~AIConfigManager(); - + // Configuration management bool load_config(const std::string& config_file = ""); bool save_config(const std::string& config_file = ""); - + // Provider management void add_provider(const std::string& name, const AIHttpConfig& config); void remove_provider(const std::string& name); AIHttpConfig get_provider_config(const std::string& name) const; std::vector list_providers() const; - + // Active provider void set_active_provider(const std::string& name); std::string get_active_provider() const { return active_provider_; } AIHttpConfig get_active_config() const; - + // Test providers std::map test_all_providers(); bool test_provider(const std::string& name); - -private: + + private: std::map providers_; std::string active_provider_; std::string config_file_path_; - + void load_default_providers(); AIHttpConfig create_default_config() const; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/include/bolt/ai/bpe_tokenizer.hpp b/include/bolt/ai/bpe_tokenizer.hpp index ec9755b1..86c4492b 100644 --- a/include/bolt/ai/bpe_tokenizer.hpp +++ b/include/bolt/ai/bpe_tokenizer.hpp @@ -1,61 +1,61 @@ -#ifndef BPE_TOKENIZER_HPP -#define BPE_TOKENIZER_HPP +#ifndef BOLT_AI_BPE_TOKENIZER_HPP_ +#define BOLT_AI_BPE_TOKENIZER_HPP_ +#include #include -#include #include -#include +#include namespace bolt { class BPETokenizer { -public: + public: BPETokenizer() = default; - + // Load vocabulary from token and score arrays bool loadVocabulary(const std::vector& tokens, - const std::vector& scores = std::vector()); - + const std::vector& scores = std::vector()); + // Encode text to token IDs std::vector encode(const std::string& text) const; - + // Decode token IDs to text std::string decode(const std::vector& tokens) const; - + // Vocabulary information int getVocabSize() const { return vocab_size_; } int getBOSToken() const { return bos_token_; } int getEOSToken() const { return eos_token_; } int getPADToken() const { return pad_token_; } int getUNKToken() const { return unk_token_; } - + // Check if loaded bool isLoaded() const { return vocab_size_ > 0; } - + // Get token string by ID std::string getTokenString(int token_id) const; - + // Get token ID by string int getTokenId(const std::string& token) const; - -private: + + private: int vocab_size_ = 0; - int bos_token_ = 1; // Beginning of sequence - int eos_token_ = 2; // End of sequence - int pad_token_ = 0; // Padding token - int unk_token_ = 0; // Unknown token - + int bos_token_ = 1; // Beginning of sequence + int eos_token_ = 2; // End of sequence + int pad_token_ = 0; // Padding token + int unk_token_ = 0; // Unknown token + // Vocabulary mappings std::vector id_to_token_; std::unordered_map token_to_id_; std::vector token_scores_; - + // Helper methods void identifySpecialTokens(); std::vector splitToBytes(const std::string& text) const; std::vector greedyEncode(const std::string& text) const; }; -} // namespace bolt +} // namespace bolt -#endif // BPE_TOKENIZER_HPP +#endif // BOLT_AI_BPE_TOKENIZER_HPP_ diff --git a/include/bolt/ai/direct_gguf_inference.hpp b/include/bolt/ai/direct_gguf_inference.hpp index 85302a41..3e94aba5 100644 --- a/include/bolt/ai/direct_gguf_inference.hpp +++ b/include/bolt/ai/direct_gguf_inference.hpp @@ -1,8 +1,9 @@ #pragma once -#include #include +#include #include + #include "../drawkern/ai_integration.hpp" namespace bolt { @@ -10,47 +11,42 @@ namespace ai { // Direct GGUF file loader and inference engine class DirectGGUFInference { -public: + public: DirectGGUFInference(); ~DirectGGUFInference(); // Load a GGUF model from file bool load_model(const std::string& model_path); - + // Generate text completion - drawkern::AIInferenceResponse generate_text( - const std::string& prompt, - int max_tokens = 100, - float temperature = 0.7f - ); - + drawkern::AIInferenceResponse generate_text(const std::string& prompt, int max_tokens = 100, + float temperature = 0.7f); + // Chat-specific inference with conversation context - drawkern::AIInferenceResponse chat( - const std::string& message, - const std::vector& conversation_history = {} - ); - + drawkern::AIInferenceResponse chat(const std::string& message, + const std::vector& conversation_history = {}); + // Check if model is loaded bool is_loaded() const { return model_loaded_; } - + // Get model info std::string get_model_info() const; - + // Fallback responses for when no model is available drawkern::AIInferenceResponse get_fallback_response(const std::string& input); -private: + private: struct ModelData; std::unique_ptr model_data_; bool model_loaded_; std::string model_path_; - + // Internal text generation std::string generate_internal(const std::string& prompt, int max_tokens, float temperature); - + // Conversation formatting std::string format_chat_prompt(const std::string& message, const std::vector& history); - + // Smart fallback responses std::string get_smart_fallback(const std::string& input); std::string get_coding_help(const std::string& input); @@ -59,19 +55,19 @@ class DirectGGUFInference { // Factory for creating GGUF inference engines class DirectGGUFFactory { -public: + public: // Create from model file static std::unique_ptr create_from_file(const std::string& model_path); - + // Create with auto-detection of available models static std::unique_ptr create_auto_detect(); - + // Find available GGUF models in common locations static std::vector find_available_models(); - + // Download a tiny model for testing (if needed) static bool download_test_model(const std::string& output_path); }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/include/bolt/ai/enhanced_ai_manager.hpp b/include/bolt/ai/enhanced_ai_manager.hpp index b256e743..5b614755 100644 --- a/include/bolt/ai/enhanced_ai_manager.hpp +++ b/include/bolt/ai/enhanced_ai_manager.hpp @@ -1,12 +1,13 @@ #pragma once -#include "ai_http_client.hpp" -#include "direct_gguf_inference.hpp" -#include "../drawkern/ai_integration.hpp" +#include #include #include -#include #include +#include "../drawkern/ai_integration.hpp" +#include "bolt/ai/ai_http_client.hpp" +#include "bolt/ai/direct_gguf_inference.hpp" + namespace bolt { namespace ai { @@ -18,7 +19,7 @@ struct AIStats { float average_inference_time_ms = 0.0f; size_t total_tokens_generated = 0; size_t total_tokens_processed = 0; - + // Provider-specific stats could be added here }; @@ -32,52 +33,52 @@ struct ProviderInfo { // Enhanced AI Manager that combines local models and HTTP clients class EnhancedAIManager { -public: + public: EnhancedAIManager(); ~EnhancedAIManager(); - + // Core AI operations bolt::drawkern::AIInferenceResponse chat(const std::string& message, const std::string& session_id = ""); bolt::drawkern::AIInferenceResponse complete_code(const std::string& code, const std::string& language = "cpp"); bolt::drawkern::AIInferenceResponse analyze_code(const std::string& code, const std::string& language = "cpp"); - + // Provider management bool switch_provider(const std::string& provider_name); bool test_connection(); bool test_all_providers(); void add_provider(const std::string& name, const AIHttpConfig& config); std::vector list_providers() const; - + // Session management void create_session(const std::string& session_id); void destroy_session(const std::string& session_id); std::vector list_sessions() const; std::vector get_session_history(const std::string& session_id) const; void clear_session_history(const std::string& session_id); - + // Statistics and monitoring AIStats get_statistics() const; void reset_statistics(); - + // Configuration void update_config(const AIHttpConfig& config); bool is_ready() const; std::string get_current_provider() const; AIHttpConfig get_current_config() const; - + // GGUF direct file loading bool load_gguf_model(const std::string& model_path); bool has_direct_model() const; std::string get_model_info() const; - + // Auto-detect and load available models bool auto_detect_models(); // RWKV direct file loading (minimal) bool load_rwkv_model(const std::string& model_path); bool has_rwkv_model() const; - -private: + + private: std::unique_ptr http_client_; std::unique_ptr config_manager_; std::unique_ptr direct_inference_; @@ -87,22 +88,22 @@ class EnhancedAIManager { bool use_direct_inference_ = false; bool use_rwkv_direct_ = false; std::string rwkv_model_path_; - + bool initialize_active_provider(); void update_stats(const bolt::drawkern::AIInferenceResponse& response); }; // Auto-detection and setup utilities namespace AutoSetup { - // Detect local AI servers automatically - bool detect_and_setup_local_server(); - - // Print setup instructions for various AI providers - void print_setup_instructions(); - - // Run interactive setup wizard - bool quick_setup_wizard(); -} - -} // namespace ai -} // namespace bolt +// Detect local AI servers automatically +bool detect_and_setup_local_server(); + +// Print setup instructions for various AI providers +void print_setup_instructions(); + +// Run interactive setup wizard +bool quick_setup_wizard(); +} // namespace AutoSetup + +} // namespace ai +} // namespace bolt diff --git a/include/bolt/ai/ggml.hpp b/include/bolt/ai/ggml.hpp index f93097e1..120f94a5 100644 --- a/include/bolt/ai/ggml.hpp +++ b/include/bolt/ai/ggml.hpp @@ -1,5 +1,5 @@ -#ifndef BOLT_AI_GGML_HPP -#define BOLT_AI_GGML_HPP +#ifndef BOLT_AI_GGML_HPP_ +#define BOLT_AI_GGML_HPP_ #include #include @@ -15,7 +15,7 @@ namespace bolt { #ifdef BOLT_HAVE_GGML // Utility functions for working with GGML class GGMLContext { -public: + public: explicit GGMLContext(size_t mem_size) { ggml_init_params params = { .mem_size = mem_size, @@ -27,24 +27,22 @@ class GGMLContext { throw std::runtime_error("Failed to initialize GGML context"); } } - + ~GGMLContext() { if (ctx_) { ggml_free(ctx_); } } - + ggml_context* get() { return ctx_; } - + // Non-copyable GGMLContext(const GGMLContext&) = delete; GGMLContext& operator=(const GGMLContext&) = delete; - + // Movable - GGMLContext(GGMLContext&& other) noexcept : ctx_(other.ctx_) { - other.ctx_ = nullptr; - } - + GGMLContext(GGMLContext&& other) noexcept : ctx_(other.ctx_) { other.ctx_ = nullptr; } + GGMLContext& operator=(GGMLContext&& other) noexcept { if (this != &other) { if (ctx_) { @@ -56,13 +54,13 @@ class GGMLContext { return *this; } -private: + private: ggml_context* ctx_ = nullptr; }; #else // Stub when GGML is not available class GGMLContext { -public: + public: explicit GGMLContext(size_t /*mem_size*/) { throw std::runtime_error("GGML not available - build with ENABLE_LLAMA_CPP=ON"); } @@ -73,6 +71,6 @@ class GGMLContext { }; #endif -} // namespace bolt +} // namespace bolt -#endif // BOLT_AI_GGML_HPP +#endif // BOLT_AI_GGML_HPP_ diff --git a/include/bolt/ai/ggml_loader.hpp b/include/bolt/ai/ggml_loader.hpp index 4d023a66..c7132b7a 100644 --- a/include/bolt/ai/ggml_loader.hpp +++ b/include/bolt/ai/ggml_loader.hpp @@ -1,22 +1,22 @@ -#ifndef GGML_LOADER_HPP -#define GGML_LOADER_HPP -#include +#ifndef BOLT_AI_GGML_LOADER_HPP_ +#define BOLT_AI_GGML_LOADER_HPP_ +#include +#include +#include +#include #include -#include #include -#include -#include -#include +#include namespace bolt { // GGML legacy file format constants -constexpr uint32_t GGML_MAGIC_UNVERSIONED = 0x67676d6c; // "ggml" in little-endian -constexpr uint32_t GGML_MAGIC_GGMF_V1 = 0x67676d66; // "ggmf" in little-endian -constexpr uint32_t GGML_MAGIC_GGJT_V1 = 0x67676a74; // "ggjt" v1 -constexpr uint32_t GGML_MAGIC_GGJT_V2 = 0x67676a74; // "ggjt" v2 -constexpr uint32_t GGML_MAGIC_GGJT_V3 = 0x67676a74; // "ggjt" v3 +constexpr uint32_t GGML_MAGIC_UNVERSIONED = 0x67676d6c; // "ggml" in little-endian +constexpr uint32_t GGML_MAGIC_GGMF_V1 = 0x67676d66; // "ggmf" in little-endian +constexpr uint32_t GGML_MAGIC_GGJT_V1 = 0x67676a74; // "ggjt" v1 +constexpr uint32_t GGML_MAGIC_GGJT_V2 = 0x67676a74; // "ggjt" v2 +constexpr uint32_t GGML_MAGIC_GGJT_V3 = 0x67676a74; // "ggjt" v3 // GGML format versions enum class GGMLFormatVersion { @@ -30,43 +30,53 @@ enum class GGMLFormatVersion { // GGML file type (quantization) enum class GGMLFileType : uint32_t { - F32 = 0, // All weights are float32 - F16 = 1, // All weights are float16 - Q4_0 = 2, // 4-bit quantization, type 0 - Q4_1 = 3, // 4-bit quantization, type 1 - Q5_0 = 6, // 5-bit quantization, type 0 - Q5_1 = 7, // 5-bit quantization, type 1 - Q8_0 = 8, // 8-bit quantization - Q8_1 = 9, // 8-bit quantization, type 1 - Q2_K = 10, // K-quantization, 2-bit - Q3_K = 11, // K-quantization, 3-bit - Q4_K = 12, // K-quantization, 4-bit - Q5_K = 13, // K-quantization, 5-bit - Q6_K = 14, // K-quantization, 6-bit - Q8_K = 15, // K-quantization, 8-bit + F32 = 0, // All weights are float32 + F16 = 1, // All weights are float16 + Q4_0 = 2, // 4-bit quantization, type 0 + Q4_1 = 3, // 4-bit quantization, type 1 + Q5_0 = 6, // 5-bit quantization, type 0 + Q5_1 = 7, // 5-bit quantization, type 1 + Q8_0 = 8, // 8-bit quantization + Q8_1 = 9, // 8-bit quantization, type 1 + Q2_K = 10, // K-quantization, 2-bit + Q3_K = 11, // K-quantization, 3-bit + Q4_K = 12, // K-quantization, 4-bit + Q5_K = 13, // K-quantization, 5-bit + Q6_K = 14, // K-quantization, 6-bit + Q8_K = 15, // K-quantization, 8-bit }; // GGML hyperparameters (architecture-specific) struct GGMLHyperparameters { // Common parameters - uint32_t n_vocab; // Vocabulary size - uint32_t n_embd; // Embedding dimension - uint32_t n_mult; // Multiplier for FFN dimension - uint32_t n_head; // Number of attention heads - uint32_t n_layer; // Number of layers - uint32_t n_rot; // Rotary embedding dimension - uint32_t ftype; // File type (quantization) - + uint32_t n_vocab; // Vocabulary size + uint32_t n_embd; // Embedding dimension + uint32_t n_mult; // Multiplier for FFN dimension + uint32_t n_head; // Number of attention heads + uint32_t n_layer; // Number of layers + uint32_t n_rot; // Rotary embedding dimension + uint32_t ftype; // File type (quantization) + // Optional parameters (model-specific) - uint32_t n_ctx; // Context length - uint32_t n_ff; // Feedforward dimension - uint32_t n_head_kv; // Number of KV heads (for GQA) - float rope_freq_base; // RoPE frequency base - float rope_freq_scale; // RoPE frequency scale - - GGMLHyperparameters() - : n_vocab(0), n_embd(0), n_mult(0), n_head(0), n_layer(0), n_rot(0), ftype(0), - n_ctx(0), n_ff(0), n_head_kv(0), rope_freq_base(10000.0f), rope_freq_scale(1.0f) {} + uint32_t n_ctx; // Context length + uint32_t n_ff; // Feedforward dimension + uint32_t n_head_kv; // Number of KV heads (for GQA) + float rope_freq_base; // RoPE frequency base + float rope_freq_scale; // RoPE frequency scale + + GGMLHyperparameters() + : n_vocab(0), + n_embd(0), + n_mult(0), + n_head(0), + n_layer(0), + n_rot(0), + ftype(0), + n_ctx(0), + n_ff(0), + n_head_kv(0), + rope_freq_base(10000.0f), + rope_freq_scale(1.0f) {} }; // GGML Tensor information @@ -75,8 +85,8 @@ struct GGMLTensorInfo { uint32_t n_dims; std::vector dims; // Note: GGML uses uint32_t for dimensions ggml_type type; - uint64_t offset; // Offset in file - size_t size; // Size in bytes + uint64_t offset; // Offset in file + size_t size; // Size in bytes }; // GGML Vocabulary entry @@ -88,53 +98,53 @@ struct GGMLVocabEntry { /** * @brief Loader for legacy GGML file formats (GGML, GGMF, GGJT) - * + * * This class provides support for loading legacy GGML format model files, * which preceded the GGUF format. It supports: * - Original unversioned GGML format * - GGMF (GGML Format) v1 * - GGJT (GGML with JSON Tokenizer) v1, v2, v3 - * + * * The loader automatically detects the format version and parses accordingly. */ class GGMLLoader { -public: + public: explicit GGMLLoader(const std::string& file_path); ~GGMLLoader(); - + /** * @brief Load and parse the GGML file * @return true if successful, false otherwise */ bool load(); - + /** * @brief Check if file is loaded */ bool isLoaded() const { return loaded_; } - + /** * @brief Get the detected format version */ GGMLFormatVersion getFormatVersion() const { return format_version_; } - + /** * @brief Get hyperparameters */ const GGMLHyperparameters& getHyperparameters() const { return hparams_; } - + /** * @brief Get vocabulary */ const std::vector& getVocabulary() const { return vocabulary_; } - + /** * @brief Tensor access */ bool hasTensor(const std::string& name) const; const GGMLTensorInfo* getTensorInfo(const std::string& name) const; std::vector getTensorNames() const; - + /** * @brief Load tensor data into GGML context * @param ctx GGML context to load tensor into @@ -142,68 +152,68 @@ class GGMLLoader { * @return Pointer to loaded tensor, or nullptr on failure */ ggml_tensor* loadTensor(ggml_context* ctx, const std::string& name); - + /** * @brief Get error message if loading failed */ std::string getError() const { return error_message_; } - + /** * @brief Get file type (quantization method) */ GGMLFileType getFileType() const { return static_cast(hparams_.ftype); } - + /** * @brief Get architecture name (if available) */ std::string getArchitecture() const { return architecture_; } - -private: + + private: std::string file_path_; std::ifstream file_; bool loaded_; std::string error_message_; std::string architecture_; // Model architecture (llama, gpt, etc.) - + // Format information uint32_t magic_; GGMLFormatVersion format_version_; uint32_t format_version_number_; // Numeric version within format - + // Model hyperparameters GGMLHyperparameters hparams_; - + // Vocabulary std::vector vocabulary_; - + // Tensor storage std::unordered_map tensors_; uint64_t tensor_data_offset_; - + // Internal loading methods bool detectFormat(); bool readHeader(); bool readHyperparameters(); bool readVocabulary(); bool readTensorInfo(); - + // Format-specific readers bool readHeaderUnversioned(); bool readHeaderGGMF(); bool readHeaderGGJT(); - + // Utility methods bool readString(std::string& str, uint32_t len); - - template + + template bool readValue(T& value); - + void setError(const std::string& message); - + // Convert GGML file type to ggml_type ggml_type fileTypeToGGMLType(GGMLFileType ftype) const; }; -} // namespace bolt +} // namespace bolt -#endif // GGML_LOADER_HPP +#endif // BOLT_AI_GGML_LOADER_HPP_ diff --git a/include/bolt/ai/ggml_wrapper.hpp b/include/bolt/ai/ggml_wrapper.hpp index 471baf7c..8fb4f99d 100644 --- a/include/bolt/ai/ggml_wrapper.hpp +++ b/include/bolt/ai/ggml_wrapper.hpp @@ -1,14 +1,14 @@ -#ifndef GGML_WRAPPER_HPP -#define GGML_WRAPPER_HPP +#ifndef BOLT_AI_GGML_WRAPPER_HPP_ +#define BOLT_AI_GGML_WRAPPER_HPP_ +#include #include -#include -#include #include +#include #include #include -#include +#include #ifdef BOLT_HAVE_GGML #include @@ -19,17 +19,17 @@ namespace bolt { class GGMLException : public std::runtime_error { -public: + public: explicit GGMLException(const std::string& msg) : std::runtime_error(msg) {} }; #ifdef BOLT_HAVE_GGML class GGMLModel { -public: - GGMLModel(const std::string& path, size_t ctx_size = 2048, int n_threads = -1) - : ctx_size_(ctx_size) - , n_threads_(n_threads == -1 ? static_cast(std::thread::hardware_concurrency()) : n_threads) { + public: + explicit GGMLModel(const std::string& path, size_t ctx_size = 2048, int n_threads = -1) + : ctx_size_(ctx_size), + n_threads_(n_threads == -1 ? static_cast(std::thread::hardware_concurrency()) : n_threads) { context_ = std::make_unique(ctx_size * sizeof(float) * 4); loadModel(path); } @@ -51,7 +51,7 @@ class GGMLModel { void setContext(size_t ctx_size) { ctx_size_ = ctx_size; } void setThreads(int n_threads) { n_threads_ = n_threads; } -private: + private: std::unique_ptr context_; std::string model_path_; size_t ctx_size_; @@ -69,16 +69,15 @@ class GGMLModel { return tokens; } - std::string detokenize(ggml_tensor* /*output*/) { - return "Generated response"; - } - + std::string detokenize(ggml_tensor* /*output*/) { return "Generated response"; } + int argmax(const float* array, size_t size) { return static_cast(std::max_element(array, array + size) - array); } ggml_tensor* runInference(ggml_cgraph* gf, const std::vector& tokens) { - if (tokens.empty()) return nullptr; + if (tokens.empty()) + return nullptr; const int N = static_cast(tokens.size()); auto* result = ggml_new_tensor_1d(context_->get(), GGML_TYPE_F32, N); ggml_build_forward_expand(gf, result); @@ -91,12 +90,12 @@ class GGMLModel { }; class GGMLWrapper { -public: + public: static GGMLWrapper& getInstance() { static GGMLWrapper instance; return instance; } - + void initialize(const std::string& model_path, enum ggml_type quantize_type = GGML_TYPE_F32) { try { model_ = std::make_unique(model_path); @@ -107,29 +106,30 @@ class GGMLWrapper { throw; } } - + void enableRWKV(bool enable = true) { use_rwkv_ = enable; } std::string generateResponse(const std::string& prompt) { - if (!model_) throw GGMLException("Model not initialized"); + if (!model_) + throw GGMLException("Model not initialized"); return model_->generate(prompt); } -private: + private: GGMLWrapper() = default; std::unique_ptr model_; bool use_rwkv_ = false; bool rwkv_initialized_ = false; - + void quantizeModel(enum ggml_type /*target_type*/) {} }; -#else // !BOLT_HAVE_GGML +#else // !BOLT_HAVE_GGML // Stub classes when GGML is not available class GGMLModel { -public: - GGMLModel(const std::string& /*path*/, size_t /*ctx_size*/ = 2048, int /*n_threads*/ = -1) { + public: + explicit GGMLModel(const std::string& /*path*/, size_t /*ctx_size*/ = 2048, int /*n_threads*/ = -1) { throw GGMLException("GGML not available - build with ENABLE_LLAMA_CPP=ON"); } void loadModel(const std::string& /*path*/) {} @@ -139,7 +139,7 @@ class GGMLModel { }; class GGMLWrapper { -public: + public: static GGMLWrapper& getInstance() { static GGMLWrapper instance; return instance; @@ -148,15 +148,14 @@ class GGMLWrapper { throw GGMLException("GGML not available - build with ENABLE_LLAMA_CPP=ON"); } void enableRWKV(bool /*enable*/ = true) {} - std::string generateResponse(const std::string& /*prompt*/) { - throw GGMLException("GGML not available"); - } -private: + std::string generateResponse(const std::string& /*prompt*/) { throw GGMLException("GGML not available"); } + + private: GGMLWrapper() = default; }; -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML -} // namespace bolt +} // namespace bolt -#endif // GGML_WRAPPER_HPP +#endif // BOLT_AI_GGML_WRAPPER_HPP_ diff --git a/include/bolt/ai/gguf_loader.hpp b/include/bolt/ai/gguf_loader.hpp index 7cc786fd..63759282 100644 --- a/include/bolt/ai/gguf_loader.hpp +++ b/include/bolt/ai/gguf_loader.hpp @@ -1,13 +1,13 @@ -#ifndef GGUF_LOADER_HPP -#define GGUF_LOADER_HPP +#ifndef BOLT_AI_GGUF_LOADER_HPP_ +#define BOLT_AI_GGUF_LOADER_HPP_ +#include +#include +#include #include -#include #include -#include #include -#include -#include +#include #ifdef BOLT_HAVE_GGML #include @@ -16,29 +16,33 @@ namespace bolt { // GGUF file format constants -constexpr uint32_t GGUF_MAGIC = 0x46554747; // "GGUF" in little-endian +constexpr uint32_t GGUF_MAGIC = 0x46554747; // "GGUF" in little-endian constexpr uint32_t GGUF_VERSION_V2 = 2; constexpr uint32_t GGUF_VERSION_V3 = 3; // GGUF value types enum class GGUFValueType : uint32_t { - UINT8 = 0, INT8 = 1, UINT16 = 2, INT16 = 3, - UINT32 = 4, INT32 = 5, FLOAT32 = 6, BOOL = 7, - STRING = 8, ARRAY = 9, UINT64 = 10, INT64 = 11, FLOAT64 = 12, + UINT8 = 0, + INT8 = 1, + UINT16 = 2, + INT16 = 3, + UINT32 = 4, + INT32 = 5, + FLOAT32 = 6, + BOOL = 7, + STRING = 8, + ARRAY = 9, + UINT64 = 10, + INT64 = 11, + FLOAT64 = 12, }; // Metadata value variant -using MetadataValue = std::variant< - uint8_t, int8_t, uint16_t, int16_t, - uint32_t, int32_t, uint64_t, int64_t, - float, double, bool, std::string, - std::vector, std::vector, - std::vector, std::vector, - std::vector, std::vector, - std::vector, std::vector, - std::vector, std::vector, - std::vector, std::vector ->; +using MetadataValue = + std::variant, std::vector, std::vector, std::vector, + std::vector, std::vector, std::vector, std::vector, + std::vector, std::vector, std::vector, std::vector>; #ifdef BOLT_HAVE_GGML @@ -54,69 +58,71 @@ struct TensorInfo { // GGUF Loader class class GGUFLoader { -public: + public: explicit GGUFLoader(const std::string& file_path); ~GGUFLoader(); - + bool load(); bool isLoaded() const { return loaded_; } - + bool hasMetadata(const std::string& key) const; MetadataValue getMetadata(const std::string& key) const; - + std::string getMetadataString(const std::string& key, const std::string& default_value = "") const; int64_t getMetadataInt(const std::string& key, int64_t default_value = 0) const; double getMetadataFloat(const std::string& key, double default_value = 0.0) const; bool getMetadataBool(const std::string& key, bool default_value = false) const; std::vector getMetadataStringArray(const std::string& key) const; std::vector getMetadataFloatArray(const std::string& key) const; - + bool hasTensor(const std::string& name) const; const TensorInfo* getTensorInfo(const std::string& name) const; ggml_tensor* loadTensor(ggml_context* ctx, const std::string& name); std::vector getTensorNames() const; - + uint32_t getVersion() const { return version_; } uint64_t getTensorCount() const { return tensor_count_; } uint64_t getMetadataCount() const { return metadata_kv_count_; } - + int getNumLayers() const; int getEmbedDim() const; int getVocabSize() const; std::string getArchitecture() const; - + std::string getError() const { return error_message_; } - -private: + + private: std::string file_path_; std::ifstream file_; bool loaded_; std::string error_message_; - + uint32_t magic_; uint32_t version_; uint64_t tensor_count_; uint64_t metadata_kv_count_; - + std::unordered_map metadata_; std::unordered_map tensors_; uint64_t tensor_data_offset_; uint64_t alignment_; - + bool readHeader(); bool readMetadata(); bool readTensorInfo(); bool readString(std::string& str); bool readMetadataValue(GGUFValueType type, MetadataValue& value); - - template bool readValue(T& value); - template bool readArray(std::vector& arr, uint64_t count); - + + template + bool readValue(T& value); + template + bool readArray(std::vector& arr, uint64_t count); + void setError(const std::string& message); uint64_t alignOffset(uint64_t offset) const; }; -#else // !BOLT_HAVE_GGML +#else // !BOLT_HAVE_GGML // Stub TensorInfo when GGML is not available struct TensorInfo { @@ -130,44 +136,46 @@ struct TensorInfo { // Stub GGUFLoader when GGML is not available class GGUFLoader { -public: + public: explicit GGUFLoader(const std::string& /*file_path*/) : loaded_(false) {} ~GGUFLoader() = default; - + bool load() { return false; } bool isLoaded() const { return false; } - + bool hasMetadata(const std::string& /*key*/) const { return false; } MetadataValue getMetadata(const std::string& /*key*/) const { return uint8_t(0); } - - std::string getMetadataString(const std::string& /*key*/, const std::string& default_value = "") const { return default_value; } + + std::string getMetadataString(const std::string& /*key*/, const std::string& default_value = "") const { + return default_value; + } int64_t getMetadataInt(const std::string& /*key*/, int64_t default_value = 0) const { return default_value; } double getMetadataFloat(const std::string& /*key*/, double default_value = 0.0) const { return default_value; } bool getMetadataBool(const std::string& /*key*/, bool default_value = false) const { return default_value; } std::vector getMetadataStringArray(const std::string& /*key*/) const { return {}; } std::vector getMetadataFloatArray(const std::string& /*key*/) const { return {}; } - + bool hasTensor(const std::string& /*name*/) const { return false; } const TensorInfo* getTensorInfo(const std::string& /*name*/) const { return nullptr; } std::vector getTensorNames() const { return {}; } - + uint32_t getVersion() const { return 0; } uint64_t getTensorCount() const { return 0; } uint64_t getMetadataCount() const { return 0; } - + int getNumLayers() const { return 0; } int getEmbedDim() const { return 0; } int getVocabSize() const { return 0; } std::string getArchitecture() const { return ""; } - + std::string getError() const { return "GGML not available"; } - -private: + + private: bool loaded_; }; -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML -} // namespace bolt +} // namespace bolt -#endif // GGUF_LOADER_HPP +#endif // BOLT_AI_GGUF_LOADER_HPP_ diff --git a/include/bolt/ai/gpu_acceleration.hpp b/include/bolt/ai/gpu_acceleration.hpp index 0f3b3d25..6d82f9a3 100644 --- a/include/bolt/ai/gpu_acceleration.hpp +++ b/include/bolt/ai/gpu_acceleration.hpp @@ -1,17 +1,17 @@ -#ifndef BOLT_GPU_ACCELERATION_HPP -#define BOLT_GPU_ACCELERATION_HPP +#ifndef BOLT_AI_GPU_ACCELERATION_HPP_ +#define BOLT_AI_GPU_ACCELERATION_HPP_ #include -#include -#include -#include #include +#include +#include #include +#include #ifdef BOLT_HAVE_GGML -#include #include #include +#include // Optional GPU backend headers (conditionally included based on availability) #ifdef GGML_USE_CUDA @@ -25,7 +25,7 @@ #ifdef GGML_USE_VULKAN #include #endif -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML namespace bolt { namespace ai { @@ -34,11 +34,11 @@ namespace ai { * Enum for GPU backend types */ enum class GPUBackendType { - CPU, // Fallback CPU processing - CUDA, // NVIDIA CUDA - OpenCL, // Cross-platform OpenCL - Vulkan, // Modern Vulkan compute - Metal // Apple Metal (future) + CPU, // Fallback CPU processing + CUDA, // NVIDIA CUDA + OpenCL, // Cross-platform OpenCL + Vulkan, // Modern Vulkan compute + Metal // Apple Metal (future) }; /** @@ -59,12 +59,10 @@ struct GPUDeviceInfo { */ struct GPUConfig { GPUBackendType preferredBackend = GPUBackendType::CPU; - std::vector fallbackBackends = { - GPUBackendType::CPU - }; + std::vector fallbackBackends = {GPUBackendType::CPU}; int preferredDeviceId = 0; bool enableAutomaticFallback = true; - size_t minMemoryRequirement = 1024 * 1024 * 1024; // 1GB minimum + size_t minMemoryRequirement = 1024 * 1024 * 1024; // 1GB minimum bool enableMemoryOptimization = true; bool enableAsynchronousCompute = true; }; @@ -74,24 +72,24 @@ struct GPUConfig { * GPU memory manager for efficient allocation and deallocation */ class GPUMemoryManager { -public: + public: GPUMemoryManager(ggml_backend_t backend, ggml_backend_buffer_type_t bufferType); ~GPUMemoryManager(); // Memory allocation ggml_backend_buffer_t allocateBuffer(size_t size); void deallocateBuffer(ggml_backend_buffer_t buffer); - + // Memory monitoring size_t getTotalMemory() const; size_t getUsedMemory() const; size_t getAvailableMemory() const; - + // Memory optimization void optimizeMemoryUsage(); void defragmentMemory(); -private: + private: ggml_backend_t backend_; ggml_backend_buffer_type_t bufferType_; std::vector allocatedBuffers_; @@ -103,37 +101,37 @@ class GPUMemoryManager { * Main GPU acceleration manager */ class GPUAccelerationManager { -public: + public: static GPUAccelerationManager& getInstance(); - + // Initialization and configuration bool initialize(const GPUConfig& config = GPUConfig{}); void shutdown(); bool isInitialized() const { return initialized_; } - + // Device detection and selection std::vector detectAvailableDevices(); bool selectDevice(GPUBackendType backendType, int deviceId = 0); GPUDeviceInfo getCurrentDevice() const; - + // Backend management ggml_backend_t getBackend() const { return currentBackend_; } GPUBackendType getCurrentBackendType() const { return currentBackendType_; } ggml_backend_buffer_type_t getBufferType() const { return currentBufferType_; } - + // Memory management GPUMemoryManager& getMemoryManager() { return *memoryManager_; } - + // Model operations bool loadModelToGPU(ggml_context* ctx, const std::vector& tensors); bool transferTensorToGPU(ggml_tensor* tensor); bool transferTensorToCPU(ggml_tensor* tensor); - + // Compute operations bool computeGraph(ggml_cgraph* graph); bool computeGraphAsync(ggml_cgraph* graph); void synchronize(); - + // Performance monitoring struct PerformanceStats { size_t totalComputeOps = 0; @@ -143,51 +141,51 @@ class GPUAccelerationManager { double averageOpsPerSecond = 0.0; double peakMemoryUsage = 0.0; }; - + PerformanceStats getPerformanceStats() const { return performanceStats_; } void resetPerformanceStats(); - + // Configuration management void updateConfig(const GPUConfig& config); GPUConfig getConfig() const { return config_; } -private: + private: GPUAccelerationManager() = default; ~GPUAccelerationManager() = default; - + // Prevent copying GPUAccelerationManager(const GPUAccelerationManager&) = delete; GPUAccelerationManager& operator=(const GPUAccelerationManager&) = delete; - + // Backend initialization helpers bool initializeCUDA(int deviceId = 0); bool initializeOpenCL(); bool initializeVulkan(int deviceId = 0); bool initializeCPU(); - + // Device detection helpers std::vector detectCUDADevices(); std::vector detectOpenCLDevices(); std::vector detectVulkanDevices(); - + // Utility functions bool isBackendAvailable(GPUBackendType backendType); std::string backendTypeToString(GPUBackendType backendType); - + // Member variables bool initialized_ = false; GPUConfig config_; - + ggml_backend_t currentBackend_ = nullptr; GPUBackendType currentBackendType_ = GPUBackendType::CPU; ggml_backend_buffer_type_t currentBufferType_ = nullptr; GPUDeviceInfo currentDevice_; - + std::unique_ptr memoryManager_; std::vector availableDevices_; - + PerformanceStats performanceStats_; - + // Thread safety mutable std::mutex mutex_; }; @@ -197,41 +195,41 @@ class GPUAccelerationManager { * Extends the existing GGMLModel with GPU capabilities */ class GPUAcceleratedModel { -public: - GPUAcceleratedModel(const std::string& modelPath, const GPUConfig& config = GPUConfig{}); + public: + explicit GPUAcceleratedModel(const std::string& modelPath, const GPUConfig& config = GPUConfig{}); ~GPUAcceleratedModel(); - + // Model loading and initialization bool loadModel(const std::string& path); bool isLoaded() const { return modelLoaded_; } bool isGPUAccelerated() const { return gpuAccelerated_; } - + // Inference operations std::string generate(const std::string& prompt, size_t maxTokens = 100); std::vector generateEmbedding(const std::string& input); - + // Configuration void setMaxContextSize(size_t contextSize) { maxContextSize_ = contextSize; } void setThreadCount(int threads) { threadCount_ = threads; } void enableGPUOffloading(bool enable) { gpuOffloadingEnabled_ = enable; } - + // Performance monitoring GPUAccelerationManager::PerformanceStats getPerformanceStats() const; -private: + private: // Model state - std::unique_ptr context_{nullptr, ggml_free}; + std::unique_ptr context_{nullptr, ggml_free}; std::vector modelTensors_; std::string modelPath_; bool modelLoaded_ = false; bool gpuAccelerated_ = false; bool gpuOffloadingEnabled_ = true; - + // Configuration GPUConfig gpuConfig_; size_t maxContextSize_ = 2048; int threadCount_ = -1; - + // Helper methods bool setupGPUContext(); bool loadModelWeights(); @@ -240,11 +238,11 @@ class GPUAcceleratedModel { std::string detokenize(const std::vector& tokens); }; -#else // !BOLT_HAVE_GGML +#else // !BOLT_HAVE_GGML // Stub classes when GGML is not available class GPUAccelerationManager { -public: + public: static GPUAccelerationManager& getInstance() { static GPUAccelerationManager instance; return instance; @@ -255,7 +253,7 @@ class GPUAccelerationManager { std::vector detectAvailableDevices() { return {}; } GPUBackendType getCurrentBackendType() const { return GPUBackendType::CPU; } GPUDeviceInfo getCurrentDevice() const { return {}; } - + struct PerformanceStats { size_t totalComputeOps = 0; double totalComputeTime = 0.0; @@ -267,62 +265,63 @@ class GPUAccelerationManager { PerformanceStats getPerformanceStats() const { return {}; } void resetPerformanceStats() {} GPUConfig getConfig() const { return {}; } -private: + + private: GPUAccelerationManager() = default; }; -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML /** * Exception class for GPU acceleration errors */ class GPUAccelerationException : public std::runtime_error { -public: + public: explicit GPUAccelerationException(const std::string& message, GPUBackendType failedBackend) : std::runtime_error(message), failedBackend_(failedBackend) {} - + GPUBackendType getFailedBackend() const { return failedBackend_; } -private: + private: GPUBackendType failedBackend_; }; // Utility functions namespace gpu_utils { - /** - * Check if GPU acceleration is available on this system - */ - inline bool isGPUAccelerationAvailable() { +/** + * Check if GPU acceleration is available on this system + */ +inline bool isGPUAccelerationAvailable() { #ifdef BOLT_HAVE_GGML - return true; + return true; #else - return false; + return false; #endif - } - - /** - * Get recommended GPU configuration for this system - */ - inline GPUConfig getRecommendedGPUConfig() { - return GPUConfig{}; - } - - /** - * Benchmark different GPU backends and return the best performing one - */ - inline GPUBackendType benchmarkGPUBackends() { - return GPUBackendType::CPU; - } - - /** - * Estimate memory requirements for a model - */ - inline size_t estimateModelMemoryRequirements(const std::string& /*modelPath*/) { - return 0; - } } -} // namespace ai -} // namespace bolt +/** + * Get recommended GPU configuration for this system + */ +inline GPUConfig getRecommendedGPUConfig() { + return GPUConfig{}; +} + +/** + * Benchmark different GPU backends and return the best performing one + */ +inline GPUBackendType benchmarkGPUBackends() { + return GPUBackendType::CPU; +} + +/** + * Estimate memory requirements for a model + */ +inline size_t estimateModelMemoryRequirements(const std::string& /*modelPath*/) { + return 0; +} +} // namespace gpu_utils + +} // namespace ai +} // namespace bolt -#endif // BOLT_GPU_ACCELERATION_HPP +#endif // BOLT_AI_GPU_ACCELERATION_HPP_ diff --git a/include/bolt/ai/i_rag_manager.hpp b/include/bolt/ai/i_rag_manager.hpp index 6600c360..bac3be1b 100644 --- a/include/bolt/ai/i_rag_manager.hpp +++ b/include/bolt/ai/i_rag_manager.hpp @@ -1,9 +1,9 @@ -#ifndef I_RAG_MANAGER_HPP -#define I_RAG_MANAGER_HPP +#ifndef BOLT_AI_I_RAG_MANAGER_HPP_ +#define BOLT_AI_I_RAG_MANAGER_HPP_ +#include #include #include -#include namespace bolt { namespace ai { @@ -12,16 +12,15 @@ namespace ai { * Generic RAG result structure */ struct RAGResult { - std::string id; // Unique identifier - std::string content; // Retrieved content - float score; // Relevance/similarity score - std::string source; // Source identifier - std::string metadata; // Additional metadata (JSON format) - + std::string id; // Unique identifier + std::string content; // Retrieved content + float score; // Relevance/similarity score + std::string source; // Source identifier + std::string metadata; // Additional metadata (JSON format) + RAGResult() : score(0.0f) {} - - RAGResult(const std::string& id_, const std::string& content_, - float score_, const std::string& source_) + + RAGResult(const std::string& id_, const std::string& content_, float score_, const std::string& source_) : id(id_), content(content_), score(score_), source(source_) {} }; @@ -30,16 +29,16 @@ struct RAGResult { * Ensures consistent API across different RAG backends */ class IRAGManager { -public: + public: virtual ~IRAGManager() = default; - + /** * Initialize the RAG manager with a model * @param model_path Path to the model file (optional) * @return true if initialization succeeded */ virtual bool initialize(const std::string& model_path = "") = 0; - + /** * Query the RAG system * @param query The query string @@ -47,20 +46,20 @@ class IRAGManager { * @return Vector of RAG results */ virtual std::vector query(const std::string& query, int top_k = 5) = 0; - + /** * Ingest content into the RAG system * @param content The content to ingest * @param id Unique identifier for the content */ virtual void ingest(const std::string& content, const std::string& id) = 0; - + /** * Get the name of this RAG manager * @return Name identifier (e.g., "NarrativeRAG", "TemporalRAG") */ virtual std::string getName() const = 0; - + /** * Check if the manager is initialized * @return true if initialized @@ -68,7 +67,7 @@ class IRAGManager { virtual bool isInitialized() const = 0; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // I_RAG_MANAGER_HPP +#endif // BOLT_AI_I_RAG_MANAGER_HPP_ diff --git a/include/bolt/ai/koboldcpp_provider.hpp b/include/bolt/ai/koboldcpp_provider.hpp index 5dc17e5b..eaba8801 100644 --- a/include/bolt/ai/koboldcpp_provider.hpp +++ b/include/bolt/ai/koboldcpp_provider.hpp @@ -1,12 +1,14 @@ -#ifndef BOLT_AI_KOBOLDCPP_PROVIDER_HPP -#define BOLT_AI_KOBOLDCPP_PROVIDER_HPP +#ifndef BOLT_AI_KOBOLDCPP_PROVIDER_HPP_ +#define BOLT_AI_KOBOLDCPP_PROVIDER_HPP_ -#include "bolt/ai/ai_completion_provider.hpp" +#include +#include +#include #include +#include #include -#include -#include -#include + +#include "bolt/ai/ai_completion_provider.hpp" namespace bolt { namespace ai { @@ -19,7 +21,7 @@ namespace ai { */ struct KoboldCppConfig { std::string endpoint = "http://localhost:5001"; - + // Generation parameters float temperature = 0.7f; float top_p = 0.9f; @@ -29,13 +31,13 @@ struct KoboldCppConfig { int max_tokens = 200; int max_context_length = 4096; std::vector stop_sequences; - + // Connection settings int timeout_seconds = 30; int max_retries = 3; int retry_delay_ms = 500; bool use_streaming = false; - + // API selection enum class APIMode { OPENAI_COMPATIBLE, // /v1/completions, /v1/chat/completions @@ -92,43 +94,40 @@ using StreamCallback = std::function; * - Configurable generation parameters */ class KoboldCppProvider : public AICompletionProvider { -public: + public: KoboldCppProvider(); explicit KoboldCppProvider(const KoboldCppConfig& config); explicit KoboldCppProvider(const std::string& endpoint); ~KoboldCppProvider() override; // โ”€โ”€ AICompletionProvider interface โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - std::vector generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions = 10 - ) override; - + std::vector generateCompletions(const CodeContext& context, const std::string& prefix, + size_t maxSuggestions = 10) override; + bool isReady() const override; bool initialize() override; void shutdown() override; // โ”€โ”€ KoboldCpp-specific methods โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - + /// Raw text completion via /v1/completions or /api/v1/generate KoboldCppResponse complete(const std::string& prompt); KoboldCppResponse complete(const std::string& prompt, int max_tokens); - + /// Chat completion via /v1/chat/completions KoboldCppResponse chat(const std::string& message); KoboldCppResponse chat(const std::string& message, const std::string& system_prompt); - KoboldCppResponse chat(const std::vector>& messages); - + KoboldCppResponse chat(const std::vector>& messages); + /// Streaming completion (calls callback for each token) bool complete_streaming(const std::string& prompt, StreamCallback callback); bool chat_streaming(const std::string& message, StreamCallback callback); - + /// Server health and info bool test_connection(); KoboldCppServerInfo get_server_info(); bool is_model_loaded(); - + /// Configuration void set_config(const KoboldCppConfig& config); const KoboldCppConfig& get_config() const { return config_; } @@ -137,28 +136,28 @@ class KoboldCppProvider : public AICompletionProvider { void set_max_tokens(int tokens) { config_.max_tokens = tokens; } void set_api_mode(KoboldCppConfig::APIMode mode) { config_.api_mode = mode; } -private: + private: KoboldCppConfig config_; bool initialized_ = false; KoboldCppConfig::APIMode detected_mode_ = KoboldCppConfig::APIMode::OPENAI_COMPATIBLE; - + // Internal HTTP helpers KoboldCppResponse send_openai_completion(const std::string& prompt, int max_tokens); - KoboldCppResponse send_openai_chat(const std::vector>& messages); + KoboldCppResponse send_openai_chat(const std::vector>& messages); KoboldCppResponse send_koboldai_generate(const std::string& prompt, int max_tokens); std::string http_post(const std::string& url, const std::string& json_body); std::string http_get(const std::string& url); - + // Code completion helpers std::string build_code_prompt(const CodeContext& context, const std::string& prefix) const; std::vector parse_completions(const std::string& response_text, size_t max) const; std::string infer_kind(const std::string& text) const; - + // Auto-detection bool detect_api_mode(); }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // BOLT_AI_KOBOLDCPP_PROVIDER_HPP +#endif // BOLT_AI_KOBOLDCPP_PROVIDER_HPP_ diff --git a/include/bolt/ai/llama_completion_provider.hpp b/include/bolt/ai/llama_completion_provider.hpp index f75f88db..2f867a10 100644 --- a/include/bolt/ai/llama_completion_provider.hpp +++ b/include/bolt/ai/llama_completion_provider.hpp @@ -1,10 +1,12 @@ -#ifndef LLAMA_COMPLETION_PROVIDER_HPP -#define LLAMA_COMPLETION_PROVIDER_HPP +#ifndef BOLT_AI_LLAMA_COMPLETION_PROVIDER_HPP_ +#define BOLT_AI_LLAMA_COMPLETION_PROVIDER_HPP_ -#include "bolt/ai/ai_completion_provider.hpp" -#include "bolt/ai/direct_gguf_inference.hpp" #include #include +#include + +#include "bolt/ai/ai_completion_provider.hpp" +#include "bolt/ai/direct_gguf_inference.hpp" namespace bolt { @@ -13,45 +15,42 @@ namespace bolt { * Provides intelligent code completions using GGUF language models */ class LlamaCompletionProvider : public AICompletionProvider { -private: + private: std::unique_ptr inference_engine_; bool initialized_ = false; std::string model_path_; - + // Configuration float temperature_ = 0.3f; // Lower temperature for more deterministic code int max_tokens_ = 50; // Max tokens per completion - + // Helper methods std::string buildCompletionPrompt(const CodeContext& context, const std::string& prefix) const; std::vector parseCompletionResponse(const std::string& response) const; CompletionItemKind inferCompletionKind(const std::string& completion) const; -public: + public: LlamaCompletionProvider(); explicit LlamaCompletionProvider(const std::string& model_path); ~LlamaCompletionProvider() override = default; - + // AICompletionProvider interface - std::vector generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions = 10 - ) override; - + std::vector generateCompletions(const CodeContext& context, const std::string& prefix, + size_t maxSuggestions = 10) override; + bool isReady() const override { return initialized_; } bool initialize() override; void shutdown() override; - + // Configuration methods void setTemperature(float temp) { temperature_ = temp; } void setMaxTokens(int tokens) { max_tokens_ = tokens; } void setModelPath(const std::string& path) { model_path_ = path; } - + // Model info std::string getModelInfo() const; }; -} // namespace bolt +} // namespace bolt -#endif // LLAMA_COMPLETION_PROVIDER_HPP +#endif // BOLT_AI_LLAMA_COMPLETION_PROVIDER_HPP_ diff --git a/include/bolt/ai/model_loader.hpp b/include/bolt/ai/model_loader.hpp index 8ba50215..27745c12 100644 --- a/include/bolt/ai/model_loader.hpp +++ b/include/bolt/ai/model_loader.hpp @@ -1,92 +1,90 @@ -#ifndef MODEL_LOADER_HPP -#define MODEL_LOADER_HPP +#ifndef BOLT_AI_MODEL_LOADER_HPP_ +#define BOLT_AI_MODEL_LOADER_HPP_ +#include + #include +#include +#include +#include -#include "bolt/ai/gguf_loader.hpp" #include "bolt/ai/ggml_loader.hpp" -#include -#include -#include +#include "bolt/ai/gguf_loader.hpp" namespace bolt { /** * @brief Unified model loader that automatically detects and loads both GGUF and legacy GGML formats - * + * * This class provides a unified interface for loading model files in either: * - GGUF format (current standard) * - Legacy GGML formats (GGML, GGMF, GGJT) - * + * * The loader automatically detects the format by examining the file's magic number * and uses the appropriate parser. */ class ModelLoader { -public: - enum class FormatType { - UNKNOWN, - GGUF, - GGML_LEGACY - }; - + public: + enum class FormatType { UNKNOWN, GGUF, GGML_LEGACY }; + explicit ModelLoader(const std::string& file_path); ~ModelLoader(); - + /** * @brief Load and parse the model file * @return true if successful, false otherwise */ bool load(); - + /** * @brief Check if file is loaded */ bool isLoaded() const { return loaded_; } - + /** * @brief Get the detected format type */ FormatType getFormatType() const { return format_type_; } - + /** * @brief Get format name as string */ std::string getFormatName() const; - + /** * @brief Get model architecture */ std::string getArchitecture() const; - + /** * @brief Get vocabulary size */ uint32_t getVocabSize() const; - + /** * @brief Get embedding dimension */ uint32_t getEmbeddingDim() const; - + /** * @brief Get number of layers */ uint32_t getNumLayers() const; - + /** * @brief Get number of attention heads */ uint32_t getNumHeads() const; - + /** * @brief Check if tensor exists */ bool hasTensor(const std::string& name) const; - + /** * @brief Get list of all tensor names */ std::vector getTensorNames() const; - + /** * @brief Load tensor data into GGML context * @param ctx GGML context to load tensor into @@ -94,47 +92,47 @@ class ModelLoader { * @return Pointer to loaded tensor, or nullptr on failure */ ggml_tensor* loadTensor(ggml_context* ctx, const std::string& name); - + /** * @brief Get error message if loading failed */ std::string getError() const { return error_message_; } - + /** * @brief Get GGUF loader (if format is GGUF) * @return Pointer to GGUF loader, or nullptr if not GGUF format */ GGUFLoader* getGGUFLoader() { return gguf_loader_.get(); } - + /** * @brief Get GGML loader (if format is legacy GGML) * @return Pointer to GGML loader, or nullptr if not GGML format */ GGMLLoader* getGGMLLoader() { return ggml_loader_.get(); } - + /** * @brief Print model information to stdout */ void printModelInfo() const; - -private: + + private: std::string file_path_; bool loaded_; std::string error_message_; FormatType format_type_; - + // Format-specific loaders std::unique_ptr gguf_loader_; std::unique_ptr ggml_loader_; - + /** * @brief Detect file format by reading magic number */ FormatType detectFormat(); - + void setError(const std::string& message); }; -} // namespace bolt +} // namespace bolt -#endif // MODEL_LOADER_HPP +#endif // BOLT_AI_MODEL_LOADER_HPP_ diff --git a/include/bolt/ai/narrative_rag_manager.hpp b/include/bolt/ai/narrative_rag_manager.hpp index 3965291f..c2a71ce1 100644 --- a/include/bolt/ai/narrative_rag_manager.hpp +++ b/include/bolt/ai/narrative_rag_manager.hpp @@ -1,12 +1,14 @@ -#ifndef NARRATIVE_RAG_MANAGER_HPP -#define NARRATIVE_RAG_MANAGER_HPP +#ifndef BOLT_AI_NARRATIVE_RAG_MANAGER_HPP_ +#define BOLT_AI_NARRATIVE_RAG_MANAGER_HPP_ -#include "bolt/ai/vector_database.hpp" -#include "bolt/ai/direct_gguf_inference.hpp" +#include +#include #include +#include #include -#include -#include + +#include "bolt/ai/direct_gguf_inference.hpp" +#include "bolt/ai/vector_database.hpp" namespace bolt { namespace ai { @@ -15,25 +17,25 @@ namespace ai { * Represents a narrative event in the story world */ struct NarrativeEvent { - std::string id; // Unique event ID - std::string description; // Event description - std::vector characters; // Characters involved - std::vector locations; // Locations involved - std::chrono::system_clock::time_point timestamp; // When it occurred - std::string event_type; // Type: action, dialogue, revelation, etc. - int importance; // Importance score (1-10) - std::vector tags; // Semantic tags + std::string id; // Unique event ID + std::string description; // Event description + std::vector characters; // Characters involved + std::vector locations; // Locations involved + std::chrono::system_clock::time_point timestamp; // When it occurred + std::string event_type; // Type: action, dialogue, revelation, etc. + int importance; // Importance score (1-10) + std::vector tags; // Semantic tags }; /** * Configuration for narrative RAG */ struct NarrativeRAGConfig { - int max_retrieved_events = 5; // Max events to retrieve per query - float min_relevance_score = 0.3f; // Minimum relevance threshold - bool prioritize_recent = true; // Weight recent events higher - bool character_aware = true; // Filter by character involvement - int recency_window_hours = 24; // Time window for recency boost + int max_retrieved_events = 5; // Max events to retrieve per query + float min_relevance_score = 0.3f; // Minimum relevance threshold + bool prioritize_recent = true; // Weight recent events higher + bool character_aware = true; // Filter by character involvement + int recency_window_hours = 24; // Time window for recency boost }; /** @@ -41,71 +43,64 @@ struct NarrativeRAGConfig { * Maintains a dynamic "living world" that evolves with the story */ class NarrativeRAGManager { -private: + private: std::unique_ptr inference_engine_; VectorDatabase event_db_; NarrativeRAGConfig config_; bool initialized_ = false; - + // Event tracking std::vector event_history_; std::unordered_map> character_events_; std::unordered_map> location_events_; - + // Helper methods std::vector generateEventEmbedding(const NarrativeEvent& event); - float calculateRelevanceScore(const SearchResult& result, - const std::chrono::system_clock::time_point& query_time) const; + float calculateRelevanceScore(const SearchResult& result, + const std::chrono::system_clock::time_point& query_time) const; std::string formatEventsForInjection(const std::vector& events) const; -public: + public: NarrativeRAGManager(); explicit NarrativeRAGManager(const NarrativeRAGConfig& config); ~NarrativeRAGManager() = default; - + // Initialization bool initialize(const std::string& model_path = ""); bool isInitialized() const { return initialized_; } void shutdown(); - + // Configuration void setConfig(const NarrativeRAGConfig& config) { config_ = config; } NarrativeRAGConfig getConfig() const { return config_; } - + // Event management void logEvent(const NarrativeEvent& event); std::vector getEventHistory() const { return event_history_; } std::vector getCharacterEvents(const std::string& character) const; std::vector getLocationEvents(const std::string& location) const; - + // Narrative queries - std::vector queryNarrativeMemory( - const std::string& query, - const std::vector& active_characters = {} - ); - - std::string generateMemoryInjection( - const std::string& narrative_context, - const std::vector& active_characters = {} - ); - + std::vector queryNarrativeMemory(const std::string& query, + const std::vector& active_characters = {}); + + std::string generateMemoryInjection(const std::string& narrative_context, + const std::vector& active_characters = {}); + // Character-specific queries - std::string getCharacterMemory( - const std::string& character, - const std::string& about_what - ); - + std::string getCharacterMemory(const std::string& character, const std::string& about_what); + // World state queries std::string getWorldState(const std::string& location); std::vector getRecentEvents(int hours = 24); - + // Statistics size_t getEventCount() const { return event_history_.size(); } std::vector getKnownCharacters() const; std::vector getKnownLocations() const; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // NARRATIVE_RAG_MANAGER_HPP +#endif // BOLT_AI_NARRATIVE_RAG_MANAGER_HPP_ diff --git a/include/bolt/ai/narrative_tool_manager.hpp b/include/bolt/ai/narrative_tool_manager.hpp index 8fe1ea26..936f8b64 100644 --- a/include/bolt/ai/narrative_tool_manager.hpp +++ b/include/bolt/ai/narrative_tool_manager.hpp @@ -1,12 +1,12 @@ -#ifndef NARRATIVE_TOOL_MANAGER_HPP -#define NARRATIVE_TOOL_MANAGER_HPP +#ifndef BOLT_AI_NARRATIVE_TOOL_MANAGER_HPP_ +#define BOLT_AI_NARRATIVE_TOOL_MANAGER_HPP_ -#include -#include #include -#include #include #include +#include +#include +#include namespace bolt { namespace ai { @@ -16,10 +16,10 @@ namespace ai { */ struct ToolResult { bool success; - std::string description; // Narrative description of the result - std::string outcome; // Structured outcome data - int impact_score; // How much this affects the world (1-10) - std::vector state_changes; // Changes to world state + std::string description; // Narrative description of the result + std::string outcome; // Structured outcome data + int impact_score; // How much this affects the world (1-10) + std::vector state_changes; // Changes to world state }; /** @@ -29,8 +29,8 @@ struct NarrativeTool { std::string name; std::string description; std::vector parameters; - std::string category; // combat, social, exploration, magic, etc. - int difficulty; // Base difficulty (1-20) + std::string category; // combat, social, exploration, magic, etc. + int difficulty; // Base difficulty (1-20) bool requires_target; std::function&)> handler; }; @@ -40,8 +40,8 @@ struct NarrativeTool { */ struct CharacterSheet { std::string name; - std::unordered_map skills; // skill_name -> proficiency (1-10) - std::unordered_map attributes; // strength, intelligence, etc. + std::unordered_map skills; // skill_name -> proficiency (1-10) + std::unordered_map attributes; // strength, intelligence, etc. std::vector known_abilities; int luck_modifier = 0; }; @@ -51,55 +51,49 @@ struct CharacterSheet { * Enables character agency through skill-based tool invocations */ class NarrativeToolManager { -private: + private: std::unordered_map tools_; std::unordered_map characters_; std::mt19937 rng_; bool initialized_ = false; - + // Game mechanics int rollDice(int sides, int count = 1); - bool skillCheck(const std::string& character, - const std::string& skill, - int difficulty); - + bool skillCheck(const std::string& character, const std::string& skill, int difficulty); + // Tool execution - ToolResult executeTool(const std::string& tool_name, - const std::string& character, - const std::unordered_map& params); + ToolResult executeTool(const std::string& tool_name, const std::string& character, + const std::unordered_map& params); -public: + public: NarrativeToolManager(); ~NarrativeToolManager() = default; - + // Initialization bool initialize(); bool isInitialized() const { return initialized_; } - + // Tool registration void registerTool(const NarrativeTool& tool); void unregisterTool(const std::string& tool_name); std::vector getAvailableTools() const; NarrativeTool getTool(const std::string& tool_name) const; - + // Character management void registerCharacter(const CharacterSheet& character); - void updateCharacterSkill(const std::string& character, - const std::string& skill, - int new_value); + void updateCharacterSkill(const std::string& character, const std::string& skill, int new_value); CharacterSheet getCharacter(const std::string& character) const; std::vector getCharacterAbilities(const std::string& character) const; - + // Tool invocation - ToolResult invokeTool(const std::string& tool_name, - const std::string& character, - const std::unordered_map& params); - + ToolResult invokeTool(const std::string& tool_name, const std::string& character, + const std::unordered_map& params); + // Tool discovery (for AI to query available actions) std::vector getToolsForCharacter(const std::string& character) const; std::vector getToolsByCategory(const std::string& category) const; std::string getToolsAsJSON() const; - + // Predefined tool sets void loadCombatTools(); void loadSocialTools(); @@ -108,7 +102,7 @@ class NarrativeToolManager { void loadAllStandardTools(); }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // NARRATIVE_TOOL_MANAGER_HPP +#endif // BOLT_AI_NARRATIVE_TOOL_MANAGER_HPP_ diff --git a/include/bolt/ai/rag_router.hpp b/include/bolt/ai/rag_router.hpp index d758e844..1a67fe17 100644 --- a/include/bolt/ai/rag_router.hpp +++ b/include/bolt/ai/rag_router.hpp @@ -1,11 +1,12 @@ -#ifndef RAG_ROUTER_HPP -#define RAG_ROUTER_HPP +#ifndef BOLT_AI_RAG_ROUTER_HPP_ +#define BOLT_AI_RAG_ROUTER_HPP_ +#include +#include #include -#include #include -#include -#include +#include +#include namespace bolt { namespace ai { @@ -14,10 +15,10 @@ namespace ai { * Query type classification for RAG routing */ enum class RAGQueryType { - GENERAL_SEMANTIC, // General semantic search - NARRATIVE, // Story/narrative-related query - TEMPORAL, // Time-series/temporal query - HYBRID // Requires multiple backends + GENERAL_SEMANTIC, // General semantic search + NARRATIVE, // Story/narrative-related query + TEMPORAL, // Time-series/temporal query + HYBRID // Requires multiple backends }; /** @@ -27,14 +28,14 @@ struct QueryFeatures { float narrative_score = 0.0f; float temporal_score = 0.0f; float general_score = 0.0f; - + // Detailed feature breakdown int narrative_keyword_count = 0; int temporal_keyword_count = 0; bool has_time_pattern = false; bool has_narrative_pattern = false; bool has_question_pattern = false; - + // Contextual features bool mentions_characters = false; bool mentions_events = false; @@ -51,7 +52,7 @@ struct RoutingDecision { float confidence; std::string reasoning; QueryFeatures features; - + // Alternative backends (for fallback) std::vector> alternatives; }; @@ -65,12 +66,12 @@ struct RAGRouterConfig { float temporal_threshold = 0.4f; float hybrid_threshold = 0.3f; float confidence_threshold = 0.5f; - + // Weights for different features float keyword_weight = 1.0f; float pattern_weight = 1.5f; float context_weight = 1.2f; - + // Fallback behavior bool enable_fallback = true; RAGQueryType default_fallback = RAGQueryType::GENERAL_SEMANTIC; @@ -78,10 +79,10 @@ struct RAGRouterConfig { /** * RAG Router: Intelligent query classification and routing - * + * * This component analyzes incoming queries and determines which RAG backend * (Narrative, Temporal, or General) is most appropriate for handling the query. - * + * * Features: * - Keyword-based classification * - Pattern matching (regex) @@ -90,9 +91,9 @@ struct RAGRouterConfig { * - Fallback routing */ class RAGRouter { -private: + private: RAGRouterConfig config_; - + // Keyword dictionaries std::vector narrative_keywords_; std::vector temporal_keywords_; @@ -100,61 +101,56 @@ class RAGRouter { std::vector event_keywords_; std::vector metric_keywords_; std::vector trend_keywords_; - + // Pattern matchers std::vector temporal_patterns_; std::vector narrative_patterns_; - + // Helper methods void initializeKeywords(); void initializePatterns(); - + QueryFeatures extractFeatures(const std::string& query) const; float calculateNarrativeScore(const QueryFeatures& features) const; float calculateTemporalScore(const QueryFeatures& features) const; float calculateGeneralScore(const QueryFeatures& features) const; - - RAGQueryType classifyFromScores(float narrative_score, - float temporal_score, - float general_score) const; - - float calculateConfidence(const QueryFeatures& features, - RAGQueryType type) const; - - std::string generateReasoning(const QueryFeatures& features, - RAGQueryType type) const; - - std::vector> generateAlternatives( - const QueryFeatures& features, - RAGQueryType primary_type) const; - -public: + + RAGQueryType classifyFromScores(float narrative_score, float temporal_score, float general_score) const; + + float calculateConfidence(const QueryFeatures& features, RAGQueryType type) const; + + std::string generateReasoning(const QueryFeatures& features, RAGQueryType type) const; + + std::vector> generateAlternatives(const QueryFeatures& features, + RAGQueryType primary_type) const; + + public: RAGRouter(); explicit RAGRouter(const RAGRouterConfig& config); ~RAGRouter() = default; - + // Configuration void setConfig(const RAGRouterConfig& config); RAGRouterConfig getConfig() const { return config_; } - + // Main routing method RoutingDecision route(const std::string& query) const; - + // Query analysis QueryFeatures analyzeQuery(const std::string& query) const; RAGQueryType classifyQuery(const std::string& query) const; - + // Utilities std::string queryTypeToString(RAGQueryType type) const; std::string backendNameFromType(RAGQueryType type) const; - + // Keyword management (for customization) void addNarrativeKeyword(const std::string& keyword); void addTemporalKeyword(const std::string& keyword); void clearCustomKeywords(); }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // RAG_ROUTER_HPP +#endif // BOLT_AI_RAG_ROUTER_HPP_ diff --git a/include/bolt/ai/rwkv_wrapper.hpp b/include/bolt/ai/rwkv_wrapper.hpp index 9dec0c15..b25fd344 100644 --- a/include/bolt/ai/rwkv_wrapper.hpp +++ b/include/bolt/ai/rwkv_wrapper.hpp @@ -1,18 +1,20 @@ -#ifndef RWKV_WRAPPER_HPP -#define RWKV_WRAPPER_HPP +#ifndef BOLT_AI_RWKV_WRAPPER_HPP_ +#define BOLT_AI_RWKV_WRAPPER_HPP_ #include -#include +#include #include #include -#include +#include +#include + #include "bolt/ai/ggml_wrapper.hpp" #ifdef BOLT_HAVE_GGML -#include "bolt/utils/tensor_utils.hpp" -#include "bolt/ai/gguf_loader.hpp" #include "bolt/ai/bpe_tokenizer.hpp" +#include "bolt/ai/gguf_loader.hpp" +#include "bolt/utils/tensor_utils.hpp" #endif namespace bolt { @@ -21,7 +23,7 @@ namespace bolt { // Simplified RWKV state management using GGML class RWKVState { -public: + public: RWKVState(ggml_context* ctx, int n_layers, int n_embd) : n_layers_(n_layers), n_embd_(n_embd) { for (int i = 0; i < n_layers; i++) { state_aa_.push_back(ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd)); @@ -32,18 +34,18 @@ class RWKVState { ggml_set_zero(state_pp_[i]); } } - + std::vector state_aa_; std::vector state_bb_; std::vector state_pp_; -private: + private: int n_layers_; int n_embd_; }; class RWKVWrapper { -public: + public: static RWKVWrapper& getInstance() { static RWKVWrapper instance; return instance; @@ -51,11 +53,11 @@ class RWKVWrapper { void initialize(const std::string& model_path, int ctx_size = 1024); bool isInitialized() const { return model_loaded_; } - + std::string generate(const std::string& prompt, size_t max_tokens = 256); - std::string generateImproved(const std::string& prompt, size_t max_tokens = 256, - float temperature = 1.0f, float top_p = 0.95f); - + std::string generateImproved(const std::string& prompt, size_t max_tokens = 256, float temperature = 1.0f, + float top_p = 0.95f); + ggml_tensor* forwardWithLogits(ggml_tensor* input); ggml_tensor* rwkvLayer(ggml_tensor* x, int layer_idx); ggml_tensor* timeMixing(ggml_tensor* x, int layer_idx); @@ -65,37 +67,37 @@ class RWKVWrapper { ggml_tensor* projectToVocab(ggml_tensor* hidden); int sampleToken(ggml_tensor* logits, float temperature, float top_p); ggml_tensor* forward(ggml_tensor* input); - + int getNumLayers() const { return n_layers_; } int getEmbedDim() const { return n_embd_; } -private: + private: RWKVWrapper() = default; - + std::unique_ptr context_; std::unique_ptr state_; std::unordered_map weights_; std::unique_ptr gguf_loader_; std::unique_ptr tokenizer_; std::mt19937 rng_; - + int n_layers_ = 2; int n_embd_ = 64; int n_vocab_ = 50277; int n_threads_ = 4; bool model_loaded_ = false; std::string model_path_; - + void loadModel(const std::string& path); std::vector tokenize(const std::string& text) const; std::string detokenize(const std::vector& tokens) const; }; -#else // !BOLT_HAVE_GGML +#else // !BOLT_HAVE_GGML // Stub RWKVWrapper when GGML is not available class RWKVWrapper { -public: + public: static RWKVWrapper& getInstance() { static RWKVWrapper instance; return instance; @@ -105,26 +107,24 @@ class RWKVWrapper { throw GGMLException("RWKV not available - build with ENABLE_LLAMA_CPP=ON"); } bool isInitialized() const { return false; } - - std::string generate(const std::string& /*prompt*/, size_t /*max_tokens*/ = 256) { - return ""; - } + + std::string generate(const std::string& /*prompt*/, size_t /*max_tokens*/ = 256) { return ""; } std::string generateImproved(const std::string& /*prompt*/, size_t /*max_tokens*/ = 256, float /*temperature*/ = 1.0f, float /*top_p*/ = 0.95f) { return ""; } - + int getNumLayers() const { return n_layers_; } int getEmbedDim() const { return n_embd_; } -private: + private: RWKVWrapper() = default; int n_layers_ = 2; int n_embd_ = 64; }; -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML -} // namespace bolt +} // namespace bolt -#endif // RWKV_WRAPPER_HPP +#endif // BOLT_AI_RWKV_WRAPPER_HPP_ diff --git a/include/bolt/ai/semantic_search_manager.hpp b/include/bolt/ai/semantic_search_manager.hpp index bb38677b..17f90c9f 100644 --- a/include/bolt/ai/semantic_search_manager.hpp +++ b/include/bolt/ai/semantic_search_manager.hpp @@ -1,14 +1,15 @@ -#ifndef SEMANTIC_SEARCH_MANAGER_HPP -#define SEMANTIC_SEARCH_MANAGER_HPP +#ifndef BOLT_AI_SEMANTIC_SEARCH_MANAGER_HPP_ +#define BOLT_AI_SEMANTIC_SEARCH_MANAGER_HPP_ -#include "bolt/ai/vector_database.hpp" -#include "bolt/ai/direct_gguf_inference.hpp" -#include -#include -#include +#include #include +#include +#include #include -#include +#include + +#include "bolt/ai/direct_gguf_inference.hpp" +#include "bolt/ai/vector_database.hpp" namespace bolt { namespace ai { @@ -17,11 +18,11 @@ namespace ai { * Configuration for semantic search indexing */ struct IndexingConfig { - size_t max_chunk_size = 1000; // Max characters per chunk - size_t chunk_overlap = 200; // Overlap between chunks - bool index_hidden_files = false; // Whether to index hidden files + size_t max_chunk_size = 1000; // Max characters per chunk + size_t chunk_overlap = 200; // Overlap between chunks + bool index_hidden_files = false; // Whether to index hidden files std::vector file_extensions = {".cpp", ".hpp", ".h", ".c", ".txt", ".md"}; - size_t max_file_size = 1024 * 1024; // Max file size (1MB) + size_t max_file_size = 1024 * 1024; // Max file size (1MB) }; /** @@ -40,67 +41,60 @@ struct IndexingStats { * Handles indexing, embedding generation, and similarity search */ class SemanticSearchManager { -private: + private: std::unique_ptr inference_engine_; VectorDatabase vector_db_; IndexingConfig config_; IndexingStats stats_; bool initialized_ = false; std::atomic indexing_in_progress_{false}; - + // Helper methods std::vector chunkText(const std::string& text) const; bool shouldIndexFile(const std::string& file_path) const; std::string readFileContent(const std::string& file_path) const; std::vector generateEmbedding(const std::string& text); -public: + public: SemanticSearchManager(); explicit SemanticSearchManager(const IndexingConfig& config); ~SemanticSearchManager() = default; - + // Initialization bool initialize(const std::string& model_path = ""); bool isInitialized() const { return initialized_; } void shutdown(); - + // Configuration void setConfig(const IndexingConfig& config) { config_ = config; } IndexingConfig getConfig() const { return config_; } - + // Indexing operations bool indexFile(const std::string& file_path); bool indexDirectory(const std::string& directory_path, bool recursive = true); bool removeFileFromIndex(const std::string& file_path); void clearIndex(); - + // Search operations - std::vector search( - const std::string& query, - int top_k = 5, - float min_similarity = 0.3f - ); - - std::vector searchInDirectory( - const std::string& query, - const std::string& directory_path, - int top_k = 5 - ); - + std::vector search(const std::string& query, int top_k = 5, float min_similarity = 0.3f); + + std::vector searchInDirectory(const std::string& query, const std::string& directory_path, + int top_k = 5); + // Statistics and info IndexingStats getStats() const { return stats_; } size_t getIndexedFileCount() const; bool isIndexingInProgress() const { return indexing_in_progress_; } - + // Callbacks for progress tracking using ProgressCallback = std::function; void setProgressCallback(ProgressCallback callback) { progress_callback_ = callback; } - -private: + + private: ProgressCallback progress_callback_; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // SEMANTIC_SEARCH_MANAGER_HPP +#endif // BOLT_AI_SEMANTIC_SEARCH_MANAGER_HPP_ diff --git a/include/bolt/ai/temporal_rag_manager.hpp b/include/bolt/ai/temporal_rag_manager.hpp index e5f3b929..fac9e219 100644 --- a/include/bolt/ai/temporal_rag_manager.hpp +++ b/include/bolt/ai/temporal_rag_manager.hpp @@ -1,12 +1,14 @@ -#ifndef TEMPORAL_RAG_MANAGER_HPP -#define TEMPORAL_RAG_MANAGER_HPP +#ifndef BOLT_AI_TEMPORAL_RAG_MANAGER_HPP_ +#define BOLT_AI_TEMPORAL_RAG_MANAGER_HPP_ -#include "bolt/ai/rwkv_wrapper.hpp" -#include -#include -#include #include +#include +#include #include +#include +#include + +#include "bolt/ai/rwkv_wrapper.hpp" namespace bolt { namespace ai { @@ -16,9 +18,9 @@ namespace ai { */ struct TimeSeriesPoint { std::chrono::system_clock::time_point timestamp; - std::unordered_map values; // metric_name -> value - std::string source; // Data source identifier - std::string category; // Data category (e.g., "stock", "sensor") + std::unordered_map values; // metric_name -> value + std::string source; // Data source identifier + std::string category; // Data category (e.g., "stock", "sensor") }; /** @@ -27,21 +29,21 @@ struct TimeSeriesPoint { struct TemporalQuery { std::chrono::system_clock::time_point start_time; std::chrono::system_clock::time_point end_time; - std::vector metrics; // Which metrics to retrieve - std::string source_filter; // Optional source filter - std::string category_filter; // Optional category filter - int max_points = 1000; // Max data points to retrieve + std::vector metrics; // Which metrics to retrieve + std::string source_filter; // Optional source filter + std::string category_filter; // Optional category filter + int max_points = 1000; // Max data points to retrieve }; /** * Configuration for temporal RAG */ struct TemporalRAGConfig { - int context_window_size = 2048; // RWKV context size - bool normalize_values = true; // Normalize time-series values - bool include_timestamps = true; // Include timestamps in sequence - std::string time_format = "relative"; // "relative" or "absolute" - int aggregation_window_seconds = 60; // Aggregate data into windows + int context_window_size = 2048; // RWKV context size + bool normalize_values = true; // Normalize time-series values + bool include_timestamps = true; // Include timestamps in sequence + std::string time_format = "relative"; // "relative" or "absolute" + int aggregation_window_seconds = 60; // Aggregate data into windows }; /** @@ -49,77 +51,66 @@ struct TemporalRAGConfig { * Specialized for time-series analysis and prediction */ class TemporalRAGManager { -private: + private: std::unique_ptr rwkv_model_; std::vector time_series_db_; TemporalRAGConfig config_; bool initialized_ = false; - + // Data processing std::vector queryTimeSeriesDB(const TemporalQuery& query) const; std::string formatTimeSeriesForRWKV(const std::vector& data) const; - std::vector aggregateData(const std::vector& data, - int window_seconds) const; - + std::vector aggregateData(const std::vector& data, int window_seconds) const; + // Analysis helpers double calculateTrend(const std::vector& values) const; - std::vector detectAnomalies(const std::vector& values, - double threshold = 2.0) const; + std::vector detectAnomalies(const std::vector& values, double threshold = 2.0) const; -public: + public: TemporalRAGManager(); explicit TemporalRAGManager(const TemporalRAGConfig& config); ~TemporalRAGManager() = default; - + // Initialization bool initialize(const std::string& model_path = ""); bool isInitialized() const { return initialized_; } void shutdown(); - + // Configuration void setConfig(const TemporalRAGConfig& config) { config_ = config; } TemporalRAGConfig getConfig() const { return config_; } - + // Data ingestion void ingestDataPoint(const TimeSeriesPoint& point); void ingestDataBatch(const std::vector& points); size_t getDataPointCount() const { return time_series_db_.size(); } - + // Temporal queries and analysis - std::string analyzeTimePeriod(const TemporalQuery& query, - const std::string& analysis_prompt); - - std::string detectPatterns(const std::string& metric, - const std::chrono::system_clock::time_point& start, - const std::chrono::system_clock::time_point& end); - - std::string comparePeriods(const std::string& metric, - const TemporalQuery& period1, - const TemporalQuery& period2); - + std::string analyzeTimePeriod(const TemporalQuery& query, const std::string& analysis_prompt); + + std::string detectPatterns(const std::string& metric, const std::chrono::system_clock::time_point& start, + const std::chrono::system_clock::time_point& end); + + std::string comparePeriods(const std::string& metric, const TemporalQuery& period1, const TemporalQuery& period2); + // Forecasting - std::vector forecastNextN(const std::string& metric, - int n_steps, + std::vector forecastNextN(const std::string& metric, int n_steps, const std::chrono::system_clock::time_point& from_time); - + // Anomaly detection - std::vector findAnomalies(const std::string& metric, - const TemporalQuery& query, + std::vector findAnomalies(const std::string& metric, const TemporalQuery& query, double threshold = 2.0); - + // Correlation analysis - double calculateCorrelation(const std::string& metric1, - const std::string& metric2, - const TemporalQuery& query); - + double calculateCorrelation(const std::string& metric1, const std::string& metric2, const TemporalQuery& query); + // Statistics std::vector getAvailableMetrics() const; std::vector getAvailableSources() const; - std::pair getDataTimeRange() const; + std::pair getDataTimeRange() const; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // TEMPORAL_RAG_MANAGER_HPP +#endif // BOLT_AI_TEMPORAL_RAG_MANAGER_HPP_ diff --git a/include/bolt/ai/temporal_tool_manager.hpp b/include/bolt/ai/temporal_tool_manager.hpp index 42594c8f..35dd8932 100644 --- a/include/bolt/ai/temporal_tool_manager.hpp +++ b/include/bolt/ai/temporal_tool_manager.hpp @@ -1,12 +1,12 @@ -#ifndef TEMPORAL_TOOL_MANAGER_HPP -#define TEMPORAL_TOOL_MANAGER_HPP +#ifndef BOLT_AI_TEMPORAL_TOOL_MANAGER_HPP_ +#define BOLT_AI_TEMPORAL_TOOL_MANAGER_HPP_ -#include -#include +#include #include -#include #include -#include +#include +#include +#include namespace bolt { namespace ai { @@ -30,7 +30,7 @@ struct TemporalTool { std::string name; std::string description; std::vector parameters; - std::string category; // forecasting, monitoring, trading, etc. + std::string category; // forecasting, monitoring, trading, etc. bool requires_historical_data; std::function&)> handler; }; @@ -40,7 +40,7 @@ struct TemporalTool { */ struct TemporalTrigger { std::string name; - std::string condition; // e.g., "price > 100", "anomaly_detected" + std::string condition; // e.g., "price > 100", "anomaly_detected" std::string tool_to_invoke; std::unordered_map tool_params; bool enabled = true; @@ -53,55 +53,55 @@ struct TemporalTrigger { * Enables predictive agents that can act on time-series data */ class TemporalToolManager { -private: + private: std::unordered_map tools_; std::vector triggers_; std::vector execution_history_; bool initialized_ = false; - + // Tool execution TemporalToolResult executeTool(const std::string& tool_name, const std::unordered_map& params); - + // Trigger evaluation bool evaluateTriggerCondition(const TemporalTrigger& trigger, const std::unordered_map& current_state); -public: + public: TemporalToolManager(); ~TemporalToolManager() = default; - + // Initialization bool initialize(); bool isInitialized() const { return initialized_; } - + // Tool registration void registerTool(const TemporalTool& tool); void unregisterTool(const std::string& tool_name); std::vector getAvailableTools() const; TemporalTool getTool(const std::string& tool_name) const; - + // Tool invocation TemporalToolResult invokeTool(const std::string& tool_name, const std::unordered_map& params); - + // Trigger management void registerTrigger(const TemporalTrigger& trigger); void removeTrigger(const std::string& trigger_name); void enableTrigger(const std::string& trigger_name, bool enabled); std::vector getActiveTriggers() const; - + // Automated monitoring void checkTriggers(const std::unordered_map& current_state); - + // Execution history std::vector getExecutionHistory(int last_n = 10) const; void clearExecutionHistory(); - + // Tool discovery (for AI to query available actions) std::vector getToolsByCategory(const std::string& category) const; std::string getToolsAsJSON() const; - + // Predefined tool sets void loadForecastingTools(); void loadMonitoringTools(); @@ -110,7 +110,7 @@ class TemporalToolManager { void loadAllStandardTools(); }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // TEMPORAL_TOOL_MANAGER_HPP +#endif // BOLT_AI_TEMPORAL_TOOL_MANAGER_HPP_ diff --git a/include/bolt/ai/tokenizer.hpp b/include/bolt/ai/tokenizer.hpp index ecb8913a..992106bf 100644 --- a/include/bolt/ai/tokenizer.hpp +++ b/include/bolt/ai/tokenizer.hpp @@ -1,17 +1,19 @@ -#ifndef TOKENIZER_HPP -#define TOKENIZER_HPP +#ifndef BOLT_AI_TOKENIZER_HPP_ +#define BOLT_AI_TOKENIZER_HPP_ +#include +#include #include -#include #include -#include +#include + #include "bolt/core/thread_safety.hpp" namespace bolt { class Tokenizer { -private: + private: ThreadSafe> vocab_; ThreadSafe> reverse_vocab_; int next_token_id_; @@ -24,19 +26,15 @@ class Tokenizer { addToken("", 3); } -public: + public: static Tokenizer& getInstance() { static Tokenizer instance; return instance; } void addToken(const std::string& token, int id) { - vocab_.write([&](auto& vocab) { - vocab[token] = id; - }); - reverse_vocab_.write([&](auto& rev_vocab) { - rev_vocab[id] = token; - }); + vocab_.write([&](auto& vocab) { vocab[token] = id; }); + reverse_vocab_.write([&](auto& rev_vocab) { rev_vocab[id] = token; }); next_token_id_ = std::max(next_token_id_, id + 1); } @@ -49,30 +47,24 @@ class Tokenizer { std::vector encode(const std::string& text) { std::vector tokens; std::string current_token; - + for (size_t i = 0; i < text.length(); i++) { current_token += text[i]; - bool found = vocab_.read([&](const auto& vocab) { - return vocab.find(current_token) != vocab.end(); - }); + bool found = vocab_.read([&](const auto& vocab) { return vocab.find(current_token) != vocab.end(); }); if (!found) { if (current_token.length() > 1) { std::string prev_token = current_token.substr(0, current_token.length() - 1); - int token_id = vocab_.read([&](const auto& vocab) { - return vocab.at(prev_token); - }); + int token_id = vocab_.read([&](const auto& vocab) { return vocab.at(prev_token); }); tokens.push_back(token_id); current_token = text[i]; } } else if (i == text.length() - 1) { - int token_id = vocab_.read([&](const auto& vocab) { - return vocab.at(current_token); - }); + int token_id = vocab_.read([&](const auto& vocab) { return vocab.at(current_token); }); tokens.push_back(token_id); } } - + return tokens; } @@ -89,6 +81,6 @@ class Tokenizer { } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_AI_TOKENIZER_HPP_ diff --git a/include/bolt/ai/unified_rag_manager.hpp b/include/bolt/ai/unified_rag_manager.hpp index 02aba20c..2bd24c4e 100644 --- a/include/bolt/ai/unified_rag_manager.hpp +++ b/include/bolt/ai/unified_rag_manager.hpp @@ -1,15 +1,17 @@ -#ifndef UNIFIED_RAG_MANAGER_HPP -#define UNIFIED_RAG_MANAGER_HPP +#ifndef BOLT_AI_UNIFIED_RAG_MANAGER_HPP_ +#define BOLT_AI_UNIFIED_RAG_MANAGER_HPP_ + +#include +#include +#include +#include +#include #include "bolt/ai/i_rag_manager.hpp" -#include "bolt/ai/semantic_search_manager.hpp" #include "bolt/ai/narrative_rag_manager.hpp" -#include "bolt/ai/temporal_rag_manager.hpp" #include "bolt/ai/rag_router.hpp" -#include -#include -#include -#include +#include "bolt/ai/semantic_search_manager.hpp" +#include "bolt/ai/temporal_rag_manager.hpp" namespace bolt { namespace ai { @@ -18,10 +20,10 @@ namespace ai { * Query type classification for RAG routing */ enum class RAGQueryType { - GENERAL_SEMANTIC, // General semantic search - NARRATIVE, // Story/narrative-related query - TEMPORAL, // Time-series/temporal query - HYBRID // Requires multiple backends + GENERAL_SEMANTIC, // General semantic search + NARRATIVE, // Story/narrative-related query + TEMPORAL, // Time-series/temporal query + HYBRID // Requires multiple backends }; /** @@ -51,76 +53,71 @@ struct RoutingDecision { * Provides a single interface for all RAG operations */ class UnifiedRAGManager { -private: + private: // Specialized RAG backends std::unique_ptr general_rag_; std::unique_ptr narrative_rag_; std::unique_ptr temporal_rag_; - + // RAG Router std::unique_ptr router_; - + // Configuration UnifiedRAGConfig config_; bool initialized_ = false; - + // Hybrid query processing std::vector processHybridQuery(const std::string& query, int top_k); - std::vector mergeResults( - const std::vector& results1, - const std::vector& results2 - ) const; + std::vector mergeResults(const std::vector& results1, + const std::vector& results2) const; -public: + public: UnifiedRAGManager(); explicit UnifiedRAGManager(const UnifiedRAGConfig& config); ~UnifiedRAGManager() = default; - + // Initialization - bool initialize(const std::string& general_model_path = "", - const std::string& narrative_model_path = "", - const std::string& temporal_model_path = ""); + bool initialize(const std::string& general_model_path = "", const std::string& narrative_model_path = "", + const std::string& temporal_model_path = ""); bool isInitialized() const { return initialized_; } void shutdown(); - + // Configuration void setConfig(const UnifiedRAGConfig& config) { config_ = config; } UnifiedRAGConfig getConfig() const { return config_; } - + // Main query interface std::vector query(const std::string& query, int top_k = -1); - std::vector queryWithType(const std::string& query, - RAGQueryType type, - int top_k = -1); - + std::vector queryWithType(const std::string& query, RAGQueryType type, int top_k = -1); + // Routing inspection RoutingDecision analyzeQuery(const std::string& query) const; - + // Router access RAGRouter* getRouter() { return router_.get(); } const RAGRouter* getRouter() const { return router_.get(); } - + // Data ingestion (routes to appropriate backend) void ingestGeneralDocument(const std::string& content, const std::string& id); void ingestNarrativeEvent(const NarrativeEvent& event); void ingestTemporalData(const TimeSeriesPoint& point); - + // Batch ingestion void ingestGeneralDocuments(const std::vector>& docs); void ingestNarrativeEvents(const std::vector& events); void ingestTemporalData(const std::vector& points); - + // Backend access (for specialized operations) SemanticSearchManager* getGeneralRAG() { return general_rag_.get(); } NarrativeRAGManager* getNarrativeRAG() { return narrative_rag_.get(); } TemporalRAGManager* getTemporalRAG() { return temporal_rag_.get(); } - + // Statistics std::unordered_map getBackendStatistics() const; std::vector getAvailableBackends() const; }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // UNIFIED_RAG_MANAGER_HPP +#endif // BOLT_AI_UNIFIED_RAG_MANAGER_HPP_ diff --git a/include/bolt/ai/vector_database.hpp b/include/bolt/ai/vector_database.hpp index 7616d72e..c57c4a85 100644 --- a/include/bolt/ai/vector_database.hpp +++ b/include/bolt/ai/vector_database.hpp @@ -1,11 +1,11 @@ -#ifndef VECTOR_DATABASE_HPP -#define VECTOR_DATABASE_HPP +#ifndef BOLT_AI_VECTOR_DATABASE_HPP_ +#define BOLT_AI_VECTOR_DATABASE_HPP_ -#include -#include -#include #include #include +#include +#include +#include namespace bolt { namespace ai { @@ -14,13 +14,13 @@ namespace ai { * A record in the vector database containing file metadata and embedding */ struct VectorRecord { - std::string id; // Unique identifier (file path) - std::vector embedding; // Vector embedding - std::string content_preview; // First N characters of content - std::string file_type; // File extension - size_t file_size; // File size in bytes - long last_modified; // Last modification timestamp - + std::string id; // Unique identifier (file path) + std::vector embedding; // Vector embedding + std::string content_preview; // First N characters of content + std::string file_type; // File extension + size_t file_size; // File size in bytes + long last_modified; // NOLINT(runtime/int) // Last modification timestamp + VectorRecord() : file_size(0), last_modified(0) {} }; @@ -32,12 +32,9 @@ struct SearchResult { float similarity_score; std::string content_preview; std::string file_type; - - SearchResult(const std::string& path, float score, - const std::string& preview = "", - const std::string& type = "") - : file_path(path), similarity_score(score), - content_preview(preview), file_type(type) {} + + SearchResult(const std::string& path, float score, const std::string& preview = "", const std::string& type = "") + : file_path(path), similarity_score(score), content_preview(preview), file_type(type) {} }; /** @@ -45,42 +42,39 @@ struct SearchResult { * Thread-safe implementation for concurrent access */ class VectorDatabase { -private: + private: std::unordered_map records_; mutable std::mutex mutex_; - -public: + + public: VectorDatabase() = default; ~VectorDatabase() = default; - + // Record management void addOrUpdateRecord(const VectorRecord& record); bool removeRecord(const std::string& id); bool hasRecord(const std::string& id) const; VectorRecord getRecord(const std::string& id) const; - + // Search operations - std::vector searchSimilar( - const std::vector& query_embedding, - int top_k = 5, - float min_similarity = 0.0f - ) const; - + std::vector searchSimilar(const std::vector& query_embedding, int top_k = 5, + float min_similarity = 0.0f) const; + // Statistics size_t getRecordCount() const; std::vector getAllIds() const; void clear(); - + // Similarity metrics static float cosineSimilarity(const std::vector& a, const std::vector& b); static float euclideanDistance(const std::vector& a, const std::vector& b); - + // Persistence (optional for future implementation) bool saveToFile(const std::string& file_path) const; bool loadFromFile(const std::string& file_path); }; -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt -#endif // VECTOR_DATABASE_HPP +#endif // BOLT_AI_VECTOR_DATABASE_HPP_ diff --git a/include/bolt/collaboration/collaborative_editor_integration.hpp b/include/bolt/collaboration/collaborative_editor_integration.hpp index 4f51b6e0..fbf73845 100644 --- a/include/bolt/collaboration/collaborative_editor_integration.hpp +++ b/include/bolt/collaboration/collaborative_editor_integration.hpp @@ -1,20 +1,25 @@ -#ifndef COLLABORATIVE_EDITOR_INTEGRATION_HPP -#define COLLABORATIVE_EDITOR_INTEGRATION_HPP +#ifndef BOLT_COLLABORATION_COLLABORATIVE_EDITOR_INTEGRATION_HPP_ +#define BOLT_COLLABORATION_COLLABORATIVE_EDITOR_INTEGRATION_HPP_ -#include "collaborative_session.hpp" -#include "collaboration_protocol.hpp" -#include "document_operation.hpp" -#include "../core/editor_store.hpp" -#include +#include #include +#include #include +#include +#include +#include + +#include "../core/editor_store.hpp" +#include "bolt/collaboration/collaboration_protocol.hpp" +#include "bolt/collaboration/collaborative_session.hpp" +#include "bolt/collaboration/document_operation.hpp" // Windows compatibility: undefine conflicting macros #ifdef _WIN32 #ifdef DELETE #undef DELETE #endif -#ifdef INSERT +#ifdef INSERT #undef INSERT #endif #endif @@ -23,212 +28,212 @@ namespace bolt { namespace collaboration { class CollaborativeEditorIntegration { -public: + public: static CollaborativeEditorIntegration& getInstance() { static CollaborativeEditorIntegration instance; return instance; } - + void initialize(int websocketPort = 8081) { // Initialize the collaboration protocol auto& protocol = CollaborationProtocol::getInstance(); protocol.initialize(websocketPort); - + // Set up bidirectional synchronization setupEditorStoreListeners(); setupCollaborationListeners(); - + isInitialized_ = true; } - + void shutdown() { - if (!isInitialized_) return; - + if (!isInitialized_) + return; + auto& protocol = CollaborationProtocol::getInstance(); protocol.shutdown(); - + isInitialized_ = false; } - + // Enable/disable collaboration for a document bool enableCollaboration(const std::string& filePath, const std::string& userId = "default_user") { if (!isInitialized_) { return false; } - + std::lock_guard lock(collaborativeDocsMutex_); - + // Get current document content from EditorStore auto& editorStore = EditorStore::getInstance(); if (!editorStore.hasDocument(filePath)) { return false; } - + // Create collaborative document auto& session = CollaborativeSession::getInstance(); std::string docId = generateDocumentId(filePath); - + // Get current content and create collaborative document auto* currentDoc = editorStore.getCurrentDocument(); std::string initialContent = currentDoc ? currentDoc->value : ""; - + bool success = session.createDocument(docId, initialContent); if (success) { collaborativeDocs_[filePath] = docId; - + // Join the document as the current user session.joinDocument(userId, userId, docId); - + return true; } - + return false; } - + bool disableCollaboration(const std::string& filePath) { std::lock_guard lock(collaborativeDocsMutex_); - + auto it = collaborativeDocs_.find(filePath); if (it == collaborativeDocs_.end()) { return false; } - + auto& session = CollaborativeSession::getInstance(); session.removeDocument(it->second); collaborativeDocs_.erase(it); - + return true; } - + bool isCollaborationEnabled(const std::string& filePath) const { std::lock_guard lock(collaborativeDocsMutex_); return collaborativeDocs_.find(filePath) != collaborativeDocs_.end(); } - + // Apply a text edit to both editor store and collaborative session - bool applyTextEdit(const std::string& filePath, const Position& position, - const std::string& text, const std::string& userId = "default_user", - bool isDelete = false) { - + bool applyTextEdit(const std::string& filePath, const Position& position, const std::string& text, + const std::string& userId = "default_user", bool isDelete = false) { if (!isCollaborationEnabled(filePath)) { // Just apply to editor store if collaboration is not enabled return applyToEditorStore(filePath, position, text, isDelete); } - + // Apply to collaborative session (which will broadcast to others) std::lock_guard lock(collaborativeDocsMutex_); auto it = collaborativeDocs_.find(filePath); if (it == collaborativeDocs_.end()) { return false; } - + auto& session = CollaborativeSession::getInstance(); - + OperationType opType = isDelete ? OperationType::DELETE : OperationType::INSERT; DocumentOperation op(opType, userId, position, text); - + return session.applyOperation(op, it->second); } - + // Update cursor position bool updateCursorPosition(const std::string& filePath, const Position& position, - const std::string& userId = "default_user") { + const std::string& userId = "default_user") { if (!isCollaborationEnabled(filePath)) { - return true; // No-op if collaboration is not enabled + return true; // No-op if collaboration is not enabled } - + std::lock_guard lock(collaborativeDocsMutex_); auto it = collaborativeDocs_.find(filePath); if (it == collaborativeDocs_.end()) { return false; } - + auto& session = CollaborativeSession::getInstance(); DocumentOperation cursorOp(OperationType::CURSOR_MOVE, userId, position); - + return session.applyOperation(cursorOp, it->second); } - + // Get remote users' cursor positions std::vector> getRemoteCursors(const std::string& filePath) const { std::vector> cursors; - + if (!isCollaborationEnabled(filePath)) { return cursors; } - + std::lock_guard lock(collaborativeDocsMutex_); auto it = collaborativeDocs_.find(filePath); if (it == collaborativeDocs_.end()) { return cursors; } - + auto& session = CollaborativeSession::getInstance(); auto users = session.getActiveUsers(it->second); - + for (const auto& user : users) { cursors.emplace_back(user.userId, user.cursorPosition); } - + return cursors; } - + // Get collaboration statistics struct CollaborationStats { size_t activeDocuments; size_t totalUsers; bool isServerRunning; }; - + CollaborationStats getStats() const { CollaborationStats stats = {0, 0, isInitialized_}; - + if (isInitialized_) { auto& session = CollaborativeSession::getInstance(); auto sessionStats = session.getStats(); stats.activeDocuments = sessionStats.totalDocuments; stats.totalUsers = sessionStats.totalActiveUsers; } - + return stats; } -private: + private: CollaborativeEditorIntegration() : isInitialized_(false) {} - + void setupEditorStoreListeners() { // Note: EditorStore doesn't have change callbacks in current implementation // In a real implementation, we would add callbacks to EditorStore // and sync changes to collaborative session } - + void setupCollaborationListeners() { auto& session = CollaborativeSession::getInstance(); - + // Listen for collaborative operations and apply them to EditorStore session.onOperation([this](const DocumentOperation& op, const std::string& docId) { // Find the file path for this document ID std::string filePath = findFilePathForDocId(docId); - if (filePath.empty()) return; - + if (filePath.empty()) + return; + // Apply operation to EditorStore Position pos = op.getPosition(); bool isDelete = (op.getType() == OperationType::DELETE); - + if (op.getType() == OperationType::INSERT || op.getType() == OperationType::DELETE) { applyToEditorStore(filePath, pos, op.getContent(), isDelete); } }); } - - bool applyToEditorStore(const std::string& filePath, const Position& position, - const std::string& text, bool isDelete) { + + bool applyToEditorStore(const std::string& filePath, const Position& position, const std::string& text, + bool isDelete) { auto& editorStore = EditorStore::getInstance(); - + if (!editorStore.hasDocument(filePath)) { return false; } - + // Get current document auto* doc = editorStore.getCurrentDocument(); if (!doc || doc->filePath != filePath) { @@ -236,12 +241,13 @@ class CollaborativeEditorIntegration { editorStore.setSelectedFile(filePath); doc = editorStore.getCurrentDocument(); } - - if (!doc) return false; - + + if (!doc) + return false; + // Convert document value to lines for easier manipulation std::vector lines = splitLines(doc->value); - + // Apply the operation if (isDelete) { // Delete text @@ -263,18 +269,18 @@ class CollaborativeEditorIntegration { } line.insert(position.character, text); } - + // Convert back to string and update document doc->value = joinLines(lines); - + return true; } - + std::string generateDocumentId(const std::string& filePath) const { // Simple document ID generation - in production would use better method return "doc_" + std::to_string(std::hash{}(filePath)); } - + std::string findFilePathForDocId(const std::string& docId) const { std::lock_guard lock(collaborativeDocsMutex_); for (const auto& [filePath, id] : collaborativeDocs_) { @@ -284,7 +290,7 @@ class CollaborativeEditorIntegration { } return ""; } - + std::vector splitLines(const std::string& content) const { std::vector lines; std::string line; @@ -299,7 +305,7 @@ class CollaborativeEditorIntegration { lines.push_back(line); return lines; } - + std::string joinLines(const std::vector& lines) const { std::string result; for (size_t i = 0; i < lines.size(); ++i) { @@ -310,13 +316,13 @@ class CollaborativeEditorIntegration { } return result; } - + bool isInitialized_; mutable std::mutex collaborativeDocsMutex_; - std::map collaborativeDocs_; // filePath -> docId mapping + std::map collaborativeDocs_; // filePath -> docId mapping }; -} // namespace collaboration -} // namespace bolt +} // namespace collaboration +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_COLLABORATION_COLLABORATIVE_EDITOR_INTEGRATION_HPP_ diff --git a/include/bolt/collaboration/document_operation.hpp b/include/bolt/collaboration/document_operation.hpp index 543c571c..38531299 100644 --- a/include/bolt/collaboration/document_operation.hpp +++ b/include/bolt/collaboration/document_operation.hpp @@ -1,21 +1,20 @@ -#ifndef DOCUMENT_OPERATION_HPP -#define DOCUMENT_OPERATION_HPP +#ifndef BOLT_COLLABORATION_DOCUMENT_OPERATION_HPP_ +#define BOLT_COLLABORATION_DOCUMENT_OPERATION_HPP_ +#include +#include +#include #include - +#include +#include #include #include -#include -#include -#include -#include -#include // Windows compatibility: undefine conflicting macros #ifdef _WIN32 #ifdef DELETE #undef DELETE #endif -#ifdef INSERT +#ifdef INSERT #undef INSERT #endif #endif @@ -23,40 +22,34 @@ namespace bolt { namespace collaboration { -enum class OperationType { - INSERT, - DELETE, - CURSOR_MOVE, - NOOP -}; +enum class OperationType { INSERT, DELETE, CURSOR_MOVE, NOOP }; struct Position { size_t line; size_t character; - - Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} - - bool operator==(const Position& other) const { - return line == other.line && character == other.character; - } - + + explicit Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} + + bool operator==(const Position& other) const { return line == other.line && character == other.character; } + bool operator<(const Position& other) const { - if (line != other.line) return line < other.line; + if (line != other.line) + return line < other.line; return character < other.character; } - + // Convert to linear position in document size_t toLinear(const std::vector& lines) const { size_t pos = 0; for (size_t i = 0; i < line && i < lines.size(); ++i) { - pos += lines[i].length() + 1; // +1 for newline + pos += lines[i].length() + 1; // +1 for newline } if (line < lines.size()) { pos += std::min(character, lines[line].length()); } return pos; } - + // Convert from linear position static Position fromLinear(size_t linear, const std::vector& lines) { size_t pos = 0; @@ -65,30 +58,33 @@ struct Position { if (linear <= lineEnd) { return Position(i, linear - pos); } - pos = lineEnd + 1; // +1 for newline + pos = lineEnd + 1; // +1 for newline } return Position(lines.size(), 0); } }; class DocumentOperation { -public: - DocumentOperation(OperationType type, const std::string& userId, - const Position& pos, const std::string& content = "") - : type_(type), userId_(userId), position_(pos), content_(content), + public: + DocumentOperation(OperationType type, const std::string& userId, const Position& pos, + const std::string& content = "") + : type_(type), + userId_(userId), + position_(pos), + content_(content), timestamp_(std::chrono::steady_clock::now()), sequence_(nextSequence()) {} - + virtual ~DocumentOperation() = default; - + OperationType getType() const { return type_; } const std::string& getUserId() const { return userId_; } const Position& getPosition() const { return position_; } const std::string& getContent() const { return content_; } uint64_t getSequence() const { return sequence_; } - + void setPosition(const Position& pos) { position_ = pos; } - + // Apply operation to document lines virtual bool apply(std::vector& lines) const { switch (type_) { @@ -97,41 +93,38 @@ class DocumentOperation { case OperationType::DELETE: return applyDelete(lines); case OperationType::CURSOR_MOVE: - return true; // Cursor moves don't modify document + return true; // Cursor moves don't modify document case OperationType::NOOP: return true; } return false; } - + // Create inverse operation virtual std::unique_ptr createInverse() const { switch (type_) { case OperationType::INSERT: - return std::make_unique( - OperationType::DELETE, userId_, position_, content_); + return std::make_unique(OperationType::DELETE, userId_, position_, content_); case OperationType::DELETE: - return std::make_unique( - OperationType::INSERT, userId_, position_, content_); + return std::make_unique(OperationType::INSERT, userId_, position_, content_); default: - return std::make_unique( - OperationType::NOOP, userId_, position_); + return std::make_unique(OperationType::NOOP, userId_, position_); } } - + // Serialize for network transmission std::string serialize() const { std::string result = "{"; result += "\"type\":" + std::to_string(static_cast(type_)) + ","; result += "\"userId\":\"" + userId_ + "\","; - result += "\"position\":{\"line\":" + std::to_string(position_.line) + + result += "\"position\":{\"line\":" + std::to_string(position_.line) + ",\"character\":" + std::to_string(position_.character) + "},"; result += "\"content\":\"" + escapeString(content_) + "\","; result += "\"sequence\":" + std::to_string(sequence_); result += "}"; return result; } - + // Deserialize from JSON-like string (simplified) static std::unique_ptr deserialize(const std::string& data) { // Simplified JSON parsing - in production would use proper JSON library @@ -140,105 +133,124 @@ class DocumentOperation { auto line = extractInt(data, "position\":{\"line"); auto character = extractInt(data, "character"); auto content = extractString(data, "content"); - - return std::make_unique( - static_cast(type), userId, Position(line, character), content); + + return std::make_unique(static_cast(type), userId, Position(line, character), + content); } -private: + private: OperationType type_; std::string userId_; Position position_; std::string content_; std::chrono::steady_clock::time_point timestamp_; uint64_t sequence_; - + static uint64_t nextSequence() { static uint64_t counter = 0; return ++counter; } - + bool applyInsert(std::vector& lines) const { if (position_.line >= lines.size()) { // Extend lines if necessary lines.resize(position_.line + 1); } - + std::string& line = lines[position_.line]; if (position_.character > line.length()) { line.resize(position_.character, ' '); } - + line.insert(position_.character, content_); return true; } - + bool applyDelete(std::vector& lines) const { - if (position_.line >= lines.size()) return false; - + if (position_.line >= lines.size()) + return false; + std::string& line = lines[position_.line]; - if (position_.character >= line.length()) return false; - + if (position_.character >= line.length()) + return false; + size_t deleteLen = std::min(content_.length(), line.length() - position_.character); line.erase(position_.character, deleteLen); return true; } - + std::string escapeString(const std::string& str) const { std::string result; for (char c : str) { - if (c == '"') result += "\\\""; - else if (c == '\\') result += "\\\\"; - else if (c == '\n') result += "\\n"; - else if (c == '\r') result += "\\r"; - else if (c == '\t') result += "\\t"; - else result += c; + if (c == '"') + result += "\\\""; + else if (c == '\\') + result += "\\\\"; + else if (c == '\n') + result += "\\n"; + else if (c == '\r') + result += "\\r"; + else if (c == '\t') + result += "\\t"; + else + result += c; } return result; } - + static int extractInt(const std::string& data, const std::string& key) { auto pos = data.find("\"" + key + "\":"); - if (pos == std::string::npos) return 0; + if (pos == std::string::npos) + return 0; pos = data.find(":", pos) + 1; - + // Skip whitespace - while (pos < data.length() && std::isspace(data[pos])) pos++; - + while (pos < data.length() && std::isspace(data[pos])) + pos++; + auto end = data.find_first_of(",}", pos); - if (end == std::string::npos) end = data.length(); - + if (end == std::string::npos) + end = data.length(); + std::string numberStr = data.substr(pos, end - pos); - + // Trim whitespace numberStr.erase(0, numberStr.find_first_not_of(" \t\n\r")); numberStr.erase(numberStr.find_last_not_of(" \t\n\r") + 1); - - if (numberStr.empty()) return 0; - + + if (numberStr.empty()) + return 0; + try { return std::stoi(numberStr); } catch (...) { return 0; } } - + static std::string extractString(const std::string& data, const std::string& key) { auto pos = data.find("\"" + key + "\":\""); - if (pos == std::string::npos) return ""; + if (pos == std::string::npos) + return ""; pos = data.find("\":\"", pos) + 3; - + std::string result; bool escaped = false; for (size_t i = pos; i < data.length(); ++i) { char c = data[i]; if (escaped) { - if (c == 'n') result += '\n'; - else if (c == 'r') result += '\r'; - else if (c == 't') result += '\t'; - else if (c == '"') result += '"'; - else if (c == '\\') result += '\\'; - else result += c; + if (c == 'n') + result += '\n'; + else if (c == 'r') + result += '\r'; + else if (c == 't') + result += '\t'; + else if (c == '"') + result += '"'; + else if (c == '\\') + result += '\\'; + else + result += c; escaped = false; } else if (c == '\\') { escaped = true; @@ -252,7 +264,7 @@ class DocumentOperation { } }; -} // namespace collaboration -} // namespace bolt +} // namespace collaboration +} // namespace bolt -#endif +#endif // BOLT_COLLABORATION_DOCUMENT_OPERATION_HPP_ diff --git a/include/bolt/collaboration/operational_transform.hpp b/include/bolt/collaboration/operational_transform.hpp index aa93f925..d75cdd93 100644 --- a/include/bolt/collaboration/operational_transform.hpp +++ b/include/bolt/collaboration/operational_transform.hpp @@ -1,29 +1,28 @@ -#ifndef OPERATIONAL_TRANSFORM_HPP -#define OPERATIONAL_TRANSFORM_HPP +#ifndef BOLT_COLLABORATION_OPERATIONAL_TRANSFORM_HPP_ +#define BOLT_COLLABORATION_OPERATIONAL_TRANSFORM_HPP_ -#include "document_operation.hpp" -#include -#include #include +#include +#include +#include + +#include "bolt/collaboration/document_operation.hpp" namespace bolt { namespace collaboration { class OperationalTransform { -public: + public: // Transform operation A against operation B (A was issued before B) // Returns transformed version of A that can be applied after B - static std::unique_ptr transform( - const DocumentOperation& opA, - const DocumentOperation& opB) { - + static std::unique_ptr transform(const DocumentOperation& opA, const DocumentOperation& opB) { // If operations are from same user, no transformation needed if (opA.getUserId() == opB.getUserId()) { return std::make_unique(opA); } - + auto newOpA = std::make_unique(opA); - + // Handle different operation type combinations switch (opA.getType()) { case OperationType::INSERT: @@ -39,71 +38,65 @@ class OperationalTransform { // No transformation needed for NOOP break; } - + return newOpA; } - + // Transform a batch of operations against a single operation static std::vector> transformBatch( - const std::vector>& operations, - const DocumentOperation& against) { - + const std::vector>& operations, const DocumentOperation& against) { std::vector> transformed; transformed.reserve(operations.size()); - + for (const auto& op : operations) { transformed.push_back(transform(*op, against)); } - + return transformed; } - + // Resolve conflicts when operations arrive out of order static std::vector> resolveConflicts( std::vector>& operations) { - // Sort operations by sequence number to establish a consistent order std::sort(operations.begin(), operations.end(), - [](const std::unique_ptr& a, - const std::unique_ptr& b) { - return a->getSequence() < b->getSequence(); - }); - + [](const std::unique_ptr& a, const std::unique_ptr& b) { + return a->getSequence() < b->getSequence(); + }); + std::vector> resolved; resolved.reserve(operations.size()); - + for (auto& op : operations) { // Transform this operation against all previously resolved operations auto transformedOp = std::make_unique(*op); - + for (const auto& previousOp : resolved) { auto temp = transform(*transformedOp, *previousOp); transformedOp = std::move(temp); } - + resolved.push_back(std::move(transformedOp)); } - + return resolved; } -private: + private: static void transformInsert(DocumentOperation& insert, const DocumentOperation& other) { Position insertPos = insert.getPosition(); Position otherPos = other.getPosition(); - + switch (other.getType()) { case OperationType::INSERT: { // If other insert is at same line and before/at current position if (otherPos.line == insertPos.line && otherPos.character <= insertPos.character) { insertPos.character += other.getContent().length(); insert.setPosition(insertPos); - } - // If other insert is on previous line - else if (otherPos.line < insertPos.line) { + } else if (otherPos.line < insertPos.line) { + // If other insert is on previous line // Check if the insert contains newlines - size_t newlineCount = std::count(other.getContent().begin(), - other.getContent().end(), '\n'); + size_t newlineCount = std::count(other.getContent().begin(), other.getContent().end(), '\n'); if (newlineCount > 0) { insertPos.line += newlineCount; insert.setPosition(insertPos); @@ -125,12 +118,10 @@ class OperationalTransform { insertPos.character -= other.getContent().length(); } insert.setPosition(insertPos); - } - // If delete is on previous line - else if (otherPos.line < insertPos.line) { + } else if (otherPos.line < insertPos.line) { + // If delete is on previous line // Check if the delete removes newlines - size_t newlineCount = std::count(other.getContent().begin(), - other.getContent().end(), '\n'); + size_t newlineCount = std::count(other.getContent().begin(), other.getContent().end(), '\n'); if (newlineCount > 0) { insertPos.line -= std::min(newlineCount, insertPos.line); insert.setPosition(insertPos); @@ -144,22 +135,20 @@ class OperationalTransform { break; } } - + static void transformDelete(DocumentOperation& delete_op, const DocumentOperation& other) { Position deletePos = delete_op.getPosition(); Position otherPos = other.getPosition(); - + switch (other.getType()) { case OperationType::INSERT: { // If insert is at same line and before/at current position if (otherPos.line == deletePos.line && otherPos.character <= deletePos.character) { deletePos.character += other.getContent().length(); delete_op.setPosition(deletePos); - } - // If insert is on previous line with newlines - else if (otherPos.line < deletePos.line) { - size_t newlineCount = std::count(other.getContent().begin(), - other.getContent().end(), '\n'); + } else if (otherPos.line < deletePos.line) { + // If insert is on previous line with newlines + size_t newlineCount = std::count(other.getContent().begin(), other.getContent().end(), '\n'); if (newlineCount > 0) { deletePos.line += newlineCount; delete_op.setPosition(deletePos); @@ -170,15 +159,12 @@ class OperationalTransform { case OperationType::DELETE: { // If other delete is at same line and before current position if (otherPos.line == deletePos.line && otherPos.character < deletePos.character) { - size_t deleteLen = std::min(other.getContent().length(), - deletePos.character - otherPos.character); + size_t deleteLen = std::min(other.getContent().length(), deletePos.character - otherPos.character); deletePos.character -= deleteLen; delete_op.setPosition(deletePos); - } - // If delete is on previous line with newlines - else if (otherPos.line < deletePos.line) { - size_t newlineCount = std::count(other.getContent().begin(), - other.getContent().end(), '\n'); + } else if (otherPos.line < deletePos.line) { + // If delete is on previous line with newlines + size_t newlineCount = std::count(other.getContent().begin(), other.getContent().end(), '\n'); if (newlineCount > 0) { deletePos.line -= std::min(newlineCount, deletePos.line); delete_op.setPosition(deletePos); @@ -192,22 +178,20 @@ class OperationalTransform { break; } } - + static void transformCursor(DocumentOperation& cursor, const DocumentOperation& other) { Position cursorPos = cursor.getPosition(); Position otherPos = other.getPosition(); - + switch (other.getType()) { case OperationType::INSERT: { // If insert is at same line and before/at cursor position if (otherPos.line == cursorPos.line && otherPos.character <= cursorPos.character) { cursorPos.character += other.getContent().length(); cursor.setPosition(cursorPos); - } - // If insert is on previous line with newlines - else if (otherPos.line < cursorPos.line) { - size_t newlineCount = std::count(other.getContent().begin(), - other.getContent().end(), '\n'); + } else if (otherPos.line < cursorPos.line) { + // If insert is on previous line with newlines + size_t newlineCount = std::count(other.getContent().begin(), other.getContent().end(), '\n'); if (newlineCount > 0) { cursorPos.line += newlineCount; cursor.setPosition(cursorPos); @@ -218,15 +202,12 @@ class OperationalTransform { case OperationType::DELETE: { // If delete is at same line and before cursor position if (otherPos.line == cursorPos.line && otherPos.character < cursorPos.character) { - size_t deleteLen = std::min(other.getContent().length(), - cursorPos.character - otherPos.character); + size_t deleteLen = std::min(other.getContent().length(), cursorPos.character - otherPos.character); cursorPos.character -= deleteLen; cursor.setPosition(cursorPos); - } - // If delete is on previous line with newlines - else if (otherPos.line < cursorPos.line) { - size_t newlineCount = std::count(other.getContent().begin(), - other.getContent().end(), '\n'); + } else if (otherPos.line < cursorPos.line) { + // If delete is on previous line with newlines + size_t newlineCount = std::count(other.getContent().begin(), other.getContent().end(), '\n'); if (newlineCount > 0) { cursorPos.line -= std::min(newlineCount, cursorPos.line); cursor.setPosition(cursorPos); @@ -242,7 +223,7 @@ class OperationalTransform { } }; -} // namespace collaboration -} // namespace bolt +} // namespace collaboration +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_COLLABORATION_OPERATIONAL_TRANSFORM_HPP_ diff --git a/include/bolt/core/benchmark_suite.hpp b/include/bolt/core/benchmark_suite.hpp index c2715288..cf1d536f 100644 --- a/include/bolt/core/benchmark_suite.hpp +++ b/include/bolt/core/benchmark_suite.hpp @@ -1,15 +1,17 @@ -#ifndef BOLT_BENCHMARK_SUITE_HPP -#define BOLT_BENCHMARK_SUITE_HPP +#ifndef BOLT_CORE_BENCHMARK_SUITE_HPP_ +#define BOLT_CORE_BENCHMARK_SUITE_HPP_ -#include -#include -#include -#include #include -#include #include +#include +#include #include -#include "performance_profiler.hpp" +#include +#include +#include +#include + +#include "bolt/core/performance_profiler.hpp" namespace bolt { @@ -28,10 +30,10 @@ struct BenchmarkConfig { int warmupRuns = 3; std::chrono::milliseconds timeout = std::chrono::milliseconds(30000); std::unordered_map parameters; - + // Default constructor BenchmarkConfig() = default; - + BenchmarkConfig(const std::string& benchmarkName, const std::string& benchmarkDescription) : name(benchmarkName), description(benchmarkDescription), category("GENERAL") {} }; @@ -43,31 +45,33 @@ struct BenchmarkResult { std::string name; std::string category; std::string description; - + // Performance metrics double averageDurationMs = 0.0; double minDurationMs = 0.0; double maxDurationMs = 0.0; double standardDeviationMs = 0.0; - + // Resource usage double averageMemoryUsageMB = 0.0; double maxMemoryUsageMB = 0.0; double averageCpuUsagePercent = 0.0; - + // Execution details int totalIterations = 0; int successfulRuns = 0; int failedRuns = 0; std::chrono::steady_clock::time_point timestamp; std::vector rawDurations; - + // Metadata std::unordered_map metadata; std::string errorMessage; - + bool isValid() const { return successfulRuns > 0; } - double getSuccessRate() const { return totalIterations > 0 ? (double)successfulRuns / totalIterations : 0.0; } + double getSuccessRate() const { + return totalIterations > 0 ? static_cast(successfulRuns) / totalIterations : 0.0; + } }; /** @@ -77,15 +81,15 @@ struct BenchmarkComparison { std::string benchmarkName; BenchmarkResult baseline; BenchmarkResult current; - + // Performance comparison metrics double durationChangePercent = 0.0; double memoryChangePercent = 0.0; double cpuChangePercent = 0.0; - + enum class Status { IMPROVED, DEGRADED, STABLE, INCONCLUSIVE }; Status performanceStatus = Status::INCONCLUSIVE; - + bool hasRegression() const { return performanceStatus == Status::DEGRADED; } bool hasImprovement() const { return performanceStatus == Status::IMPROVED; } }; @@ -99,53 +103,51 @@ using BenchmarkFunction = std::function; * Main benchmark suite class */ class BenchmarkSuite { -public: + public: /** * Get singleton instance */ static BenchmarkSuite& getInstance(); - + /** * Register a benchmark function */ void registerBenchmark(const BenchmarkConfig& config, BenchmarkFunction function); - + /** * Run all registered benchmarks */ std::vector runAllBenchmarks(); - + /** * Run benchmarks by category */ std::vector runBenchmarksByCategory(const std::string& category); - + /** * Run a specific benchmark by name */ BenchmarkResult runBenchmark(const std::string& name); - + /** * Compare benchmark results with baseline */ - std::vector compareWithBaseline( - const std::vector& current, - const std::vector& baseline - ); - + std::vector compareWithBaseline(const std::vector& current, + const std::vector& baseline); + /** * Generate benchmark reports */ void generateJsonReport(const std::vector& results, const std::string& filename); void generateCsvReport(const std::vector& results, const std::string& filename); void generateHtmlReport(const std::vector& results, const std::string& filename); - + /** * Load and save baseline results */ std::vector loadBaselineResults(const std::string& filename); void saveBaselineResults(const std::vector& results, const std::string& filename); - + /** * Configuration */ @@ -153,43 +155,44 @@ class BenchmarkSuite { void setDefaultWarmupRuns(int warmupRuns) { defaultWarmupRuns_ = warmupRuns; } void setDefaultTimeout(std::chrono::milliseconds timeout) { defaultTimeout_ = timeout; } void enableVerboseOutput(bool enable) { verboseOutput_ = enable; } - + /** * Get available benchmarks */ std::vector getAvailableBenchmarks() const; std::vector getAvailableCategories() const; -private: + private: BenchmarkSuite() = default; BenchmarkSuite(const BenchmarkSuite&) = delete; BenchmarkSuite& operator=(const BenchmarkSuite&) = delete; - -public: + + public: ~BenchmarkSuite() = default; - + // Internal benchmark execution BenchmarkResult executeBenchmark(const BenchmarkConfig& config, BenchmarkFunction function); - + // Statistical calculations double calculateStandardDeviation(const std::vector& values, double mean); - BenchmarkComparison::Status determinePerformanceStatus(const BenchmarkResult& baseline, const BenchmarkResult& current); - + BenchmarkComparison::Status determinePerformanceStatus(const BenchmarkResult& baseline, + const BenchmarkResult& current); + // Report generation helpers std::string formatDuration(double milliseconds); std::string formatMemory(double megabytes); std::string formatPercentage(double percentage); - + // Member variables std::unordered_map> benchmarks_; mutable std::mutex benchmarksMutex_; - + // Configuration int defaultIterations_ = 10; int defaultWarmupRuns_ = 3; std::chrono::milliseconds defaultTimeout_ = std::chrono::milliseconds(30000); bool verboseOutput_ = false; - + // Thresholds for performance status static constexpr double IMPROVEMENT_THRESHOLD = -5.0; // -5% or better is improvement static constexpr double REGRESSION_THRESHOLD = 10.0; // +10% or worse is regression @@ -198,35 +201,35 @@ class BenchmarkSuite { /** * Convenience macros for benchmark registration */ -#define BOLT_BENCHMARK(name, category) \ - void benchmark_##name(const bolt::BenchmarkConfig& config); \ - namespace { \ - struct BenchmarkRegistrar_##name { \ - BenchmarkRegistrar_##name() { \ - bolt::BenchmarkConfig config(#name, "Benchmark for " #name); \ - config.category = category; \ - bolt::BenchmarkSuite::getInstance().registerBenchmark(config, benchmark_##name); \ - } \ - }; \ - static BenchmarkRegistrar_##name benchmarkRegistrar_##name; \ - } \ +#define BOLT_BENCHMARK(name, category) \ + void benchmark_##name(const bolt::BenchmarkConfig& config); \ + namespace { \ + struct BenchmarkRegistrar_##name { \ + BenchmarkRegistrar_##name() { \ + bolt::BenchmarkConfig config(#name, "Benchmark for " #name); \ + config.category = category; \ + bolt::BenchmarkSuite::getInstance().registerBenchmark(config, benchmark_##name); \ + } \ + }; \ + static BenchmarkRegistrar_##name benchmarkRegistrar_##name; \ + } /* namespace */ \ void benchmark_##name(const bolt::BenchmarkConfig& config) -#define BOLT_BENCHMARK_CONFIG(name, category, desc, iters) \ - void benchmark_##name(const bolt::BenchmarkConfig& config); \ - namespace { \ - struct BenchmarkRegistrar_##name { \ - BenchmarkRegistrar_##name() { \ - bolt::BenchmarkConfig config(#name, desc); \ - config.category = category; \ - config.iterations = iters; \ - bolt::BenchmarkSuite::getInstance().registerBenchmark(config, benchmark_##name); \ - } \ - }; \ - static BenchmarkRegistrar_##name benchmarkRegistrar_##name; \ - } \ +#define BOLT_BENCHMARK_CONFIG(name, category, desc, iters) \ + void benchmark_##name(const bolt::BenchmarkConfig& config); \ + namespace { \ + struct BenchmarkRegistrar_##name { \ + BenchmarkRegistrar_##name() { \ + bolt::BenchmarkConfig config(#name, desc); \ + config.category = category; \ + config.iterations = iters; \ + bolt::BenchmarkSuite::getInstance().registerBenchmark(config, benchmark_##name); \ + } \ + }; \ + static BenchmarkRegistrar_##name benchmarkRegistrar_##name; \ + } /* namespace */ \ void benchmark_##name(const bolt::BenchmarkConfig& config) -} // namespace bolt +} // namespace bolt -#endif // BOLT_BENCHMARK_SUITE_HPP \ No newline at end of file +#endif // BOLT_CORE_BENCHMARK_SUITE_HPP_ diff --git a/include/bolt/core/bolt_commands.hpp b/include/bolt/core/bolt_commands.hpp index 6ddbafe2..b6febcf8 100644 --- a/include/bolt/core/bolt_commands.hpp +++ b/include/bolt/core/bolt_commands.hpp @@ -1,25 +1,27 @@ -#ifndef BOLT_COMMANDS_HPP -#define BOLT_COMMANDS_HPP +#ifndef BOLT_CORE_BOLT_COMMANDS_HPP_ +#define BOLT_CORE_BOLT_COMMANDS_HPP_ -#include +#include #include -#include #include -#include +#include +#include +#include + #include "bolt/utils/filesystem_utils.hpp" namespace bolt { class Command { -public: + public: virtual ~Command() = default; virtual void execute() = 0; virtual std::string getDescription() const = 0; }; class CommandProcessor { -public: + public: static CommandProcessor& getInstance() { static CommandProcessor instance; return instance; @@ -43,11 +45,11 @@ class CommandProcessor { return it != commands_.end() ? it->second->getDescription() : "Command not found"; } -private: + private: CommandProcessor() = default; std::unordered_map> commands_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_CORE_BOLT_COMMANDS_HPP_ diff --git a/include/bolt/core/chat_store.hpp b/include/bolt/core/chat_store.hpp index 7ce34e48..61b5975d 100644 --- a/include/bolt/core/chat_store.hpp +++ b/include/bolt/core/chat_store.hpp @@ -1,11 +1,12 @@ -#ifndef CHAT_STORE_HPP -#define CHAT_STORE_HPP +#ifndef BOLT_CORE_CHAT_STORE_HPP_ +#define BOLT_CORE_CHAT_STORE_HPP_ -#include -#include #include #include -#include "error_handling.hpp" +#include +#include + +#include "bolt/core/error_handling.hpp" namespace bolt { @@ -13,13 +14,10 @@ namespace bolt { struct SimpleChatMessage { std::string sender; std::string content; - + SimpleChatMessage() = default; - SimpleChatMessage(const std::string& s, const std::string& c) - : sender(s), content(c) { - validateMessage(); - } - + SimpleChatMessage(const std::string& s, const std::string& c) : sender(s), content(c) { validateMessage(); } + void validateMessage() const { if (sender.empty()) { throw StoreException(ErrorCode::INVALID_PARAMETER, "Message sender cannot be empty"); @@ -28,23 +26,23 @@ struct SimpleChatMessage { throw StoreException(ErrorCode::INVALID_PARAMETER, "Message content cannot be empty"); } if (sender.length() > MAX_SENDER_LENGTH) { - throw StoreException(ErrorCode::INVALID_PARAMETER, - "Sender name too long: " + std::to_string(sender.length()) + - " > " + std::to_string(MAX_SENDER_LENGTH)); + throw StoreException( + ErrorCode::INVALID_PARAMETER, + "Sender name too long: " + std::to_string(sender.length()) + " > " + std::to_string(MAX_SENDER_LENGTH)); } if (content.length() > MAX_CONTENT_LENGTH) { throw StoreException(ErrorCode::INVALID_PARAMETER, - "Message content too long: " + std::to_string(content.length()) + - " > " + std::to_string(MAX_CONTENT_LENGTH)); + "Message content too long: " + std::to_string(content.length()) + " > " + + std::to_string(MAX_CONTENT_LENGTH)); } } - + static constexpr size_t MAX_SENDER_LENGTH = 256; - static constexpr size_t MAX_CONTENT_LENGTH = 65536; // 64KB + static constexpr size_t MAX_CONTENT_LENGTH = 65536; // 64KB }; class ChatStore { -public: + public: static ChatStore& getInstance() { static ChatStore instance; return instance; @@ -68,69 +66,69 @@ class ChatStore { notifyListeners(); } - bool getChatStarted() const { + bool getChatStarted() const { std::lock_guard lock(mutex_); - return chatStarted_; + return chatStarted_; } - - bool getShowChat() const { + + bool getShowChat() const { std::lock_guard lock(mutex_); - return showChat_; + return showChat_; } - - bool getAborted() const { + + bool getAborted() const { std::lock_guard lock(mutex_); - return aborted_; + return aborted_; } void addListener(std::function listener) { ErrorHandler::validateParameter(listener != nullptr, "Listener cannot be null"); - + std::lock_guard lock(mutex_); - + if (listeners_.size() >= MAX_LISTENERS) { throw StoreException(ErrorCode::STORE_STATE_INVALID, - "Maximum number of listeners reached: " + std::to_string(MAX_LISTENERS)); + "Maximum number of listeners reached: " + std::to_string(MAX_LISTENERS)); } - + listeners_.push_back(listener); } void addMessage(const SimpleChatMessage& msg) { - msg.validateMessage(); // Validate message before adding - + msg.validateMessage(); // Validate message before adding + std::lock_guard lock(mutex_); - + if (messages_.size() >= MAX_MESSAGES) { throw StoreException(ErrorCode::STORE_STATE_INVALID, - "Maximum number of messages reached: " + std::to_string(MAX_MESSAGES)); + "Maximum number of messages reached: " + std::to_string(MAX_MESSAGES)); } - + messages_.push_back(msg); } - const std::vector& getMessages() const { + const std::vector& getMessages() const { std::lock_guard lock(mutex_); - return messages_; + return messages_; } - + size_t getMessageCount() const { std::lock_guard lock(mutex_); return messages_.size(); } - + size_t getListenerCount() const { std::lock_guard lock(mutex_); return listeners_.size(); } - + void clearMessages() { std::lock_guard lock(mutex_); messages_.clear(); notifyListeners(); } -private: + private: ChatStore() : chatStarted_(false), showChat_(true), aborted_(false) {} void notifyListeners() { @@ -154,11 +152,11 @@ class ChatStore { std::vector> listeners_; std::vector messages_; mutable std::mutex mutex_; - + static constexpr size_t MAX_LISTENERS = 100; static constexpr size_t MAX_MESSAGES = 10000; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_CORE_CHAT_STORE_HPP_ diff --git a/include/bolt/core/error_handling.hpp b/include/bolt/core/error_handling.hpp index cd31562e..65b2b681 100644 --- a/include/bolt/core/error_handling.hpp +++ b/include/bolt/core/error_handling.hpp @@ -1,5 +1,5 @@ -#ifndef BOLT_ERROR_HANDLING_HPP -#define BOLT_ERROR_HANDLING_HPP +#ifndef BOLT_CORE_ERROR_HANDLING_HPP_ +#define BOLT_CORE_ERROR_HANDLING_HPP_ #include #include @@ -14,23 +14,23 @@ enum class ErrorCode { INVALID_MEMORY_SIZE, NULL_POINTER_ACCESS, MEMORY_CORRUPTION, - + // Message handling errors MESSAGE_QUEUE_FULL = 200, INVALID_MESSAGE_TYPE, MESSAGE_PROCESSING_FAILED, MESSAGE_HANDLER_NOT_INITIALIZED, - + // Store errors STORE_STATE_INVALID = 300, STORE_LISTENER_FAILED, STORE_DATA_CORRUPTED, - + // Editor errors EDITOR_DOCUMENT_INVALID = 400, EDITOR_OPERATION_FAILED, EDITOR_FOLDING_ERROR, - + // General errors COMPONENT_NOT_INITIALIZED = 500, INVALID_PARAMETER, @@ -40,15 +40,15 @@ enum class ErrorCode { // Base exception class for Bolt components class BoltException : public std::runtime_error { -public: + public: explicit BoltException(ErrorCode code, const std::string& message) : std::runtime_error(formatMessage(code, message)), errorCode_(code) {} - + ErrorCode getErrorCode() const noexcept { return errorCode_; } - -private: + + private: ErrorCode errorCode_; - + static std::string formatMessage(ErrorCode code, const std::string& message) { return "[Bolt Error " + std::to_string(static_cast(code)) + "] " + message; } @@ -56,75 +56,68 @@ class BoltException : public std::runtime_error { // Specific exception classes for different components class MemoryException : public BoltException { -public: - explicit MemoryException(ErrorCode code, const std::string& message) - : BoltException(code, message) {} + public: + explicit MemoryException(ErrorCode code, const std::string& message) : BoltException(code, message) {} }; class MessageException : public BoltException { -public: - explicit MessageException(ErrorCode code, const std::string& message) - : BoltException(code, message) {} + public: + explicit MessageException(ErrorCode code, const std::string& message) : BoltException(code, message) {} }; class StoreException : public BoltException { -public: - explicit StoreException(ErrorCode code, const std::string& message) - : BoltException(code, message) {} + public: + explicit StoreException(ErrorCode code, const std::string& message) : BoltException(code, message) {} }; class EditorException : public BoltException { -public: - explicit EditorException(ErrorCode code, const std::string& message) - : BoltException(code, message) {} + public: + explicit EditorException(ErrorCode code, const std::string& message) : BoltException(code, message) {} }; // Error handling utilities class ErrorHandler { -public: + public: // Validate common conditions static void validateNotNull(const void* ptr, const std::string& paramName) { if (!ptr) { - throw BoltException(ErrorCode::NULL_POINTER_ACCESS, - "Parameter '" + paramName + "' cannot be null"); + throw BoltException(ErrorCode::NULL_POINTER_ACCESS, "Parameter '" + paramName + "' cannot be null"); } } - + static void validateParameter(bool condition, const std::string& message) { if (!condition) { throw BoltException(ErrorCode::INVALID_PARAMETER, message); } } - + static void validateMemorySize(size_t size) { if (size == 0) { - throw MemoryException(ErrorCode::INVALID_MEMORY_SIZE, - "Memory size cannot be zero"); + throw MemoryException(ErrorCode::INVALID_MEMORY_SIZE, "Memory size cannot be zero"); } if (size > SIZE_MAX / 2) { - throw MemoryException(ErrorCode::INVALID_MEMORY_SIZE, - "Memory size too large: " + std::to_string(size)); + throw MemoryException(ErrorCode::INVALID_MEMORY_SIZE, "Memory size too large: " + std::to_string(size)); } } - + static void validateInitialized(bool initialized, const std::string& componentName) { if (!initialized) { throw BoltException(ErrorCode::COMPONENT_NOT_INITIALIZED, - "Component '" + componentName + "' not initialized"); + "Component '" + componentName + "' not initialized"); } } }; // RAII-style error scope for automatic error handling class ErrorScope { -public: + public: explicit ErrorScope(const std::string& operation) : operation_(operation) {} - + ~ErrorScope() noexcept { // Log completion if needed } - - template + + template auto execute(Func&& func) -> decltype(func()) { try { return func(); @@ -133,22 +126,21 @@ class ErrorScope { throw; } catch (const std::exception& e) { // Wrap standard exceptions - throw BoltException(ErrorCode::UNKNOWN_ERROR, - "Error in " + operation_ + ": " + e.what()); + throw BoltException(ErrorCode::UNKNOWN_ERROR, "Error in " + operation_ + ": " + e.what()); } } - -private: + + private: std::string operation_; }; // Macro for error scope usage -#define BOLT_ERROR_SCOPE(operation) \ +#define BOLT_ERROR_SCOPE(operation) \ bolt::ErrorScope errorScope(operation); \ errorScope.execute([&]() #define BOLT_ERROR_SCOPE_END ) -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_CORE_ERROR_HANDLING_HPP_ diff --git a/include/bolt/core/logging.hpp b/include/bolt/core/logging.hpp index 7319c5ac..dddd30d6 100644 --- a/include/bolt/core/logging.hpp +++ b/include/bolt/core/logging.hpp @@ -1,46 +1,47 @@ -#ifndef BOLT_LOGGING_HPP -#define BOLT_LOGGING_HPP +#ifndef BOLT_CORE_LOGGING_HPP_ +#define BOLT_CORE_LOGGING_HPP_ -#include -#include -#include -#include -#include +#include #include +#include +#include #include +#include +#include #include -#include -#include -#include +#include #include -#include "thread_safety.hpp" +#include +#include + +#include "bolt/core/thread_safety.hpp" namespace bolt { // Log levels in order of severity enum class LogLevel { - TRACE = 0, // Detailed debugging information - DEBUG = 1, // General debugging information - INFO = 2, // Informational messages - WARN = 3, // Warning messages - ERROR = 4, // Error messages - FATAL = 5, // Fatal error messages - OFF = 6 // Disable logging + TRACE = 0, // Detailed debugging information + DEBUG = 1, // General debugging information + INFO = 2, // Informational messages + WARN = 3, // Warning messages + ERROR = 4, // Error messages + FATAL = 5, // Fatal error messages + OFF = 6 // Disable logging }; // Log categories for different components enum class LogCategory { - CORE, // Core system components - MEMORY, // Memory management - EDITOR, // Editor functionality - AI, // AI/ML components - GUI, // User interface - NETWORK, // Network operations - PLUGIN, // Plugin system - COLLABORATION,// Collaborative editing - DEBUGGER, // Debugger functionality - TESTING, // Test framework - UNKNOWN // Unknown or miscellaneous + CORE, // Core system components + MEMORY, // Memory management + EDITOR, // Editor functionality + AI, // AI/ML components + GUI, // User interface + NETWORK, // Network operations + PLUGIN, // Plugin system + COLLABORATION, // Collaborative editing + DEBUGGER, // Debugger functionality + TESTING, // Test framework + UNKNOWN // Unknown or miscellaneous }; // Forward declarations @@ -57,40 +58,45 @@ struct LogEntry { std::string function; std::chrono::system_clock::time_point timestamp; std::thread::id threadId; - - LogEntry(LogLevel lvl, LogCategory cat, const std::string& msg, - const std::string& f = "", int l = 0, const std::string& func = "") - : level(lvl), category(cat), message(msg), file(f), line(l), - function(func), timestamp(std::chrono::system_clock::now()), + + LogEntry(LogLevel lvl, LogCategory cat, const std::string& msg, const std::string& f = "", int l = 0, + const std::string& func = "") + : level(lvl), + category(cat), + message(msg), + file(f), + line(l), + function(func), + timestamp(std::chrono::system_clock::now()), threadId(std::this_thread::get_id()) {} }; // Abstract base class for log formatters class LogFormatter { -public: + public: virtual ~LogFormatter() = default; virtual std::string format(const LogEntry& entry) = 0; }; // Simple text formatter class SimpleFormatter : public LogFormatter { -public: + public: std::string format(const LogEntry& entry) override; }; // Detailed formatter with timestamp, thread ID, etc. class DetailedFormatter : public LogFormatter { -private: + private: bool includeTimestamp_; bool includeThreadId_; bool includeLocation_; - -public: - DetailedFormatter(bool timestamp = true, bool threadId = true, bool location = false) + + public: + explicit DetailedFormatter(bool timestamp = true, bool threadId = true, bool location = false) : includeTimestamp_(timestamp), includeThreadId_(threadId), includeLocation_(location) {} - + std::string format(const LogEntry& entry) override; - + void setIncludeTimestamp(bool include) { includeTimestamp_ = include; } void setIncludeThreadId(bool include) { includeThreadId_ = include; } void setIncludeLocation(bool include) { includeLocation_ = include; } @@ -98,13 +104,13 @@ class DetailedFormatter : public LogFormatter { // JSON formatter for structured logging class JsonFormatter : public LogFormatter { -public: + public: std::string format(const LogEntry& entry) override; }; // Abstract base class for log output destinations class LogSink { -public: + public: virtual ~LogSink() = default; virtual void write(const LogEntry& entry, const std::string& formattedMessage) = 0; virtual void flush() = 0; @@ -113,12 +119,12 @@ class LogSink { // Console output sink class ConsoleSink : public LogSink { -private: + private: bool useStderr_; - -public: + + public: explicit ConsoleSink(bool useStderr = false) : useStderr_(useStderr) {} - + void write(const LogEntry& entry, const std::string& formattedMessage) override; void flush() override; bool isOpen() const override { return true; } @@ -126,39 +132,39 @@ class ConsoleSink : public LogSink { // File output sink class FileSink : public LogSink { -private: + private: std::ofstream file_; std::string filename_; std::mutex mutex_; - -public: + + public: explicit FileSink(const std::string& filename); ~FileSink(); - + void write(const LogEntry& entry, const std::string& formattedMessage) override; void flush() override; bool isOpen() const override; - + const std::string& getFilename() const { return filename_; } }; // Rotating file sink (creates new files when size limit is reached) class RotatingFileSink : public LogSink { -private: + private: std::string baseFilename_; size_t maxFileSize_; size_t maxFiles_; std::unique_ptr currentFile_; size_t currentFileSize_; std::mutex mutex_; - + void rotateFile(); std::string getRotatedFilename(size_t index); - -public: + + public: RotatingFileSink(const std::string& baseFilename, size_t maxFileSize, size_t maxFiles); ~RotatingFileSink(); - + void write(const LogEntry& entry, const std::string& formattedMessage) override; void flush() override; bool isOpen() const override; @@ -166,49 +172,44 @@ class RotatingFileSink : public LogSink { // Log filter interface class LogFilter { -public: + public: virtual ~LogFilter() = default; virtual bool shouldLog(const LogEntry& entry) = 0; }; // Level-based filter class LevelFilter : public LogFilter { -private: + private: LogLevel minLevel_; - -public: + + public: explicit LevelFilter(LogLevel minLevel) : minLevel_(minLevel) {} - - bool shouldLog(const LogEntry& entry) override { - return entry.level >= minLevel_; - } - + + bool shouldLog(const LogEntry& entry) override { return entry.level >= minLevel_; } + void setMinLevel(LogLevel level) { minLevel_ = level; } LogLevel getMinLevel() const { return minLevel_; } }; // Category-based filter class CategoryFilter : public LogFilter { -private: + private: std::unordered_map categoryLevels_; LogLevel defaultLevel_; - -public: - explicit CategoryFilter(LogLevel defaultLevel = LogLevel::INFO) - : defaultLevel_(defaultLevel) {} - + + public: + explicit CategoryFilter(LogLevel defaultLevel = LogLevel::INFO) : defaultLevel_(defaultLevel) {} + bool shouldLog(const LogEntry& entry) override; - - void setCategoryLevel(LogCategory category, LogLevel level) { - categoryLevels_[category] = level; - } - + + void setCategoryLevel(LogCategory category, LogLevel level) { categoryLevels_[category] = level; } + void setDefaultLevel(LogLevel level) { defaultLevel_ = level; } }; // Main logger class class Logger { -private: + private: LogLevel level_; LogCategory defaultCategory_; std::vector> sinks_; @@ -216,109 +217,129 @@ class Logger { std::unique_ptr formatter_; ThreadSafe enabled_; mutable std::mutex mutex_; - + // Performance metrics std::atomic totalMessages_; std::atomic droppedMessages_; - + bool shouldLog(const LogEntry& entry) const; void writeToSinks(const LogEntry& entry); - -public: - Logger(LogLevel level = LogLevel::INFO, LogCategory defaultCategory = LogCategory::CORE); + + public: + explicit Logger(LogLevel level = LogLevel::INFO, LogCategory defaultCategory = LogCategory::CORE); ~Logger(); - + // Core logging methods - void log(LogLevel level, LogCategory category, const std::string& message, - const std::string& file = "", int line = 0, const std::string& function = ""); - - void log(LogLevel level, const std::string& message, - const std::string& file = "", int line = 0, const std::string& function = "") { + void log(LogLevel level, LogCategory category, const std::string& message, const std::string& file = "", + int line = 0, const std::string& function = ""); + + void log(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, defaultCategory_, message, file, line, function); } - + // Convenience methods for different log levels - void trace(const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + void trace(const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(LogLevel::TRACE, message, file, line, function); } - - void debug(const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void debug(const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(LogLevel::DEBUG, message, file, line, function); } - - void info(const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void info(const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(LogLevel::INFO, message, file, line, function); } - - void warn(const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void warn(const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(LogLevel::WARN, message, file, line, function); } - - void error(const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void error(const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(LogLevel::ERROR, message, file, line, function); } - - void fatal(const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void fatal(const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(LogLevel::FATAL, message, file, line, function); } - + // Category-specific logging - void logCore(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + void logCore(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::CORE, message, file, line, function); } - - void logMemory(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void logMemory(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::MEMORY, message, file, line, function); } - - void logEditor(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void logEditor(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::EDITOR, message, file, line, function); } - - void logAI(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void logAI(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::AI, message, file, line, function); } - - void logGUI(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void logGUI(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::GUI, message, file, line, function); } - - void logNetwork(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void logNetwork(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::NETWORK, message, file, line, function); } - - void logPlugin(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, const std::string& function = "") { + + void logPlugin(LogLevel level, const std::string& message, const std::string& file = "", int line = 0, + const std::string& function = "") { log(level, LogCategory::PLUGIN, message, file, line, function); } - + // Configuration methods void setLevel(LogLevel level) { level_ = level; } LogLevel getLevel() const { return level_; } - + void setDefaultCategory(LogCategory category) { defaultCategory_ = category; } LogCategory getDefaultCategory() const { return defaultCategory_; } - - void setEnabled(bool enabled) { enabled_.write([enabled](bool& e) { e = enabled; }); } - bool isEnabled() const { return enabled_.read([](const bool& e) { return e; }); } - + + void setEnabled(bool enabled) { + enabled_.write([enabled](bool& e) { e = enabled; }); + } + bool isEnabled() const { + return enabled_.read([](const bool& e) { return e; }); + } + // Sink management void addSink(std::unique_ptr sink); void clearSinks(); size_t getSinkCount() const; - + // Filter management void addFilter(std::unique_ptr filter); void clearFilters(); size_t getFilterCount() const; - + // Formatter management void setFormatter(std::unique_ptr formatter); - + // Performance metrics size_t getTotalMessages() const { return totalMessages_.load(); } size_t getDroppedMessages() const { return droppedMessages_.load(); } - void resetMetrics() { totalMessages_.store(0); droppedMessages_.store(0); } - + void resetMetrics() { + totalMessages_.store(0); + droppedMessages_.store(0); + } + // Utility methods void flush(); static std::string levelToString(LogLevel level); @@ -329,25 +350,27 @@ class Logger { // Global logger instance manager class LogManager { -private: + private: static std::unique_ptr globalLogger_; static std::mutex mutex_; - -public: + + public: static Logger& getInstance(); static void setGlobalLogger(std::unique_ptr logger); static void reset(); - + // Quick configuration methods static void configureConsoleLogging(LogLevel level = LogLevel::INFO, bool useDetailedFormat = true); - static void configureFileLogging(const std::string& filename, LogLevel level = LogLevel::DEBUG, bool useDetailedFormat = true); - static void configureRotatingFileLogging(const std::string& baseFilename, size_t maxFileSize, size_t maxFiles, LogLevel level = LogLevel::DEBUG); - static void configureDualLogging(const std::string& filename, LogLevel consoleLevel = LogLevel::INFO, LogLevel fileLevel = LogLevel::DEBUG); + static void configureFileLogging(const std::string& filename, LogLevel level = LogLevel::DEBUG, + bool useDetailedFormat = true); + static void configureRotatingFileLogging(const std::string& baseFilename, size_t maxFileSize, size_t maxFiles, + LogLevel level = LogLevel::DEBUG); + static void configureDualLogging(const std::string& filename, LogLevel consoleLevel = LogLevel::INFO, + LogLevel fileLevel = LogLevel::DEBUG); }; // Utility macros for easier logging with file/line information -#define BOLT_LOG(level, message) \ - bolt::LogManager::getInstance().log(level, message, __FILE__, __LINE__, __func__) +#define BOLT_LOG(level, message) bolt::LogManager::getInstance().log(level, message, __FILE__, __LINE__, __func__) #define BOLT_LOG_CATEGORY(level, category, message) \ bolt::LogManager::getInstance().log(level, category, message, __FILE__, __LINE__, __func__) @@ -370,19 +393,19 @@ class LogManager { // Scoped logging for tracking function entry/exit class ScopedLogger { -private: + private: std::string function_; LogCategory category_; std::chrono::steady_clock::time_point startTime_; - -public: - ScopedLogger(const std::string& function, LogCategory category = LogCategory::CORE); + + public: + explicit ScopedLogger(const std::string& function, LogCategory category = LogCategory::CORE); ~ScopedLogger(); }; #define BOLT_SCOPED_LOG(category) bolt::ScopedLogger _scopedLogger(__func__, category) #define BOLT_SCOPED_LOG_CORE() BOLT_SCOPED_LOG(bolt::LogCategory::CORE) -} // namespace bolt +} // namespace bolt -#endif // BOLT_LOGGING_HPP \ No newline at end of file +#endif // BOLT_CORE_LOGGING_HPP_ diff --git a/include/bolt/core/memory_leak_detector.hpp b/include/bolt/core/memory_leak_detector.hpp index 6210ea70..3eaccc56 100644 --- a/include/bolt/core/memory_leak_detector.hpp +++ b/include/bolt/core/memory_leak_detector.hpp @@ -1,13 +1,13 @@ #pragma once -#include -#include -#include -#include #include -#include #include +#include +#include #include +#include +#include +#include namespace bolt { @@ -23,13 +23,17 @@ struct AllocationInfo { std::chrono::steady_clock::time_point timestamp; std::string category; bool tracked; - - AllocationInfo(void* ptr = nullptr, size_t sz = 0, - const std::string& f = "", int l = 0, + + AllocationInfo(void* ptr = nullptr, size_t sz = 0, const std::string& f = "", int l = 0, const std::string& func = "", const std::string& cat = "general") - : pointer(ptr), size(sz), file(f), line(l), function(func) - , timestamp(std::chrono::steady_clock::now()) - , category(cat), tracked(true) {} + : pointer(ptr), + size(sz), + file(f), + line(l), + function(func), + timestamp(std::chrono::steady_clock::now()), + category(cat), + tracked(true) {} }; /** @@ -43,13 +47,13 @@ struct LeakDetectionStats { std::map leaksByCategory; std::map leaksByFile; std::chrono::steady_clock::time_point detectionTime; - + LeakDetectionStats() : detectionTime(std::chrono::steady_clock::now()) {} }; /** * @brief Enhanced Memory Leak Detector - * + * * Provides comprehensive memory leak detection with: * - Allocation tracking with source location * - Leak categorization and reporting @@ -57,12 +61,12 @@ struct LeakDetectionStats { * - Integration with existing MemoryManager */ class MemoryLeakDetector { -public: + public: static MemoryLeakDetector& getInstance() { static MemoryLeakDetector instance; return instance; } - + /** * @brief Enable or disable leak detection */ @@ -70,41 +74,42 @@ class MemoryLeakDetector { std::lock_guard lock(mutex_); enabled_ = enabled; } - + bool isEnabled() const { std::lock_guard lock(mutex_); return enabled_; } - + /** * @brief Track a memory allocation with source location */ - void trackAllocation(void* ptr, size_t size, const std::string& file, - int line, const std::string& function, - const std::string& category = "general") { + void trackAllocation(void* ptr, size_t size, const std::string& file, int line, const std::string& function, + const std::string& category = "general") { std::lock_guard lock(mutex_); - - if (!enabled_ || !ptr) return; - + + if (!enabled_ || !ptr) + return; + AllocationInfo info(ptr, size, file, line, function, category); allocations_[ptr] = info; - + currentMemoryUsage_ += size; if (currentMemoryUsage_ > peakMemoryUsage_) { peakMemoryUsage_ = currentMemoryUsage_; } - + categoryStats_[category] += size; } - + /** * @brief Untrack a memory deallocation */ void untrackAllocation(void* ptr) { std::lock_guard lock(mutex_); - - if (!enabled_ || !ptr) return; - + + if (!enabled_ || !ptr) + return; + auto it = allocations_.find(ptr); if (it != allocations_.end()) { currentMemoryUsage_ -= it->second.size; @@ -112,7 +117,7 @@ class MemoryLeakDetector { allocations_.erase(it); } } - + /** * @brief Check if there are any memory leaks */ @@ -120,7 +125,7 @@ class MemoryLeakDetector { std::lock_guard lock(mutex_); return !allocations_.empty(); } - + /** * @brief Get the number of leaked allocations */ @@ -128,7 +133,7 @@ class MemoryLeakDetector { std::lock_guard lock(mutex_); return allocations_.size(); } - + /** * @brief Get total bytes leaked */ @@ -140,7 +145,7 @@ class MemoryLeakDetector { } return total; } - + /** * @brief Get all leaked allocations */ @@ -152,7 +157,7 @@ class MemoryLeakDetector { } return leaks; } - + /** * @brief Get leak detection statistics */ @@ -161,86 +166,84 @@ class MemoryLeakDetector { LeakDetectionStats stats; stats.totalLeaks = allocations_.size(); stats.totalLeakedBytes = 0; - + for (const auto& pair : allocations_) { stats.totalLeakedBytes += pair.second.size; } - + stats.peakMemoryUsage = peakMemoryUsage_; stats.currentMemoryUsage = currentMemoryUsage_; - + // Group leaks by category for (const auto& pair : allocations_) { const auto& info = pair.second; stats.leaksByCategory[info.category] += info.size; stats.leaksByFile[info.file] += info.size; } - + return stats; } - + /** * @brief Generate a detailed leak report */ std::string generateReport() const { std::lock_guard lock(mutex_); std::ostringstream report; - + report << "=== Memory Leak Detection Report ===\n\n"; - + if (allocations_.empty()) { report << "โœ“ No memory leaks detected!\n"; report << "Peak memory usage: " << formatBytes(peakMemoryUsage_) << "\n"; return report.str(); } - + // Calculate stats inline (we already have the lock) size_t totalLeaks = allocations_.size(); size_t totalLeakedBytes = 0; std::map leaksByCategory; std::map leaksByFile; - + for (const auto& pair : allocations_) { const auto& info = pair.second; totalLeakedBytes += info.size; leaksByCategory[info.category] += info.size; leaksByFile[info.file] += info.size; } - + report << "โš  Memory leaks detected!\n\n"; report << "Summary:\n"; report << " Total leaks: " << totalLeaks << "\n"; report << " Total leaked: " << formatBytes(totalLeakedBytes) << "\n"; report << " Peak usage: " << formatBytes(peakMemoryUsage_) << "\n"; report << " Current usage: " << formatBytes(currentMemoryUsage_) << "\n\n"; - + // Leaks by category if (!leaksByCategory.empty()) { report << "Leaks by category:\n"; for (const auto& pair : leaksByCategory) { - report << " " << pair.first << ": " - << formatBytes(pair.second) << "\n"; + report << " " << pair.first << ": " << formatBytes(pair.second) << "\n"; } report << "\n"; } - + // Leaks by file if (!leaksByFile.empty()) { report << "Leaks by file:\n"; for (const auto& pair : leaksByFile) { - report << " " << pair.first << ": " - << formatBytes(pair.second) << "\n"; + report << " " << pair.first << ": " << formatBytes(pair.second) << "\n"; } report << "\n"; } - + // Detailed leak information report << "Detailed leak information:\n"; std::vector leaks; for (const auto& pair : allocations_) { leaks.push_back(pair.second); } - + for (size_t i = 0; i < leaks.size(); ++i) { const auto& leak = leaks[i]; report << "\nLeak #" << (i + 1) << ":\n"; @@ -249,23 +252,23 @@ class MemoryLeakDetector { report << " Location: " << leak.file << ":" << leak.line << "\n"; report << " Function: " << leak.function << "\n"; report << " Category: " << leak.category << "\n"; - + // Calculate allocation age auto age = std::chrono::steady_clock::now() - leak.timestamp; auto seconds = std::chrono::duration_cast(age).count(); report << " Age: " << seconds << " seconds\n"; } - + return report.str(); } - + /** * @brief Generate a summary report */ std::string generateSummary() const { std::lock_guard lock(mutex_); std::ostringstream summary; - + if (allocations_.empty()) { summary << "No memory leaks detected."; } else { @@ -273,13 +276,12 @@ class MemoryLeakDetector { for (const auto& pair : allocations_) { totalLeakedBytes += pair.second.size; } - summary << allocations_.size() << " leaks, " - << formatBytes(totalLeakedBytes) << " leaked"; + summary << allocations_.size() << " leaks, " << formatBytes(totalLeakedBytes) << " leaked"; } - + return summary.str(); } - + /** * @brief Clear all tracked allocations (use with caution!) */ @@ -289,7 +291,7 @@ class MemoryLeakDetector { currentMemoryUsage_ = 0; categoryStats_.clear(); } - + /** * @brief Reset statistics but keep tracking */ @@ -297,46 +299,41 @@ class MemoryLeakDetector { std::lock_guard lock(mutex_); peakMemoryUsage_ = currentMemoryUsage_; } - -private: + + private: MemoryLeakDetector() = default; ~MemoryLeakDetector() = default; MemoryLeakDetector(const MemoryLeakDetector&) = delete; MemoryLeakDetector& operator=(const MemoryLeakDetector&) = delete; - + std::string formatBytes(size_t bytes) const { std::ostringstream oss; - + if (bytes < 1024) { oss << bytes << " B"; } else if (bytes < 1024 * 1024) { - oss << std::fixed << std::setprecision(2) - << (bytes / 1024.0) << " KB"; + oss << std::fixed << std::setprecision(2) << (bytes / 1024.0) << " KB"; } else if (bytes < 1024 * 1024 * 1024) { - oss << std::fixed << std::setprecision(2) - << (bytes / (1024.0 * 1024.0)) << " MB"; + oss << std::fixed << std::setprecision(2) << (bytes / (1024.0 * 1024.0)) << " MB"; } else { - oss << std::fixed << std::setprecision(2) - << (bytes / (1024.0 * 1024.0 * 1024.0)) << " GB"; + oss << std::fixed << std::setprecision(2) << (bytes / (1024.0 * 1024.0 * 1024.0)) << " GB"; } - + return oss.str(); } - + bool enabled_ = true; std::map allocations_; size_t currentMemoryUsage_ = 0; size_t peakMemoryUsage_ = 0; std::map categoryStats_; - mutable std::mutex mutex_; // Thread safety for all operations + mutable std::mutex mutex_; // Thread safety for all operations }; // Convenience macros for leak detection #define TRACK_ALLOCATION(ptr, size, category) \ - bolt::MemoryLeakDetector::getInstance().trackAllocation( \ - ptr, size, __FILE__, __LINE__, __FUNCTION__, category) + bolt::MemoryLeakDetector::getInstance().trackAllocation(ptr, size, __FILE__, __LINE__, __FUNCTION__, category) -#define UNTRACK_ALLOCATION(ptr) \ - bolt::MemoryLeakDetector::getInstance().untrackAllocation(ptr) +#define UNTRACK_ALLOCATION(ptr) bolt::MemoryLeakDetector::getInstance().untrackAllocation(ptr) -} // namespace bolt +} // namespace bolt diff --git a/include/bolt/core/memory_manager.hpp b/include/bolt/core/memory_manager.hpp index 849d9698..6bfaacc9 100644 --- a/include/bolt/core/memory_manager.hpp +++ b/include/bolt/core/memory_manager.hpp @@ -1,26 +1,28 @@ -#ifndef MEMORY_MANAGER_HPP -#define MEMORY_MANAGER_HPP +#ifndef BOLT_CORE_MEMORY_MANAGER_HPP_ +#define BOLT_CORE_MEMORY_MANAGER_HPP_ +#include +#include #include +#include #include +#include #include -#include -#include -#include -#include "error_handling.hpp" + +#include "bolt/core/error_handling.hpp" namespace bolt { class MemoryManager { -private: + private: size_t totalAllocated_ = 0; size_t peakUsage_ = 0; size_t maxAllowedUsage_ = SIZE_MAX; std::unordered_map allocations_; - mutable std::mutex mutex_; // Thread safety for memory operations + mutable std::mutex mutex_; // Thread safety for memory operations -public: + public: static MemoryManager& getInstance() { static MemoryManager instance; return instance; @@ -35,43 +37,44 @@ class MemoryManager { void* allocate(size_t size) { ErrorHandler::validateMemorySize(size); - + std::lock_guard lock(mutex_); - + // Check if allocation would exceed maximum allowed usage if (totalAllocated_ + size > maxAllowedUsage_) { throw MemoryException(ErrorCode::MEMORY_ALLOCATION_FAILED, - "Allocation would exceed maximum allowed usage. Requested: " + - std::to_string(size) + ", Current: " + std::to_string(totalAllocated_) + - ", Max: " + std::to_string(maxAllowedUsage_)); + "Allocation would exceed maximum allowed usage. Requested: " + std::to_string(size) + + ", Current: " + std::to_string(totalAllocated_) + + ", Max: " + std::to_string(maxAllowedUsage_)); } - + void* ptr = std::malloc(size); if (!ptr) { throw MemoryException(ErrorCode::MEMORY_ALLOCATION_FAILED, - "Failed to allocate " + std::to_string(size) + " bytes"); + "Failed to allocate " + std::to_string(size) + " bytes"); } - + allocations_[ptr] = size; totalAllocated_ += size; if (totalAllocated_ > peakUsage_) { peakUsage_ = totalAllocated_; } - + return ptr; } void deallocate(void* ptr) { - if (!ptr) return; // Allow null pointer deallocation (like standard free) - + if (!ptr) + return; // Allow null pointer deallocation (like standard free) + std::lock_guard lock(mutex_); - + auto it = allocations_.find(ptr); if (it == allocations_.end()) { throw MemoryException(ErrorCode::MEMORY_CORRUPTION, - "Attempting to deallocate untracked or already freed pointer"); + "Attempting to deallocate untracked or already freed pointer"); } - + totalAllocated_ -= it->second; allocations_.erase(it); std::free(ptr); @@ -115,13 +118,13 @@ class MemoryManager { void reset() { std::lock_guard lock(mutex_); - + if (!allocations_.empty()) { throw MemoryException(ErrorCode::MEMORY_CORRUPTION, - "Cannot reset memory manager with " + std::to_string(allocations_.size()) + - " active allocations. This would cause memory leaks."); + "Cannot reset memory manager with " + std::to_string(allocations_.size()) + + " active allocations. This would cause memory leaks."); } - + totalAllocated_ = 0; peakUsage_ = 0; } @@ -129,18 +132,18 @@ class MemoryManager { // Safe reset that frees all allocations (use with caution) void forceReset() { std::lock_guard lock(mutex_); - + // Free all tracked allocations for (const auto& allocation : allocations_) { std::free(allocation.first); } - + allocations_.clear(); totalAllocated_ = 0; peakUsage_ = 0; } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_CORE_MEMORY_MANAGER_HPP_ diff --git a/include/bolt/core/memory_pool.hpp b/include/bolt/core/memory_pool.hpp index 2c7fc3ee..0a979934 100644 --- a/include/bolt/core/memory_pool.hpp +++ b/include/bolt/core/memory_pool.hpp @@ -1,16 +1,17 @@ -#ifndef MEMORY_POOL_HPP -#define MEMORY_POOL_HPP +#ifndef BOLT_CORE_MEMORY_POOL_HPP_ +#define BOLT_CORE_MEMORY_POOL_HPP_ #include -#include -#include #include +#include +#include +#include namespace bolt { class MemoryPool { -private: + private: struct Block { void* data; bool used; @@ -35,8 +36,8 @@ class MemoryPool { return nullptr; } -public: - explicit MemoryPool(size_t initialSize = 1024 * 1024) // 1MB default + public: + explicit MemoryPool(size_t initialSize = 1024 * 1024) // 1MB default : freeList(nullptr), blockSize(initialSize), totalSize(0) { expandPool(); } @@ -49,7 +50,7 @@ class MemoryPool { void* allocate(size_t size) { std::lock_guard lock(mtx); - + Block* block = findFreeBlock(size); if (!block) { expandPool(); @@ -60,13 +61,13 @@ class MemoryPool { block->used = true; return block->data; } - + return nullptr; } void deallocate(void* ptr) { std::lock_guard lock(mtx); - + Block* current = freeList; while (current) { if (current->data == ptr) { @@ -79,7 +80,7 @@ class MemoryPool { } } -private: + private: void expandPool() { void* newChunk = ::operator new(blockSize); memoryChunks.push_back(newChunk); @@ -104,11 +105,11 @@ class MemoryPool { } }; -template +template class PoolAllocator { static MemoryPool pool; -public: + public: using value_type = T; using pointer = T*; using const_pointer = const T*; @@ -117,7 +118,7 @@ class PoolAllocator { using size_type = std::size_t; using difference_type = std::ptrdiff_t; - template + template struct rebind { using other = PoolAllocator; }; @@ -125,28 +126,27 @@ class PoolAllocator { pointer allocate(size_type n) { size_type size = n * sizeof(T); void* p = pool.allocate(size); - if (!p) throw std::bad_alloc(); + if (!p) + throw std::bad_alloc(); return static_cast(p); } - void deallocate(pointer p, size_type) { - pool.deallocate(p); - } + void deallocate(pointer p, size_type) { pool.deallocate(p); } - template + template void construct(U* p, Args&&... args) { - new(p) U(std::forward(args)...); + new (p) U(std::forward(args)...); } - template + template void destroy(U* p) { p->~U(); } }; -template +template MemoryPool PoolAllocator::pool; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_CORE_MEMORY_POOL_HPP_ diff --git a/include/bolt/core/message_handler.hpp b/include/bolt/core/message_handler.hpp index fe095b4b..8d411c66 100644 --- a/include/bolt/core/message_handler.hpp +++ b/include/bolt/core/message_handler.hpp @@ -1,53 +1,49 @@ -#ifndef BOLT_MESSAGE_HANDLER_HPP -#define BOLT_MESSAGE_HANDLER_HPP +#ifndef BOLT_CORE_MESSAGE_HANDLER_HPP_ +#define BOLT_CORE_MESSAGE_HANDLER_HPP_ -#include #include -#include "error_handling.hpp" +#include + +#include "bolt/core/error_handling.hpp" namespace bolt { -enum class MessageType { - Chat, - Command, - System -}; +enum class MessageType { Chat, Command, System }; struct Message { MessageType type; std::string content; - + Message() : type(MessageType::System), content("") { // Default constructor creates empty system message - this is allowed } - - Message(MessageType t, const std::string& c) - : type(t), content(c) { + + Message(MessageType t, const std::string& c) : type(t), content(c) { // Only validate non-empty messages for explicit construction if (!content.empty()) { validateMessage(); } } - + // Validate message content void validateMessage() const { if (content.length() > MAX_MESSAGE_LENGTH) { throw MessageException(ErrorCode::INVALID_PARAMETER, - "Message content too long: " + std::to_string(content.length()) + - " > " + std::to_string(MAX_MESSAGE_LENGTH)); + "Message content too long: " + std::to_string(content.length()) + " > " + + std::to_string(MAX_MESSAGE_LENGTH)); } } - - static constexpr size_t MAX_MESSAGE_LENGTH = 65536; // 64KB max message size + + static constexpr size_t MAX_MESSAGE_LENGTH = 65536; // 64KB max message size }; class MessageHandlerImpl; class MessageHandler { -public: + public: static MessageHandler& getInstance(); - + void initialize(); void pushMessage(const Message& msg); void processMessages(); @@ -56,12 +52,12 @@ class MessageHandler { void setMaxQueueSize(size_t maxSize); static constexpr size_t DEFAULT_MAX_QUEUE_SIZE = 1000; - -private: + + private: MessageHandler() = default; std::unique_ptr impl_; }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_MESSAGE_HANDLER_HPP +#endif // BOLT_CORE_MESSAGE_HANDLER_HPP_ diff --git a/include/bolt/core/performance_profiler.hpp b/include/bolt/core/performance_profiler.hpp index 676906c1..ead08beb 100644 --- a/include/bolt/core/performance_profiler.hpp +++ b/include/bolt/core/performance_profiler.hpp @@ -1,17 +1,18 @@ -#ifndef BOLT_PERFORMANCE_PROFILER_HPP -#define BOLT_PERFORMANCE_PROFILER_HPP +#ifndef BOLT_CORE_PERFORMANCE_PROFILER_HPP_ +#define BOLT_CORE_PERFORMANCE_PROFILER_HPP_ -#include +#include +#include +#include #include #include -#include -#include -#include -#include +#include #include -#include -#include "logging.hpp" -#include "thread_safety.hpp" +#include +#include + +#include "bolt/core/logging.hpp" +#include "bolt/core/thread_safety.hpp" namespace bolt { @@ -30,48 +31,48 @@ struct PerformanceMetric { double cpuUsage; std::thread::id threadId; std::unordered_map metadata; - + PerformanceMetric(const std::string& metricName, const std::string& metricCategory) - : name(metricName), category(metricCategory), + : name(metricName), + category(metricCategory), startTime(std::chrono::steady_clock::now()), - memoryUsage(0), cpuUsage(0.0), + memoryUsage(0), + cpuUsage(0.0), threadId(std::this_thread::get_id()) {} - + void finish() { endTime = std::chrono::steady_clock::now(); duration = std::chrono::duration_cast>(endTime - startTime); } - - double getDurationMs() const { - return duration.count(); - } + + double getDurationMs() const { return duration.count(); } }; // Profiler session for grouping related metrics class ProfilerSession { -private: + private: std::string sessionName_; std::chrono::steady_clock::time_point startTime_; std::chrono::steady_clock::time_point endTime_; std::vector> metrics_; mutable std::mutex metricsMutex_; bool isActive_; - -public: + + public: explicit ProfilerSession(const std::string& name); ~ProfilerSession(); - + const std::string& getName() const { return sessionName_; } bool isActive() const { return isActive_; } - + void start(); void stop(); void addMetric(std::shared_ptr metric); - + std::vector> getMetrics() const; double getTotalDurationMs() const; size_t getMetricsCount() const; - + // Statistics double getAverageDurationMs() const; double getMinDurationMs() const; @@ -80,66 +81,66 @@ class ProfilerSession { // Main performance profiler class class PerformanceProfiler { -private: + private: static std::unique_ptr instance_; static std::mutex instanceMutex_; - + mutable std::mutex sessionsMutex_; mutable std::mutex metricsMutex_; - + std::unordered_map> sessions_; std::vector> globalMetrics_; - + std::atomic isEnabled_; std::atomic isSystemMonitoringEnabled_; - + // Thread-local current session storage thread_local static std::shared_ptr currentSession_; - + PerformanceProfiler(); - -public: + + public: static PerformanceProfiler& getInstance(); - + // Core functionality void enable() { isEnabled_ = true; } void disable() { isEnabled_ = false; } bool isEnabled() const { return isEnabled_; } - + void enableSystemMonitoring() { isSystemMonitoringEnabled_ = true; } void disableSystemMonitoring() { isSystemMonitoringEnabled_ = false; } bool isSystemMonitoringEnabled() const { return isSystemMonitoringEnabled_; } - + // Session management std::shared_ptr createSession(const std::string& name); std::shared_ptr getSession(const std::string& name) const; void setCurrentSession(const std::string& name); std::shared_ptr getCurrentSession() const; void endSession(const std::string& name); - + // Metric recording std::shared_ptr startMetric(const std::string& name, const std::string& category = "GENERAL"); void endMetric(std::shared_ptr metric); void recordInstantMetric(const std::string& name, double value, const std::string& category = "GENERAL"); - + // System monitoring size_t getCurrentMemoryUsage() const; double getCurrentCPUUsage() const; - + // Data export and reporting void exportToJson(const std::string& filename) const; void exportToCsv(const std::string& filename) const; void printSummary() const; void printDetailedReport() const; - + // Integration with logging system void logMetric(const PerformanceMetric& metric, LogLevel level = LogLevel::INFO) const; void logSessionSummary(const ProfilerSession& session, LogLevel level = LogLevel::INFO) const; - + // Cleanup void reset(); void clearOldMetrics(std::chrono::minutes olderThan); - + // Statistics size_t getTotalMetricsCount() const; double getAverageMetricDuration() const; @@ -149,29 +150,26 @@ class PerformanceProfiler { // RAII performance measurement class that integrates with existing ScopedLogger class ScopedProfiler { -private: + private: std::shared_ptr metric_; bool wasEnabled_; - -public: - ScopedProfiler(const std::string& name, const std::string& category = "GENERAL"); + + public: + explicit ScopedProfiler(const std::string& name, const std::string& category = "GENERAL"); ~ScopedProfiler(); - + void addMetadata(const std::string& key, const std::string& value); double getCurrentDurationMs() const; }; // Convenience macros -#define BOLT_PROFILE_FUNCTION() \ - bolt::ScopedProfiler __profiler__(__FUNCTION__, "FUNCTION") +#define BOLT_PROFILE_FUNCTION() bolt::ScopedProfiler __profiler__(__FUNCTION__, "FUNCTION") -#define BOLT_PROFILE_SCOPE(name) \ - bolt::ScopedProfiler __profiler__(name, "SCOPE") +#define BOLT_PROFILE_SCOPE(name) bolt::ScopedProfiler __profiler__(name, "SCOPE") -#define BOLT_PROFILE_CATEGORY(name, category) \ - bolt::ScopedProfiler __profiler__(name, category) +#define BOLT_PROFILE_CATEGORY(name, category) bolt::ScopedProfiler __profiler__(name, category) -#define BOLT_PROFILE_SESSION(sessionName) \ +#define BOLT_PROFILE_SESSION(sessionName) \ auto __session__ = bolt::PerformanceProfiler::getInstance().createSession(sessionName); \ bolt::PerformanceProfiler::getInstance().setCurrentSession(sessionName) @@ -183,6 +181,6 @@ class ScopedProfiler { #define BOLT_PROFILE_GUI(name) BOLT_PROFILE_CATEGORY(name, "GUI") #define BOLT_PROFILE_NETWORK(name) BOLT_PROFILE_CATEGORY(name, "NETWORK") -} // namespace bolt +} // namespace bolt -#endif // BOLT_PERFORMANCE_PROFILER_HPP \ No newline at end of file +#endif // BOLT_CORE_PERFORMANCE_PROFILER_HPP_ diff --git a/include/bolt/core/plugin_interface.hpp b/include/bolt/core/plugin_interface.hpp index 7f04e5a8..2d8815da 100644 --- a/include/bolt/core/plugin_interface.hpp +++ b/include/bolt/core/plugin_interface.hpp @@ -1,14 +1,14 @@ -#ifndef PLUGIN_INTERFACE_HPP -#define PLUGIN_INTERFACE_HPP +#ifndef BOLT_CORE_PLUGIN_INTERFACE_HPP_ +#define BOLT_CORE_PLUGIN_INTERFACE_HPP_ -#include -#include -#include +#include #include +#include #include -#include - +#include #include +#include +#include namespace bolt { @@ -17,7 +17,7 @@ class EditorStore; class IntegratedEditor; class PluginContext; -} +} // namespace bolt namespace bolt { @@ -33,11 +33,9 @@ struct PluginAPIVersion { int major = 1; int minor = 0; int patch = 0; - - bool isCompatible(const PluginAPIVersion& other) const { - return major == other.major && minor >= other.minor; - } - + + bool isCompatible(const PluginAPIVersion& other) const { return major == other.major && minor >= other.minor; } + std::string toString() const { return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); } @@ -55,22 +53,14 @@ struct PluginMetadata { std::vector dependencies; PluginAPIVersion apiVersion; std::unordered_map customProperties; - - bool isValid() const { - return !name.empty() && !version.empty(); - } + + bool isValid() const { return !name.empty() && !version.empty(); } }; /** * Plugin lifecycle states */ -enum class PluginState { - Unloaded, - Loaded, - Initialized, - Active, - Error -}; +enum class PluginState { Unloaded, Loaded, Initialized, Active, Error }; /** * Plugin event types for the event system @@ -95,8 +85,8 @@ struct PluginEvent { PluginEventType type; std::string source; std::unordered_map data; - - template + + template T getData(const std::string& key) const { auto it = data.find(key); if (it != data.end()) { @@ -104,8 +94,8 @@ struct PluginEvent { } throw std::runtime_error("Plugin event data key not found: " + key); } - - template + + template T getData(const std::string& key, const T& defaultValue) const { auto it = data.find(key); if (it != data.end()) { @@ -123,29 +113,29 @@ struct PluginEvent { * Base interface for all plugin types */ class IPlugin { -public: + public: virtual ~IPlugin() = default; - + // Plugin metadata virtual PluginMetadata getMetadata() const = 0; - + // Lifecycle methods virtual bool initialize(PluginContext* context) = 0; virtual void activate() = 0; virtual void deactivate() = 0; virtual void cleanup() = 0; - + // Configuration virtual bool configure(const std::unordered_map& config) { return true; } virtual std::unordered_map getConfiguration() const { return {}; } - + // Event handling virtual void onEvent(const PluginEvent& event) {} - + // State management virtual PluginState getState() const { return state_; } - -protected: + + protected: PluginState state_ = PluginState::Unloaded; }; @@ -153,14 +143,15 @@ class IPlugin { * Editor plugin interface for plugins that modify editor behavior */ class IEditorPlugin : public IPlugin { -public: + public: // Editor integration hooks virtual void onDocumentOpened(const std::string& filePath, const std::string& content) {} virtual void onDocumentClosed(const std::string& filePath) {} virtual void onDocumentModified(const std::string& filePath, const std::string& content) {} virtual void onCursorChanged(const std::string& filePath, size_t line, size_t column) {} - virtual void onSelectionChanged(const std::string& filePath, size_t startLine, size_t startCol, size_t endLine, size_t endCol) {} - + virtual void onSelectionChanged(const std::string& filePath, size_t startLine, size_t startCol, size_t endLine, + size_t endCol) {} + // Text processing hooks virtual std::string processText(const std::string& text) { return text; } virtual bool canHandleFileType(const std::string& fileExtension) { return false; } @@ -170,14 +161,21 @@ class IEditorPlugin : public IPlugin { * Language server plugin interface */ class ILanguagePlugin : public IEditorPlugin { -public: + public: // Language-specific features - virtual std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) { return {}; } - virtual std::vector getDiagnostics(const std::string& filePath, const std::string& content) { return {}; } + virtual std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) { + return {}; + } + virtual std::vector getDiagnostics(const std::string& filePath, const std::string& content) { + return {}; + } virtual std::string formatCode(const std::string& code) { return code; } - virtual std::vector> findReferences(const std::string& filePath, size_t line, size_t column) { return {}; } + virtual std::vector> findReferences(const std::string& filePath, size_t line, + size_t column) { + return {}; + } virtual std::string getHoverInfo(const std::string& filePath, size_t line, size_t column) { return ""; } - + // Supported file extensions virtual std::vector getSupportedExtensions() const = 0; }; @@ -186,11 +184,11 @@ class ILanguagePlugin : public IEditorPlugin { * UI plugin interface for plugins that add UI components */ class IUIPlugin : public IPlugin { -public: + public: // UI component management virtual void renderUI() {} virtual void onUIEvent(const std::string& componentId, const std::string& eventType, const std::any& eventData) {} - + // Menu and toolbar integration virtual std::vector getMenuItems() { return {}; } virtual std::vector getToolbarItems() { return {}; } @@ -202,7 +200,7 @@ class IUIPlugin : public IPlugin { * Theme plugin interface */ class IThemePlugin : public IPlugin { -public: + public: virtual std::string getThemeName() const = 0; virtual std::unordered_map getThemeColors() const = 0; virtual std::unordered_map getThemeFonts() const { return {}; } @@ -213,32 +211,32 @@ class IThemePlugin : public IPlugin { * Plugin context provides access to editor APIs */ class PluginContext { -public: + public: virtual ~PluginContext() = default; - + // Editor access virtual EditorStore* getEditorStore() = 0; virtual IntegratedEditor* getIntegratedEditor() = 0; - + // Event system virtual void subscribeToEvent(PluginEventType eventType, std::function handler) = 0; virtual void unsubscribeFromEvent(PluginEventType eventType) = 0; virtual void publishEvent(const PluginEvent& event) = 0; - + // Configuration access virtual std::any getConfigValue(const std::string& key) = 0; virtual void setConfigValue(const std::string& key, const std::any& value) = 0; - + // Logging virtual void logInfo(const std::string& message) = 0; virtual void logWarning(const std::string& message) = 0; virtual void logError(const std::string& message) = 0; - + // Plugin communication virtual std::shared_ptr getPlugin(const std::string& name) = 0; virtual std::vector> getPlugins() = 0; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_CORE_PLUGIN_INTERFACE_HPP_ diff --git a/include/bolt/core/plugin_system.hpp b/include/bolt/core/plugin_system.hpp index 46c6de8d..b699ee29 100644 --- a/include/bolt/core/plugin_system.hpp +++ b/include/bolt/core/plugin_system.hpp @@ -1,13 +1,13 @@ -#ifndef PLUGIN_SYSTEM_HPP -#define PLUGIN_SYSTEM_HPP +#ifndef BOLT_CORE_PLUGIN_SYSTEM_HPP_ +#define BOLT_CORE_PLUGIN_SYSTEM_HPP_ +#include #include -#include -#include #include +#include #include -#include +#include // Platform-specific dynamic library loading headers #ifndef _WIN32 @@ -16,10 +16,10 @@ #include #endif -#include "bolt/core/thread_safety.hpp" -#include "bolt/core/plugin_interface.hpp" -#include "bolt/core/error_handling.hpp" #include "bolt/core/editor_store.hpp" +#include "bolt/core/error_handling.hpp" +#include "bolt/core/plugin_interface.hpp" +#include "bolt/core/thread_safety.hpp" #include "bolt/editor/integrated_editor.hpp" namespace bolt { @@ -38,13 +38,13 @@ struct Plugin { * Dynamic plugin loader for .so/.dll files */ class PluginLoader { -public: + public: struct LoadedPlugin { void* handle; std::shared_ptr plugin; PluginMetadata metadata; std::string filePath; - + ~LoadedPlugin() { if (handle) { #ifdef _WIN32 @@ -59,8 +59,8 @@ class PluginLoader { static std::unique_ptr loadPlugin(const std::string& filePath); static bool unloadPlugin(LoadedPlugin* plugin); static std::vector discoverPlugins(const std::string& directory); - -private: + + private: static bool validatePlugin(IPlugin* plugin); }; @@ -68,7 +68,7 @@ class PluginLoader { * Plugin context implementation */ class PluginContextImpl : public PluginContext { -private: + private: EditorStore* editorStore_; IntegratedEditor* integratedEditor_; std::unordered_map>> eventHandlers_; @@ -76,131 +76,133 @@ class PluginContextImpl : public PluginContext { std::function(const std::string&)> pluginGetter_; std::function>()> allPluginsGetter_; -public: + public: PluginContextImpl(EditorStore* editorStore, IntegratedEditor* integratedEditor); - + // PluginContext interface EditorStore* getEditorStore() override { return editorStore_; } IntegratedEditor* getIntegratedEditor() override { return integratedEditor_; } - + void subscribeToEvent(PluginEventType eventType, std::function handler) override; void unsubscribeFromEvent(PluginEventType eventType) override; void publishEvent(const PluginEvent& event) override; - + std::any getConfigValue(const std::string& key) override; void setConfigValue(const std::string& key, const std::any& value) override; - + void logInfo(const std::string& message) override; void logWarning(const std::string& message) override; void logError(const std::string& message) override; - + std::shared_ptr getPlugin(const std::string& name) override; std::vector> getPlugins() override; - + // Internal methods void setPluginGetter(std::function(const std::string&)> getter) { pluginGetter_ = getter; } - void setAllPluginsGetter(std::function>()> getter) { allPluginsGetter_ = getter; } + void setAllPluginsGetter(std::function>()> getter) { + allPluginsGetter_ = getter; + } }; /** * Enhanced plugin system with dynamic loading and modern interface support */ class PluginSystem { -private: + private: // Legacy plugins for backward compatibility ThreadSafe> legacyPlugins_; - + // Modern plugin management ThreadSafe>> loadedPlugins_; ThreadSafe>> activePlugins_; - + // Plugin registry by type ThreadSafe>>> editorPlugins_; ThreadSafe>>> languagePlugins_; ThreadSafe>>> uiPlugins_; ThreadSafe>> themePlugins_; - + // Plugin directories std::vector pluginDirectories_; - + // Plugin context std::unique_ptr context_; - + // Event system void publishEventToPlugins(const PluginEvent& event); -public: + public: static PluginSystem& getInstance() { static PluginSystem instance; return instance; } - + // Initialization void initialize(EditorStore* editorStore, IntegratedEditor* integratedEditor); void shutdown(); - + // Legacy plugin support void registerPlugin(Plugin plugin); void initializeAll(); void cleanupAll(); - + // Modern plugin management bool loadPlugin(const std::string& filePath); bool loadPlugin(std::shared_ptr plugin); bool unloadPlugin(const std::string& name); void reloadPlugin(const std::string& name); - + // Plugin discovery void addPluginDirectory(const std::string& directory); void removePluginDirectory(const std::string& directory); void discoverAndLoadPlugins(); - + // Plugin queries std::vector getLoadedPluginNames() const; std::shared_ptr getPlugin(const std::string& name) const; std::vector> getPlugins() const; std::vector getPluginMetadata() const; - + // Type-specific plugin access std::vector> getEditorPlugins() const; std::vector> getLanguagePluginsForFile(const std::string& filePath) const; std::vector> getUIPlugins() const; std::shared_ptr getActiveThemePlugin() const; - + // Plugin state management bool isPluginLoaded(const std::string& name) const; bool isPluginActive(const std::string& name) const; PluginState getPluginState(const std::string& name) const; bool activatePlugin(const std::string& name); bool deactivatePlugin(const std::string& name); - + // Configuration bool configurePlugin(const std::string& name, const std::unordered_map& config); std::unordered_map getPluginConfiguration(const std::string& name) const; - + // Event system void publishEvent(const PluginEvent& event); PluginContext* getPluginContext() { return context_.get(); } - + // Error handling void handlePluginError(const std::string& pluginName, const std::string& error); std::vector getPluginErrors() const; void clearPluginErrors(); - -private: + + private: PluginSystem() = default; ~PluginSystem() = default; - + // Internal helpers std::string getFileExtension(const std::string& filePath) const; void registerPluginByType(std::shared_ptr plugin); void unregisterPluginByType(const std::string& name); bool validatePluginCompatibility(const PluginMetadata& metadata) const; - + // Error tracking ThreadSafe> pluginErrors_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_CORE_PLUGIN_SYSTEM_HPP_ diff --git a/include/bolt/core/thread_safety.hpp b/include/bolt/core/thread_safety.hpp index 129f986c..61eea187 100644 --- a/include/bolt/core/thread_safety.hpp +++ b/include/bolt/core/thread_safety.hpp @@ -1,33 +1,34 @@ -#ifndef THREAD_SAFETY_HPP -#define THREAD_SAFETY_HPP +#ifndef BOLT_CORE_THREAD_SAFETY_HPP_ +#define BOLT_CORE_THREAD_SAFETY_HPP_ -#include -#include -#include #include +#include #include +#include +#include +#include namespace bolt { -template +template class ThreadSafe { -private: + private: mutable std::shared_mutex mutex_; T data_; -public: - ThreadSafe(T data = T{}) : data_(std::move(data)) {} + public: + explicit ThreadSafe(T data = T{}) : data_(std::move(data)) {} // Read operations - template + template auto read(F&& func) const { std::shared_lock lock(mutex_); return func(data_); } // Write operations - template + template auto write(F&& func) { std::unique_lock lock(mutex_); return func(data_); @@ -43,19 +44,18 @@ class ThreadSafe { class SpinLock { std::atomic_flag flag_ = ATOMIC_FLAG_INIT; -public: + public: void lock() { - while (flag_.test_and_set(std::memory_order_acquire)) {} + while (flag_.test_and_set(std::memory_order_acquire)) { + } } - void unlock() { - flag_.clear(std::memory_order_release); - } + void unlock() { flag_.clear(std::memory_order_release); } }; -template +template class LockFreeQueue { -private: + private: struct Node { std::shared_ptr data; std::atomic next; @@ -65,7 +65,7 @@ class LockFreeQueue { std::atomic head_; std::atomic tail_; -public: + public: LockFreeQueue() { Node* dummy = new Node; head_.store(dummy); @@ -82,11 +82,11 @@ class LockFreeQueue { void push(T value) { Node* new_node = new Node; new_node->data = std::make_shared(std::move(value)); - + while (true) { Node* last = tail_.load(); Node* next = last->next.load(); - + if (last == tail_.load()) { if (next == nullptr) { if (last->next.compare_exchange_strong(next, new_node)) { @@ -105,7 +105,7 @@ class LockFreeQueue { Node* first = head_.load(); Node* last = tail_.load(); Node* next = first->next.load(); - + if (first == head_.load()) { if (first == last) { if (next == nullptr) { @@ -127,6 +127,6 @@ class LockFreeQueue { } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_CORE_THREAD_SAFETY_HPP_ diff --git a/include/bolt/core/workbench_store.hpp b/include/bolt/core/workbench_store.hpp index 696ca1aa..c2db90be 100644 --- a/include/bolt/core/workbench_store.hpp +++ b/include/bolt/core/workbench_store.hpp @@ -1,59 +1,58 @@ -#ifndef WORKBENCH_STORE_HPP -#define WORKBENCH_STORE_HPP +#ifndef BOLT_CORE_WORKBENCH_STORE_HPP_ +#define BOLT_CORE_WORKBENCH_STORE_HPP_ +#include #include +#include #include #include -#include -#include -#include "bolt/gui_components.hpp" + #include "bolt/core/error_handling.hpp" +#include "bolt/gui_components.hpp" namespace bolt { class WorkbenchStore { -public: + public: static WorkbenchStore& getInstance() { static WorkbenchStore instance; return instance; } - void setShowWorkbench(bool show) { + void setShowWorkbench(bool show) { std::lock_guard lock(mutex_); showWorkbench_ = show; notifyListeners(); } - bool getShowWorkbench() const { + bool getShowWorkbench() const { std::lock_guard lock(mutex_); - return showWorkbench_; + return showWorkbench_; } void setCurrentView(const std::string& view) { ErrorHandler::validateParameter(!view.empty(), "View name cannot be empty"); if (view.length() > MAX_VIEW_NAME_LENGTH) { - throw StoreException(ErrorCode::INVALID_PARAMETER, - "View name too long: " + std::to_string(view.length()) + - " > " + std::to_string(MAX_VIEW_NAME_LENGTH)); + throw StoreException(ErrorCode::INVALID_PARAMETER, "View name too long: " + std::to_string(view.length()) + + " > " + std::to_string(MAX_VIEW_NAME_LENGTH)); } - + std::lock_guard lock(mutex_); currentView_ = view; notifyListeners(); } - std::string getCurrentView() const { + std::string getCurrentView() const { std::lock_guard lock(mutex_); - return currentView_; + return currentView_; } void setSelectedFile(const std::string& file) { if (!file.empty() && file.length() > MAX_FILE_PATH_LENGTH) { - throw StoreException(ErrorCode::INVALID_PARAMETER, - "File path too long: " + std::to_string(file.length()) + - " > " + std::to_string(MAX_FILE_PATH_LENGTH)); + throw StoreException(ErrorCode::INVALID_PARAMETER, "File path too long: " + std::to_string(file.length()) + + " > " + std::to_string(MAX_FILE_PATH_LENGTH)); } - + std::lock_guard lock(mutex_); selectedFile_ = file; notifyListeners(); @@ -77,30 +76,30 @@ class WorkbenchStore { void addListener(std::function listener) { ErrorHandler::validateParameter(listener != nullptr, "Listener cannot be null"); - + std::lock_guard lock(mutex_); - + if (listeners_.size() >= MAX_LISTENERS) { - throw StoreException(ErrorCode::STORE_STATE_INVALID, - "Too many listeners: " + std::to_string(listeners_.size()) + - " >= " + std::to_string(MAX_LISTENERS)); + throw StoreException( + ErrorCode::STORE_STATE_INVALID, + "Too many listeners: " + std::to_string(listeners_.size()) + " >= " + std::to_string(MAX_LISTENERS)); } - + listeners_.push_back(listener); } - Workbench& getWorkbench() { + Workbench& getWorkbench() { std::lock_guard lock(mutex_); ErrorHandler::validateNotNull(workbench_.get(), "workbench"); - return *workbench_; + return *workbench_; } - + size_t getListenerCount() const { std::lock_guard lock(mutex_); return listeners_.size(); } -private: + private: WorkbenchStore() : workbench_(std::make_unique()) { showWorkbench_ = false; currentView_ = "code"; @@ -128,12 +127,12 @@ class WorkbenchStore { std::unique_ptr workbench_; std::vector> listeners_; mutable std::mutex mutex_; - + static constexpr size_t MAX_VIEW_NAME_LENGTH = 256; static constexpr size_t MAX_FILE_PATH_LENGTH = 2048; static constexpr size_t MAX_LISTENERS = 100; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_CORE_WORKBENCH_STORE_HPP_ diff --git a/include/bolt/drawkern/dis_vm.hpp b/include/bolt/drawkern/dis_vm.hpp index 5ce698b4..90c1610a 100644 --- a/include/bolt/drawkern/dis_vm.hpp +++ b/include/bolt/drawkern/dis_vm.hpp @@ -1,12 +1,12 @@ #pragma once -#include -#include +#include +#include #include +#include #include #include -#include -#include -#include +#include +#include namespace bolt { namespace drawkern { @@ -16,105 +16,99 @@ namespace drawkern { enum class DISOpcode : uint8_t { // Stack operations - LOAD = 0x01, // Load from memory to stack - STORE = 0x02, // Store from stack to memory - POP = 0x03, // Pop stack - DUP = 0x04, // Duplicate top of stack - + LOAD = 0x01, // Load from memory to stack + STORE = 0x02, // Store from stack to memory + POP = 0x03, // Pop stack + DUP = 0x04, // Duplicate top of stack + // Arithmetic operations - ADD = 0x10, // Add two values - SUB = 0x11, // Subtract - MUL = 0x12, // Multiply - DIV = 0x13, // Divide - MOD = 0x14, // Modulo - + ADD = 0x10, // Add two values + SUB = 0x11, // Subtract + MUL = 0x12, // Multiply + DIV = 0x13, // Divide + MOD = 0x14, // Modulo + // Comparison operations - EQ = 0x20, // Equal - NE = 0x21, // Not equal - LT = 0x22, // Less than - GT = 0x23, // Greater than - LE = 0x24, // Less or equal - GE = 0x25, // Greater or equal - + EQ = 0x20, // Equal + NE = 0x21, // Not equal + LT = 0x22, // Less than + GT = 0x23, // Greater than + LE = 0x24, // Less or equal + GE = 0x25, // Greater or equal + // Control flow - JMP = 0x30, // Unconditional jump - JMPT = 0x31, // Jump if true - JMPF = 0x32, // Jump if false - CALL = 0x33, // Function call - RET = 0x34, // Return from function - + JMP = 0x30, // Unconditional jump + JMPT = 0x31, // Jump if true + JMPF = 0x32, // Jump if false + CALL = 0x33, // Function call + RET = 0x34, // Return from function + // String operations - NEWSTR = 0x40, // Create new string - CONCAT = 0x41, // Concatenate strings - STRLEN = 0x42, // String length - + NEWSTR = 0x40, // Create new string + CONCAT = 0x41, // Concatenate strings + STRLEN = 0x42, // String length + // List/Array operations NEWLIST = 0x50, // Create new list - APPEND = 0x51, // Append to list - INDEX = 0x52, // Index into list - + APPEND = 0x51, // Append to list + INDEX = 0x52, // Index into list + // I/O operations - PRINT = 0x60, // Print to output - READ = 0x61, // Read from input - + PRINT = 0x60, // Print to output + READ = 0x61, // Read from input + // AI operations (DrawKern extensions) - AI_INIT = 0x70, // Initialize AI model + AI_INIT = 0x70, // Initialize AI model AI_COMPLETE = 0x71, // AI completion - AI_CHAT = 0x72, // AI chat - + AI_CHAT = 0x72, // AI chat + // DrawKern operations RENDER_GLYPH = 0x80, // Render a glyph - SPAWN_VM = 0x81, // Spawn new VM - MOUNT_NS = 0x82, // Mount namespace - + SPAWN_VM = 0x81, // Spawn new VM + MOUNT_NS = 0x82, // Mount namespace + // System operations - HALT = 0xFF // Halt VM + HALT = 0xFF // Halt VM }; struct DISValue { enum Type { INT, FLOAT, STRING, LIST, REF } type; - + union { int64_t int_val; double float_val; void* ptr_val; }; - + std::string string_val; std::vector list_val; - + DISValue() : type(INT), int_val(0) {} - DISValue(int64_t v) : type(INT), int_val(v) {} - DISValue(double v) : type(FLOAT), float_val(v) {} - DISValue(const std::string& v) : type(STRING), string_val(v) {} - DISValue(const std::vector& v) : type(LIST), list_val(v) {} + explicit DISValue(int64_t v) : type(INT), int_val(v) {} + explicit DISValue(double v) : type(FLOAT), float_val(v) {} + explicit DISValue(const std::string& v) : type(STRING), string_val(v) {} + explicit DISValue(const std::vector& v) : type(LIST), list_val(v) {} }; struct DISInstruction { DISOpcode opcode; std::vector operands; - - DISInstruction(DISOpcode op) : opcode(op) {} - DISInstruction(DISOpcode op, const DISValue& operand) : opcode(op) { - operands.push_back(operand); - } + + explicit DISInstruction(DISOpcode op) : opcode(op) {} + DISInstruction(DISOpcode op, const DISValue& operand) : opcode(op) { operands.push_back(operand); } }; // Limbo bytecode program struct DISProgram { std::vector instructions; - std::map labels; // Label -> instruction index - std::map globals; // Global variables - std::string source_limbo; // Original Limbo source - - void add_instruction(const DISInstruction& inst) { - instructions.push_back(inst); - } - - void add_label(const std::string& label) { - labels[label] = instructions.size(); - } - + std::map labels; // Label -> instruction index + std::map globals; // Global variables + std::string source_limbo; // Original Limbo source + + void add_instruction(const DISInstruction& inst) { instructions.push_back(inst); } + + void add_label(const std::string& label) { labels[label] = instructions.size(); } + size_t get_label_address(const std::string& label) const { auto it = labels.find(label); return it != labels.end() ? it->second : 0; @@ -122,37 +116,37 @@ struct DISProgram { }; class DISVM { -public: + public: DISVM(); ~DISVM(); - + // Program execution bool load_program(const DISProgram& program); bool load_limbo_source(const std::string& source); bool run(); void step(); void halt(); - + // State management void reset(); bool is_running() const { return running_; } size_t get_pc() const { return pc_; } size_t get_program_size() const { return program_.instructions.size(); } - + // Stack operations void push(const DISValue& value); DISValue pop(); DISValue peek() const; size_t stack_size() const { return stack_.size(); } - + // Memory management void set_global(const std::string& name, const DISValue& value); DISValue get_global(const std::string& name) const; std::vector get_global_names() const; - + // AI integration void set_ai_handler(std::function handler); - + // DrawKern integration void set_glyph_renderer(std::function renderer); void set_vm_spawner(std::function spawner); @@ -164,47 +158,47 @@ class DISVM { void set_error_callback(std::function callback); void set_completion_callback(std::function callback); void set_output_callback(std::function callback); - + // Debugging void dump_stack() const; void dump_globals() const; std::string get_instruction_info(size_t pc) const; - + // Breakpoint management bool set_breakpoint(size_t pc); bool remove_breakpoint(size_t pc); void clear_all_breakpoints(); std::vector get_breakpoints() const; bool has_breakpoint(size_t pc) const; - + // Advanced debugging controls void step_over(); void step_into(); void step_out(); void continue_execution(); bool is_at_breakpoint() const; - + // Call stack inspection std::vector get_call_stack() const; size_t get_call_stack_depth() const; - -private: + + private: DISProgram program_; std::stack stack_; std::map globals_; - size_t pc_; // Program counter + size_t pc_; // Program counter bool running_; bool halted_; - + // Call stack for function calls std::stack call_stack_; - + // Debugging state std::set breakpoints_; bool at_breakpoint_; bool step_mode_; size_t step_depth_; // For step over/out functionality - + // Handler functions std::function ai_handler_; std::function glyph_renderer_; @@ -217,10 +211,10 @@ class DISVM { std::function error_callback_; std::function completion_callback_; std::function output_callback_; - + // Instruction execution void execute_instruction(const DISInstruction& inst); - + // Opcode handlers void handle_load(const DISInstruction& inst); void handle_store(const DISInstruction& inst); @@ -232,7 +226,7 @@ class DISVM { void handle_io_ops(const DISInstruction& inst); void handle_ai_ops(const DISInstruction& inst); void handle_drawkern_ops(const DISInstruction& inst); - + // Helper methods bool check_stack_size(size_t required) const; void runtime_error(const std::string& message); @@ -240,76 +234,74 @@ class DISVM { // Limbo to DIS bytecode compiler (simplified) class LimboCompiler { -public: + public: LimboCompiler(); ~LimboCompiler(); - + // Compile Limbo source to DIS bytecode DISProgram compile(const std::string& source); - + // Get compilation errors std::vector get_errors() const { return errors_; } bool has_errors() const { return !errors_.empty(); } - -private: + + private: std::vector errors_; - + // Parsing helpers std::vector tokenize(const std::string& source); DISProgram parse_tokens(const std::vector& tokens); - - void add_error(const std::string& error) { - errors_.push_back(error); - } + + void add_error(const std::string& error) { errors_.push_back(error); } }; // Factory for creating common DIS programs class DISProgramFactory { -public: + public: // Create AI workbench program static DISProgram create_ai_workbench(const std::string& model_name); - + // Create simple echo server static DISProgram create_echo_server(); - + // Create file server static DISProgram create_file_server(const std::string& root_path); - + // Create DrawKern renderer static DISProgram create_drawkern_renderer(); - + // Load program from Limbo source static DISProgram from_limbo_source(const std::string& source); }; // VM manager for multiple DIS VMs class DISVMManager { -public: + public: DISVMManager(); ~DISVMManager(); - + // VM lifecycle std::string create_vm(const DISProgram& program); bool start_vm(const std::string& vm_id); bool stop_vm(const std::string& vm_id); bool destroy_vm(const std::string& vm_id); - + // VM communication bool send_message(const std::string& vm_id, const DISValue& message); std::vector get_messages(const std::string& vm_id); - + // VM status std::vector list_vms() const; bool is_vm_running(const std::string& vm_id) const; std::string get_vm_status(const std::string& vm_id) const; - -private: + + private: std::map> vms_; std::map> vm_message_queues_; size_t next_vm_id_; - + std::string generate_vm_id(); }; -} // namespace drawkern -} // namespace bolt \ No newline at end of file +} // namespace drawkern +} // namespace bolt diff --git a/include/bolt/drawkern/styx_protocol.hpp b/include/bolt/drawkern/styx_protocol.hpp index 76200870..c6361591 100644 --- a/include/bolt/drawkern/styx_protocol.hpp +++ b/include/bolt/drawkern/styx_protocol.hpp @@ -1,10 +1,10 @@ #pragma once -#include -#include #include +#include #include #include -#include +#include +#include namespace bolt { namespace drawkern { @@ -14,25 +14,42 @@ namespace drawkern { enum class StyxMessageType : uint8_t { // Core Styx messages - Tversion = 100, Rversion = 101, - Tauth = 102, Rauth = 103, - Tattach = 104, Rattach = 105, - Terror = 106, Rerror = 107, - Tflush = 108, Rflush = 109, - Twalk = 110, Rwalk = 111, - Topen = 112, Ropen = 113, - Tcreate = 114, Rcreate = 115, - Tread = 116, Rread = 117, - Twrite = 118, Rwrite = 119, - Tclunk = 120, Rclunk = 121, - Tremove = 122, Rremove = 123, - Tstat = 124, Rstat = 125, - Twstat = 126, Rwstat = 127, - + Tversion = 100, + Rversion = 101, + Tauth = 102, + Rauth = 103, + Tattach = 104, + Rattach = 105, + Terror = 106, + Rerror = 107, + Tflush = 108, + Rflush = 109, + Twalk = 110, + Rwalk = 111, + Topen = 112, + Ropen = 113, + Tcreate = 114, + Rcreate = 115, + Tread = 116, + Rread = 117, + Twrite = 118, + Rwrite = 119, + Tclunk = 120, + Rclunk = 121, + Tremove = 122, + Rremove = 123, + Tstat = 124, + Rstat = 125, + Twstat = 126, + Rwstat = 127, + // DrawKern extensions - Tdrawkern = 200, Rdrawkern = 201, - Tglyph = 202, Rglyph = 203, - Tvmspawn = 204, Rvmspawn = 205 + Tdrawkern = 200, + Rdrawkern = 201, + Tglyph = 202, + Rglyph = 203, + Tvmspawn = 204, + Rvmspawn = 205 }; struct StyxQid { @@ -61,80 +78,80 @@ struct StyxMessage { StyxMessageType type = StyxMessageType::Terror; uint16_t tag = 0; std::vector data; - + // Default constructor StyxMessage() = default; - + // Helper methods for serialization void serialize(std::vector& buffer) const; static StyxMessage deserialize(const std::vector& buffer); }; class StyxConnection { -public: - StyxConnection(const std::string& address); + public: + explicit StyxConnection(const std::string& address); ~StyxConnection(); - + bool connect(); void disconnect(); bool is_connected() const { return connected_; } - + // Core protocol operations bool version(const std::string& version = "9P2000"); bool attach(const std::string& aname = "", const std::string& uname = "drawkern"); - + // File operations uint32_t walk(uint32_t fid, uint32_t newfid, const std::vector& path); uint32_t open(uint32_t fid, uint8_t mode); std::vector read(uint32_t fid, uint64_t offset, uint32_t count); uint32_t write(uint32_t fid, uint64_t offset, const std::vector& data); bool clunk(uint32_t fid); - + // DrawKern specific operations bool send_glyph(const std::string& glyph_data); bool spawn_vm(const std::string& vm_spec); - + StyxMessage send_message(const StyxMessage& message); - -private: + + private: std::string address_; int socket_fd_; bool connected_; uint16_t next_tag_; uint32_t next_fid_; - + bool send_data(const std::vector& data); std::vector receive_data(); }; class StyxServer { -public: - StyxServer(const std::string& address); + public: + explicit StyxServer(const std::string& address); ~StyxServer(); - + bool start(); void stop(); void run(); - + // File system interface for DrawKern void serve_file(const std::string& path, const std::string& content); void serve_vm_namespace(const std::string& vm_id); - + // DrawKern operations void register_glyph_handler(std::function handler); void register_vm_handler(std::function handler); - -private: + + private: std::string address_; int listen_fd_; bool running_; std::map virtual_files_; std::function glyph_handler_; std::function vm_handler_; - + void handle_client(int client_fd); StyxMessage handle_message(const StyxMessage& message); - + // Message handlers StyxMessage handle_version(const StyxMessage& message); StyxMessage handle_attach(const StyxMessage& message); @@ -143,7 +160,7 @@ class StyxServer { StyxMessage handle_read(const StyxMessage& message); StyxMessage handle_write(const StyxMessage& message); StyxMessage handle_clunk(const StyxMessage& message); - + // DrawKern extensions StyxMessage handle_glyph(const StyxMessage& message); StyxMessage handle_vm_spawn(const StyxMessage& message); @@ -151,25 +168,25 @@ class StyxServer { // Network file system mount point for DrawKern class DrawKernNamespace { -public: + public: DrawKernNamespace(); ~DrawKernNamespace(); - + // Mount DrawKern services bool mount(const std::string& address, const std::string& local_path); bool unmount(const std::string& local_path); - + // Access DrawKern resources as files std::string read_glyph(const std::string& glyph_id); bool write_glyph(const std::string& glyph_id, const std::string& content); - + // VM management through filesystem bool spawn_vm_from_file(const std::string& vm_spec_path); std::string get_vm_status(const std::string& vm_id); - -private: + + private: std::map> mounted_services_; }; -} // namespace drawkern -} // namespace bolt \ No newline at end of file +} // namespace drawkern +} // namespace bolt diff --git a/include/bolt/drawkern/yacc_grammar.hpp b/include/bolt/drawkern/yacc_grammar.hpp index dde5017c..ef1c3eb3 100644 --- a/include/bolt/drawkern/yacc_grammar.hpp +++ b/include/bolt/drawkern/yacc_grammar.hpp @@ -1,10 +1,11 @@ #pragma once -#include -#include +#include #include #include -#include +#include +#include #include +#include namespace bolt { namespace drawkern { @@ -19,40 +20,49 @@ struct AIWorkbenchGlyph; // AST Node types for the glyph description language enum class ASTNodeType { - PROGRAM, // Root program node - VM_DECL, // VM declaration - GLYPH_DECL, // Glyph declaration - PROPERTY, // Property assignment - BLOCK, // Block statement - EXPRESSION, // Expression - IDENTIFIER, // Identifier - LITERAL, // Literal value - LIST, // List of items - CALL // Function call + PROGRAM, // Root program node + VM_DECL, // VM declaration + GLYPH_DECL, // Glyph declaration + PROPERTY, // Property assignment + BLOCK, // Block statement + EXPRESSION, // Expression + IDENTIFIER, // Identifier + LITERAL, // Literal value + LIST, // List of items + CALL // Function call }; // Token types for lexical analysis enum class TokenType { // Keywords - VM, GLYPH, WORKBENCH, DIS, NATIVE, WASM, - RENDER, AI, MODEL, TOOLS, NAMESPACE, - + VM, + GLYPH, + WORKBENCH, + DIS, + NATIVE, + WASM, + RENDER, + AI, + MODEL, + TOOLS, + NAMESPACE, + // Operators and punctuation - ASSIGN, // = - SEMICOLON, // ; - COMMA, // , - LBRACE, // { - RBRACE, // } - LPAREN, // ( - RPAREN, // ) - LBRACKET, // [ - RBRACKET, // ] - + ASSIGN, // = + SEMICOLON, // ; + COMMA, // , + LBRACE, // { + RBRACE, // } + LPAREN, // ( + RPAREN, // ) + LBRACKET, // [ + RBRACKET, // ] + // Literals IDENTIFIER, STRING, NUMBER, - + // Special END_OF_FILE, UNKNOWN @@ -63,128 +73,122 @@ struct Token { std::string value; size_t line; size_t column; - - Token(TokenType t, const std::string& v, size_t l = 0, size_t c = 0) - : type(t), value(v), line(l), column(c) {} + + Token(TokenType t, const std::string& v, size_t l = 0, size_t c = 0) : type(t), value(v), line(l), column(c) {} }; // AST Node base class class ASTNode { -public: + public: ASTNodeType type; std::vector> children; std::map attributes; - - ASTNode(ASTNodeType t) : type(t) {} + + explicit ASTNode(ASTNodeType t) : type(t) {} virtual ~ASTNode() = default; - - void add_child(std::unique_ptr child) { - children.push_back(std::move(child)); - } - - void set_attribute(const std::string& key, const std::string& value) { - attributes[key] = value; - } - + + void add_child(std::unique_ptr child) { children.push_back(std::move(child)); } + + void set_attribute(const std::string& key, const std::string& value) { attributes[key] = value; } + std::string get_attribute(const std::string& key) const { auto it = attributes.find(key); return it != attributes.end() ? it->second : ""; } - + virtual std::string to_string() const; }; // Specialized AST node types class ProgramNode : public ASTNode { -public: + public: ProgramNode() : ASTNode(ASTNodeType::PROGRAM) {} }; class VMDeclNode : public ASTNode { -public: + public: std::string vm_id; std::string vm_type; - - VMDeclNode(const std::string& id, const std::string& type) + + VMDeclNode(const std::string& id, const std::string& type) : ASTNode(ASTNodeType::VM_DECL), vm_id(id), vm_type(type) {} }; class GlyphDeclNode : public ASTNode { -public: + public: std::string glyph_id; std::string base_vm; - - GlyphDeclNode(const std::string& id, const std::string& vm) + + GlyphDeclNode(const std::string& id, const std::string& vm) : ASTNode(ASTNodeType::GLYPH_DECL), glyph_id(id), base_vm(vm) {} }; class PropertyNode : public ASTNode { -public: + public: std::string name; std::string value; - - PropertyNode(const std::string& n, const std::string& v) - : ASTNode(ASTNodeType::PROPERTY), name(n), value(v) {} + + PropertyNode(const std::string& n, const std::string& v) : ASTNode(ASTNodeType::PROPERTY), name(n), value(v) {} }; // Lexer for tokenizing glyph description language class GlyphLexer { -public: - GlyphLexer(const std::string& input); + public: + explicit GlyphLexer(const std::string& input); ~GlyphLexer(); - + std::vector tokenize(); Token next_token(); - + bool has_errors() const { return !errors_.empty(); } std::vector get_errors() const { return errors_; } - -private: + + private: std::string input_; size_t pos_; size_t line_; size_t column_; std::vector errors_; - + char current_char(); char peek_char(); void advance(); void skip_whitespace(); void skip_comment(); - + Token read_identifier(); Token read_string(); Token read_number(); - + bool is_alpha(char c); bool is_digit(char c); bool is_alnum(char c); - + void add_error(const std::string& message); }; // Parser for glyph description language class GlyphParser { -public: - GlyphParser(const std::vector& tokens); + public: + explicit GlyphParser(const std::vector& tokens); ~GlyphParser(); - + std::unique_ptr parse(); - + bool has_errors() const { return !errors_.empty(); } std::vector get_errors() const { return errors_; } - -private: + + private: std::vector tokens_; size_t pos_; std::vector errors_; - + Token current_token(); Token peek_token(); void advance(); bool match(TokenType type); bool consume(TokenType type); - + std::unique_ptr parse_statement(); std::unique_ptr parse_vm_declaration(); std::unique_ptr parse_glyph_declaration(); @@ -192,33 +196,33 @@ class GlyphParser { std::unique_ptr parse_block(); std::unique_ptr parse_expression(); std::unique_ptr parse_list(); - + void add_error(const std::string& message); }; // Code generator - converts AST to executable VM glyphs class GlyphCodeGenerator { -public: + public: GlyphCodeGenerator(); ~GlyphCodeGenerator(); - + // Generate VM glyph from AST VMGlyph generate_vm_glyph(const ASTNode& ast); AIWorkbenchGlyph generate_ai_workbench(const ASTNode& ast); DISProgram generate_dis_program(const ASTNode& ast); - + // Generate different output formats std::string generate_cpp_code(const ASTNode& ast); std::string generate_json(const ASTNode& ast); std::string generate_yaml(const ASTNode& ast); - + bool has_errors() const { return !errors_.empty(); } std::vector get_errors() const { return errors_; } - -private: + + private: std::vector errors_; std::map vm_registry_; - + void add_error(const std::string& message); void process_vm_declaration(const VMDeclNode& node); void process_glyph_declaration(const GlyphDeclNode& node); @@ -259,46 +263,46 @@ mount ::= 'mount' STRING 'as' STRING ';' // High-level interface for the grammar system class YaccGrammarSystem { -public: + public: YaccGrammarSystem(); ~YaccGrammarSystem(); - + // Parse glyph description and generate VM VMGlyph parse_vm_glyph(const std::string& description); AIWorkbenchGlyph parse_ai_workbench(const std::string& description); - + // Validate glyph description bool validate_description(const std::string& description); std::vector get_validation_errors() const; - + // Generate code from description std::string generate_cpp_code(const std::string& description); std::string generate_deployment_script(const std::string& description); - + // Built-in templates std::string get_ai_workbench_template(); std::string get_file_server_template(); std::string get_echo_server_template(); - + // Grammar introspection std::vector get_supported_vm_types(); std::vector get_supported_properties(); std::string get_grammar_documentation(); - -private: + + private: std::unique_ptr lexer_; std::unique_ptr parser_; std::unique_ptr generator_; std::vector errors_; - + void clear_errors(); void collect_errors(); }; // Example glyph descriptions as string constants namespace GlyphTemplates { - - constexpr const char* AI_WORKBENCH = R"( + +constexpr const char* AI_WORKBENCH = R"( vm bolt_dis : dis { architecture = "portable"; capabilities = ["ai-inference", "code-parsing", "file-io"]; @@ -329,7 +333,7 @@ workbench bolt_ai on bolt_dis { } )"; - constexpr const char* FILE_SERVER = R"( +constexpr const char* FILE_SERVER = R"( vm file_server_vm : dis { architecture = "arm64"; capabilities = ["file-io", "network"]; @@ -347,7 +351,7 @@ glyph file_server on file_server_vm { } )"; - constexpr const char* ECHO_SERVER = R"( +constexpr const char* ECHO_SERVER = R"( vm echo_vm : native { architecture = "x86_64"; capabilities = ["network"]; @@ -364,7 +368,7 @@ glyph echo_server on echo_vm { } )"; -} // namespace GlyphTemplates +} // namespace GlyphTemplates -} // namespace drawkern -} // namespace bolt \ No newline at end of file +} // namespace drawkern +} // namespace bolt diff --git a/include/bolt/editor/code_completion.hpp b/include/bolt/editor/code_completion.hpp index 1daeaa97..4e61ba6f 100644 --- a/include/bolt/editor/code_completion.hpp +++ b/include/bolt/editor/code_completion.hpp @@ -1,12 +1,14 @@ -#ifndef CODE_COMPLETION_HPP -#define CODE_COMPLETION_HPP +#ifndef BOLT_EDITOR_CODE_COMPLETION_HPP_ +#define BOLT_EDITOR_CODE_COMPLETION_HPP_ -#include -#include -#include #include #include +#include +#include +#include +#include + #include "bolt/core/thread_safety.hpp" namespace bolt { @@ -19,10 +21,10 @@ struct CompletionItem { }; class CodeCompletionEngine { -private: + private: ThreadSafe> completionCache_; - -public: + + public: static CodeCompletionEngine& getInstance() { static CodeCompletionEngine instance; return instance; @@ -31,17 +33,11 @@ class CodeCompletionEngine { std::vector getCompletions(const std::string& prefix, size_t limit = 10) { return completionCache_.read([&](const auto& cache) { std::vector results; - std::copy_if(cache.begin(), cache.end(), - std::back_inserter(results), - [&](const auto& item) { - return item.label.find(prefix) == 0; - }); - - std::sort(results.begin(), results.end(), - [](const auto& a, const auto& b) { - return a.score > b.score; - }); - + std::copy_if(cache.begin(), cache.end(), std::back_inserter(results), + [&](const auto& item) { return item.label.find(prefix) == 0; }); + + std::sort(results.begin(), results.end(), [](const auto& a, const auto& b) { return a.score > b.score; }); + if (results.size() > limit) { results.resize(limit); } @@ -50,9 +46,7 @@ class CodeCompletionEngine { } void addCompletion(CompletionItem item) { - completionCache_.write([&](auto& cache) { - cache.push_back(std::move(item)); - }); + completionCache_.write([&](auto& cache) { cache.push_back(std::move(item)); }); } }; @@ -60,24 +54,24 @@ class CodeCompletionEngine { class CodeCompletionImpl; class CodeCompletion { -private: + private: std::unique_ptr impl_; - -public: + + public: CodeCompletion(); ~CodeCompletion(); - + void activate(); void deactivate(); bool isActive() const; - + void setSuggestions(const std::vector& suggestions); CompletionItem getSelectedSuggestion() const; - + void selectNext(); void selectPrevious(); }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_EDITOR_CODE_COMPLETION_HPP_ diff --git a/include/bolt/editor/code_folding.hpp b/include/bolt/editor/code_folding.hpp index 0baf6f20..4b2f0495 100644 --- a/include/bolt/editor/code_folding.hpp +++ b/include/bolt/editor/code_folding.hpp @@ -1,10 +1,11 @@ -#ifndef CODE_FOLDING_HPP -#define CODE_FOLDING_HPP +#ifndef BOLT_EDITOR_CODE_FOLDING_HPP_ +#define BOLT_EDITOR_CODE_FOLDING_HPP_ +#include #include #include -#include + #include "../core/thread_safety.hpp" namespace bolt { @@ -17,19 +18,17 @@ struct FoldRange { }; class CodeFolding { -private: + private: ThreadSafe>> foldingRanges_; -public: + public: static CodeFolding& getInstance() { static CodeFolding instance; return instance; } void addFoldRange(const std::string& filePath, size_t startLine, size_t endLine) { - foldingRanges_.write([&](auto& ranges) { - ranges[filePath].push_back({startLine, endLine, false, "..."}); - }); + foldingRanges_.write([&](auto& ranges) { ranges[filePath].push_back({startLine, endLine, false, "..."}); }); } void toggleFold(const std::string& filePath, size_t line) { @@ -52,6 +51,6 @@ class CodeFolding { } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_EDITOR_CODE_FOLDING_HPP_ diff --git a/include/bolt/editor/code_folding_detector.hpp b/include/bolt/editor/code_folding_detector.hpp index 611f22ae..722e0038 100644 --- a/include/bolt/editor/code_folding_detector.hpp +++ b/include/bolt/editor/code_folding_detector.hpp @@ -1,19 +1,20 @@ -#ifndef CODE_FOLDING_DETECTOR_HPP -#define CODE_FOLDING_DETECTOR_HPP +#ifndef BOLT_EDITOR_CODE_FOLDING_DETECTOR_HPP_ +#define BOLT_EDITOR_CODE_FOLDING_DETECTOR_HPP_ -#include "code_folding.hpp" #include #include +#include "bolt/editor/code_folding.hpp" + namespace bolt { class CodeFoldingDetector { -public: + public: static std::vector detectFoldableRanges(const std::string& content); static bool isFoldableRegion(const std::string& line); static int findMatchingEnd(const std::vector& lines, int startLine); }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_CODE_FOLDING_DETECTOR_HPP_ diff --git a/include/bolt/editor/code_folding_manager.hpp b/include/bolt/editor/code_folding_manager.hpp index b5e6222b..d7523a4e 100644 --- a/include/bolt/editor/code_folding_manager.hpp +++ b/include/bolt/editor/code_folding_manager.hpp @@ -1,24 +1,25 @@ -#ifndef CODE_FOLDING_MANAGER_HPP -#define CODE_FOLDING_MANAGER_HPP +#ifndef BOLT_EDITOR_CODE_FOLDING_MANAGER_HPP_ +#define BOLT_EDITOR_CODE_FOLDING_MANAGER_HPP_ -#include "code_folding.hpp" -#include "code_folding_detector.hpp" -#include "code_folding_visibility.hpp" +#include #include #include #include -#include + +#include "bolt/editor/code_folding.hpp" +#include "bolt/editor/code_folding_detector.hpp" +#include "bolt/editor/code_folding_visibility.hpp" namespace bolt { class CodeFoldingManager { -private: + private: std::map> foldingRanges_; ThreadSafe foldingEnabled_{true}; CodeFoldingVisibilityManager visibilityManager_; std::function onFoldingChanged_; -public: + public: static CodeFoldingManager& getInstance() { static CodeFoldingManager instance; return instance; @@ -32,10 +33,10 @@ class CodeFoldingManager { void handleClick(const std::string& filePath, size_t lineNumber); void setOnFoldingChanged(std::function callback); -private: + private: void refreshFoldingRanges(); }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_CODE_FOLDING_MANAGER_HPP_ diff --git a/include/bolt/editor/code_folding_ui.hpp b/include/bolt/editor/code_folding_ui.hpp index 2d2375c9..63159ab4 100644 --- a/include/bolt/editor/code_folding_ui.hpp +++ b/include/bolt/editor/code_folding_ui.hpp @@ -1,18 +1,19 @@ -#ifndef CODE_FOLDING_UI_HPP -#define CODE_FOLDING_UI_HPP +#ifndef BOLT_EDITOR_CODE_FOLDING_UI_HPP_ +#define BOLT_EDITOR_CODE_FOLDING_UI_HPP_ -#include "code_folding_manager.hpp" #include #include +#include "bolt/editor/code_folding_manager.hpp" + namespace bolt { class CodeFoldingUI { -private: + private: bool visible_; std::shared_ptr foldingManager_; -public: + public: struct FoldingGutter { bool isVisible; int width; @@ -21,7 +22,7 @@ class CodeFoldingUI { }; CodeFoldingUI(); - + void toggleVisibility(); void setVisibility(bool visible); bool isVisible() const; @@ -30,12 +31,12 @@ class CodeFoldingUI { void renderFoldingMarkers(const std::string& filePath); FoldingGutter createGutter(); -private: + private: void renderMarker(size_t startLine, size_t endLine, bool isCollapsed); void drawIcon(int x, int y, const std::string& icon); - static constexpr int lineHeight = 20; // Default line height in pixels + static constexpr int lineHeight = 20; // Default line height in pixels }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_CODE_FOLDING_UI_HPP_ diff --git a/include/bolt/editor/code_folding_visibility.hpp b/include/bolt/editor/code_folding_visibility.hpp index 43834ac8..d2cda7ff 100644 --- a/include/bolt/editor/code_folding_visibility.hpp +++ b/include/bolt/editor/code_folding_visibility.hpp @@ -1,18 +1,19 @@ -#ifndef CODE_FOLDING_VISIBILITY_HPP -#define CODE_FOLDING_VISIBILITY_HPP +#ifndef BOLT_EDITOR_CODE_FOLDING_VISIBILITY_HPP_ +#define BOLT_EDITOR_CODE_FOLDING_VISIBILITY_HPP_ -#include "code_folding.hpp" #include #include #include +#include "bolt/editor/code_folding.hpp" + namespace bolt { class CodeFoldingVisibilityManager { -private: + private: std::map> visibilityMap_; -public: + public: void setLineVisibility(const std::string& filePath, size_t line, bool visible); bool isLineVisible(const std::string& filePath, size_t line) const; void toggleFoldedSection(const std::string& filePath, size_t startLine, size_t endLine); @@ -20,6 +21,6 @@ class CodeFoldingVisibilityManager { void updateFoldedSections(const std::string& filePath, const std::vector& foldRanges); }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_CODE_FOLDING_VISIBILITY_HPP_ diff --git a/include/bolt/editor/cursor_manager.hpp b/include/bolt/editor/cursor_manager.hpp index 8b9556dc..8a97371c 100644 --- a/include/bolt/editor/cursor_manager.hpp +++ b/include/bolt/editor/cursor_manager.hpp @@ -1,9 +1,11 @@ -#ifndef CURSOR_MANAGER_HPP -#define CURSOR_MANAGER_HPP +#ifndef BOLT_EDITOR_CURSOR_MANAGER_HPP_ +#define BOLT_EDITOR_CURSOR_MANAGER_HPP_ -#include #include +#include +#include + #include "bolt/core/thread_safety.hpp" namespace bolt { @@ -13,14 +15,12 @@ struct Selection { size_t startColumn; size_t endLine; size_t endColumn; - - bool hasSelection() const { - return !(startLine == endLine && startColumn == endColumn); - } - + + bool hasSelection() const { return !(startLine == endLine && startColumn == endColumn); } + bool operator==(const Selection& other) const { - return startLine == other.startLine && startColumn == other.startColumn && - endLine == other.endLine && endColumn == other.endColumn; + return startLine == other.startLine && startColumn == other.startColumn && endLine == other.endLine && + endColumn == other.endColumn; } }; @@ -29,21 +29,19 @@ struct Cursor { size_t column; bool isActive; Selection selection; // Selection range for this cursor - + Cursor() : line(0), column(0), isActive(true), selection{0, 0, 0, 0} {} Cursor(size_t l, size_t c) : line(l), column(c), isActive(true), selection{l, c, l, c} {} - - bool operator==(const Cursor& other) const { - return line == other.line && column == other.column; - } + + bool operator==(const Cursor& other) const { return line == other.line && column == other.column; } }; class CursorManager { -private: + private: ThreadSafe> cursors_; ThreadSafe primaryCursorIndex_{0}; -public: + public: static CursorManager& getInstance(); void addCursor(size_t line, size_t column); @@ -67,24 +65,24 @@ class CursorManager { void deleteAtCursors(); void deleteSelectionAtCursors(); std::vector getSelectedText() const; - + // Selection operations void updateCursorSelection(size_t cursorIndex, const Selection& selection); void clearAllSelections(); void selectWordAtCursors(); void selectLineAtCursors(); - + // Find and multi-cursor operations void findNextOccurrence(const std::string& text, const std::string& documentContent); void addCursorAtNextOccurrence(const std::string& text, const std::string& documentContent); void selectAllOccurrences(const std::string& text, const std::string& documentContent); - + // Utility methods size_t getCursorCount() const; bool hasCursors() const; void sortCursorsByPosition(); }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_EDITOR_CURSOR_MANAGER_HPP_ diff --git a/include/bolt/editor/debugger_interface.hpp b/include/bolt/editor/debugger_interface.hpp index 44a658f5..16610ce8 100644 --- a/include/bolt/editor/debugger_interface.hpp +++ b/include/bolt/editor/debugger_interface.hpp @@ -1,11 +1,13 @@ #pragma once -#include "bolt/drawkern/dis_vm.hpp" -#include -#include +#include #include #include -#include +#include +#include +#include + +#include "bolt/drawkern/dis_vm.hpp" // Fix Windows macro collision #ifdef ERROR @@ -19,11 +21,11 @@ class IntegratedEditor; // Debugger session state enum class DebugState { - STOPPED, // No debugging session active - RUNNING, // Executing code - PAUSED, // Paused at breakpoint or after step - FINISHED, // Execution completed - ERROR // Error occurred during debugging + STOPPED, // No debugging session active + RUNNING, // Executing code + PAUSED, // Paused at breakpoint or after step + FINISHED, // Execution completed + ERROR // Error occurred during debugging }; // Debug event types for UI notifications @@ -42,9 +44,8 @@ struct WatchExpression { std::string value; std::string type; bool valid; - - WatchExpression(const std::string& expr) - : expression(expr), valid(false) {} + + explicit WatchExpression(const std::string& expr) : expression(expr), valid(false) {} }; // Breakpoint information @@ -54,8 +55,8 @@ struct BreakpointInfo { size_t line_number; bool enabled; std::string condition; // For conditional breakpoints (future enhancement) - - BreakpointInfo(size_t pc_val, const std::string& file = "", size_t line = 0) + + explicit BreakpointInfo(size_t pc_val, const std::string& file = "", size_t line = 0) : pc(pc_val), file_path(file), line_number(line), enabled(true) {} }; @@ -64,30 +65,30 @@ using DebugEventCallback = std::function get_all_breakpoints() const; bool has_breakpoint(size_t pc) const; - + // State inspection size_t get_current_pc() const; std::string get_current_instruction() const; @@ -107,51 +108,51 @@ class DebuggerInterface { size_t get_call_stack_depth() const; std::vector get_stack_contents() const; std::map get_global_variables() const; - + // Watch expressions bool add_watch_expression(const std::string& expression); bool remove_watch_expression(const std::string& expression); void clear_watch_expressions(); std::vector get_watch_expressions() const; void update_watch_expressions(); - + // Event handling void set_event_callback(DebugEventCallback callback); - + // Integration with editor void set_editor(IntegratedEditor* editor); void highlight_current_line(); void clear_current_line_highlight(); void refresh_breakpoint_markers(); - + // Program information size_t get_program_size() const; std::string get_instruction_at(size_t pc) const; bool is_valid_pc(size_t pc) const; - + // Debug output and logging void enable_debug_output(bool enabled); std::vector get_debug_log() const; void clear_debug_log(); - -private: + + private: std::unique_ptr vm_; std::vector breakpoints_; std::vector watch_expressions_; - std::map file_line_to_pc_; // File/line to PC mapping + std::map file_line_to_pc_; // File/line to PC mapping std::map> pc_to_file_line_; // PC to file/line mapping - + DebugState state_; DebugEventCallback event_callback_; IntegratedEditor* editor_; - + std::vector debug_log_; bool debug_output_enabled_; - + // Current debug position tracking std::string current_debug_file_; size_t current_debug_line_; - + // Internal helpers void transition_state(DebugState new_state, const std::string& message = ""); void fire_event(DebugEvent event, const std::string& message = ""); @@ -163,4 +164,4 @@ class DebuggerInterface { void setup_vm_handlers(); }; -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/include/bolt/editor/debugger_ui.hpp b/include/bolt/editor/debugger_ui.hpp index 2a21a361..9aa905b5 100644 --- a/include/bolt/editor/debugger_ui.hpp +++ b/include/bolt/editor/debugger_ui.hpp @@ -1,29 +1,30 @@ #pragma once -#include "bolt/editor/debugger_interface.hpp" +#include #include #include -#include + +#include "bolt/editor/debugger_interface.hpp" namespace bolt { /** * @brief Debugger UI Component - * + * * Provides user interface elements for the integrated debugger, * including control panels, variable inspection, and debug output. */ class DebuggerUI { -public: + public: DebuggerUI(); ~DebuggerUI(); - + // UI State management void initialize(); void shutdown(); bool is_visible() const; void set_visible(bool visible); - + // Rendering void render(); void render_controls(); @@ -32,11 +33,11 @@ class DebuggerUI { void render_variables(); void render_watch_expressions(); void render_debug_output(); - + // Debugger integration void set_debugger(std::shared_ptr debugger); void on_debug_event(DebugEvent event, const std::string& message); - + // UI Actions void handle_continue_clicked(); void handle_step_over_clicked(); @@ -44,37 +45,37 @@ class DebuggerUI { void handle_step_out_clicked(); void handle_pause_clicked(); void handle_stop_clicked(); - + // Breakpoint UI void handle_breakpoint_toggle(size_t pc); void handle_breakpoint_condition_edit(size_t pc, const std::string& condition); - + // Watch expression UI void handle_add_watch_expression(); void handle_remove_watch_expression(const std::string& expression); - + // Layout and appearance void set_layout_style(const std::string& style); void set_panel_size(float width, float height); void set_auto_refresh(bool enabled, float interval_ms = 100.0f); - -private: + + private: std::shared_ptr debugger_; bool visible_; bool initialized_; - + // UI State std::string new_watch_expression_; std::string status_message_; bool auto_refresh_enabled_; float refresh_interval_ms_; float last_refresh_time_; - + // Panel sizes and layout float controls_panel_height_; float variables_panel_width_; float output_panel_height_; - + // Helper methods void render_control_button(const std::string& label, bool enabled, std::function callback); void render_breakpoint_item(const BreakpointInfo& bp); @@ -86,4 +87,4 @@ class DebuggerUI { std::string format_pc_address(size_t pc) const; }; -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/include/bolt/editor/editor_features.hpp b/include/bolt/editor/editor_features.hpp index 16d2c2c1..5de0d0be 100644 --- a/include/bolt/editor/editor_features.hpp +++ b/include/bolt/editor/editor_features.hpp @@ -1,9 +1,10 @@ -#ifndef EDITOR_FEATURES_HPP -#define EDITOR_FEATURES_HPP +#ifndef BOLT_EDITOR_EDITOR_FEATURES_HPP_ +#define BOLT_EDITOR_EDITOR_FEATURES_HPP_ +#include #include #include -#include + #include "bolt/core/thread_safety.hpp" namespace bolt { @@ -15,12 +16,12 @@ struct FoldingRange { }; class EditorFeatures { -private: + private: ThreadSafe>> foldingRanges_; ThreadSafe showFoldingMarkers_{true}; ThreadSafe showLineNumbers_{true}; -public: + public: static EditorFeatures& getInstance() { static EditorFeatures instance; return instance; @@ -38,9 +39,7 @@ class EditorFeatures { } void addFoldingRange(const std::string& filePath, int startLine, int endLine) { - foldingRanges_.write([&](auto& ranges) { - ranges[filePath].push_back({startLine, endLine, false}); - }); + foldingRanges_.write([&](auto& ranges) { ranges[filePath].push_back({startLine, endLine, false}); }); } void toggleFold(const std::string& filePath, int line) { @@ -70,11 +69,9 @@ class EditorFeatures { for (size_t i = 0; i < content.length(); ++i) { if (content[i] == '\n') { lineNumber++; - } - else if (content[i] == '{') { + } else if (content[i] == '{') { bracketStack.push_back(lineNumber); - } - else if (content[i] == '}' && !bracketStack.empty()) { + } else if (content[i] == '}' && !bracketStack.empty()) { int startLine = bracketStack.back(); bracketStack.pop_back(); if (lineNumber > startLine) { @@ -83,12 +80,10 @@ class EditorFeatures { } } - foldingRanges_.write([&](auto& allRanges) { - allRanges[filePath] = ranges; - }); + foldingRanges_.write([&](auto& allRanges) { allRanges[filePath] = ranges; }); } }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_EDITOR_FEATURES_HPP_ diff --git a/include/bolt/editor/editor_pane.hpp b/include/bolt/editor/editor_pane.hpp index ad11c0a0..2a361369 100644 --- a/include/bolt/editor/editor_pane.hpp +++ b/include/bolt/editor/editor_pane.hpp @@ -1,11 +1,13 @@ -#ifndef EDITOR_PANE_HPP -#define EDITOR_PANE_HPP +#ifndef BOLT_EDITOR_EDITOR_PANE_HPP_ +#define BOLT_EDITOR_EDITOR_PANE_HPP_ + +#include +#include +#include #include "bolt/core/editor_store.hpp" #include "bolt/editor/minimap.hpp" #include "bolt/editor/minimap_ui.hpp" -#include -#include namespace bolt { @@ -18,9 +20,9 @@ class CursorManager; * Each pane can display a different document and maintain its own state */ class EditorPane { -public: + public: struct PanePosition { - int x, y; // Position within the parent container + int x, y; // Position within the parent container int width, height; // Dimensions of the pane }; @@ -34,18 +36,18 @@ class EditorPane { bool isVisible = true; }; -private: + private: std::string paneId_; PanePosition position_; PaneState state_; EditorStore& editorStore_; - + // Minimap integration std::unique_ptr minimap_; std::unique_ptr minimapUI_; bool minimapEnabled_ = true; -public: + public: explicit EditorPane(const std::string& paneId); ~EditorPane() = default; @@ -53,37 +55,37 @@ class EditorPane { const std::string& getId() const { return paneId_; } void setPosition(const PanePosition& position); const PanePosition& getPosition() const { return position_; } - + // Document operations void openDocument(const std::string& filePath); void closeDocument(); const std::string& getDocumentPath() const { return state_.documentPath; } bool hasDocument() const { return !state_.documentPath.empty(); } - + // State management void setFocus(bool focus); bool hasFocus() const { return state_.hasFocus; } void setVisible(bool visible); bool isVisible() const { return state_.isVisible; } - + // Cursor and scroll operations void setCursorPosition(size_t line, size_t column); void getCursorPosition(size_t& line, size_t& column) const; void setScrollPosition(size_t line, size_t column); void getScrollPosition(size_t& line, size_t& column) const; - + // Content operations std::string getDocumentContent() const; void updateDocumentContent(const std::string& content); - + // Rendering and display void render(); void refresh(); - + // Pane state const PaneState& getState() const { return state_; } void restoreState(const PaneState& state); - + // Minimap operations void setMinimapEnabled(bool enabled); bool isMinimapEnabled() const { return minimapEnabled_; } @@ -92,7 +94,7 @@ class EditorPane { void updateMinimap(); std::vector renderMinimap() const; -private: + private: void syncWithEditorStore(); void updateEditorStoreDocument(); void initializeMinimap(); @@ -100,6 +102,6 @@ class EditorPane { std::vector getDocumentLines() const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_EDITOR_PANE_HPP_ diff --git a/include/bolt/editor/file_tree.hpp b/include/bolt/editor/file_tree.hpp index c6f418d5..aaefecd8 100644 --- a/include/bolt/editor/file_tree.hpp +++ b/include/bolt/editor/file_tree.hpp @@ -1,12 +1,14 @@ -#ifndef FILE_TREE_HPP -#define FILE_TREE_HPP +#ifndef BOLT_EDITOR_FILE_TREE_HPP_ +#define BOLT_EDITOR_FILE_TREE_HPP_ // Main file tree navigation component header // This includes all file tree functionality for the editor -#include "file_tree_node.hpp" -#include "file_tree_manager.hpp" -#include "file_tree_ui.hpp" +#include + +#include "bolt/editor/file_tree_manager.hpp" +#include "bolt/editor/file_tree_node.hpp" +#include "bolt/editor/file_tree_ui.hpp" namespace bolt { @@ -20,6 +22,6 @@ inline std::unique_ptr createFileTreeUI() { return std::make_unique(); } -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_FILE_TREE_HPP_ diff --git a/include/bolt/editor/file_tree_manager.hpp b/include/bolt/editor/file_tree_manager.hpp index 37abb621..ee56b53b 100644 --- a/include/bolt/editor/file_tree_manager.hpp +++ b/include/bolt/editor/file_tree_manager.hpp @@ -1,65 +1,67 @@ -#ifndef FILE_TREE_MANAGER_HPP -#define FILE_TREE_MANAGER_HPP +#ifndef BOLT_EDITOR_FILE_TREE_MANAGER_HPP_ +#define BOLT_EDITOR_FILE_TREE_MANAGER_HPP_ -#include "file_tree_node.hpp" -#include "bolt/core/thread_safety.hpp" -#include -#include -#include #include +#include +#include +#include +#include + +#include "bolt/core/thread_safety.hpp" +#include "bolt/editor/file_tree_node.hpp" namespace bolt { class FileTreeManager { -private: + private: std::shared_ptr rootNode_; ThreadSafe currentRootPath_; ThreadSafe showHiddenFiles_{false}; std::function onFileSelected_; std::function onDirectoryExpanded_; - -public: + + public: static FileTreeManager& getInstance() { static FileTreeManager instance; return instance; } - + // Root directory management void setRootDirectory(const std::string& path); std::string getRootDirectory() const; std::shared_ptr getRootNode() const { return rootNode_; } - + // Tree operations void refreshTree(); void refreshNode(std::shared_ptr node); bool expandDirectory(const std::string& path); bool collapseDirectory(const std::string& path); bool toggleDirectory(const std::string& path); - + // Selection void selectFile(const std::string& path); void clearSelection(); std::shared_ptr getSelectedNode() const; - + // Navigation std::shared_ptr findNode(const std::string& path) const; std::vector> getVisibleNodes() const; - + // Settings void setShowHiddenFiles(bool show); bool getShowHiddenFiles() const; - + // Callbacks void setOnFileSelected(std::function callback); void setOnDirectoryExpanded(std::function callback); - + // File operations bool createFile(const std::string& parentPath, const std::string& fileName); bool createDirectory(const std::string& parentPath, const std::string& dirName); bool deleteNode(const std::string& path); bool renameNode(const std::string& path, const std::string& newName); - -private: + + private: FileTreeManager() = default; void buildTreeFromPath(const std::string& path, std::shared_ptr parent); void scanDirectory(std::shared_ptr dirNode); @@ -67,9 +69,10 @@ class FileTreeManager { void notifyFileSelected(const std::string& path); void notifyDirectoryExpanded(const std::string& path); void clearSelectionRecursive(std::shared_ptr node); - void collectVisibleNodes(std::shared_ptr node, std::vector>& result) const; + void collectVisibleNodes(std::shared_ptr node, + std::vector>& result) const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_FILE_TREE_MANAGER_HPP_ diff --git a/include/bolt/editor/file_tree_node.hpp b/include/bolt/editor/file_tree_node.hpp index 1c842b57..64c032da 100644 --- a/include/bolt/editor/file_tree_node.hpp +++ b/include/bolt/editor/file_tree_node.hpp @@ -1,18 +1,15 @@ -#ifndef FILE_TREE_NODE_HPP -#define FILE_TREE_NODE_HPP +#ifndef BOLT_EDITOR_FILE_TREE_NODE_HPP_ +#define BOLT_EDITOR_FILE_TREE_NODE_HPP_ -#include -#include -#include #include #include +#include +#include +#include namespace bolt { -enum class FileTreeNodeType { - FILE, - DIRECTORY -}; +enum class FileTreeNodeType { FILE, DIRECTORY }; struct FileTreeNode : public std::enable_shared_from_this { std::string name; @@ -20,33 +17,33 @@ struct FileTreeNode : public std::enable_shared_from_this { FileTreeNodeType type; size_t size; // in bytes, 0 for directories std::filesystem::file_time_type lastModified; - + bool isExpanded; // for directories bool isSelected; - + // Hierarchy std::weak_ptr parent; std::vector> children; - + FileTreeNode(const std::string& name, const std::string& fullPath, FileTreeNodeType type) : name(name), fullPath(fullPath), type(type), size(0), isExpanded(false), isSelected(false) {} - + bool isDirectory() const { return type == FileTreeNodeType::DIRECTORY; } bool isFile() const { return type == FileTreeNodeType::FILE; } - + // Helper methods std::shared_ptr findChild(const std::string& name) const; void addChild(std::shared_ptr child); void removeChild(const std::string& name); void sortChildren(); - + // Get depth in tree (0 for root) size_t getDepth() const; - + // Get all descendant files std::vector> getAllFiles() const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_FILE_TREE_NODE_HPP_ diff --git a/include/bolt/editor/file_tree_ui.hpp b/include/bolt/editor/file_tree_ui.hpp index 2fa9927f..db032d6e 100644 --- a/include/bolt/editor/file_tree_ui.hpp +++ b/include/bolt/editor/file_tree_ui.hpp @@ -1,11 +1,12 @@ -#ifndef FILE_TREE_UI_HPP -#define FILE_TREE_UI_HPP +#ifndef BOLT_EDITOR_FILE_TREE_UI_HPP_ +#define BOLT_EDITOR_FILE_TREE_UI_HPP_ -#include "file_tree_node.hpp" -#include "file_tree_manager.hpp" +#include #include #include -#include + +#include "bolt/editor/file_tree_manager.hpp" +#include "bolt/editor/file_tree_node.hpp" namespace bolt { @@ -16,58 +17,52 @@ struct FileTreeRenderOptions { char collapsedIcon; char fileIcon; char directoryIcon; - - FileTreeRenderOptions() - : showIcons(true) - , indentSize(2) - , expandedIcon('v') - , collapsedIcon('>') - , fileIcon('-') - , directoryIcon('/') - {} + + FileTreeRenderOptions() + : showIcons(true), indentSize(2), expandedIcon('v'), collapsedIcon('>'), fileIcon('-'), directoryIcon('/') {} }; class FileTreeUI { -private: + private: FileTreeManager& manager_; FileTreeRenderOptions options_; ThreadSafe isVisible_{true}; - -public: + + public: FileTreeUI() : manager_(FileTreeManager::getInstance()) {} - + // Rendering void render(); void renderToString(std::string& output); std::vector renderToLines() const; - + // UI Settings void setRenderOptions(const FileTreeRenderOptions& options); FileTreeRenderOptions getRenderOptions() const { return options_; } - + // Visibility void setVisible(bool visible); bool isVisible() const; - + // Interaction handling void handleClick(size_t lineNumber); void handleDoubleClick(size_t lineNumber); void handleKeyPress(const std::string& key); - + // Context menu (future expansion) void showContextMenu(const std::string& path); - -private: + + private: void renderNode(std::shared_ptr node, std::string& output, size_t depth) const; void renderNodeToLine(std::shared_ptr node, std::vector& lines, size_t depth) const; std::string getIndentation(size_t depth) const; std::string getNodePrefix(std::shared_ptr node) const; std::string formatFileSize(size_t size) const; - + // Convert line number to node path std::string getPathFromLineNumber(size_t lineNumber) const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_FILE_TREE_UI_HPP_ diff --git a/include/bolt/editor/find_replace.hpp b/include/bolt/editor/find_replace.hpp index 867d0992..c5176d83 100644 --- a/include/bolt/editor/find_replace.hpp +++ b/include/bolt/editor/find_replace.hpp @@ -1,11 +1,10 @@ -#ifndef BOLT_EDITOR_FIND_REPLACE_HPP -#define BOLT_EDITOR_FIND_REPLACE_HPP +#ifndef BOLT_EDITOR_FIND_REPLACE_HPP_ +#define BOLT_EDITOR_FIND_REPLACE_HPP_ +#include // Added for std::transform +#include #include #include -#include -#include //Added for std::transform - namespace bolt { @@ -15,12 +14,13 @@ struct TextRange { }; class FindReplace { -public: + public: FindReplace() : case_sensitive_(false), use_regex_(false) {} std::vector find(const std::string& text, const std::string& search_term) { std::vector results; - if (search_term.empty()) return results; + if (search_term.empty()) + return results; if (use_regex_) { results = findWithRegex(text, search_term); @@ -46,7 +46,7 @@ class FindReplace { bool isCaseSensitive() const { return case_sensitive_; } bool isUsingRegex() const { return use_regex_; } -private: + private: bool case_sensitive_; bool use_regex_; @@ -92,6 +92,6 @@ class FindReplace { } }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_EDITOR_FIND_REPLACE_HPP \ No newline at end of file +#endif // BOLT_EDITOR_FIND_REPLACE_HPP_ diff --git a/include/bolt/editor/integrated_editor.hpp b/include/bolt/editor/integrated_editor.hpp index 6a866e22..28586395 100644 --- a/include/bolt/editor/integrated_editor.hpp +++ b/include/bolt/editor/integrated_editor.hpp @@ -1,29 +1,32 @@ -#ifndef INTEGRATED_EDITOR_HPP -#define INTEGRATED_EDITOR_HPP +#ifndef BOLT_EDITOR_INTEGRATED_EDITOR_HPP_ +#define BOLT_EDITOR_INTEGRATED_EDITOR_HPP_ +#include +#include +#include +#include +#include +#include +#include + +#include "bolt/ai/ai_completion_provider.hpp" #include "bolt/core/editor_store.hpp" +#include "bolt/editor/code_completion.hpp" +#include "bolt/editor/code_folding_detector.hpp" #include "bolt/editor/code_folding_manager.hpp" #include "bolt/editor/code_folding_ui.hpp" -#include "bolt/editor/code_folding_detector.hpp" -#include "bolt/editor/file_tree.hpp" #include "bolt/editor/cursor_manager.hpp" +#include "bolt/editor/debugger_interface.hpp" +#include "bolt/editor/debugger_ui.hpp" +#include "bolt/editor/file_tree.hpp" #include "bolt/editor/keyboard_shortcuts.hpp" #include "bolt/editor/split_view_manager.hpp" -#include "bolt/editor/code_completion.hpp" #include "bolt/editor/tab_bar.hpp" -#include "bolt/editor/debugger_interface.hpp" -#include "bolt/editor/debugger_ui.hpp" -#include "bolt/ai/ai_completion_provider.hpp" -#include -#include -#include -#include -#include namespace bolt { class IntegratedEditor { -private: + private: EditorStore& editorStore_; CodeFoldingManager& foldingManager_; std::unique_ptr foldingUI_; @@ -35,12 +38,12 @@ class IntegratedEditor { TabBar& tabBar_; AICodeCompletionEngine& aiCompletionEngine_; std::unique_ptr codeCompletion_; - + // Debugger integration std::shared_ptr debugger_; std::unique_ptr debuggerUI_; -public: + public: static IntegratedEditor& getInstance() { static IntegratedEditor instance; return instance; @@ -50,33 +53,33 @@ class IntegratedEditor { void openDocument(const std::string& filePath, const std::string& content); void updateDocumentContent(const std::string& filePath, const std::string& content); void closeDocument(const std::string& filePath); - + // Folding operations void toggleFold(const std::string& filePath, size_t line); void expandAllFolds(const std::string& filePath); void collapseAllFolds(const std::string& filePath); void refreshFolding(const std::string& filePath); - + // UI operations void renderEditor(const std::string& filePath); void handleClick(const std::string& filePath, size_t line, size_t character); - + // File tree operations void setFileTreeRootDirectory(const std::string& path); void refreshFileTree(); void toggleFileTreeVisibility(); bool isFileTreeVisible() const; void renderFileTree(); - + // File tree integration with editor void openFileFromTree(const std::string& filePath); void showFileInTree(const std::string& filePath); - + // Folding state queries std::vector getFoldingRanges(const std::string& filePath) const; bool isFoldingEnabled() const; void setFoldingEnabled(bool enabled); - + // Multi-cursor operations void addCursorAtPosition(size_t line, size_t column); void addCursorAtNextOccurrence(const std::string& text); @@ -86,11 +89,11 @@ class IntegratedEditor { void deleteAtCursors(); size_t getCursorCount() const; std::vector getAllCursors() const; - + // Keyboard shortcut handling bool handleKeyboardShortcut(const std::string& key, const std::string& command); void initializeKeyboardShortcuts(); - + // Split view operations std::string createHorizontalSplit(const std::string& filePath = ""); std::string createVerticalSplit(const std::string& filePath = ""); @@ -98,7 +101,7 @@ class IntegratedEditor { bool focusPane(const std::string& paneId); void navigateToNextPane(); void navigateToPreviousPane(); - + // Split view management bool isSplitViewEnabled() const; void setSplitViewEnabled(bool enabled); @@ -107,63 +110,65 @@ class IntegratedEditor { std::vector getAllPaneIds() const; std::string getActivePaneId() const; EditorPane* getActivePane(); - + // Document operations in split view void openDocumentInPane(const std::string& paneId, const std::string& filePath); - void openDocumentInNewPane(const std::string& filePath, SplitViewManager::SplitDirection direction = SplitViewManager::SplitDirection::Horizontal); + void openDocumentInNewPane(const std::string& filePath, SplitViewManager::SplitDirection direction = + SplitViewManager::SplitDirection::Horizontal); std::vector getOpenDocuments() const; std::string findPaneWithDocument(const std::string& filePath) const; - + // AI Code Completion operations void triggerCodeCompletion(const std::string& filePath, size_t line, size_t column); void triggerCodeCompletion(const std::string& filePath, const std::string& prefix); - std::vector getAICompletions(const std::string& filePath, const std::string& prefix, size_t limit = 10); + std::vector getAICompletions(const std::string& filePath, const std::string& prefix, + size_t limit = 10); bool isCodeCompletionActive() const; void acceptCompletion(); void cancelCompletion(); void selectNextCompletion(); void selectPreviousCompletion(); CompletionItem getSelectedCompletion() const; - + // AI completion settings void setAICompletionEnabled(bool enabled); bool isAICompletionEnabled() const; bool isAICompletionReady() const; - + // Debugger operations bool startDebugSession(const std::string& filePath); bool startDebugSessionFromSource(const std::string& limboSource); void stopDebugSession(); bool isDebugging() const; DebugState getDebugState() const; - + // Debug execution control void debugContinue(); void debugStepOver(); void debugStepInto(); void debugStepOut(); void debugPause(); - + // Debug breakpoint management bool toggleBreakpointAtLine(const std::string& filePath, size_t line); bool setBreakpointAtLine(const std::string& filePath, size_t line); bool removeBreakpointAtLine(const std::string& filePath, size_t line); void clearAllBreakpoints(); std::vector getAllBreakpoints() const; - + // Debug UI void showDebugger(); void hideDebugger(); bool isDebuggerVisible() const; void toggleDebuggerVisibility(); - + // Debug information size_t getCurrentDebugPC() const; std::string getCurrentDebugInstruction() const; std::vector getDebugCallStack() const; std::vector getDebugStackContents() const; std::map getDebugGlobalVariables() const; - + // Tab management operations size_t openDocumentInTab(const std::string& filePath, const std::string& content); bool closeTabById(size_t tabId); @@ -183,12 +188,12 @@ class IntegratedEditor { // Debugger-Editor Integration: Line highlighting enum class HighlightType { - DebugCurrent, // Current execution line (yellow/orange) - DebugBreakpoint, // Breakpoint hit (red) - DebugStepTarget, // Step target line (green) - SearchResult, // Search result highlight - Error, // Error line (red underline) - Warning // Warning line (yellow underline) + DebugCurrent, // Current execution line (yellow/orange) + DebugBreakpoint, // Breakpoint hit (red) + DebugStepTarget, // Step target line (green) + SearchResult, // Search result highlight + Error, // Error line (red underline) + Warning // Warning line (yellow underline) }; void highlightLine(const std::string& filePath, size_t line, HighlightType type); @@ -216,7 +221,7 @@ class IntegratedEditor { std::optional getPCForLine(const std::string& filePath, size_t line) const; std::optional> getLineForPC(size_t pc) const; -private: + private: IntegratedEditor(); void detectAndUpdateFolding(const std::string& filePath, const std::string& content); void synchronizeFoldingState(const std::string& filePath); @@ -232,6 +237,6 @@ class IntegratedEditor { std::map> pcToLine_; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_INTEGRATED_EDITOR_HPP_ diff --git a/include/bolt/editor/keyboard_shortcuts.hpp b/include/bolt/editor/keyboard_shortcuts.hpp index a2766d8b..b4b0d605 100644 --- a/include/bolt/editor/keyboard_shortcuts.hpp +++ b/include/bolt/editor/keyboard_shortcuts.hpp @@ -1,23 +1,17 @@ -#ifndef BOLT_KEYBOARD_SHORTCUTS_HPP -#define BOLT_KEYBOARD_SHORTCUTS_HPP +#ifndef BOLT_EDITOR_KEYBOARD_SHORTCUTS_HPP_ +#define BOLT_EDITOR_KEYBOARD_SHORTCUTS_HPP_ -#include -#include -#include #include +#include +#include #include +#include namespace bolt { using ShortcutCallback = std::function; -enum class ShortcutContext { - Global, - Editor, - FileTree, - Search, - Debugging -}; +enum class ShortcutContext { Global, Editor, FileTree, Search, Debugging }; struct KeyCombination { bool ctrl = false; @@ -25,7 +19,7 @@ struct KeyCombination { bool alt = false; bool meta = false; // Command key on Mac, Windows key on PC std::string key; // The main key (e.g., "A", "F1", "Enter", "Escape") - + bool operator<(const KeyCombination& other) const; std::string toString() const; static KeyCombination fromString(const std::string& keyString); @@ -38,85 +32,86 @@ struct ShortcutInfo { std::string description; ShortcutContext context; ShortcutCallback callback; - + bool operator<(const ShortcutInfo& other) const { - if (context != other.context) return context < other.context; - if (keyCombination < other.keyCombination) return true; - if (other.keyCombination < keyCombination) return false; + if (context != other.context) + return context < other.context; + if (keyCombination < other.keyCombination) + return true; + if (other.keyCombination < keyCombination) + return false; return command < other.command; } }; class KeyboardShortcuts { -public: + public: static KeyboardShortcuts& getInstance(); // Core shortcut management - bool registerShortcut(const std::string& keyString, const std::string& command, - ShortcutCallback callback, ShortcutContext context = ShortcutContext::Global, - const std::string& description = ""); - bool registerShortcut(const KeyCombination& keyCombination, const std::string& command, - ShortcutCallback callback, ShortcutContext context = ShortcutContext::Global, - const std::string& description = ""); - bool unregisterShortcut(const std::string& keyString, const std::string& command, - ShortcutContext context = ShortcutContext::Global); + bool registerShortcut(const std::string& keyString, const std::string& command, ShortcutCallback callback, + ShortcutContext context = ShortcutContext::Global, const std::string& description = ""); + bool registerShortcut(const KeyCombination& keyCombination, const std::string& command, ShortcutCallback callback, + ShortcutContext context = ShortcutContext::Global, const std::string& description = ""); + bool unregisterShortcut(const std::string& keyString, const std::string& command, + ShortcutContext context = ShortcutContext::Global); bool unregisterShortcut(const KeyCombination& keyCombination, const std::string& command, - ShortcutContext context = ShortcutContext::Global); - + ShortcutContext context = ShortcutContext::Global); + // Shortcut execution bool executeShortcut(const std::string& keyString, ShortcutContext context = ShortcutContext::Global); bool executeShortcut(const KeyCombination& keyCombination, ShortcutContext context = ShortcutContext::Global); - + // Context management void setActiveContext(ShortcutContext context); ShortcutContext getActiveContext() const; void pushContext(ShortcutContext context); void popContext(); - + // Query and discovery std::vector getShortcutsForContext(ShortcutContext context) const; std::vector getAllShortcuts() const; std::vector findShortcutsByCommand(const std::string& command) const; std::vector findShortcutsByKey(const std::string& keyString) const; bool hasShortcut(const KeyCombination& keyCombination, ShortcutContext context) const; - + // Configuration bool loadShortcutsFromFile(const std::string& filePath); bool saveShortcutsToFile(const std::string& filePath) const; void resetToDefaults(); - + // Help and documentation std::string getHelpText(ShortcutContext context = ShortcutContext::Global) const; - std::string getShortcutDescription(const std::string& keyString, ShortcutContext context = ShortcutContext::Global) const; - + std::string getShortcutDescription(const std::string& keyString, + ShortcutContext context = ShortcutContext::Global) const; + // Enable/disable shortcuts void setEnabled(bool enabled); bool isEnabled() const; - + // Initialize default shortcuts void initDefaultShortcuts(); -private: + private: KeyboardShortcuts() = default; - + std::map shortcuts_; std::vector contextStack_; ShortcutContext activeContext_ = ShortcutContext::Global; bool enabled_ = true; - + // Helper methods void initGlobalShortcuts(); void initEditorShortcuts(); void initFileTreeShortcuts(); void initSearchShortcuts(); void initDebuggingShortcuts(); - - bool isKeyConflict(const KeyCombination& keyCombination, ShortcutContext context, - const std::string& command) const; + + bool isKeyConflict(const KeyCombination& keyCombination, ShortcutContext context, const std::string& command) const; std::string contextToString(ShortcutContext context) const; ShortcutContext stringToContext(const std::string& contextStr) const; }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_KEYBOARD_SHORTCUTS_HPP \ No newline at end of file +#endif // BOLT_EDITOR_KEYBOARD_SHORTCUTS_HPP_ diff --git a/include/bolt/editor/line_numbers.hpp b/include/bolt/editor/line_numbers.hpp index e005904e..55428dd3 100644 --- a/include/bolt/editor/line_numbers.hpp +++ b/include/bolt/editor/line_numbers.hpp @@ -1,29 +1,28 @@ -#ifndef LINE_NUMBERS_HPP -#define LINE_NUMBERS_HPP +#ifndef BOLT_EDITOR_LINE_NUMBERS_HPP_ +#define BOLT_EDITOR_LINE_NUMBERS_HPP_ #include #include + #include "bolt/core/thread_safety.hpp" namespace bolt { class LineNumberManager { -private: + private: ThreadSafe showLineNumbers_{true}; ThreadSafe lineNumberFormat_{"%d"}; ThreadSafe gutterWidth_{4}; -public: + public: static LineNumberManager& getInstance() { static LineNumberManager instance; return instance; } void toggleLineNumbers() { - showLineNumbers_.write([](bool& show) { - show = !show; - }); + showLineNumbers_.write([](bool& show) { show = !show; }); } bool areLineNumbersVisible() const { @@ -31,9 +30,7 @@ class LineNumberManager { } void setGutterWidth(size_t width) { - gutterWidth_.write([width](size_t& w) { - w = width; - }); + gutterWidth_.write([width](size_t& w) { w = width; }); } size_t getGutterWidth() const { @@ -57,6 +54,6 @@ class LineNumberManager { } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_EDITOR_LINE_NUMBERS_HPP_ diff --git a/include/bolt/editor/lsp_client.hpp b/include/bolt/editor/lsp_client.hpp index a59459b6..8ff03d8e 100644 --- a/include/bolt/editor/lsp_client.hpp +++ b/include/bolt/editor/lsp_client.hpp @@ -1,16 +1,19 @@ -#ifndef LSP_CLIENT_HPP -#define LSP_CLIENT_HPP +#ifndef BOLT_EDITOR_LSP_CLIENT_HPP_ +#define BOLT_EDITOR_LSP_CLIENT_HPP_ -#include "bolt/editor/lsp_protocol.hpp" -#include "bolt/editor/lsp_json_rpc.hpp" -#include -#include -#include -#include #include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "bolt/editor/lsp_json_rpc.hpp" +#include "bolt/editor/lsp_protocol.hpp" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN @@ -22,7 +25,7 @@ namespace lsp { // LSP Client Connection Interface class ILspConnection { -public: + public: virtual ~ILspConnection() = default; virtual bool start(const std::string& command, const std::vector& args) = 0; virtual void stop() = 0; @@ -34,12 +37,12 @@ class ILspConnection { // Process-based LSP Connection (stdio) class ProcessLspConnection : public ILspConnection { -private: + private: std::string command_; std::vector args_; std::atomic connected_{false}; std::atomic shouldStop_{false}; - + #ifdef _WIN32 // Windows handles HANDLE processHandle_ = INVALID_HANDLE_VALUE; @@ -52,24 +55,24 @@ class ProcessLspConnection : public ILspConnection { int stdinPipe_ = -1; int stdoutPipe_ = -1; #endif - + std::thread readerThread_; std::queue messageQueue_; mutable std::mutex queueMutex_; std::condition_variable messageAvailable_; - -public: + + public: ProcessLspConnection() = default; ~ProcessLspConnection() override; - + bool start(const std::string& command, const std::vector& args) override; void stop() override; bool isConnected() const override { return connected_.load(); } void sendMessage(const std::string& message) override; std::string receiveMessage() override; bool hasMessage() const override; - -private: + + private: void readerThreadFunc(); bool createProcess(); void terminateProcess(); @@ -90,79 +93,78 @@ struct LspClientConfig { // LSP Client for communicating with external language servers class LspClient { -private: + private: std::unique_ptr connection_; JsonRpcHandler rpcHandler_; LspClientConfig config_; bool initialized_ = false; std::atomic running_{false}; - + std::thread messageProcessor_; std::string nextRequestId_; std::map)>> pendingRequests_; mutable std::mutex requestMutex_; - -public: + + public: explicit LspClient(std::unique_ptr connection); ~LspClient(); - + // Client lifecycle bool connect(const LspClientConfig& config); void disconnect(); bool isConnected() const; bool isInitialized() const { return initialized_; } - + // LSP Operations (async) void initialize(std::function callback = nullptr); void shutdown(std::function callback = nullptr); - + // Document operations void didOpenTextDocument(const TextDocumentItem& document); - void didChangeTextDocument(const VersionedTextDocumentIdentifier& document, - const std::vector& changes); + void didChangeTextDocument(const VersionedTextDocumentIdentifier& document, + const std::vector& changes); void didCloseTextDocument(const TextDocumentIdentifier& document); void didSaveTextDocument(const TextDocumentIdentifier& document); - + // Language features (async with callbacks) - void completion(const TextDocumentPositionParams& params, - std::function callback); - void hover(const TextDocumentPositionParams& params, - std::function&)> callback); - void definition(const TextDocumentPositionParams& params, - std::function&)> callback); - void references(const TextDocumentPositionParams& params, - std::function&)> callback); - void documentSymbol(const TextDocumentIdentifier& document, - std::function&)> callback); + void completion(const TextDocumentPositionParams& params, std::function callback); + void hover(const TextDocumentPositionParams& params, std::function&)> callback); + void definition(const TextDocumentPositionParams& params, + std::function&)> callback); + void references(const TextDocumentPositionParams& params, + std::function&)> callback); + void documentSymbol(const TextDocumentIdentifier& document, + std::function&)> callback); void formatting(const TextDocumentIdentifier& document, const FormattingOptions& options, - std::function&)> callback); - + std::function&)> callback); + // Synchronous versions with timeout CompletionList completionSync(const TextDocumentPositionParams& params, int timeoutMs = 5000); std::optional hoverSync(const TextDocumentPositionParams& params, int timeoutMs = 5000); std::vector definitionSync(const TextDocumentPositionParams& params, int timeoutMs = 5000); std::vector referencesSync(const TextDocumentPositionParams& params, int timeoutMs = 5000); std::vector documentSymbolSync(const TextDocumentIdentifier& document, int timeoutMs = 5000); - std::vector formattingSync(const TextDocumentIdentifier& document, const FormattingOptions& options, int timeoutMs = 5000); - + std::vector formattingSync(const TextDocumentIdentifier& document, const FormattingOptions& options, + int timeoutMs = 5000); + // Configuration const LspClientConfig& getConfig() const { return config_; } - -private: + + private: void messageProcessorFunc(); std::string generateRequestId(); - - void sendRequest(const std::string& method, std::shared_ptr params, - std::function)> callback = nullptr); + + void sendRequest(const std::string& method, std::shared_ptr params, + std::function)> callback = nullptr); void sendNotification(const std::string& method, std::shared_ptr params); - + // JSON conversion helpers (similar to server) std::shared_ptr textDocumentItemToJson(const TextDocumentItem& item); std::shared_ptr textDocumentIdentifierToJson(const TextDocumentIdentifier& identifier); std::shared_ptr versionedTextDocumentIdentifierToJson(const VersionedTextDocumentIdentifier& identifier); std::shared_ptr textDocumentPositionParamsToJson(const TextDocumentPositionParams& params); std::shared_ptr formattingOptionsToJson(const FormattingOptions& options); - + CompletionList jsonToCompletionList(std::shared_ptr json); Hover jsonToHover(std::shared_ptr json); Location jsonToLocation(std::shared_ptr json); @@ -174,49 +176,50 @@ class LspClient { // LSP Client Manager for managing multiple language servers class LspClientManager { -private: + private: std::map> clients_; std::map fileExtensionToLanguage_; std::map languageConfigs_; mutable std::mutex clientsMutex_; - -public: + + public: LspClientManager() = default; ~LspClientManager(); - + // Configuration void registerLanguageServer(const std::string& languageId, const LspClientConfig& config); void unregisterLanguageServer(const std::string& languageId); - + // Client management LspClient* getClientForFile(const std::string& filePath); LspClient* getClientForLanguage(const std::string& languageId); std::vector getRegisteredLanguages() const; - + // Document operations (routes to appropriate client) - void didOpenTextDocument(const std::string& filePath, const std::string& content, const std::string& languageId = ""); + void didOpenTextDocument(const std::string& filePath, const std::string& content, + const std::string& languageId = ""); void didChangeTextDocument(const std::string& filePath, const std::string& content, int version = 1); void didCloseTextDocument(const std::string& filePath); void didSaveTextDocument(const std::string& filePath); - + // Language features (routes to appropriate client) - void completion(const std::string& filePath, size_t line, size_t character, - std::function callback); - void hover(const std::string& filePath, size_t line, size_t character, - std::function&)> callback); - void definition(const std::string& filePath, size_t line, size_t character, - std::function&)> callback); - + void completion(const std::string& filePath, size_t line, size_t character, + std::function callback); + void hover(const std::string& filePath, size_t line, size_t character, + std::function&)> callback); + void definition(const std::string& filePath, size_t line, size_t character, + std::function&)> callback); + // Shutdown all clients void shutdown(); - -private: + + private: std::string getLanguageIdFromFilePath(const std::string& filePath); std::string filePathToUri(const std::string& filePath); LspClient* createClientForLanguage(const std::string& languageId); }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif +#endif // BOLT_EDITOR_LSP_CLIENT_HPP_ diff --git a/include/bolt/editor/lsp_editor_bridge.hpp b/include/bolt/editor/lsp_editor_bridge.hpp index f8f8ebe3..b2760c3e 100644 --- a/include/bolt/editor/lsp_editor_bridge.hpp +++ b/include/bolt/editor/lsp_editor_bridge.hpp @@ -1,7 +1,7 @@ /** * @file lsp_editor_bridge.hpp * @brief Bridge component connecting LSP clients to the ImGui-based code editor - * + * * This component handles: * - Document synchronization between editor and LSP servers * - Code completion requests and response handling @@ -9,21 +9,22 @@ * - Diagnostics collection and display */ -#ifndef BOLT_LSP_EDITOR_BRIDGE_HPP -#define BOLT_LSP_EDITOR_BRIDGE_HPP +#ifndef BOLT_EDITOR_LSP_EDITOR_BRIDGE_HPP_ +#define BOLT_EDITOR_LSP_EDITOR_BRIDGE_HPP_ -#include "bolt/editor/lsp_client.hpp" -#include "bolt/editor/lsp_server_configs.hpp" -#include "bolt/editor/lsp_protocol.hpp" -#include "bolt/editor/code_completion.hpp" -#include -#include -#include -#include -#include #include -#include #include +#include +#include +#include +#include +#include +#include + +#include "bolt/editor/code_completion.hpp" +#include "bolt/editor/lsp_client.hpp" +#include "bolt/editor/lsp_protocol.hpp" +#include "bolt/editor/lsp_server_configs.hpp" namespace bolt { namespace lsp { @@ -154,7 +155,7 @@ struct HoverTooltipState { */ // Forward declaration for config manager class LspServerConfigManager { -public: + public: void autoConfigureServers(); std::map getAllConfigs() const; bool isServerAvailable(const std::string& languageId) const; @@ -162,31 +163,32 @@ class LspServerConfigManager { }; class LspEditorBridge { -public: - using DiagnosticsCallback = std::function& diagnostics)>; - + public: + using DiagnosticsCallback = + std::function& diagnostics)>; + LspEditorBridge(); ~LspEditorBridge(); - + /** * @brief Initialize the bridge with auto-detected language servers * @return true if at least one language server is available */ bool initialize(); - + /** * @brief Shutdown all LSP connections */ void shutdown(); - + /** * @brief Check if LSP is available for a given language * @param languageId The language identifier (e.g., "cpp", "python") */ bool isLanguageSupported(const std::string& languageId) const; - + // Document lifecycle - + /** * @brief Notify LSP that a document was opened * @param filePath Full path to the file @@ -194,7 +196,7 @@ class LspEditorBridge { * @param languageId Language identifier */ void documentOpened(const std::string& filePath, const std::string& content, const std::string& languageId); - + /** * @brief Notify LSP that document content changed * @param filePath Full path to the file @@ -202,15 +204,15 @@ class LspEditorBridge { * @param version Document version number */ void documentChanged(const std::string& filePath, const std::string& content, int version); - + /** * @brief Notify LSP that a document was closed * @param filePath Full path to the file */ void documentClosed(const std::string& filePath); - + // Code completion - + /** * @brief Request code completion at a position * @param filePath Full path to the file @@ -218,34 +220,34 @@ class LspEditorBridge { * @param column Column number (0-indexed) * @param triggerChar Optional trigger character */ - void requestCompletion(const std::string& filePath, size_t line, size_t column, - const std::string& triggerChar = ""); - + void requestCompletion(const std::string& filePath, size_t line, size_t column, + const std::string& triggerChar = ""); + /** * @brief Get current completion popup state */ CompletionPopupState& getCompletionState() { return completionState_; } const CompletionPopupState& getCompletionState() const { return completionState_; } - + /** * @brief Accept the currently selected completion * @return The text to insert */ std::string acceptCompletion(); - + /** * @brief Dismiss the completion popup */ void dismissCompletion(); - + /** * @brief Navigate completion selection */ void selectNextCompletion(); void selectPreviousCompletion(); - + // Hover information - + /** * @brief Request hover information at a position * @param filePath Full path to the file @@ -253,20 +255,20 @@ class LspEditorBridge { * @param column Column number (0-indexed) */ void requestHover(const std::string& filePath, size_t line, size_t column); - + /** * @brief Get current hover tooltip state */ HoverTooltipState& getHoverState() { return hoverState_; } const HoverTooltipState& getHoverState() const { return hoverState_; } - + /** * @brief Dismiss the hover tooltip */ void dismissHover(); - + // Go-to-Definition - + /** * @brief Request definition at a position (Ctrl+Click or F12) * @param filePath Full path to the file @@ -274,26 +276,26 @@ class LspEditorBridge { * @param column Column number (0-indexed) */ void requestDefinition(const std::string& filePath, size_t line, size_t column); - + /** * @brief Get current definition result state */ LocationResultState& getDefinitionState() { return definitionState_; } const LocationResultState& getDefinitionState() const { return definitionState_; } - + /** * @brief Navigate to the selected definition * @return The location to navigate to, or nullopt if none selected */ std::optional acceptDefinition(); - + /** * @brief Dismiss the definition results */ void dismissDefinition(); - + // Find References - + /** * @brief Request all references at a position (Shift+F12) * @param filePath Full path to the file @@ -301,56 +303,56 @@ class LspEditorBridge { * @param column Column number (0-indexed) */ void requestReferences(const std::string& filePath, size_t line, size_t column); - + /** * @brief Get current references result state */ LocationResultState& getReferencesState() { return referencesState_; } const LocationResultState& getReferencesState() const { return referencesState_; } - + /** * @brief Navigate to the selected reference * @return The location to navigate to, or nullopt if none selected */ std::optional acceptReference(); - + /** * @brief Dismiss the references results */ void dismissReferences(); - + // Document Symbols (Outline) - + /** * @brief Request document symbols for outline view (Ctrl+Shift+O) * @param filePath Full path to the file */ void requestDocumentSymbols(const std::string& filePath); - + /** * @brief Get current symbol outline state */ SymbolOutlineState& getSymbolOutlineState() { return symbolOutlineState_; } const SymbolOutlineState& getSymbolOutlineState() const { return symbolOutlineState_; } - + /** * @brief Navigate to the selected symbol * @return The location to navigate to, or nullopt if none selected */ std::optional acceptSymbol(); - + /** * @brief Dismiss the symbol outline */ void dismissSymbolOutline(); - + /** * @brief Filter symbols by name */ void filterSymbols(const std::string& filter); - + // Code Formatting - + /** * @brief Request document formatting (Shift+Alt+F) * @param filePath Full path to the file @@ -358,75 +360,75 @@ class LspEditorBridge { * @param insertSpaces Use spaces instead of tabs */ void requestFormatting(const std::string& filePath, size_t tabSize = 4, bool insertSpaces = true); - + /** * @brief Get pending formatting edits * @return Vector of text edits to apply */ std::vector getFormattingEdits(); - + /** * @brief Check if formatting is pending */ bool hasFormattingPending() const { return formattingPending_.load(); } - + // Diagnostics - + /** * @brief Get diagnostics for a file * @param filePath Full path to the file */ std::vector getDiagnostics(const std::string& filePath) const; - + /** * @brief Set callback for diagnostics updates */ void setDiagnosticsCallback(DiagnosticsCallback callback); - + /** * @brief Get total diagnostic count for a file */ size_t getDiagnosticCount(const std::string& filePath) const; - + /** * @brief Get error count for a file */ size_t getErrorCount(const std::string& filePath) const; - + /** * @brief Get warning count for a file */ size_t getWarningCount(const std::string& filePath) const; - + // Utility - + /** * @brief Convert file path to LSP URI format */ static std::string pathToUri(const std::string& path); - + /** * @brief Convert LSP URI to file path */ static std::string uriToPath(const std::string& uri); - + /** * @brief Detect language ID from file extension */ static std::string detectLanguageId(const std::string& filePath); - + /** * @brief Update the bridge state (call each frame) */ void update(); - -private: + + private: // LSP client manager std::unique_ptr clientManager_; - + // Server configuration manager std::unique_ptr configManager_; - + // Document state tracking struct DocumentState { std::string languageId; @@ -436,44 +438,44 @@ class LspEditorBridge { }; std::map openDocuments_; mutable std::mutex documentsMutex_; - + // Completion state CompletionPopupState completionState_; std::mutex completionMutex_; std::atomic completionPending_{false}; - + // Hover state HoverTooltipState hoverState_; std::mutex hoverMutex_; std::atomic hoverPending_{false}; - + // Definition state LocationResultState definitionState_; std::mutex definitionMutex_; std::atomic definitionPending_{false}; - + // References state LocationResultState referencesState_; std::mutex referencesMutex_; std::atomic referencesPending_{false}; - + // Symbol outline state SymbolOutlineState symbolOutlineState_; std::vector allSymbols_; // Unfiltered symbols std::mutex symbolsMutex_; std::atomic symbolsPending_{false}; - + // Formatting state std::vector formattingEdits_; std::mutex formattingMutex_; std::atomic formattingPending_{false}; - + // Diagnostics callback DiagnosticsCallback diagnosticsCallback_; - + // Initialization state std::atomic initialized_{false}; - + // Internal helpers LspClient* getClientForLanguage(const std::string& languageId); void handleCompletionResponse(std::shared_ptr result); @@ -483,7 +485,7 @@ class LspEditorBridge { EditorDiagnostic convertDiagnostic(std::shared_ptr diagnostic); }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif // BOLT_LSP_EDITOR_BRIDGE_HPP +#endif // BOLT_EDITOR_LSP_EDITOR_BRIDGE_HPP_ diff --git a/include/bolt/editor/lsp_json_rpc.hpp b/include/bolt/editor/lsp_json_rpc.hpp index 7949798c..07a0c8d2 100644 --- a/include/bolt/editor/lsp_json_rpc.hpp +++ b/include/bolt/editor/lsp_json_rpc.hpp @@ -1,11 +1,12 @@ -#ifndef LSP_JSON_RPC_HPP -#define LSP_JSON_RPC_HPP +#ifndef BOLT_EDITOR_LSP_JSON_RPC_HPP_ +#define BOLT_EDITOR_LSP_JSON_RPC_HPP_ -#include +#include +#include #include #include -#include -#include +#include +#include namespace bolt { namespace lsp { @@ -14,11 +15,7 @@ namespace lsp { class JsonValue; // JSON-RPC Message Types -enum class MessageType { - Request, - Response, - Notification -}; +enum class MessageType { Request, Response, Notification }; // JSON-RPC Request struct JsonRpcRequest { @@ -26,9 +23,9 @@ struct JsonRpcRequest { std::string method; std::optional id; std::shared_ptr params; - + JsonRpcRequest() = default; - JsonRpcRequest(const std::string& m, const std::string& reqId = "") + explicit JsonRpcRequest(const std::string& m, const std::string& reqId = "") : method(m), id(reqId.empty() ? std::nullopt : std::optional(reqId)) {} }; @@ -38,9 +35,9 @@ struct JsonRpcResponse { std::string id; std::shared_ptr result; std::shared_ptr error; - + JsonRpcResponse() = default; - JsonRpcResponse(const std::string& reqId) : id(reqId) {} + explicit JsonRpcResponse(const std::string& reqId) : id(reqId) {} }; // JSON-RPC Notification @@ -48,73 +45,85 @@ struct JsonRpcNotification { std::string jsonrpc = "2.0"; std::string method; std::shared_ptr params; - + JsonRpcNotification() = default; - JsonRpcNotification(const std::string& m) : method(m) {} + explicit JsonRpcNotification(const std::string& m) : method(m) {} }; // Simple JSON Value representation (minimal implementation) class JsonValue { -public: - enum Type { - Null, - Bool, - Number, - String, - Array, - Object - }; - -private: + public: + enum Type { Null, Bool, Number, String, Array, Object }; + + private: Type type_; std::string stringValue_; double numberValue_; bool boolValue_; std::vector> arrayValue_; std::map> objectValue_; - -public: + + public: JsonValue() : type_(Null) {} explicit JsonValue(Type type) : type_(type) {} // Explicit type constructor - JsonValue(const std::string& value) : type_(String), stringValue_(value) {} - JsonValue(const char* value) : type_(String), stringValue_(value) {} // Prevent implicit bool conversion - JsonValue(double value) : type_(Number), numberValue_(value) {} - explicit JsonValue(int value) : type_(Number), numberValue_(static_cast(value)) {} // Explicit int constructor - JsonValue(bool value) : type_(Bool), boolValue_(value) {} - + explicit JsonValue(const std::string& value) : type_(String), stringValue_(value) {} + explicit JsonValue(const char* value) : type_(String), stringValue_(value) {} // Prevent implicit bool conversion + explicit JsonValue(double value) : type_(Number), numberValue_(value) {} + explicit JsonValue(int value) + : type_(Number), numberValue_(static_cast(value)) {} // Explicit int constructor + explicit JsonValue(bool value) : type_(Bool), boolValue_(value) {} + Type getType() const { return type_; } - + const std::string& asString() const { return stringValue_; } double asNumber() const { return numberValue_; } bool asBool() const { return boolValue_; } - - void setString(const std::string& value) { type_ = String; stringValue_ = value; } - void setNumber(double value) { type_ = Number; numberValue_ = value; } - void setBool(bool value) { type_ = Bool; boolValue_ = value; } - + + void setString(const std::string& value) { + type_ = String; + stringValue_ = value; + } + void setNumber(double value) { + type_ = Number; + numberValue_ = value; + } + void setBool(bool value) { + type_ = Bool; + boolValue_ = value; + } + // Object operations - void setObject() { type_ = Object; objectValue_.clear(); } + void setObject() { + type_ = Object; + objectValue_.clear(); + } void setProperty(const std::string& key, std::shared_ptr value) { - if (type_ != Object) setObject(); + if (type_ != Object) + setObject(); objectValue_[key] = value; } std::shared_ptr getProperty(const std::string& key) const { - if (type_ != Object) return nullptr; + if (type_ != Object) + return nullptr; auto it = objectValue_.find(key); return it != objectValue_.end() ? it->second : nullptr; } - + // Array operations - void setArray() { type_ = Array; arrayValue_.clear(); } + void setArray() { + type_ = Array; + arrayValue_.clear(); + } void addArrayElement(std::shared_ptr value) { - if (type_ != Array) setArray(); + if (type_ != Array) + setArray(); arrayValue_.push_back(value); } size_t getArraySize() const { return type_ == Array ? arrayValue_.size() : 0; } std::shared_ptr getArrayElement(size_t index) const { return (type_ == Array && index < arrayValue_.size()) ? arrayValue_[index] : nullptr; } - + // Serialization (basic implementation) std::string toString() const; static std::shared_ptr fromString(const std::string& json); @@ -122,39 +131,39 @@ class JsonValue { // JSON-RPC Message Handler class JsonRpcHandler { -public: + public: using RequestHandler = std::function(const std::string&, std::shared_ptr)>; using NotificationHandler = std::function)>; - -private: + + private: std::map requestHandlers_; std::map notificationHandlers_; - -public: + + public: // Register handlers void registerRequestHandler(const std::string& method, RequestHandler handler); void registerNotificationHandler(const std::string& method, NotificationHandler handler); - + // Process incoming messages std::string processMessage(const std::string& message); - + // Send outgoing messages std::string createRequest(const std::string& method, std::shared_ptr params, const std::string& id = ""); std::string createNotification(const std::string& method, std::shared_ptr params); std::string createResponse(const std::string& id, std::shared_ptr result); std::string createErrorResponse(const std::string& id, int code, const std::string& message); - -private: + + private: JsonRpcRequest parseRequest(std::shared_ptr json); JsonRpcResponse parseResponse(std::shared_ptr json); JsonRpcNotification parseNotification(std::shared_ptr json); - + std::shared_ptr createJsonRpcObject(const JsonRpcRequest& request); std::shared_ptr createJsonRpcObject(const JsonRpcResponse& response); std::shared_ptr createJsonRpcObject(const JsonRpcNotification& notification); }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_LSP_JSON_RPC_HPP_ diff --git a/include/bolt/editor/lsp_plugin_adapter.hpp b/include/bolt/editor/lsp_plugin_adapter.hpp index d855625b..b1b728a1 100644 --- a/include/bolt/editor/lsp_plugin_adapter.hpp +++ b/include/bolt/editor/lsp_plugin_adapter.hpp @@ -1,40 +1,46 @@ -#ifndef LSP_PLUGIN_ADAPTER_HPP -#define LSP_PLUGIN_ADAPTER_HPP +#ifndef BOLT_EDITOR_LSP_PLUGIN_ADAPTER_HPP_ +#define BOLT_EDITOR_LSP_PLUGIN_ADAPTER_HPP_ + +#include +#include +#include +#include +#include +#include #include "bolt/core/plugin_interface.hpp" +#include "bolt/editor/integrated_editor.hpp" +#include "bolt/editor/lsp_client.hpp" #include "bolt/editor/lsp_protocol.hpp" #include "bolt/editor/lsp_server.hpp" -#include "bolt/editor/lsp_client.hpp" -#include "bolt/editor/integrated_editor.hpp" -#include -#include namespace bolt { namespace lsp { // Adapter that converts existing ILanguagePlugin to LSP protocol class LanguagePluginLspAdapter { -private: + private: std::shared_ptr plugin_; std::string languageId_; - -public: + + public: LanguagePluginLspAdapter(std::shared_ptr plugin, const std::string& languageId); ~LanguagePluginLspAdapter() = default; - + // Convert plugin methods to LSP types CompletionList getCompletion(const std::string& filePath, const Position& position); std::optional getHover(const std::string& filePath, const Position& position); std::vector getDefinition(const std::string& filePath, const Position& position); std::vector getReferences(const std::string& filePath, const Position& position); std::vector getDiagnostics(const std::string& filePath, const std::string& content); - std::vector formatDocument(const std::string& filePath, const std::string& content, const FormattingOptions& options); - + std::vector formatDocument(const std::string& filePath, const std::string& content, + const FormattingOptions& options); + // Get the underlying plugin std::shared_ptr getPlugin() const { return plugin_; } const std::string& getLanguageId() const { return languageId_; } - -private: + + private: // Helper methods for conversion CompletionItem convertToLspCompletionItem(const std::string& item); Location createLocationFromReferences(const std::string& filePath, const std::pair& ref); @@ -44,17 +50,17 @@ class LanguagePluginLspAdapter { // LSP Integration Plugin that provides LSP support within Bolt's plugin system class LspIntegrationPlugin : public ILanguagePlugin { -private: + private: std::unique_ptr lspServer_; std::unique_ptr clientManager_; std::map> pluginAdapters_; std::map languageIdMapping_; bool enabled_ = true; - -public: + + public: LspIntegrationPlugin(); ~LspIntegrationPlugin() override = default; - + // IPlugin interface PluginMetadata getMetadata() const override { PluginMetadata metadata; @@ -65,53 +71,54 @@ class LspIntegrationPlugin : public ILanguagePlugin { metadata.apiVersion = {1, 0, 0}; return metadata; } - + bool initialize(PluginContext* context) override; void activate() override; void deactivate() override; void cleanup() override; - + PluginState getState() const override { return enabled_ ? PluginState::Active : PluginState::Loaded; } std::unordered_map getConfiguration() const override; bool configure(const std::unordered_map& config) override; - + // IEditorPlugin interface void onDocumentOpened(const std::string& filePath, const std::string& content) override; void onDocumentClosed(const std::string& filePath) override; void onDocumentModified(const std::string& filePath, const std::string& content) override; void onCursorChanged(const std::string& filePath, size_t line, size_t column) override; - + // ILanguagePlugin interface std::vector getCodeCompletions(const std::string& filePath, size_t line, size_t column) override; std::vector getDiagnostics(const std::string& filePath, const std::string& content) override; std::string formatCode(const std::string& code) override; - std::vector> findReferences(const std::string& filePath, size_t line, size_t column) override; + std::vector> findReferences(const std::string& filePath, size_t line, + size_t column) override; std::string getHoverInfo(const std::string& filePath, size_t line, size_t column) override; std::vector getSupportedExtensions() const override; - + // LSP-specific functionality void registerLanguagePlugin(const std::string& languageId, std::shared_ptr plugin); void registerExternalLanguageServer(const std::string& languageId, const LspClientConfig& config); void unregisterLanguagePlugin(const std::string& languageId); void unregisterExternalLanguageServer(const std::string& languageId); - + // LSP server access LanguageServer* getLspServer() const { return lspServer_.get(); } LspClientManager* getClientManager() const { return clientManager_.get(); } - + // Message processing for external LSP clients std::string processLspMessage(const std::string& message); - + // Enable/disable LSP features void setEnabled(bool enabled) { enabled_ = enabled; } bool isEnabled() const { return enabled_; } - -private: + + private: std::string getLanguageIdFromFilePath(const std::string& filePath); std::string getFileExtension(const std::string& filePath); void initializeLspServer(); void initializeClientManager(); - + // Helper conversion methods std::vector convertLspCompletions(const CompletionList& completions); std::vector convertLspDiagnostics(const std::vector& diagnostics); @@ -122,7 +129,7 @@ class LspIntegrationPlugin : public ILanguagePlugin { // Factory function to create LSP Integration Plugin std::shared_ptr createLspIntegrationPlugin(); -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_LSP_PLUGIN_ADAPTER_HPP_ diff --git a/include/bolt/editor/lsp_protocol.hpp b/include/bolt/editor/lsp_protocol.hpp index 93fbe3e6..bfaf4f2c 100644 --- a/include/bolt/editor/lsp_protocol.hpp +++ b/include/bolt/editor/lsp_protocol.hpp @@ -1,11 +1,11 @@ -#ifndef LSP_PROTOCOL_HPP -#define LSP_PROTOCOL_HPP +#ifndef BOLT_EDITOR_LSP_PROTOCOL_HPP_ +#define BOLT_EDITOR_LSP_PROTOCOL_HPP_ -#include -#include #include -#include #include +#include +#include +#include namespace bolt { namespace lsp { @@ -14,15 +14,15 @@ namespace lsp { struct Position { size_t line; size_t character; - - Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} + + explicit Position(size_t l = 0, size_t c = 0) : line(l), character(c) {} }; // LSP Range struct Range { Position start; Position end; - + Range() = default; Range(const Position& s, const Position& e) : start(s), end(e) {} }; @@ -31,7 +31,7 @@ struct Range { struct Location { std::string uri; Range range; - + Location() = default; Location(const std::string& u, const Range& r) : uri(u), range(r) {} }; @@ -40,7 +40,7 @@ struct Location { struct TextEdit { Range range; std::string newText; - + TextEdit() = default; TextEdit(const Range& r, const std::string& text) : range(r), newText(text) {} }; @@ -75,9 +75,9 @@ struct CompletionItem { std::optional documentation; std::optional insertText; std::optional textEdit; - + CompletionItem() = default; - CompletionItem(const std::string& l) : label(l) {} + explicit CompletionItem(const std::string& l) : label(l) {} }; // LSP Completion List @@ -87,12 +87,7 @@ struct CompletionList { }; // LSP Diagnostic Severity -enum class DiagnosticSeverity { - Error = 1, - Warning = 2, - Information = 3, - Hint = 4 -}; +enum class DiagnosticSeverity { Error = 1, Warning = 2, Information = 3, Hint = 4 }; // LSP Diagnostic struct Diagnostic { @@ -101,7 +96,7 @@ struct Diagnostic { std::optional code; std::optional source; std::string message; - + Diagnostic() = default; Diagnostic(const Range& r, const std::string& msg) : range(r), message(msg) {} }; @@ -110,9 +105,9 @@ struct Diagnostic { struct Hover { std::string contents; std::optional range; - + Hover() = default; - Hover(const std::string& c) : contents(c) {} + explicit Hover(const std::string& c) : contents(c) {} }; // LSP Document Symbol Kind @@ -145,9 +140,9 @@ struct DocumentSymbol { Range range; Range selectionRange; std::vector children; - + DocumentSymbol() = default; - DocumentSymbol(const std::string& n, SymbolKind k, const Range& r, const Range& sr) + DocumentSymbol(const std::string& n, SymbolKind k, const Range& r, const Range& sr) : name(n), kind(k), range(r), selectionRange(sr) {} }; @@ -161,15 +156,15 @@ struct FormattingOptions { // LSP Text Document Identifier struct TextDocumentIdentifier { std::string uri; - + TextDocumentIdentifier() = default; - TextDocumentIdentifier(const std::string& u) : uri(u) {} + explicit TextDocumentIdentifier(const std::string& u) : uri(u) {} }; // LSP Versioned Text Document Identifier struct VersionedTextDocumentIdentifier : public TextDocumentIdentifier { int version; - + VersionedTextDocumentIdentifier() : version(0) {} VersionedTextDocumentIdentifier(const std::string& u, int v) : TextDocumentIdentifier(u), version(v) {} }; @@ -180,7 +175,7 @@ struct TextDocumentItem { std::string languageId; int version; std::string text; - + TextDocumentItem() : version(0) {} TextDocumentItem(const std::string& u, const std::string& lang, int v, const std::string& t) : uri(u), languageId(lang), version(v), text(t) {} @@ -191,22 +186,22 @@ struct TextDocumentContentChangeEvent { std::optional range; std::optional rangeLength; std::string text; - + TextDocumentContentChangeEvent() = default; - TextDocumentContentChangeEvent(const std::string& t) : text(t) {} + explicit TextDocumentContentChangeEvent(const std::string& t) : text(t) {} }; // LSP Text Document Position Params struct TextDocumentPositionParams { TextDocumentIdentifier textDocument; Position position; - + TextDocumentPositionParams() = default; TextDocumentPositionParams(const TextDocumentIdentifier& doc, const Position& pos) : textDocument(doc), position(pos) {} }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_LSP_PROTOCOL_HPP_ diff --git a/include/bolt/editor/lsp_server.hpp b/include/bolt/editor/lsp_server.hpp index 5aa08f51..e59aa20d 100644 --- a/include/bolt/editor/lsp_server.hpp +++ b/include/bolt/editor/lsp_server.hpp @@ -1,13 +1,15 @@ -#ifndef LSP_SERVER_HPP -#define LSP_SERVER_HPP +#ifndef BOLT_EDITOR_LSP_SERVER_HPP_ +#define BOLT_EDITOR_LSP_SERVER_HPP_ -#include "bolt/editor/lsp_protocol.hpp" -#include "bolt/editor/lsp_json_rpc.hpp" -#include "bolt/core/plugin_interface.hpp" -#include -#include -#include #include +#include +#include +#include +#include + +#include "bolt/core/plugin_interface.hpp" +#include "bolt/editor/lsp_json_rpc.hpp" +#include "bolt/editor/lsp_protocol.hpp" namespace bolt { namespace lsp { @@ -49,34 +51,34 @@ struct InitializeResult { // LSP Language Server class LanguageServer { -private: + private: JsonRpcHandler rpcHandler_; ServerCapabilities capabilities_; bool initialized_ = false; std::string rootPath_; - + // Document storage std::map documents_; - + // Language plugin registry std::map> languagePlugins_; - -public: + + public: LanguageServer(); ~LanguageServer() = default; - + // Server lifecycle void initialize(const InitializeParams& params); void shutdown(); bool isInitialized() const { return initialized_; } - + // Document management void didOpenTextDocument(const TextDocumentItem& document); - void didChangeTextDocument(const VersionedTextDocumentIdentifier& document, - const std::vector& changes); + void didChangeTextDocument(const VersionedTextDocumentIdentifier& document, + const std::vector& changes); void didCloseTextDocument(const TextDocumentIdentifier& document); void didSaveTextDocument(const TextDocumentIdentifier& document); - + // Language features CompletionList completion(const TextDocumentPositionParams& params); std::optional hover(const TextDocumentPositionParams& params); @@ -85,34 +87,39 @@ class LanguageServer { std::vector documentSymbol(const TextDocumentIdentifier& document); std::vector formatting(const TextDocumentIdentifier& document, const FormattingOptions& options); std::vector diagnostics(const TextDocumentIdentifier& document); - + // Plugin management void registerLanguagePlugin(const std::string& languageId, std::shared_ptr plugin); void unregisterLanguagePlugin(const std::string& languageId); std::shared_ptr getLanguagePlugin(const std::string& uri); - + // Message processing std::string processMessage(const std::string& message); - + // Capabilities const ServerCapabilities& getCapabilities() const { return capabilities_; } void setCapabilities(const ServerCapabilities& caps) { capabilities_ = caps; } - -private: + + private: void setupMessageHandlers(); std::string getLanguageIdFromUri(const std::string& uri); std::string uriToFilePath(const std::string& uri); std::string filePathToUri(const std::string& filePath); - + // JSON-RPC handlers std::shared_ptr handleInitialize(const std::string& method, std::shared_ptr params); - std::shared_ptr handleTextDocumentCompletion(const std::string& method, std::shared_ptr params); + std::shared_ptr handleTextDocumentCompletion(const std::string& method, + std::shared_ptr params); std::shared_ptr handleTextDocumentHover(const std::string& method, std::shared_ptr params); - std::shared_ptr handleTextDocumentDefinition(const std::string& method, std::shared_ptr params); - std::shared_ptr handleTextDocumentReferences(const std::string& method, std::shared_ptr params); - std::shared_ptr handleTextDocumentDocumentSymbol(const std::string& method, std::shared_ptr params); - std::shared_ptr handleTextDocumentFormatting(const std::string& method, std::shared_ptr params); - + std::shared_ptr handleTextDocumentDefinition(const std::string& method, + std::shared_ptr params); + std::shared_ptr handleTextDocumentReferences(const std::string& method, + std::shared_ptr params); + std::shared_ptr handleTextDocumentDocumentSymbol(const std::string& method, + std::shared_ptr params); + std::shared_ptr handleTextDocumentFormatting(const std::string& method, + std::shared_ptr params); + void handleTextDocumentDidOpen(const std::string& method, std::shared_ptr params); void handleTextDocumentDidChange(const std::string& method, std::shared_ptr params); void handleTextDocumentDidClose(const std::string& method, std::shared_ptr params); @@ -120,13 +127,13 @@ class LanguageServer { void handleInitialized(const std::string& method, std::shared_ptr params); void handleShutdown(const std::string& method, std::shared_ptr params); void handleExit(const std::string& method, std::shared_ptr params); - + // JSON conversion helpers Position jsonToPosition(std::shared_ptr json); Range jsonToRange(std::shared_ptr json); TextDocumentIdentifier jsonToTextDocumentIdentifier(std::shared_ptr json); TextDocumentPositionParams jsonToTextDocumentPositionParams(std::shared_ptr json); - + std::shared_ptr positionToJson(const Position& pos); std::shared_ptr rangeToJson(const Range& range); std::shared_ptr completionItemToJson(const CompletionItem& item); @@ -137,7 +144,7 @@ class LanguageServer { std::shared_ptr textEditToJson(const TextEdit& edit); }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_LSP_SERVER_HPP_ diff --git a/include/bolt/editor/lsp_server_configs.hpp b/include/bolt/editor/lsp_server_configs.hpp index 525eafed..8d0b5176 100644 --- a/include/bolt/editor/lsp_server_configs.hpp +++ b/include/bolt/editor/lsp_server_configs.hpp @@ -1,46 +1,45 @@ -#ifndef LSP_SERVER_CONFIGS_HPP -#define LSP_SERVER_CONFIGS_HPP +#ifndef BOLT_EDITOR_LSP_SERVER_CONFIGS_HPP_ +#define BOLT_EDITOR_LSP_SERVER_CONFIGS_HPP_ -#include "bolt/editor/lsp_client.hpp" +#include +#include #include #include -#include -#include + +#include "bolt/editor/lsp_client.hpp" namespace bolt { namespace lsp { /** * @brief Pre-configured language server configurations for common languages. - * + * * This class provides factory methods for creating LspClientConfig objects * for well-known language servers like clangd, pyright, rust-analyzer, etc. */ class LspServerConfigs { -public: + public: /** * @brief Get the configuration for clangd (C/C++ language server). - * + * * @param rootPath The root path of the project. * @param extraArgs Additional command-line arguments for clangd. * @return LspClientConfig configured for clangd. */ - static LspClientConfig clangd(const std::string& rootPath = ".", - const std::vector& extraArgs = {}); + static LspClientConfig clangd(const std::string& rootPath = ".", const std::vector& extraArgs = {}); /** * @brief Get the configuration for pyright (Python language server). - * + * * @param rootPath The root path of the project. * @param extraArgs Additional command-line arguments for pyright. * @return LspClientConfig configured for pyright. */ - static LspClientConfig pyright(const std::string& rootPath = ".", - const std::vector& extraArgs = {}); + static LspClientConfig pyright(const std::string& rootPath = ".", const std::vector& extraArgs = {}); /** * @brief Get the configuration for rust-analyzer (Rust language server). - * + * * @param rootPath The root path of the project. * @param extraArgs Additional command-line arguments for rust-analyzer. * @return LspClientConfig configured for rust-analyzer. @@ -50,7 +49,7 @@ class LspServerConfigs { /** * @brief Get the configuration for typescript-language-server. - * + * * @param rootPath The root path of the project. * @param extraArgs Additional command-line arguments. * @return LspClientConfig configured for TypeScript/JavaScript. @@ -60,24 +59,23 @@ class LspServerConfigs { /** * @brief Get a list of all available pre-configured language servers. - * + * * @return Vector of language IDs that have pre-configured settings. */ static std::vector getAvailableConfigs(); /** * @brief Get configuration by language ID. - * + * * @param languageId The language ID (e.g., "cpp", "python", "rust"). * @param rootPath The root path of the project. * @return LspClientConfig for the specified language, or empty config if not found. */ - static LspClientConfig getConfigForLanguage(const std::string& languageId, - const std::string& rootPath = "."); + static LspClientConfig getConfigForLanguage(const std::string& languageId, const std::string& rootPath = "."); /** * @brief Check if a language server is available on the system. - * + * * @param languageId The language ID to check. * @return true if the language server executable is found. */ @@ -85,7 +83,7 @@ class LspServerConfigs { /** * @brief Get the file extensions supported by a language. - * + * * @param languageId The language ID. * @return Vector of file extensions (e.g., {".cpp", ".hpp", ".c", ".h"}). */ @@ -93,16 +91,16 @@ class LspServerConfigs { /** * @brief Get the language ID for a file based on its extension. - * + * * @param filePath The file path or name. * @return The language ID, or empty string if not recognized. */ static std::string getLanguageIdForFile(const std::string& filePath); -private: + private: // Helper to find executable in PATH static std::string findExecutable(const std::string& name); - + // Extension to language ID mapping static const std::map& getExtensionMap(); }; @@ -111,10 +109,10 @@ class LspServerConfigs { * @brief Auto-configuration helper that detects and configures available language servers. */ class LspAutoConfigurator { -public: + public: /** * @brief Automatically configure all available language servers. - * + * * @param manager The LspClientManager to configure. * @param rootPath The root path of the project. * @return Number of language servers configured. @@ -123,7 +121,7 @@ class LspAutoConfigurator { /** * @brief Configure language servers for a specific project based on detected files. - * + * * @param manager The LspClientManager to configure. * @param projectPath The path to the project directory. * @return Number of language servers configured. @@ -132,13 +130,13 @@ class LspAutoConfigurator { /** * @brief Get a report of available and missing language servers. - * + * * @return A formatted string describing the status of each language server. */ static std::string getAvailabilityReport(); }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif // LSP_SERVER_CONFIGS_HPP +#endif // BOLT_EDITOR_LSP_SERVER_CONFIGS_HPP_ diff --git a/include/bolt/editor/minimap.hpp b/include/bolt/editor/minimap.hpp index 6e101bac..e5bb2cba 100644 --- a/include/bolt/editor/minimap.hpp +++ b/include/bolt/editor/minimap.hpp @@ -1,9 +1,10 @@ -#ifndef MINIMAP_HPP -#define MINIMAP_HPP +#ifndef BOLT_EDITOR_MINIMAP_HPP_ +#define BOLT_EDITOR_MINIMAP_HPP_ +#include #include +#include #include -#include namespace bolt { @@ -16,7 +17,7 @@ class MinimapUI; * Provides a miniaturized view of file content and navigation */ class Minimap { -public: + public: struct MinimapConfig { size_t width = 120; // Width in characters size_t height = 40; // Height in lines @@ -27,13 +28,13 @@ class Minimap { }; struct ViewportInfo { - size_t startLine = 0; // First visible line in main editor - size_t endLine = 0; // Last visible line in main editor - size_t totalLines = 0; // Total lines in document - size_t currentLine = 0; // Current cursor line + size_t startLine = 0; // First visible line in main editor + size_t endLine = 0; // Last visible line in main editor + size_t totalLines = 0; // Total lines in document + size_t currentLine = 0; // Current cursor line }; -private: + private: std::string documentPath_; std::vector documentLines_; MinimapConfig config_; @@ -41,7 +42,7 @@ class Minimap { std::unique_ptr renderer_; bool enabled_ = true; -public: + public: Minimap(); explicit Minimap(const MinimapConfig& config); ~Minimap(); @@ -77,13 +78,13 @@ class Minimap { size_t getVisibleLines() const; double getScrollPercentage() const; -private: + private: void initializeRenderer(); size_t calculateStartLine() const; size_t calculateEndLine() const; size_t calculateLinesPerMinimapLine() const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_MINIMAP_HPP_ diff --git a/include/bolt/editor/minimap_renderer.hpp b/include/bolt/editor/minimap_renderer.hpp index 0d80117e..bf29a236 100644 --- a/include/bolt/editor/minimap_renderer.hpp +++ b/include/bolt/editor/minimap_renderer.hpp @@ -1,5 +1,5 @@ -#ifndef MINIMAP_RENDERER_HPP -#define MINIMAP_RENDERER_HPP +#ifndef BOLT_EDITOR_MINIMAP_RENDERER_HPP_ +#define BOLT_EDITOR_MINIMAP_RENDERER_HPP_ #include #include @@ -11,14 +11,14 @@ namespace bolt { * Converts full document content into miniaturized representation */ class MinimapRenderer { -public: + public: struct RenderConfig { size_t width = 120; size_t height = 40; - char fillChar = '#'; // Character for filled areas - char emptyChar = ' '; // Character for empty areas - char viewportChar = '*'; // Character for viewport indicator - char currentLineChar = '|'; // Character for current line + char fillChar = '#'; // Character for filled areas + char emptyChar = ' '; // Character for empty areas + char viewportChar = '*'; // Character for viewport indicator + char currentLineChar = '|'; // Character for current line }; struct RenderContext { @@ -30,10 +30,10 @@ class MinimapRenderer { size_t viewportEnd; }; -private: + private: RenderConfig config_; -public: + public: MinimapRenderer(); explicit MinimapRenderer(const RenderConfig& config); @@ -50,17 +50,16 @@ class MinimapRenderer { char analyzeLinesRange(const std::vector& lines, size_t start, size_t end) const; // Viewport rendering - std::string addViewportOverlay(const std::string& line, size_t minimapLine, - const RenderContext& context) const; + std::string addViewportOverlay(const std::string& line, size_t minimapLine, const RenderContext& context) const; bool isViewportLine(size_t minimapLine, const RenderContext& context) const; bool isCurrentLine(size_t minimapLine, const RenderContext& context) const; -private: + private: size_t mapDocumentLineToMinimap(size_t documentLine, size_t totalLines, size_t minimapHeight) const; size_t calculateContentDensity(const std::string& line) const; char selectRepresentationChar(size_t density) const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_MINIMAP_RENDERER_HPP_ diff --git a/include/bolt/editor/minimap_ui.hpp b/include/bolt/editor/minimap_ui.hpp index ee1055db..ab8156fa 100644 --- a/include/bolt/editor/minimap_ui.hpp +++ b/include/bolt/editor/minimap_ui.hpp @@ -1,10 +1,12 @@ -#ifndef MINIMAP_UI_HPP -#define MINIMAP_UI_HPP +#ifndef BOLT_EDITOR_MINIMAP_UI_HPP_ +#define BOLT_EDITOR_MINIMAP_UI_HPP_ -#include "minimap.hpp" +#include #include +#include #include -#include + +#include "bolt/editor/minimap.hpp" namespace bolt { @@ -13,7 +15,7 @@ namespace bolt { * Handles user interaction and display integration */ class MinimapUI { -public: + public: using NavigationCallback = std::function; using ClickHandler = std::function; @@ -34,14 +36,14 @@ class MinimapUI { size_t height = 0; }; -private: + private: Minimap& minimap_; UIConfig config_; Position position_; NavigationCallback navigationCallback_; bool visible_ = true; -public: + public: explicit MinimapUI(Minimap& minimap); MinimapUI(Minimap& minimap, const UIConfig& config); @@ -75,13 +77,13 @@ class MinimapUI { size_t getRequiredHeight() const; bool fitsInArea(size_t width, size_t height) const; -private: + private: void navigateToLine(size_t line); bool isInsideMinimap(size_t x, size_t y) const; std::pair translateCoordinates(size_t x, size_t y) const; std::string addBorder(const std::string& content) const; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_MINIMAP_UI_HPP_ diff --git a/include/bolt/editor/split_view_manager.hpp b/include/bolt/editor/split_view_manager.hpp index ecea20e3..9201e2b2 100644 --- a/include/bolt/editor/split_view_manager.hpp +++ b/include/bolt/editor/split_view_manager.hpp @@ -1,13 +1,14 @@ -#ifndef SPLIT_VIEW_MANAGER_HPP -#define SPLIT_VIEW_MANAGER_HPP +#ifndef BOLT_EDITOR_SPLIT_VIEW_MANAGER_HPP_ +#define BOLT_EDITOR_SPLIT_VIEW_MANAGER_HPP_ -#include "bolt/editor/editor_pane.hpp" -#include "bolt/core/thread_safety.hpp" -#include -#include +#include #include +#include #include -#include +#include + +#include "bolt/core/thread_safety.hpp" +#include "bolt/editor/editor_pane.hpp" namespace bolt { @@ -16,18 +17,13 @@ namespace bolt { * Handles creation, management, and layout of multiple editor panes */ class SplitViewManager { -public: + public: enum class SplitDirection { Horizontal, // Split left/right Vertical // Split top/bottom }; - - enum class PaneOperation { - Create, - Close, - Focus, - Resize - }; + + enum class PaneOperation { Create, Close, Focus, Resize }; struct SplitLayout { std::string paneId; @@ -39,21 +35,21 @@ class SplitViewManager { // Callback type for pane operation notifications using PaneOperationCallback = std::function; -private: + private: ThreadSafe>> panes_; ThreadSafe activePaneId_; ThreadSafe> layouts_; ThreadSafe nextPaneId_{1}; ThreadSafe isEnabled_{true}; - + // Callbacks PaneOperationCallback onPaneOperation_; - + // Layout constraints static constexpr int MIN_PANE_WIDTH = 100; static constexpr int MIN_PANE_HEIGHT = 50; -public: + public: static SplitViewManager& getInstance() { static SplitViewManager instance; return instance; @@ -64,7 +60,7 @@ class SplitViewManager { std::string createVerticalSplit(const std::string& sourcePaneId = ""); bool closePane(const std::string& paneId); bool focusPane(const std::string& paneId); - + // Pane management std::string createPane(); EditorPane* getPane(const std::string& paneId); @@ -72,73 +68,71 @@ class SplitViewManager { EditorPane* getActivePane(); const EditorPane* getActivePane() const; std::string getActivePaneId() const; - + // Layout management void setContainerSize(int width, int height); void resizePane(const std::string& paneId, int width, int height); void redistributeLayout(); std::vector getAllPaneIds() const; size_t getPaneCount() const; - + // Document operations across panes void openDocumentInPane(const std::string& paneId, const std::string& filePath); void openDocumentInNewPane(const std::string& filePath, SplitDirection direction = SplitDirection::Horizontal); std::vector getOpenDocuments() const; std::string findPaneWithDocument(const std::string& filePath) const; - + // Split view state bool isEnabled() const; void setEnabled(bool enabled); bool hasSplits() const; void collapseAllSplits(); - + // Navigation std::string getNextPane(const std::string& currentPaneId, bool forward = true) const; bool navigateToNextPane(); bool navigateToPreviousPane(); - + // Callbacks void setOnPaneOperation(PaneOperationCallback callback); - + // Layout persistence (for future use) std::string serializeLayout() const; bool restoreLayout(const std::string& layoutData); - + // Cleanup void clearAllPanes(); -private: + private: SplitViewManager(); ~SplitViewManager() = default; - + // Layout calculations void calculatePanePositions(); void updateLayout(const std::string& modifiedPaneId = ""); - EditorPane::PanePosition calculateSplitPosition( - const EditorPane::PanePosition& sourcePosition, - SplitDirection direction, - float splitRatio = 0.5f - ); - + EditorPane::PanePosition calculateSplitPosition(const EditorPane::PanePosition& sourcePosition, + SplitDirection direction, float splitRatio = 0.5f); + // Internal helpers std::string generatePaneId(); void notifyPaneOperation(PaneOperation op, const std::string& paneId); bool isValidPaneId(const std::string& paneId) const; void removePaneFromLayout(const std::string& paneId); void addPaneToLayout(const std::string& paneId, const EditorPane::PanePosition& position); - + // Layout constraints bool validatePaneSize(int width, int height) const; void enforceSizeConstraints(EditorPane::PanePosition& position) const; - + // Thread safety helpers - template - auto withPanes(Func&& func) const -> decltype(func(std::declval>&>())); - - template + template + auto withPanes(Func&& func) const + -> decltype(func(std::declval>&>())); + + template auto withPanes(Func&& func) -> decltype(func(std::declval>&>())); }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_EDITOR_SPLIT_VIEW_MANAGER_HPP_ diff --git a/include/bolt/editor/syntax_highlighter.hpp b/include/bolt/editor/syntax_highlighter.hpp index 34113797..a1cfddbc 100644 --- a/include/bolt/editor/syntax_highlighter.hpp +++ b/include/bolt/editor/syntax_highlighter.hpp @@ -1,11 +1,13 @@ -#ifndef SYNTAX_HIGHLIGHTER_HPP -#define SYNTAX_HIGHLIGHTER_HPP +#ifndef BOLT_EDITOR_SYNTAX_HIGHLIGHTER_HPP_ +#define BOLT_EDITOR_SYNTAX_HIGHLIGHTER_HPP_ +#include +#include #include +#include #include -#include -#include + #include "bolt/core/thread_safety.hpp" namespace bolt { @@ -17,37 +19,33 @@ struct Token { }; class SyntaxHighlighter { -private: + private: ThreadSafe>>> rules_; bool enabled_ = true; -public: + public: static SyntaxHighlighter& getInstance() { static SyntaxHighlighter instance; return instance; } - void addLanguageRules(const std::string& language, - const std::vector>& patterns) { + void 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; - }); + + rules_.write([&](auto& rulesMap) { rulesMap[language] = compiledRules; }); } void addLanguageRule(const std::string& language, const std::string& pattern, const std::string& tokenType) { - rules_.write([&](auto& rulesMap) { - rulesMap[language].emplace_back(std::regex(pattern), tokenType); - }); + rules_.write([&](auto& rulesMap) { rulesMap[language].emplace_back(std::regex(pattern), tokenType); }); } std::vector highlight(const std::string& code, const std::string& language) { std::vector tokens; - + auto rules = rules_.read([&](const auto& rulesMap) { auto it = rulesMap.find(language); return it != rulesMap.end() ? it->second : std::vector>(); @@ -102,16 +100,16 @@ class SyntaxHighlighter { void loadDefaultRules() { // Load C++ default rules - addLanguageRules("cpp", { - {"\\b(int|void|return|if|else|for|while|class|struct|namespace|using|include|template|typename|const|static|virtual|override|public|private|protected)\\b", "keyword"}, - {"\\d+\\.?\\d*", "number"}, - {"\"[^\"]*\"", "string"}, - {"//.*$", "comment"}, - {"/\\*[\\s\\S]*?\\*/", "comment"} - }); + addLanguageRules("cpp", {{"\\b(int|void|return|if|else|for|while|class|struct|namespace|using|include|template|" + "typename|const|static|virtual|override|public|private|protected)\\b", + "keyword"}, + {"\\d+\\.?\\d*", "number"}, + {"\"[^\"]*\"", "string"}, + {"//.*$", "comment"}, + {"/\\*[\\s\\S]*?\\*/", "comment"}}); } }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_EDITOR_SYNTAX_HIGHLIGHTER_HPP_ diff --git a/include/bolt/editor/tab_bar.hpp b/include/bolt/editor/tab_bar.hpp index abcf23bc..0095f668 100644 --- a/include/bolt/editor/tab_bar.hpp +++ b/include/bolt/editor/tab_bar.hpp @@ -1,11 +1,13 @@ -#ifndef TAB_BAR_HPP -#define TAB_BAR_HPP +#ifndef BOLT_EDITOR_TAB_BAR_HPP_ +#define BOLT_EDITOR_TAB_BAR_HPP_ -#include -#include -#include #include +#include #include +#include +#include +#include + #include "bolt/core/thread_safety.hpp" namespace bolt { @@ -19,188 +21,175 @@ struct EditorTab { bool isDirty; // Has unsaved changes bool isPinned; // Tab is pinned (won't close easily) size_t id; // Unique tab identifier - + EditorTab() : isDirty(false), isPinned(false), id(0) {} - - EditorTab(const std::string& path, size_t tabId) - : filePath(path), isDirty(false), isPinned(false), id(tabId) { + + EditorTab(const std::string& path, size_t tabId) : filePath(path), isDirty(false), isPinned(false), id(tabId) { // Extract filename from path for display size_t lastSlash = path.find_last_of("/\\"); - displayName = (lastSlash != std::string::npos) - ? path.substr(lastSlash + 1) - : path; - } - - bool operator==(const EditorTab& other) const { - return id == other.id; + displayName = (lastSlash != std::string::npos) ? path.substr(lastSlash + 1) : path; } + + bool operator==(const EditorTab& other) const { return id == other.id; } }; /** * @brief Manages a collection of editor tabs - * + * * The TabBar manages the list of open file tabs, handles tab switching, * closing, reordering, and provides callbacks for tab-related events. */ class TabBar { -private: + private: ThreadSafe> tabs_; ThreadSafe> activeTabId_; size_t nextTabId_ = 1; - + // Callbacks std::function onTabActivated_; std::function onTabClosed_; std::function onTabAdded_; std::function onTabDirtyChanged_; -public: + public: /** * @brief Add a new tab for a file * @param filePath Path to the file * @return ID of the created tab, or existing tab ID if file already open */ size_t addTab(const std::string& filePath); - + /** * @brief Close a tab by ID * @param tabId ID of the tab to close * @return true if tab was closed, false if not found or pinned */ bool closeTab(size_t tabId); - + /** * @brief Close a tab by file path * @param filePath Path to the file whose tab to close * @return true if tab was closed, false if not found or pinned */ bool closeTabByPath(const std::string& filePath); - + /** * @brief Close all tabs except the specified one * @param exceptTabId ID of tab to keep open */ void closeOtherTabs(size_t exceptTabId); - + /** * @brief Close all tabs (except pinned ones) */ void closeAllTabs(); - + /** * @brief Switch to a specific tab * @param tabId ID of the tab to activate * @return true if tab was activated, false if not found */ bool activateTab(size_t tabId); - + /** * @brief Switch to tab by file path * @param filePath Path to the file whose tab to activate * @return true if tab was activated, false if not found */ bool activateTabByPath(const std::string& filePath); - + /** * @brief Switch to next tab (right) */ void activateNextTab(); - + /** * @brief Switch to previous tab (left) */ void activatePreviousTab(); - + /** * @brief Get the currently active tab * @return Copy of active tab, or nullopt if no tabs */ std::optional getActiveTab() const; - + /** * @brief Get tab by ID * @param tabId ID of the tab * @return Copy of tab, or nullopt if not found */ std::optional getTab(size_t tabId) const; - + /** * @brief Get tab by file path * @param filePath Path to the file * @return Copy of tab, or nullopt if not found */ std::optional getTabByPath(const std::string& filePath) const; - + /** * @brief Get all tabs * @return Vector of all tabs */ std::vector getAllTabs() const; - + /** * @brief Get count of open tabs * @return Number of tabs */ size_t getTabCount() const; - + /** * @brief Check if there are any tabs open * @return true if at least one tab exists */ bool hasTabs() const; - + /** * @brief Mark a tab as dirty (has unsaved changes) * @param tabId ID of the tab * @param isDirty true if tab has unsaved changes */ void setTabDirty(size_t tabId, bool isDirty); - + /** * @brief Mark a tab as dirty by file path * @param filePath Path to the file * @param isDirty true if tab has unsaved changes */ void setTabDirtyByPath(const std::string& filePath, bool isDirty); - + /** * @brief Pin/unpin a tab * @param tabId ID of the tab * @param isPinned true to pin the tab */ void setTabPinned(size_t tabId, bool isPinned); - + /** * @brief Reorder tabs by moving a tab to a new position * @param tabId ID of the tab to move * @param newIndex New position (0-based index) */ void moveTab(size_t tabId, size_t newIndex); - + /** * @brief Find tab ID by file path * @param filePath Path to the file * @return Tab ID if found, 0 if not found */ size_t findTabIdByPath(const std::string& filePath) const; - + // Callback setters - void setOnTabActivated(std::function callback) { - onTabActivated_ = std::move(callback); - } - - void setOnTabClosed(std::function callback) { - onTabClosed_ = std::move(callback); - } - - void setOnTabAdded(std::function callback) { - onTabAdded_ = std::move(callback); - } - - void setOnTabDirtyChanged(std::function callback) { - onTabDirtyChanged_ = std::move(callback); - } - + void setOnTabActivated(std::function callback) { onTabActivated_ = std::move(callback); } + + void setOnTabClosed(std::function callback) { onTabClosed_ = std::move(callback); } + + void setOnTabAdded(std::function callback) { onTabAdded_ = std::move(callback); } + + void setOnTabDirtyChanged(std::function callback) { onTabDirtyChanged_ = std::move(callback); } + /** * @brief Singleton instance */ @@ -209,14 +198,14 @@ class TabBar { return instance; } -private: + private: TabBar() = default; - + // Helper to find tab index by ID std::optional findTabIndexById(size_t tabId) const; std::optional findTabIndexByPath(const std::string& filePath) const; }; -} // namespace bolt +} // namespace bolt -#endif // TAB_BAR_HPP +#endif // BOLT_EDITOR_TAB_BAR_HPP_ diff --git a/include/bolt/editor/theme_system.hpp b/include/bolt/editor/theme_system.hpp index c512cd61..6105dece 100644 --- a/include/bolt/editor/theme_system.hpp +++ b/include/bolt/editor/theme_system.hpp @@ -1,5 +1,5 @@ -#ifndef BOLT_THEME_SYSTEM_HPP -#define BOLT_THEME_SYSTEM_HPP +#ifndef BOLT_EDITOR_THEME_SYSTEM_HPP_ +#define BOLT_EDITOR_THEME_SYSTEM_HPP_ #include #include @@ -32,7 +32,7 @@ struct Theme { }; class ThemeSystem { -public: + public: static ThemeSystem& getInstance(); void setTheme(const std::string& themeName); @@ -40,17 +40,15 @@ class ThemeSystem { ColorScheme getCurrentColors() const; FontSettings getCurrentFontSettings() const; void loadDefaultThemes(); - + // Additional functionality std::vector getAvailableThemes() const; std::string getCurrentThemeName() const; bool hasTheme(const std::string& themeName) const; -private: - ThemeSystem() { - initializeDefaults(); - } - + private: + ThemeSystem() { initializeDefaults(); } + void initializeDefaults(); std::map themes_; std::string currentTheme_; @@ -58,6 +56,6 @@ class ThemeSystem { FontSettings defaultFontSettings_; }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_THEME_SYSTEM_HPP \ No newline at end of file +#endif // BOLT_EDITOR_THEME_SYSTEM_HPP_ diff --git a/include/bolt/git/git.hpp b/include/bolt/git/git.hpp index bb953c0f..9509d86a 100644 --- a/include/bolt/git/git.hpp +++ b/include/bolt/git/git.hpp @@ -1,9 +1,9 @@ -#ifndef GIT_HPP -#define GIT_HPP +#ifndef BOLT_GIT_GIT_HPP_ +#define BOLT_GIT_GIT_HPP_ /** * Git integration module for Bolt C++ IDE - * + * * This module provides comprehensive Git integration including: * - Repository status monitoring * - Basic Git operations (add, commit, push, pull) @@ -12,8 +12,10 @@ * - Integration with editor components */ -#include "git_repository.hpp" -#include "git_integration.hpp" +#include + +#include "bolt/git/git_integration.hpp" +#include "bolt/git/git_repository.hpp" namespace bolt { namespace git { @@ -70,9 +72,9 @@ inline std::optional status(const std::string& filePath) { return GitIntegration::getInstance().getFileStatus(filePath); } -} // namespace quick +} // namespace quick -} // namespace git -} // namespace bolt +} // namespace git +} // namespace bolt -#endif // GIT_HPP \ No newline at end of file +#endif // BOLT_GIT_GIT_HPP_ diff --git a/include/bolt/git/git_integration.hpp b/include/bolt/git/git_integration.hpp index edeb967e..d61fed40 100644 --- a/include/bolt/git/git_integration.hpp +++ b/include/bolt/git/git_integration.hpp @@ -1,13 +1,16 @@ -#ifndef GIT_INTEGRATION_HPP -#define GIT_INTEGRATION_HPP +#ifndef BOLT_GIT_GIT_INTEGRATION_HPP_ +#define BOLT_GIT_GIT_INTEGRATION_HPP_ -#include "git_repository.hpp" -#include -#include -#include -#include #include +#include +#include #include +#include +#include +#include +#include + +#include "bolt/git/git_repository.hpp" namespace bolt { namespace git { @@ -17,67 +20,67 @@ namespace git { * Provides high-level Git integration with editor components */ class GitIntegration { -public: + public: /** * Get the singleton instance */ static GitIntegration& getInstance(); - + /** * Initialize Git integration for a project directory */ bool initialize(const std::string& projectPath); - + /** * Shutdown Git integration */ void shutdown(); - + /** * Check if Git integration is active */ bool isActive() const; - + /** * Get the Git repository instance */ std::shared_ptr getRepository() const; - + /** * Refresh Git status (async) */ void refreshStatus(); - + /** * Get cached Git status for a file */ std::optional getFileStatus(const std::string& filePath) const; - + /** * Get all files with their Git status */ std::vector getAllFileStatus() const; - + /** * Register callback for Git status updates */ void setStatusUpdateCallback(std::function&)> callback); - + /** * Register callback for Git operation results */ void setOperationCallback(std::function callback); - + /** * Enable/disable automatic status refresh */ void setAutoRefresh(bool enabled, int intervalSeconds = 5); - + /** * File change notification (call when files are modified) */ void notifyFileChanged(const std::string& filePath); - + /** * Quick Git operations */ @@ -86,7 +89,7 @@ class GitIntegration { bool commitChanges(const std::string& message); bool pushChanges(); bool pullChanges(); - + /** * Get current branch information */ @@ -98,7 +101,7 @@ class GitIntegration { bool hasRemote; }; BranchStatus getBranchStatus() const; - + /** * Get repository summary */ @@ -112,56 +115,56 @@ class GitIntegration { }; RepositoryInfo getRepositoryInfo() const; -private: + private: GitIntegration() = default; ~GitIntegration() = default; - + // Non-copyable GitIntegration(const GitIntegration&) = delete; GitIntegration& operator=(const GitIntegration&) = delete; - + std::shared_ptr repository_; std::string projectPath_; std::atomic isActive_{false}; std::atomic autoRefreshEnabled_{false}; std::atomic refreshIntervalSeconds_{5}; - + // Cached status mutable std::mutex statusMutex_; std::unordered_map fileStatusCache_; std::vector allFileStatus_; BranchStatus cachedBranchStatus_; - + // Callbacks std::function&)> statusUpdateCallback_; std::function operationCallback_; - + // Background refresh std::unique_ptr refreshThread_; std::atomic shouldStopRefresh_{false}; - + /** * Background refresh loop */ void refreshLoop(); - + /** * Update internal status cache */ void updateStatusCache(); - + /** * Update branch status cache */ void updateBranchStatusCache(); - + /** * Notify callbacks of status update */ void notifyStatusUpdate(); }; -} // namespace git -} // namespace bolt +} // namespace git +} // namespace bolt -#endif // GIT_INTEGRATION_HPP \ No newline at end of file +#endif // BOLT_GIT_GIT_INTEGRATION_HPP_ diff --git a/include/bolt/git/git_repository.hpp b/include/bolt/git/git_repository.hpp index f2541bb5..8c1d1895 100644 --- a/include/bolt/git/git_repository.hpp +++ b/include/bolt/git/git_repository.hpp @@ -1,12 +1,13 @@ -#ifndef GIT_REPOSITORY_HPP -#define GIT_REPOSITORY_HPP +#ifndef BOLT_GIT_GIT_REPOSITORY_HPP_ +#define BOLT_GIT_GIT_REPOSITORY_HPP_ -#include -#include +#include #include #include #include -#include +#include +#include +#include namespace bolt { namespace git { @@ -14,16 +15,7 @@ namespace git { /** * Git file status enumeration */ -enum class GitFileStatus { - UNTRACKED, - MODIFIED, - STAGED, - DELETED, - RENAMED, - COPIED, - IGNORED, - CLEAN -}; +enum class GitFileStatus { UNTRACKED, MODIFIED, STAGED, DELETED, RENAMED, COPIED, IGNORED, CLEAN }; /** * Information about a file's Git status @@ -32,10 +24,9 @@ struct GitFileInfo { std::string filePath; GitFileStatus status; std::string originalPath; // For renames - - GitFileInfo(const std::string& path, GitFileStatus stat) - : filePath(path), status(stat) {} - + + GitFileInfo(const std::string& path, GitFileStatus stat) : filePath(path), status(stat) {} + GitFileInfo(const std::string& path, GitFileStatus stat, const std::string& orig) : filePath(path), status(stat), originalPath(orig) {} }; @@ -48,8 +39,8 @@ struct GitBranchInfo { bool isCurrent; bool isRemote; std::string tracking; // Tracking branch name if any - - GitBranchInfo(const std::string& branchName, bool current = false) + + explicit GitBranchInfo(const std::string& branchName, bool current = false) : name(branchName), isCurrent(current), isRemote(false) {} }; @@ -58,82 +49,82 @@ struct GitBranchInfo { * Provides interface to Git operations for the IDE */ class GitRepository { -public: + public: /** * Create a Git repository manager for the given path */ explicit GitRepository(const std::string& repositoryPath); - + /** * Check if the current directory is a Git repository */ bool isGitRepository() const; - + /** * Get the root path of the Git repository */ std::string getRepositoryRoot() const; - + /** * Get current branch name */ std::optional getCurrentBranch() const; - + /** * Get all branches */ std::vector getBranches() const; - + /** * Get status of all files in the repository */ std::vector getFileStatus() const; - + /** * Get status of a specific file */ std::optional getFileStatus(const std::string& filePath) const; - + /** * Stage a file for commit */ bool addFile(const std::string& filePath); - + /** * Stage all changes */ bool addAll(); - + /** * Commit staged changes */ bool commit(const std::string& message); - + /** * Push to remote repository */ bool push(const std::string& remote = "origin", const std::string& branch = ""); - + /** * Pull from remote repository */ bool pull(const std::string& remote = "origin", const std::string& branch = ""); - + /** * Get the diff for a file */ std::string getFileDiff(const std::string& filePath) const; - + /** * Get recent commit log */ std::vector getCommitLog(int limit = 10) const; - + /** * Check if there are uncommitted changes */ bool hasUncommittedChanges() const; - + /** * Check if repository is ahead/behind remote */ @@ -143,44 +134,44 @@ class GitRepository { bool hasRemote = false; }; RemoteStatus getRemoteStatus() const; - + /** * Set callback for Git operation results */ void setStatusCallback(std::function callback); - -private: + + private: std::string repositoryPath_; mutable std::string cachedRepositoryRoot_; std::function statusCallback_; - + /** * Execute a Git command and return output */ std::pair executeGitCommand(const std::vector& args) const; - + /** * Parse Git status porcelain output */ std::vector parseStatusOutput(const std::string& output) const; - + /** * Parse Git branch output */ std::vector parseBranchOutput(const std::string& output) const; - + /** * Get relative path from repository root */ std::string getRelativePath(const std::string& absolutePath) const; - + /** * Find repository root by walking up directories */ std::string findRepositoryRoot() const; }; -} // namespace git -} // namespace bolt +} // namespace git +} // namespace bolt -#endif // GIT_REPOSITORY_HPP \ No newline at end of file +#endif // BOLT_GIT_GIT_REPOSITORY_HPP_ diff --git a/include/bolt/gui/bolt_gui_app.hpp b/include/bolt/gui/bolt_gui_app.hpp index 2459a7ff..0ded3771 100644 --- a/include/bolt/gui/bolt_gui_app.hpp +++ b/include/bolt/gui/bolt_gui_app.hpp @@ -1,20 +1,24 @@ #pragma once #ifdef BOLT_HAVE_IMGUI +#include #include #include #include -#include #endif -#include -#include #include #include +#include #include +#include // Forward declaration -namespace bolt { namespace ai { class EnhancedAIManager; } } +namespace bolt { +namespace ai { +class EnhancedAIManager; +} +} // namespace bolt namespace bolt { namespace gui { @@ -25,32 +29,32 @@ struct ChatMessage { std::string author; std::string content; bool is_user; - - ChatMessage(const std::string& auth, const std::string& msg, bool user) + + ChatMessage(const std::string& auth, const std::string& msg, bool user) : author(auth), content(msg), is_user(user) {} }; class BoltGuiApp { -public: + public: BoltGuiApp(); ~BoltGuiApp(); - + bool Initialize(); void Run(); void Shutdown(); - -private: + + private: // Window management GLFWwindow* window_; int window_width_ = 1400; int window_height_ = 900; - + // AI Management std::unique_ptr ai_manager_; bool ai_ready_ = false; std::mutex chat_mutex_; std::vector pending_messages_; - + // UI State char chat_input_buffer_[1024] = ""; char code_buffer_[8192] = "// Welcome to Bolt AI IDE!\n// Start typing your code here...\n\n"; @@ -68,23 +72,18 @@ class BoltGuiApp { bool show_theme_settings_ = false; bool show_console_window_ = false; bool show_about_window_ = false; - + // Theme Management - enum class ThemeMode { - Dark, - Light, - HighContrast, - Custom - }; + enum class ThemeMode { Dark, Light, HighContrast, Custom }; ThemeMode current_theme_ = ThemeMode::Dark; - + // UI Colors and Style void SetupCustomStyle(); void ApplyDarkTheme(); void ApplyLightTheme(); void ApplyHighContrastTheme(); void SetTheme(ThemeMode theme); - + // UI Panels void RenderMainMenuBar(); void RenderFileTree(); @@ -96,7 +95,7 @@ class BoltGuiApp { void RenderThemeSettingsWindow(); void RenderConsoleWindow(); void RenderAboutWindow(); - + // Chat functionality void ProcessChatInput(); void AddChatMessage(const std::string& author, const std::string& message, bool is_user); @@ -104,19 +103,19 @@ class BoltGuiApp { std::string GenerateAiResponse(const std::string& input); std::string GenerateFallbackResponse(const std::string& input); void ProcessPendingMessages(); - + // File operations void InitializeFileTree(); void OnFileSelected(int index); void OpenFileDialog(); void SaveCurrentFile(); void SaveFileAsDialog(); - + // Keyboard shortcuts void HandleKeyboardShortcuts(); }; -#endif // BOLT_HAVE_IMGUI +#endif // BOLT_HAVE_IMGUI -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt diff --git a/include/bolt/gui/dark_theme.hpp b/include/bolt/gui/dark_theme.hpp index 40273d32..a3192c94 100644 --- a/include/bolt/gui/dark_theme.hpp +++ b/include/bolt/gui/dark_theme.hpp @@ -1,5 +1,5 @@ -#ifndef BOLT_GUI_DARK_THEME_HPP -#define BOLT_GUI_DARK_THEME_HPP +#ifndef BOLT_GUI_DARK_THEME_HPP_ +#define BOLT_GUI_DARK_THEME_HPP_ namespace bolt { namespace gui { @@ -72,7 +72,7 @@ void ApplyBoltFileTreeTheme(); */ void ApplyBoltSettingsTheme(); -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt -#endif // BOLT_GUI_DARK_THEME_HPP +#endif // BOLT_GUI_DARK_THEME_HPP_ diff --git a/include/bolt/gui/lsp_ui_components.hpp b/include/bolt/gui/lsp_ui_components.hpp index b4cd95ae..643f66ea 100644 --- a/include/bolt/gui/lsp_ui_components.hpp +++ b/include/bolt/gui/lsp_ui_components.hpp @@ -3,12 +3,14 @@ * @brief ImGui UI components for LSP features (completion, hover, diagnostics) */ -#ifndef BOLT_LSP_UI_COMPONENTS_HPP -#define BOLT_LSP_UI_COMPONENTS_HPP +#ifndef BOLT_GUI_LSP_UI_COMPONENTS_HPP_ +#define BOLT_GUI_LSP_UI_COMPONENTS_HPP_ -#include "bolt/editor/lsp_editor_bridge.hpp" -#include #include +#include +#include + +#include "bolt/editor/lsp_editor_bridge.hpp" // Forward declare ImGui types to avoid header dependency struct ImVec2; @@ -21,12 +23,12 @@ namespace gui { * @brief UI component for rendering LSP code completion popup */ class LspCompletionPopup { -public: + public: using AcceptCallback = std::function; - + LspCompletionPopup(); ~LspCompletionPopup(); - + /** * @brief Render the completion popup * @param state Current completion state from LspEditorBridge @@ -35,29 +37,29 @@ class LspCompletionPopup { * @param lineHeight Height of a line in the editor */ void render(lsp::CompletionPopupState& state, float editorPosX, float editorPosY, float lineHeight); - + /** * @brief Set callback for when a completion is accepted */ void setAcceptCallback(AcceptCallback callback) { acceptCallback_ = callback; } - + /** * @brief Handle keyboard input for the popup * @return true if input was handled */ bool handleInput(lsp::CompletionPopupState& state); - + /** * @brief Get the icon for a completion kind */ static const char* getKindIcon(const std::string& kind); - + /** * @brief Get the color for a completion kind */ static void getKindColor(const std::string& kind, float& r, float& g, float& b); - -private: + + private: AcceptCallback acceptCallback_; int maxVisibleItems_ = 10; float popupWidth_ = 400.0f; @@ -68,10 +70,10 @@ class LspCompletionPopup { * @brief UI component for rendering LSP hover tooltip */ class LspHoverTooltip { -public: + public: LspHoverTooltip(); ~LspHoverTooltip(); - + /** * @brief Render the hover tooltip * @param state Current hover state from LspEditorBridge @@ -79,13 +81,13 @@ class LspHoverTooltip { * @param mouseY Current mouse Y position */ void render(const lsp::HoverTooltipState& state, float mouseX, float mouseY); - + /** * @brief Set maximum width for the tooltip */ void setMaxWidth(float width) { maxWidth_ = width; } - -private: + + private: float maxWidth_ = 500.0f; float padding_ = 8.0f; }; @@ -94,10 +96,10 @@ class LspHoverTooltip { * @brief UI component for rendering LSP diagnostics in the editor gutter */ class LspDiagnosticsGutter { -public: + public: LspDiagnosticsGutter(); ~LspDiagnosticsGutter(); - + /** * @brief Render diagnostic markers in the gutter * @param diagnostics List of diagnostics for the current file @@ -107,10 +109,9 @@ class LspDiagnosticsGutter { * @param lineHeight Height of each line * @param scrollY Current scroll position */ - void render(const std::vector& diagnostics, - float gutterX, size_t firstVisibleLine, size_t lastVisibleLine, - float lineHeight, float scrollY); - + void render(const std::vector& diagnostics, float gutterX, size_t firstVisibleLine, + size_t lastVisibleLine, float lineHeight, float scrollY); + /** * @brief Render diagnostic tooltip when hovering over a marker * @param diagnostic The diagnostic to show @@ -118,23 +119,23 @@ class LspDiagnosticsGutter { * @param mouseY Mouse Y position */ void renderDiagnosticTooltip(const lsp::EditorDiagnostic& diagnostic, float mouseX, float mouseY); - + /** * @brief Get icon for diagnostic severity */ static const char* getSeverityIcon(lsp::DiagnosticSeverity severity); - + /** * @brief Get color for diagnostic severity */ static void getSeverityColor(lsp::DiagnosticSeverity severity, float& r, float& g, float& b); - + /** * @brief Set gutter width */ void setGutterWidth(float width) { gutterWidth_ = width; } - -private: + + private: float gutterWidth_ = 20.0f; }; @@ -142,10 +143,10 @@ class LspDiagnosticsGutter { * @brief UI component for rendering inline diagnostics (squiggly underlines) */ class LspInlineDiagnostics { -public: + public: LspInlineDiagnostics(); ~LspInlineDiagnostics(); - + /** * @brief Render inline diagnostic decorations (underlines) * @param diagnostics List of diagnostics for the current file @@ -156,35 +157,33 @@ class LspInlineDiagnostics { * @param charWidth Width of each character (monospace) * @param scrollY Current scroll position */ - void render(const std::vector& diagnostics, - float editorX, float editorY, size_t firstVisibleLine, - float lineHeight, float charWidth, float scrollY); - -private: - void drawSquigglyLine(float x1, float y, float x2, float amplitude, - float r, float g, float b, float a); + void render(const std::vector& diagnostics, float editorX, float editorY, + size_t firstVisibleLine, float lineHeight, float charWidth, float scrollY); + + private: + void drawSquigglyLine(float x1, float y, float x2, float amplitude, float r, float g, float b, float a); }; /** * @brief Status bar component showing LSP status and diagnostic summary */ class LspStatusBar { -public: + public: LspStatusBar(); ~LspStatusBar(); - + /** * @brief Render the LSP status section in the status bar * @param bridge The LSP editor bridge * @param currentFile Currently open file path */ void render(const lsp::LspEditorBridge& bridge, const std::string& currentFile); - -private: + + private: float sectionWidth_ = 200.0f; }; -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt -#endif // BOLT_LSP_UI_COMPONENTS_HPP +#endif // BOLT_GUI_LSP_UI_COMPONENTS_HPP_ diff --git a/include/bolt/gui/widget_framework.hpp b/include/bolt/gui/widget_framework.hpp index c76cb7e1..a30ac74f 100644 --- a/include/bolt/gui/widget_framework.hpp +++ b/include/bolt/gui/widget_framework.hpp @@ -1,13 +1,13 @@ #pragma once -#include -#include -#include -#include -#include #include +#include +#include #include +#include #include +#include +#include #ifdef BOLT_HAVE_IMGUI #include @@ -42,17 +42,17 @@ class WidgetEvent; struct Size { float width = 0.0f; float height = 0.0f; - + Size() = default; Size(float w, float h) : width(w), height(h) {} - + bool isValid() const { return width >= 0.0f && height >= 0.0f; } }; struct Position { float x = 0.0f; float y = 0.0f; - + Position() = default; Position(float x_pos, float y_pos) : x(x_pos), y(y_pos) {} }; @@ -60,15 +60,13 @@ struct Position { struct Rect { Position position; Size size; - + Rect() = default; Rect(const Position& pos, const Size& sz) : position(pos), size(sz) {} Rect(float x, float y, float w, float h) : position(x, y), size(w, h) {} - + bool contains(const Position& point) const { - return point.x >= position.x && - point.x <= position.x + size.width && - point.y >= position.y && + return point.x >= position.x && point.x <= position.x + size.width && point.y >= position.y && point.y <= position.y + size.height; } }; @@ -83,20 +81,20 @@ struct WidgetStyle { std::optional textColor; std::optional hoverColor; std::optional activeColor; - + // Dimensions std::optional borderWidth; std::optional cornerRadius; std::optional padding; std::optional margin; - + // Typography std::optional fontSize; std::optional fontFamily; - + // Animation std::optional animationDuration; - + void merge(const WidgetStyle& other); void applyToImGui() const; void restoreImGui() const; @@ -123,21 +121,20 @@ enum class WidgetEventType { }; class WidgetEvent { -public: + public: WidgetEventType type; Widget* source; std::unordered_map data; bool handled = false; - - WidgetEvent(WidgetEventType eventType, Widget* src) - : type(eventType), source(src) {} - - template + + WidgetEvent(WidgetEventType eventType, Widget* src) : type(eventType), source(src) {} + + template void setData(const std::string& key, const T& value) { data[key] = value; } - - template + + template T getData(const std::string& key, const T& defaultValue = T{}) const { auto it = data.find(key); if (it != data.end()) { @@ -156,25 +153,18 @@ using WidgetEventHandler = std::function; /** * Layout management */ -enum class LayoutType { - None, - Vertical, - Horizontal, - Grid, - Absolute, - Flex -}; +enum class LayoutType { None, Vertical, Horizontal, Grid, Absolute, Flex }; struct LayoutParameters { LayoutType type = LayoutType::None; float spacing = 0.0f; - ImVec2 alignment = ImVec2(0.0f, 0.0f); // 0.0 = left/top, 1.0 = right/bottom + ImVec2 alignment = ImVec2(0.0f, 0.0f); // 0.0 = left/top, 1.0 = right/bottom bool fillAvailableSpace = false; - + // Grid-specific int columns = 1; int rows = 1; - + // Flex-specific float flexGrow = 0.0f; float flexShrink = 1.0f; @@ -184,76 +174,76 @@ struct LayoutParameters { * Core widget base class */ class Widget { -public: - Widget(const std::string& id = ""); + public: + explicit Widget(const std::string& id = ""); virtual ~Widget() = default; - + // Identity and hierarchy const std::string& getId() const { return id_; } void setId(const std::string& id) { id_ = id; } - + Widget* getParent() const { return parent_; } void setParent(Widget* parent) { parent_ = parent; } - + const std::vector>& getChildren() const { return children_; } void addChild(std::shared_ptr child); void removeChild(std::shared_ptr child); void removeChild(const std::string& childId); void clearChildren(); - + // Visibility and state bool isVisible() const { return visible_; } void setVisible(bool visible) { visible_ = visible; } void show() { setVisible(true); } void hide() { setVisible(false); } - + bool isEnabled() const { return enabled_; } void setEnabled(bool enabled) { enabled_ = enabled; } void enable() { setEnabled(true); } void disable() { setEnabled(false); } - + bool isFocused() const { return focused_; } void setFocused(bool focused) { focused_ = focused; } - + // Geometry const Rect& getBounds() const { return bounds_; } void setBounds(const Rect& bounds) { bounds_ = bounds; } void setPosition(const Position& pos) { bounds_.position = pos; } void setSize(const Size& size) { bounds_.size = size; } - + Size getMinimumSize() const { return minimumSize_; } void setMinimumSize(const Size& size) { minimumSize_ = size; } - + Size getMaximumSize() const { return maximumSize_; } void setMaximumSize(const Size& size) { maximumSize_ = size; } - + // Styling const WidgetStyle& getStyle() const { return style_; } void setStyle(const WidgetStyle& style) { style_ = style; } void mergeStyle(const WidgetStyle& style) { style_.merge(style); } - + // Layout const LayoutParameters& getLayoutParams() const { return layoutParams_; } void setLayoutParams(const LayoutParameters& params) { layoutParams_ = params; } - + // Event handling void addEventListener(WidgetEventType type, WidgetEventHandler handler); void removeEventListener(WidgetEventType type); bool fireEvent(const WidgetEvent& event); - + // Rendering and updates virtual void render(); virtual void update(float deltaTime); virtual Size calculatePreferredSize() const; virtual void layout(); - + // Custom properties - template + template void setProperty(const std::string& name, const T& value) { properties_[name] = value; } - - template + + template T getProperty(const std::string& name, const T& defaultValue = T{}) const { auto it = properties_.find(name); if (it != properties_.end()) { @@ -265,47 +255,43 @@ class Widget { } return defaultValue; } - - bool hasProperty(const std::string& name) const { - return properties_.find(name) != properties_.end(); - } - - void removeProperty(const std::string& name) { - properties_.erase(name); - } - -protected: + + bool hasProperty(const std::string& name) const { return properties_.find(name) != properties_.end(); } + + void removeProperty(const std::string& name) { properties_.erase(name); } + + protected: // Override these for custom widget behavior virtual void onRender() {} virtual void onUpdate(float deltaTime) {} virtual void onLayout() {} virtual void onStyleChanged() {} virtual void onEvent(const WidgetEvent& event) {} - + // Helper methods for ImGui integration void pushImGuiStyle() const; void popImGuiStyle() const; std::string getImGuiId() const; - -private: + + private: std::string id_; Widget* parent_; std::vector> children_; - + bool visible_; bool enabled_; bool focused_; - + Rect bounds_; Size minimumSize_; Size maximumSize_; - + WidgetStyle style_; LayoutParameters layoutParams_; - + std::unordered_map> eventHandlers_; std::unordered_map properties_; - + mutable int imguiStylePushCount_; }; @@ -313,21 +299,21 @@ class Widget { * Container widget for laying out child widgets */ class WidgetContainer : public Widget { -public: - WidgetContainer(const std::string& id = "", LayoutType layoutType = LayoutType::Vertical); - + public: + explicit WidgetContainer(const std::string& id = "", LayoutType layoutType = LayoutType::Vertical); + void setLayoutType(LayoutType type); LayoutType getLayoutType() const { return getLayoutParams().type; } - + void setSpacing(float spacing); float getSpacing() const { return getLayoutParams().spacing; } - -protected: + + protected: void onRender() override; void onLayout() override; Size calculatePreferredSize() const override; - -private: + + private: void layoutVertical(); void layoutHorizontal(); void layoutGrid(); @@ -338,24 +324,22 @@ class WidgetContainer : public Widget { * Widget factory for creating widgets by type */ class WidgetFactory { -public: + public: using WidgetCreator = std::function(const std::string&)>; - + static WidgetFactory& getInstance(); - - template + + template void registerWidget(const std::string& typeName) { - creators_[typeName] = [](const std::string& id) -> std::shared_ptr { - return std::make_shared(id); - }; + creators_[typeName] = [](const std::string& id) -> std::shared_ptr { return std::make_shared(id); }; } - + std::shared_ptr createWidget(const std::string& typeName, const std::string& id = ""); - + std::vector getRegisteredTypes() const; bool isTypeRegistered(const std::string& typeName) const; - -private: + + private: WidgetFactory() = default; std::unordered_map creators_; }; @@ -364,23 +348,23 @@ class WidgetFactory { * Theme system for consistent widget styling */ class WidgetTheme { -public: - WidgetTheme(const std::string& name) : name_(name) {} - + public: + explicit WidgetTheme(const std::string& name) : name_(name) {} + const std::string& getName() const { return name_; } - + void setDefaultStyle(const WidgetStyle& style) { defaultStyle_ = style; } const WidgetStyle& getDefaultStyle() const { return defaultStyle_; } - + void setWidgetStyle(const std::string& widgetType, const WidgetStyle& style); WidgetStyle getWidgetStyle(const std::string& widgetType) const; - + void setWidgetStyle(const std::string& widgetType, const std::string& state, const WidgetStyle& style); WidgetStyle getWidgetStyle(const std::string& widgetType, const std::string& state) const; - + void applyToWidget(Widget* widget, const std::string& widgetType = "", const std::string& state = "default") const; - -private: + + private: std::string name_; WidgetStyle defaultStyle_; std::unordered_map widgetStyles_; @@ -391,27 +375,28 @@ class WidgetTheme { * Theme manager for managing multiple themes */ class ThemeManager { -public: + public: static ThemeManager& getInstance(); - + void addTheme(std::shared_ptr theme); void removeTheme(const std::string& themeName); - + std::shared_ptr getTheme(const std::string& themeName) const; std::shared_ptr getCurrentTheme() const { return currentTheme_; } - + void setCurrentTheme(const std::string& themeName); void setCurrentTheme(std::shared_ptr theme); - + std::vector getThemeNames() const; - - void applyCurrentTheme(Widget* widget, const std::string& widgetType = "", const std::string& state = "default") const; - -private: + + void applyCurrentTheme(Widget* widget, const std::string& widgetType = "", + const std::string& state = "default") const; + + private: ThemeManager() = default; std::unordered_map> themes_; std::shared_ptr currentTheme_; }; -} // namespace gui -} // namespace bolt \ No newline at end of file +} // namespace gui +} // namespace bolt diff --git a/include/bolt/gui/widget_registration.hpp b/include/bolt/gui/widget_registration.hpp index d8312135..2faf48ac 100644 --- a/include/bolt/gui/widget_registration.hpp +++ b/include/bolt/gui/widget_registration.hpp @@ -1,5 +1,9 @@ #pragma once +#include +#include +#include + #include "bolt/gui/widget_framework.hpp" #include "bolt/gui/widgets.hpp" @@ -10,46 +14,46 @@ namespace gui { * Widget registration utility for registering all built-in widgets */ class WidgetRegistration { -public: + public: /** * Register all built-in widget types with the widget factory */ static void registerAllWidgets(); - + /** * Register core widgets (Widget, WidgetContainer) */ static void registerCoreWidgets(); - + /** * Register basic input widgets (Button, TextInput, etc.) */ static void registerInputWidgets(); - + /** * Register display widgets (Label, ProgressBar, etc.) */ static void registerDisplayWidgets(); - + /** * Register container widgets (Panel, TabContainer, Splitter) */ static void registerContainerWidgets(); - + /** * Get list of all registered widget types */ static std::vector getRegisteredTypes(); - + /** * Create a widget by type name with automatic registration */ static std::shared_ptr createWidget(const std::string& typeName, const std::string& id = ""); - -private: + + private: static bool registered_; static void ensureRegistered(); - + // Allow WidgetFrameworkInit to reset registration state friend class WidgetFrameworkInit; }; @@ -58,71 +62,63 @@ class WidgetRegistration { * Default theme definitions */ class DefaultThemes { -public: + public: /** * Create and register all default themes */ static void registerAllThemes(); - + /** * Create the default dark theme */ static std::shared_ptr createDarkTheme(); - + /** - * Create the default light theme + * Create the default light theme */ static std::shared_ptr createLightTheme(); - + /** * Create the high contrast theme */ static std::shared_ptr createHighContrastTheme(); - + /** * Create a custom theme with specified base colors */ - static std::shared_ptr createCustomTheme( - const std::string& name, - const ImVec4& backgroundColor, - const ImVec4& textColor, - const ImVec4& accentColor - ); - -private: - static WidgetStyle createBaseStyle( - const ImVec4& backgroundColor, - const ImVec4& textColor, - const ImVec4& borderColor, - const ImVec4& accentColor - ); + static std::shared_ptr createCustomTheme(const std::string& name, const ImVec4& backgroundColor, + const ImVec4& textColor, const ImVec4& accentColor); + + private: + static WidgetStyle createBaseStyle(const ImVec4& backgroundColor, const ImVec4& textColor, + const ImVec4& borderColor, const ImVec4& accentColor); }; /** * Utility functions for widget framework initialization */ class WidgetFrameworkInit { -public: + public: /** * Initialize the complete widget framework * Registers all widgets and themes */ static void initialize(); - + /** * Shutdown the widget framework * Cleans up resources */ static void shutdown(); - + /** * Check if the framework is initialized */ static bool isInitialized(); - -private: + + private: static bool initialized_; }; -} // namespace gui -} // namespace bolt \ No newline at end of file +} // namespace gui +} // namespace bolt diff --git a/include/bolt/gui_components.hpp b/include/bolt/gui_components.hpp index 9dfc0db7..17e02003 100644 --- a/include/bolt/gui_components.hpp +++ b/include/bolt/gui_components.hpp @@ -1,10 +1,10 @@ -#ifndef BOLT_GUI_COMPONENTS_HPP -#define BOLT_GUI_COMPONENTS_HPP +#ifndef BOLT_GUI_COMPONENTS_HPP_ +#define BOLT_GUI_COMPONENTS_HPP_ +#include #include #include -#include namespace bolt { @@ -15,29 +15,29 @@ struct BracketMatch { }; class Workbench { -public: + public: Workbench() = default; virtual ~Workbench() = default; - + void setCurrentProject(const std::string& path) { currentProject_ = path; } std::string getCurrentProject() const { return currentProject_; } - -private: + + private: std::string currentProject_; }; class Widget { -public: + public: virtual ~Widget() = default; virtual void render() = 0; }; class Button : public Widget { -private: + private: std::string label_; bool enabled_{true}; -public: + public: explicit Button(const std::string& label) : label_(label) {} void render() override; void setEnabled(bool enabled) { enabled_ = enabled; } @@ -45,26 +45,26 @@ class Button : public Widget { }; class Panel : public Widget { -private: + private: std::vector> children_; -public: + public: void addWidget(std::shared_ptr widget); void render() override; }; class TextInput : public Widget { -private: + private: std::string text_; std::string placeholder_; -public: + public: explicit TextInput(const std::string& placeholder = "") : placeholder_(placeholder) {} void render() override; void setText(const std::string& text) { text_ = text; } std::string getText() const { return text_; } }; -} // namespace bolt +} // namespace bolt -#endif // BOLT_GUI_COMPONENTS_HPP +#endif // BOLT_GUI_COMPONENTS_HPP_ diff --git a/include/bolt/lsp/lsp_client.hpp b/include/bolt/lsp/lsp_client.hpp index 0868cccb..46ddd64b 100644 --- a/include/bolt/lsp/lsp_client.hpp +++ b/include/bolt/lsp/lsp_client.hpp @@ -1,12 +1,13 @@ -#ifndef LSP_CLIENT_HPP -#define LSP_CLIENT_HPP +#ifndef BOLT_LSP_LSP_CLIENT_HPP_ +#define BOLT_LSP_LSP_CLIENT_HPP_ -#include -#include +#include +#include #include +#include #include -#include -#include +#include + #include "bolt/editor/lsp_json_rpc.hpp" namespace bolt { @@ -57,7 +58,7 @@ struct Hover { // LSP Client implementation class LSPClient { -public: + public: explicit LSPClient(const std::string& server_command); ~LSPClient(); @@ -74,13 +75,14 @@ class LSPClient { // Language features std::vector completion(const std::string& uri, int line, int character); std::optional gotoDefinition(const std::string& uri, int line, int character); - std::vector findReferences(const std::string& uri, int line, int character, bool include_declaration = false); + std::vector findReferences(const std::string& uri, int line, int character, + bool include_declaration = false); std::optional hover(const std::string& uri, int line, int character); // Diagnostics std::vector getDiagnostics(const std::string& uri); -private: + private: std::string server_command_; bool initialized_; int next_request_id_; @@ -110,7 +112,7 @@ class LSPClient { // LSP Manager - manages multiple LSP clients for different languages class LSPManager { -public: + public: static LSPManager& getInstance() { static LSPManager instance; return instance; @@ -128,7 +130,7 @@ class LSPManager { // Shutdown all servers void shutdownAll(); -private: + private: LSPManager() = default; std::unordered_map> clients_; @@ -136,7 +138,7 @@ class LSPManager { std::mutex mutex_; }; -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt -#endif // LSP_CLIENT_HPP +#endif // BOLT_LSP_LSP_CLIENT_HPP_ diff --git a/include/bolt/network/connection_pool.hpp b/include/bolt/network/connection_pool.hpp index 22cc93cd..301051a4 100644 --- a/include/bolt/network/connection_pool.hpp +++ b/include/bolt/network/connection_pool.hpp @@ -1,14 +1,14 @@ -#ifndef CONNECTION_POOL_HPP -#define CONNECTION_POOL_HPP +#ifndef BOLT_NETWORK_CONNECTION_POOL_HPP_ +#define BOLT_NETWORK_CONNECTION_POOL_HPP_ -#include -#include +#include +#include +#include #include #include -#include +#include #include -#include -#include +#include namespace bolt { @@ -23,19 +23,22 @@ struct PooledConnection { std::chrono::steady_clock::time_point created; bool inUse; size_t useCount; - - PooledConnection(int s, const std::string& h, int p) - : socket(s), host(h), port(p), + + PooledConnection(int s, const std::string& h, int p) + : socket(s), + host(h), + port(p), lastUsed(std::chrono::steady_clock::now()), created(std::chrono::steady_clock::now()), - inUse(false), useCount(0) {} + inUse(false), + useCount(0) {} }; /** * High-performance connection pool with keep-alive support */ class ConnectionPool { -public: + public: static ConnectionPool& getInstance() { static ConnectionPool instance; return instance; @@ -51,12 +54,12 @@ class ConnectionPool { std::shared_ptr getConnection(const std::string& host, int port); void releaseConnection(std::shared_ptr conn); void closeConnection(std::shared_ptr conn); - + // Pool maintenance void cleanupExpiredConnections(); size_t getActiveConnections() const; size_t getTotalConnections() const; - + // Statistics struct Stats { std::atomic connectionsCreated{0}; @@ -64,43 +67,44 @@ class ConnectionPool { std::atomic connectionsClosed{0}; std::atomic timeouts{0}; std::atomic errors{0}; - + // Disable copy constructor and assignment operator Stats() = default; Stats(const Stats&) = delete; Stats& operator=(const Stats&) = delete; - + // Allow move construction and assignment Stats(Stats&&) = default; Stats& operator=(Stats&&) = default; }; - + const Stats& getStats() const { return stats_; } void resetStats(); -private: - ConnectionPool() : maxConnectionsPerHost_(10), - connectionTimeout_(std::chrono::seconds(30)), - keepAliveTimeout_(std::chrono::seconds(60)), - maxIdleTime_(std::chrono::seconds(300)) {} - + private: + ConnectionPool() + : maxConnectionsPerHost_(10), + connectionTimeout_(std::chrono::seconds(30)), + keepAliveTimeout_(std::chrono::seconds(60)), + maxIdleTime_(std::chrono::seconds(300)) {} + ~ConnectionPool(); - + std::shared_ptr createConnection(const std::string& host, int port); bool isConnectionValid(const std::shared_ptr& conn); std::string getConnectionKey(const std::string& host, int port); - + mutable std::mutex poolMutex_; std::unordered_map>> pool_; - + size_t maxConnectionsPerHost_; std::chrono::seconds connectionTimeout_; std::chrono::seconds keepAliveTimeout_; std::chrono::seconds maxIdleTime_; - + Stats stats_; }; -} // namespace bolt +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_NETWORK_CONNECTION_POOL_HPP_ diff --git a/include/bolt/network/http_server.hpp b/include/bolt/network/http_server.hpp index 92aa1b94..d824f064 100644 --- a/include/bolt/network/http_server.hpp +++ b/include/bolt/network/http_server.hpp @@ -1,40 +1,38 @@ -#ifndef HTTP_SERVER_HPP -#define HTTP_SERVER_HPP +#ifndef BOLT_NETWORK_HTTP_SERVER_HPP_ +#define BOLT_NETWORK_HTTP_SERVER_HPP_ -#include #include +#include #include -#include "network_commands.hpp" + +#include "bolt/network/network_commands.hpp" #ifdef _WIN32 #include #include #else -#include #include +#include #endif #include + #include namespace bolt { class HTTPResponse { -public: + public: HTTPResponse() : status_code_(200), status_message_("OK") {} - + void setStatus(int code, const std::string& message) { status_code_ = code; status_message_ = message; } - - void setHeader(const std::string& key, const std::string& value) { - headers_[key] = value; - } - - void setBody(const std::string& body) { - body_ = body; - } - + + void setHeader(const std::string& key, const std::string& value) { headers_[key] = value; } + + void setBody(const std::string& body) { body_ = body; } + std::string toString() const { std::stringstream ss; ss << "HTTP/1.1 " << status_code_ << " " << status_message_ << "\r\n"; @@ -47,7 +45,7 @@ class HTTPResponse { return ss.str(); } -private: + private: int status_code_; std::string status_message_; std::unordered_map headers_; @@ -55,77 +53,76 @@ class HTTPResponse { }; class HTTPServerCommand : public NetworkCommand { -public: + public: HTTPServerCommand() : sockfd_(-1), port_(8080) {} - + bool connect(const std::string& host, int port) override { port_ = port; sockfd_ = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd_ < 0) return false; - + if (sockfd_ < 0) + return false; + struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port_); - + if (bind(sockfd_, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) { return false; } - + if (listen(sockfd_, 5) < 0) { return false; } - + return true; } - + void disconnect() override { if (sockfd_ >= 0) { close(sockfd_); sockfd_ = -1; } } - + void execute() override { if (connect("0.0.0.0", port_)) { std::cout << "HTTP Server listening on port " << port_ << std::endl; - + while (true) { struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); int client_fd = accept(sockfd_, (struct sockaddr*)&client_addr, &client_len); - + if (client_fd < 0) { continue; } - + handleClient(client_fd); close(client_fd); } } } - - std::string getDescription() const override { - return "HTTP Server Command"; - } -private: + std::string getDescription() const override { return "HTTP Server Command"; } + + private: void handleClient(int client_fd) { char buffer[1024] = {0}; read(client_fd, buffer, 1024); - + HTTPResponse response; response.setHeader("Content-Type", "text/html"); response.setBody("

Bolt C++ HTTP Server

"); - + std::string response_str = response.toString(); write(client_fd, response_str.c_str(), response_str.length()); } - + int sockfd_; int port_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_NETWORK_HTTP_SERVER_HPP_ diff --git a/include/bolt/network/message_compression.hpp b/include/bolt/network/message_compression.hpp index 7a86bf07..91f70945 100644 --- a/include/bolt/network/message_compression.hpp +++ b/include/bolt/network/message_compression.hpp @@ -1,13 +1,12 @@ -#ifndef MESSAGE_COMPRESSION_HPP -#define MESSAGE_COMPRESSION_HPP +#ifndef BOLT_NETWORK_MESSAGE_COMPRESSION_HPP_ +#define BOLT_NETWORK_MESSAGE_COMPRESSION_HPP_ #include - +#include #include #include -#include #ifdef BOLT_HAVE_ZLIB - #include +#include #endif namespace bolt { @@ -40,8 +39,8 @@ struct CompressionStats { * High-performance message compression for network protocols */ class MessageCompressor { -public: - MessageCompressor(CompressionType type = CompressionType::GZIP, int level = 6); + public: + explicit MessageCompressor(CompressionType type = CompressionType::GZIP, int level = 6); ~MessageCompressor(); // Compression operations @@ -49,38 +48,38 @@ class MessageCompressor { std::vector compress(const std::vector& data); std::string decompress(const std::vector& compressedData); std::vector decompressToBytes(const std::vector& compressedData); - + // Configuration void setCompressionLevel(int level); void setCompressionType(CompressionType type); void setMinCompressionSize(size_t minSize) { minCompressionSize_ = minSize; } - + // Statistics const CompressionStats& getStats() const { return stats_; } void resetStats(); - + // Utility methods bool shouldCompress(const std::string& data) const; bool shouldCompress(const std::vector& data) const; static bool isCompressed(const std::vector& data); -private: + private: void initializeZlib(); void cleanupZlib(); - + CompressionType type_; int compressionLevel_; size_t minCompressionSize_; - + #ifdef BOLT_HAVE_ZLIB // Zlib streams for reuse z_stream compressStream_; z_stream decompressStream_; #endif bool zlibInitialized_; - + CompressionStats stats_; - + // Internal compression methods std::vector compressGzip(const uint8_t* data, size_t size); std::vector compressDeflate(const uint8_t* data, size_t size); @@ -92,37 +91,37 @@ class MessageCompressor { * WebSocket extension for per-message-deflate compression */ class WebSocketCompression { -public: + public: WebSocketCompression(); - + // WebSocket specific compression methods std::vector compressMessage(const std::string& message, bool& compressed); std::string decompressMessage(const std::vector& data, bool isCompressed); - + // Extension negotiation std::string getExtensionOffer() const; bool parseExtensionResponse(const std::string& response); - + // Configuration void setServerMaxWindowBits(int bits) { serverMaxWindowBits_ = bits; } void setClientMaxWindowBits(int bits) { clientMaxWindowBits_ = bits; } void setServerMaxNoContextTakeover(bool enabled) { serverMaxNoContextTakeover_ = enabled; } void setClientMaxNoContextTakeover(bool enabled) { clientMaxNoContextTakeover_ = enabled; } -private: + private: MessageCompressor compressor_; - + // WebSocket compression parameters int serverMaxWindowBits_; int clientMaxWindowBits_; bool serverMaxNoContextTakeover_; bool clientMaxNoContextTakeover_; - + // Compression thresholds size_t minCompressionSize_; double minCompressionRatio_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_NETWORK_MESSAGE_COMPRESSION_HPP_ diff --git a/include/bolt/network/network_buffer.hpp b/include/bolt/network/network_buffer.hpp index 53d4c503..528b6a18 100644 --- a/include/bolt/network/network_buffer.hpp +++ b/include/bolt/network/network_buffer.hpp @@ -1,13 +1,13 @@ -#ifndef NETWORK_BUFFER_HPP -#define NETWORK_BUFFER_HPP +#ifndef BOLT_NETWORK_NETWORK_BUFFER_HPP_ +#define BOLT_NETWORK_NETWORK_BUFFER_HPP_ +#include #include - -#include +#include #include #include -#include #include -#include +#include +#include namespace bolt { @@ -15,7 +15,7 @@ namespace bolt { * High-performance buffer for network I/O operations */ class NetworkBuffer { -public: + public: explicit NetworkBuffer(size_t initialSize = 8192); ~NetworkBuffer() = default; @@ -26,7 +26,7 @@ class NetworkBuffer { size_t capacity() const { return data_.capacity(); } bool empty() const { return size_ == 0; } void clear(); - + // Data access uint8_t* data() { return data_.data(); } const uint8_t* data() const { return data_.data(); } @@ -34,28 +34,28 @@ class NetworkBuffer { uint8_t* end() { return data_.data() + size_; } const uint8_t* begin() const { return data_.data(); } const uint8_t* end() const { return data_.data() + size_; } - + // Write operations void append(const void* data, size_t length); void append(const std::string& str); void append(const std::vector& vec); void append(uint8_t byte); - + // Read operations std::vector consume(size_t length); std::string consumeString(size_t length); void consume(void* dest, size_t length); void discard(size_t length); - + // Efficient operations - void compact(); // Remove consumed data from front + void compact(); // Remove consumed data from front void ensureSpace(size_t needed); - + // Zero-copy operations uint8_t* prepareWrite(size_t length); void commitWrite(size_t length); - -private: + + private: std::vector data_; size_t size_; size_t readPos_; @@ -65,23 +65,23 @@ class NetworkBuffer { * Memory pool for network buffers to reduce allocations */ class NetworkBufferPool { -public: + public: static NetworkBufferPool& getInstance() { static NetworkBufferPool instance; return instance; } - + std::unique_ptr getBuffer(size_t minSize = 8192); void returnBuffer(std::unique_ptr buffer); - + // Pool statistics size_t getPoolSize() const; size_t getActiveBuffers() const { return activeBuffers_; } void setMaxPoolSize(size_t maxSize) { maxPoolSize_ = maxSize; } - -private: + + private: NetworkBufferPool() : maxPoolSize_(100), activeBuffers_(0) {} - + mutable std::mutex poolMutex_; std::queue> pool_; size_t maxPoolSize_; @@ -92,36 +92,36 @@ class NetworkBufferPool { * Ring buffer for high-throughput streaming data */ class RingBuffer { -public: + public: explicit RingBuffer(size_t size); ~RingBuffer() = default; - + // Write operations (producer) size_t write(const void* data, size_t length); size_t writeAvailable() const; bool canWrite(size_t length) const; - + // Read operations (consumer) size_t read(void* data, size_t length); size_t readAvailable() const; bool canRead(size_t length) const; - + // Buffer state bool empty() const; bool full() const; void clear(); size_t size() const { return size_; } - + // Advanced operations size_t peek(void* data, size_t length) const; void skip(size_t length); - -private: + + private: std::vector buffer_; size_t size_; std::atomic writePos_; std::atomic readPos_; - + size_t nextPos(size_t pos) const; }; @@ -131,7 +131,7 @@ class RingBuffer { struct IOVector { void* data; size_t length; - + IOVector(void* d, size_t len) : data(d), length(len) {} }; @@ -139,26 +139,26 @@ struct IOVector { * Efficient scatter-gather buffer for network I/O */ class ScatterGatherBuffer { -public: + public: ScatterGatherBuffer() = default; - + // Add data segments void addSegment(void* data, size_t length); void addSegment(const std::string& str); void addSegment(const std::vector& vec); - + // Access segments const std::vector& getSegments() const { return segments_; } size_t getSegmentCount() const { return segments_.size(); } size_t getTotalSize() const; - + // Convert to contiguous buffer if needed std::vector flatten() const; - + // Clear all segments void clear(); - -private: + + private: std::vector segments_; }; @@ -166,40 +166,40 @@ class ScatterGatherBuffer { * Zero-copy buffer for high-performance network operations */ class ZeroCopyBuffer { -public: + public: ZeroCopyBuffer() = default; - + // Add data by reference (no copying) void addReference(const void* data, size_t length); void addReference(const std::string& str); void addReference(const std::vector& vec); - + // Access data size_t getTotalSize() const; void copyTo(void* dest) const; std::vector copyToVector() const; - + // Iterate through segments - template + template void forEachSegment(Func&& func) const { for (const auto& segment : segments_) { func(segment.data, segment.length); } } - + void clear(); - -private: + + private: struct Segment { const void* data; size_t length; - + Segment(const void* d, size_t len) : data(d), length(len) {} }; - + std::vector segments_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_NETWORK_NETWORK_BUFFER_HPP_ diff --git a/include/bolt/network/network_commands.hpp b/include/bolt/network/network_commands.hpp index ead32882..c6bcaa8b 100644 --- a/include/bolt/network/network_commands.hpp +++ b/include/bolt/network/network_commands.hpp @@ -1,19 +1,19 @@ -#ifndef NETWORK_COMMANDS_HPP -#define NETWORK_COMMANDS_HPP +#ifndef BOLT_NETWORK_NETWORK_COMMANDS_HPP_ +#define BOLT_NETWORK_NETWORK_COMMANDS_HPP_ #include #ifdef _WIN32 - #include - #include - #include - #define close closesocket +#include +#include +#include +#define close closesocket #else - #include - #include - #include - #include +#include +#include +#include +#include #endif #include "bolt/core/bolt_commands.hpp" @@ -21,54 +21,53 @@ namespace bolt { class NetworkCommand : public Command { -public: + public: virtual ~NetworkCommand() = default; virtual bool connect(const std::string& host, int port) = 0; virtual void disconnect() = 0; }; class TCPCommand : public NetworkCommand { -public: + public: TCPCommand() : sockfd_(-1) {} - + bool connect(const std::string& host, int port) override { #ifdef _WIN32 sockfd_ = static_cast(socket(AF_INET, SOCK_STREAM, 0)); #else sockfd_ = socket(AF_INET, SOCK_STREAM, 0); #endif - if (sockfd_ < 0) return false; - + if (sockfd_ < 0) + return false; + struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); inet_pton(AF_INET, host.c_str(), &serv_addr.sin_addr); - + return ::connect(sockfd_, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) >= 0; } - + void disconnect() override { if (sockfd_ >= 0) { close(sockfd_); sockfd_ = -1; } } - + void execute() override { if (connect("0.0.0.0", 8080)) { // Example connection disconnect(); } } - - std::string getDescription() const override { - return "TCP Network Command"; - } -private: + std::string getDescription() const override { return "TCP Network Command"; } + + private: int sockfd_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_NETWORK_NETWORK_COMMANDS_HPP_ diff --git a/include/bolt/network/optimized_websocket_server.hpp b/include/bolt/network/optimized_websocket_server.hpp index 01cec890..c81e1026 100644 --- a/include/bolt/network/optimized_websocket_server.hpp +++ b/include/bolt/network/optimized_websocket_server.hpp @@ -1,15 +1,19 @@ -#ifndef OPTIMIZED_WEBSOCKET_SERVER_HPP -#define OPTIMIZED_WEBSOCKET_SERVER_HPP +#ifndef BOLT_NETWORK_OPTIMIZED_WEBSOCKET_SERVER_HPP_ +#define BOLT_NETWORK_OPTIMIZED_WEBSOCKET_SERVER_HPP_ +#include +#include #include +#include +#include +#include +#include +#include -#include "bolt/network/websocket_server.hpp" #include "bolt/network/connection_pool.hpp" #include "bolt/network/message_compression.hpp" #include "bolt/network/network_buffer.hpp" #include "bolt/network/network_metrics.hpp" -#include -#include -#include +#include "bolt/network/websocket_server.hpp" namespace bolt { @@ -17,57 +21,57 @@ namespace bolt { * High-performance WebSocket connection with optimizations */ class OptimizedWebSocketConnection : public WebSocketConnection { -public: + public: OptimizedWebSocketConnection(int socket, const std::string& endpoint); ~OptimizedWebSocketConnection(); - + // Enhanced send operations void sendOptimized(const std::string& message, bool compress = true); void sendBinary(const std::vector& data, bool compress = true); void sendPing(const std::string& payload = ""); void sendPong(const std::string& payload = ""); - + // Connection management void enableKeepAlive(std::chrono::seconds interval = std::chrono::seconds(30)); void disableKeepAlive(); bool isAlive() const; void setCompression(bool enabled) { compressionEnabled_ = enabled; } - + // Statistics size_t getBytesSent() const { return bytesSent_; } size_t getBytesReceived() const { return bytesReceived_; } std::chrono::steady_clock::time_point getLastActivity() const { return lastActivity_; } - + // Buffer management void setReceiveBufferSize(size_t size); void setSendBufferSize(size_t size); - -private: + + private: std::string endpoint_; std::unique_ptr receiveBuffer_; std::unique_ptr sendBuffer_; std::unique_ptr compression_; - + // Keep-alive management std::atomic keepAliveEnabled_; std::chrono::seconds keepAliveInterval_; std::thread keepAliveThread_; std::chrono::steady_clock::time_point lastPongReceived_; - + // Statistics std::atomic bytesSent_; std::atomic bytesReceived_; std::chrono::steady_clock::time_point lastActivity_; bool compressionEnabled_; - + void startKeepAlive(); void stopKeepAlive(); void keepAliveWorker(); void updateLastActivity(); - + // Frame processing - std::vector createOptimizedFrame(const std::vector& payload, - uint8_t opcode, bool compressed = false); + std::vector createOptimizedFrame(const std::vector& payload, uint8_t opcode, + bool compressed = false); bool processIncomingFrame(const std::vector& frame); }; @@ -75,96 +79,93 @@ class OptimizedWebSocketConnection : public WebSocketConnection { * High-performance WebSocket server with all optimizations */ class OptimizedWebSocketServer { -public: + public: static OptimizedWebSocketServer& getInstance() { static OptimizedWebSocketServer instance; return instance; } - + // Server configuration void setMaxConnections(size_t max) { maxConnections_ = max; } void setKeepAliveInterval(std::chrono::seconds interval) { keepAliveInterval_ = interval; } void setCompressionEnabled(bool enabled) { compressionEnabled_ = enabled; } void setMetricsEnabled(bool enabled) { metricsEnabled_ = enabled; } - + // Server lifecycle void start(int port = 8080, size_t threadPoolSize = 4); void stop(); bool isRunning() const { return running_; } - + // Connection management void broadcast(const std::string& message, bool compress = true); void broadcastBinary(const std::vector& data, bool compress = true); void broadcastToEndpoint(const std::string& endpoint, const std::string& message); size_t getConnectionCount() const; std::vector getConnectedEndpoints() const; - + // Event handlers void onMessage(std::function callback) { messageCallback_ = callback; } - - void onConnect(std::function callback) { - connectCallback_ = callback; - } - - void onDisconnect(std::function callback) { - disconnectCallback_ = callback; - } - + + void onConnect(std::function callback) { connectCallback_ = callback; } + + void onDisconnect(std::function callback) { disconnectCallback_ = callback; } + void onError(std::function callback) { errorCallback_ = callback; } - + // Performance monitoring NetworkStats getServerStats() const; std::string generatePerformanceReport() const; void resetMetrics(); - + // Advanced features void enableRateLimiting(size_t messagesPerSecond, size_t bytesPerSecond); void disableRateLimiting(); void setMaxMessageSize(size_t maxSize) { maxMessageSize_ = maxSize; } void enableConnectionPooling(bool enabled) { connectionPoolingEnabled_ = enabled; } -private: - OptimizedWebSocketServer() : maxConnections_(1000), - keepAliveInterval_(std::chrono::seconds(30)), - compressionEnabled_(true), - metricsEnabled_(true), - running_(false), - maxMessageSize_(64 * 1024 * 1024), // 64MB - connectionPoolingEnabled_(true), - rateLimitEnabled_(false) {} - + private: + OptimizedWebSocketServer() + : maxConnections_(1000), + keepAliveInterval_(std::chrono::seconds(30)), + compressionEnabled_(true), + metricsEnabled_(true), + running_(false), + maxMessageSize_(64 * 1024 * 1024), // 64MB + connectionPoolingEnabled_(true), + rateLimitEnabled_(false) {} + ~OptimizedWebSocketServer() { stop(); } - + // Server configuration size_t maxConnections_; std::chrono::seconds keepAliveInterval_; bool compressionEnabled_; bool metricsEnabled_; - + // Server state std::atomic running_; int serverSocket_; std::vector threadPool_; - + // Connection management mutable std::mutex connectionsMutex_; std::unordered_map> connections_; std::unique_ptr bufferPool_; - + // Event callbacks std::function messageCallback_; std::function connectCallback_; std::function disconnectCallback_; std::function errorCallback_; - + // Performance features size_t maxMessageSize_; bool connectionPoolingEnabled_; - + // Rate limiting bool rateLimitEnabled_; size_t maxMessagesPerSecond_; @@ -172,21 +173,21 @@ class OptimizedWebSocketServer { std::unordered_map lastMessageTime_; std::unordered_map messageCount_; std::unordered_map byteCount_; - + // Worker methods void acceptConnections(); void handleClient(int clientSocket); void workerThread(); - + // Connection management void addConnection(const std::string& endpoint, OptimizedWebSocketConnection* conn); void removeConnection(const std::string& endpoint, OptimizedWebSocketConnection* conn); - + // Rate limiting bool checkRateLimit(const std::string& endpoint, size_t messageSize); void updateRateLimitCounters(const std::string& endpoint, size_t messageSize); void cleanupRateLimitCounters(); - + // Utility methods std::string extractEndpointFromRequest(const std::string& request); bool performOptimizedHandshake(int socket, std::string& endpoint); @@ -196,7 +197,7 @@ class OptimizedWebSocketServer { * WebSocket frame parser optimized for high throughput */ class OptimizedFrameParser { -public: + public: struct Frame { bool fin; uint8_t opcode; @@ -205,53 +206,37 @@ class OptimizedFrameParser { uint8_t mask[4]; std::vector payload; bool compressed; - - bool isControlFrame() const { - return opcode >= 0x08; - } - - bool isDataFrame() const { - return opcode == 0x01 || opcode == 0x02; - } - - bool isPing() const { - return opcode == 0x09; - } - - bool isPong() const { - return opcode == 0x0A; - } - - bool isClose() const { - return opcode == 0x08; - } + + bool isControlFrame() const { return opcode >= 0x08; } + + bool isDataFrame() const { return opcode == 0x01 || opcode == 0x02; } + + bool isPing() const { return opcode == 0x09; } + + bool isPong() const { return opcode == 0x0A; } + + bool isClose() const { return opcode == 0x08; } }; - + // Parse frames from buffer std::vector parseFrames(NetworkBuffer& buffer); - + // Create frames - static std::vector createFrame(const std::vector& payload, - uint8_t opcode, bool compressed = false); + static std::vector createFrame(const std::vector& payload, uint8_t opcode, + bool compressed = false); static std::vector createPingFrame(const std::string& payload = ""); static std::vector createPongFrame(const std::string& payload = ""); - static std::vector createCloseFrame(uint16_t code = 1000, - const std::string& reason = ""); + static std::vector createCloseFrame(uint16_t code = 1000, const std::string& reason = ""); -private: + private: // Internal parsing state - enum class ParseState { - HEADER, - EXTENDED_LENGTH, - MASK, - PAYLOAD - }; - + enum class ParseState { HEADER, EXTENDED_LENGTH, MASK, PAYLOAD }; + ParseState state_ = ParseState::HEADER; Frame currentFrame_; - size_t bytesNeeded_ = 2; // Start with basic header + size_t bytesNeeded_ = 2; // Start with basic header size_t bytesRead_ = 0; - + bool parseHeader(NetworkBuffer& buffer); bool parseExtendedLength(NetworkBuffer& buffer); bool parseMask(NetworkBuffer& buffer); @@ -259,6 +244,6 @@ class OptimizedFrameParser { void resetParser(); }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_NETWORK_OPTIMIZED_WEBSOCKET_SERVER_HPP_ diff --git a/include/bolt/network/websocket_server.hpp b/include/bolt/network/websocket_server.hpp index 256cbe96..741e3453 100644 --- a/include/bolt/network/websocket_server.hpp +++ b/include/bolt/network/websocket_server.hpp @@ -1,34 +1,34 @@ -#ifndef WEBSOCKET_SERVER_HPP -#define WEBSOCKET_SERVER_HPP +#ifndef BOLT_NETWORK_WEBSOCKET_SERVER_HPP_ +#define BOLT_NETWORK_WEBSOCKET_SERVER_HPP_ #include - -#include #include -#include #include +#include +#include #include #include -#include "network_commands.hpp" + +#include "bolt/network/network_commands.hpp" namespace bolt { class WebSocketConnection { -public: - WebSocketConnection(int socket) : socket_(socket) {} + public: + explicit WebSocketConnection(int socket) : socket_(socket) {} void send(const std::string& message, bool binary = false); void close(); bool performHandshake(); int getSocket() const { return socket_; } - -private: + + private: int socket_; std::string generateAcceptKey(const std::string& clientKey); std::vector createFrame(const std::string& payload, bool binary); }; class WebSocketServer { -public: + public: static WebSocketServer& getInstance() { static WebSocketServer instance; return instance; @@ -37,24 +37,20 @@ class WebSocketServer { void start(int port = 8080); void stop(); void broadcast(const std::string& message, bool binary = false); - + void onMessage(std::function callback) { messageCallback_ = callback; } - void onConnect(std::function callback) { - connectCallback_ = callback; - } + void onConnect(std::function callback) { connectCallback_ = callback; } - void onDisconnect(std::function callback) { - disconnectCallback_ = callback; - } + void onDisconnect(std::function callback) { disconnectCallback_ = callback; } -private: + private: WebSocketServer() = default; void handleClient(int clientSocket); std::vector parseFrame(const std::vector& buffer, bool& isBinary); - + bool running_ = false; int serverSocket_ = -1; std::thread serverThread_; @@ -65,6 +61,6 @@ class WebSocketServer { std::function disconnectCallback_; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_NETWORK_WEBSOCKET_SERVER_HPP_ diff --git a/include/bolt/utils/data_processor.hpp b/include/bolt/utils/data_processor.hpp index b36760c1..694d5936 100644 --- a/include/bolt/utils/data_processor.hpp +++ b/include/bolt/utils/data_processor.hpp @@ -1,15 +1,15 @@ -#ifndef DATA_PROCESSOR_HPP -#define DATA_PROCESSOR_HPP +#ifndef BOLT_UTILS_DATA_PROCESSOR_HPP_ +#define BOLT_UTILS_DATA_PROCESSOR_HPP_ -#include #include #include #include +#include -template +template class DataProcessor { -public: + public: static T calculateAverage(const std::vector& data) { if (data.empty()) { throw std::runtime_error("Cannot calculate average of empty dataset"); @@ -37,4 +37,4 @@ class DataProcessor { } }; -#endif +#endif // BOLT_UTILS_DATA_PROCESSOR_HPP_ diff --git a/include/bolt/utils/filesystem_utils.hpp b/include/bolt/utils/filesystem_utils.hpp index ceee43d4..771e7077 100644 --- a/include/bolt/utils/filesystem_utils.hpp +++ b/include/bolt/utils/filesystem_utils.hpp @@ -1,21 +1,20 @@ -#ifndef FILESYSTEM_UTILS_HPP -#define FILESYSTEM_UTILS_HPP +#ifndef BOLT_UTILS_FILESYSTEM_UTILS_HPP_ +#define BOLT_UTILS_FILESYSTEM_UTILS_HPP_ #include +#include #include #include -#include class FileSystemUtils { -public: + public: static std::string readFile(const std::string& filename) { std::ifstream file(filename); if (!file.is_open()) { throw std::runtime_error("Could not open file: " + filename); } - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; } @@ -36,4 +35,4 @@ class FileSystemUtils { } }; -#endif \ No newline at end of file +#endif // BOLT_UTILS_FILESYSTEM_UTILS_HPP_ diff --git a/include/bolt/utils/math_utils.hpp b/include/bolt/utils/math_utils.hpp index 3bc7d2c3..7bc5d167 100644 --- a/include/bolt/utils/math_utils.hpp +++ b/include/bolt/utils/math_utils.hpp @@ -1,23 +1,20 @@ -#ifndef MATH_UTILS_HPP -#define MATH_UTILS_HPP +#ifndef BOLT_UTILS_MATH_UTILS_HPP_ +#define BOLT_UTILS_MATH_UTILS_HPP_ #include class MathUtils { -public: - static double squareRoot(double num) { - return std::sqrt(num); - } + public: + static double squareRoot(double num) { return std::sqrt(num); } - static double power(double base, double exponent) { - return std::pow(base, exponent); - } + static double power(double base, double exponent) { return std::pow(base, exponent); } - static unsigned long long factorial(unsigned int num) { - if (num <= 1) return 1; + static unsigned long long factorial(unsigned int num) { // NOLINT(runtime/int) + if (num <= 1) + return 1; return num * factorial(num - 1); } }; -#endif +#endif // BOLT_UTILS_MATH_UTILS_HPP_ diff --git a/include/bolt/utils/string_utils.hpp b/include/bolt/utils/string_utils.hpp index 79194640..81f659ef 100644 --- a/include/bolt/utils/string_utils.hpp +++ b/include/bolt/utils/string_utils.hpp @@ -1,12 +1,12 @@ -#ifndef STRING_UTILS_HPP -#define STRING_UTILS_HPP +#ifndef BOLT_UTILS_STRING_UTILS_HPP_ +#define BOLT_UTILS_STRING_UTILS_HPP_ -#include #include +#include class StringUtils { -public: + public: static std::string reverseString(const std::string& input) { std::string result = input; std::reverse(result.begin(), result.end()); @@ -24,8 +24,8 @@ class StringUtils { static int countVowels(const std::string& input) { const std::string vowels = "aeiouAEIOU"; return std::count_if(input.begin(), input.end(), - [&vowels](char c) { return vowels.find(c) != std::string::npos; }); + [&vowels](char c) { return vowels.find(c) != std::string::npos; }); } }; -#endif +#endif // BOLT_UTILS_STRING_UTILS_HPP_ diff --git a/real_tinyllama_chat.cpp b/real_tinyllama_chat.cpp index 394699ea..f0622400 100644 --- a/real_tinyllama_chat.cpp +++ b/real_tinyllama_chat.cpp @@ -1,8 +1,8 @@ +#include #include +#include #include #include -#include -#include // Include llama.cpp headers extern "C" { @@ -10,13 +10,13 @@ extern "C" { } class RealTinyLlamaChat { -private: + private: llama_model* model = nullptr; llama_context* ctx = nullptr; std::string model_path; bool model_loaded = false; -public: + public: ~RealTinyLlamaChat() { if (ctx) { llama_free(ctx); @@ -28,25 +28,21 @@ class RealTinyLlamaChat { } bool find_and_load_model() { - std::vector search_paths = { - "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/", - "./models/TinyLlama-1.1B-Chat-v1.0-GGUF/", - "models/TinyLlama-1.1B-Chat-v1.0-GGUF/" - }; + std::vector search_paths = {"/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/", + "./models/TinyLlama-1.1B-Chat-v1.0-GGUF/", + "models/TinyLlama-1.1B-Chat-v1.0-GGUF/"}; std::cout << "๐Ÿ” Searching for TinyLlama GGUF models..." << std::endl; - + for (const auto& search_path : search_paths) { std::cout << " ๐Ÿ“ Checking: " << search_path << std::endl; - + if (std::filesystem::exists(search_path)) { // Look for GGUF files (prefer smaller quantized models) - std::vector preferred_models = { - "tinyllama-1.1b-chat-v1.0.Q2_K.gguf", - "tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf", - "tinyllama-1.1b-chat-v1.0.Q4_0.gguf" - }; - + std::vector preferred_models = {"tinyllama-1.1b-chat-v1.0.Q2_K.gguf", + "tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf", + "tinyllama-1.1b-chat-v1.0.Q4_0.gguf"}; + for (const auto& model_name : preferred_models) { std::string full_path = search_path + model_name; if (std::filesystem::exists(full_path)) { @@ -55,7 +51,7 @@ class RealTinyLlamaChat { return load_model(); } } - + // If no preferred model, take any GGUF file for (const auto& entry : std::filesystem::directory_iterator(search_path)) { if (entry.path().extension() == ".gguf") { @@ -68,32 +64,32 @@ class RealTinyLlamaChat { std::cout << " โŒ Path not found: " << search_path << std::endl; } } - + std::cout << "โŒ No GGUF models found in any search path" << std::endl; return false; } - + bool load_model() { std::cout << "๐Ÿ“ฅ Loading model: " << model_path << std::endl; - + // Initialize llama backend llama_backend_init(); - + // Load model llama_model_params model_params = llama_model_default_params(); - model_params.n_gpu_layers = 0; // CPU only for compatibility - + model_params.n_gpu_layers = 0; // CPU only for compatibility + model = llama_load_model_from_file(model_path.c_str(), model_params); if (!model) { std::cerr << "โŒ Failed to load model" << std::endl; return false; } - + // Create context llama_context_params ctx_params = llama_context_default_params(); - ctx_params.n_ctx = 2048; // Context size - ctx_params.seed = -1; // Random seed - + ctx_params.n_ctx = 2048; // Context size + ctx_params.seed = -1; // Random seed + ctx = llama_new_context_with_model(model, ctx_params); if (!ctx) { std::cerr << "โŒ Failed to create context" << std::endl; @@ -101,117 +97,118 @@ class RealTinyLlamaChat { model = nullptr; return false; } - + model_loaded = true; std::cout << "โœ… Model loaded successfully!" << std::endl; return true; } - + std::string chat(const std::string& message) { if (!model_loaded) { return "โŒ No model loaded. Please ensure TinyLlama GGUF model is available."; } - + // Format prompt for chat - std::string prompt = "<|system|>\nYou are a helpful AI assistant.\n<|user|>\n" + message + "\n<|assistant|>\n"; - + std::string prompt = + "<|system|>\nYou are a helpful AI assistant.\n<|user|>\n" + message + "\n<|assistant|>\n"; + // Tokenize prompt std::vector tokens = tokenize(prompt); - + if (tokens.empty()) { return "โŒ Failed to tokenize input"; } - + // Clear previous context and evaluate prompt llama_kv_cache_clear(ctx); - + int n_eval = 0; const int n_batch = 512; - + // Process prompt in batches for (size_t i = 0; i < tokens.size(); i += n_batch) { - int n_tokens = std::min(n_batch, (int)(tokens.size() - i)); - + int n_tokens = std::min(n_batch, static_cast(tokens.size() - i)); + if (llama_decode(ctx, llama_batch_get_one(&tokens[i], n_tokens, n_eval, 0))) { return "โŒ Failed to evaluate prompt"; } - + n_eval += n_tokens; } - + // Generate response std::string response; const int max_tokens = 256; - + for (int i = 0; i < max_tokens; i++) { llama_token new_token = sample_next_token(); - + if (new_token == llama_token_eos(model)) { break; } - + // Convert token to text and add to response char buf[256]; int n = llama_token_to_piece(model, new_token, buf, sizeof(buf), 0, true); if (n > 0) { response.append(buf, n); } - + // Evaluate the new token if (llama_decode(ctx, llama_batch_get_one(&new_token, 1, n_eval, 0))) { break; } - + n_eval++; } - + return response; } - -private: + + private: std::vector tokenize(const std::string& text) { std::vector tokens(text.length() + 64); int n = llama_tokenize(model, text.c_str(), text.length(), tokens.data(), tokens.size(), true, true); - + if (n < 0) { tokens.resize(-n); n = llama_tokenize(model, text.c_str(), text.length(), tokens.data(), tokens.size(), true, true); } - + if (n >= 0) { tokens.resize(n); } else { tokens.clear(); } - + return tokens; } - + llama_token sample_next_token() { auto* logits = llama_get_logits(ctx); auto n_vocab = llama_n_vocab(model); - + // Simple greedy sampling (take highest probability token) llama_token max_token = 0; float max_logit = logits[0]; - + for (llama_token token = 1; token < n_vocab; token++) { if (logits[token] > max_logit) { max_logit = logits[token]; max_token = token; } } - + return max_token; } - -public: + + public: void show_model_info() { if (model_loaded) { std::cout << "\n๐Ÿ“‹ Model Information:" << std::endl; std::cout << " ๐Ÿ“„ File: " << std::filesystem::path(model_path).filename().string() << std::endl; std::cout << " ๐Ÿ“ Path: " << model_path << std::endl; - + // Show file size try { auto size = std::filesystem::file_size(model_path); @@ -219,7 +216,7 @@ class RealTinyLlamaChat { } catch (...) { std::cout << " ๐Ÿ“Š Size: Unknown" << std::endl; } - + // Show model details std::cout << " ๐Ÿ”ข Vocab size: " << llama_n_vocab(model) << std::endl; std::cout << " ๐Ÿ“ Context length: " << llama_n_ctx(ctx) << std::endl; @@ -232,50 +229,50 @@ class RealTinyLlamaChat { int main() { std::cout << "๐Ÿฆ™ Real TinyLlama Chat Terminal (with llama.cpp)" << std::endl; std::cout << "===============================================" << std::endl; - + RealTinyLlamaChat chat; - + // Try to find and load model if (!chat.find_and_load_model()) { std::cout << "โŒ Could not load TinyLlama model. Exiting." << std::endl; return 1; } - + std::cout << "โœ… TinyLlama model ready for real inference!" << std::endl; chat.show_model_info(); - + std::cout << "\n๐Ÿ’ฌ Chat with Real TinyLlama (type 'quit' to exit, 'info' for model details):" << std::endl; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; - + std::string input; while (true) { std::cout << "\n๐Ÿ‘ค You: "; - + if (!std::getline(std::cin, input)) { - break; // EOF or error + break; // EOF or error } - + if (input == "quit" || input == "exit") { std::cout << "๐Ÿ‘‹ Goodbye!" << std::endl; break; } - + if (input == "info") { chat.show_model_info(); continue; } - + if (input.empty()) { continue; } - + std::cout << "\n๐Ÿค– TinyLlama: "; std::cout.flush(); - + std::string response = chat.chat(input); std::cout << response << std::endl; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; } - + return 0; } diff --git a/simple_ai_demo.cpp b/simple_ai_demo.cpp index 60bb253d..5849eacb 100644 --- a/simple_ai_demo.cpp +++ b/simple_ai_demo.cpp @@ -1,7 +1,7 @@ #include +#include #include #include -#include // Simple standalone includes - avoiding dependencies that cause build issues struct CodeGenerationContext { @@ -19,36 +19,34 @@ struct GeneratedCode { }; class SimpleAICodeGenerator { -public: + public: GeneratedCode generateFunction(const std::string& description, const CodeGenerationContext& context = {}) { GeneratedCode result; result.generatorType = "simple_template"; result.confidence = 0.8; result.description = "Generated function from simple template"; - + std::string functionName = extractFunctionName(description); - + result.code = "/**\n * " + description + "\n */\n"; result.code += "void " + functionName + "() {\n"; result.code += " // TODO: Implement function logic\n"; result.code += " // Description: " + description + "\n"; result.code += "}"; - - result.suggestions = { - "Consider adding parameter validation", - "Add proper return type", - "Include error handling" - }; - + + result.suggestions = {"Consider adding parameter validation", "Add proper return type", + "Include error handling"}; + return result; } - - GeneratedCode generateClass(const std::string& className, const std::string& description, const CodeGenerationContext& context = {}) { + + GeneratedCode generateClass(const std::string& className, const std::string& description, + const CodeGenerationContext& context = {}) { GeneratedCode result; result.generatorType = "simple_template"; result.confidence = 0.8; result.description = "Generated class from simple template"; - + result.code = "/**\n * " + description + "\n */\n"; result.code += "class " + className + " {\n"; result.code += "private:\n"; @@ -60,19 +58,16 @@ class SimpleAICodeGenerator { result.code += " ~" + className + "();\n\n"; result.code += " // TODO: Add public methods\n"; result.code += "};"; - - result.suggestions = { - "Consider using RAII principles", - "Add copy/move constructors if needed", - "Make destructor virtual if inheritance expected" - }; - + + result.suggestions = {"Consider using RAII principles", "Add copy/move constructors if needed", + "Make destructor virtual if inheritance expected"}; + return result; } - + std::string generateDocumentation(const std::string& code) { std::string doc = "/**\n * Auto-generated documentation\n *\n"; - + if (code.find("class ") != std::string::npos) { doc += " * This class provides functionality for code management.\n"; doc += " * @note This is auto-generated documentation\n"; @@ -83,12 +78,12 @@ class SimpleAICodeGenerator { } else { doc += " * Code documentation\n"; } - + doc += " */"; return doc; } - -private: + + private: std::string extractFunctionName(const std::string& description) { // Simple extraction - look for common patterns if (description.find("calculate") != std::string::npos) { @@ -112,10 +107,10 @@ struct SimpleRefactoringSuggestion { }; class SimpleRefactoringEngine { -public: + public: std::vector analyzeCode(const std::string& code) { std::vector suggestions; - + // Check for long functions if (code.length() > 300) { SimpleRefactoringSuggestion suggestion; @@ -123,30 +118,21 @@ class SimpleRefactoringEngine { suggestion.description = "This function appears to be quite long and could benefit from being broken down."; suggestion.refactoringType = "extract_method"; suggestion.confidenceScore = 0.8; - suggestion.benefits = { - "Improved readability", - "Better testability", - "Reduced complexity" - }; + suggestion.benefits = {"Improved readability", "Better testability", "Reduced complexity"}; suggestions.push_back(suggestion); } - + // Check for nested conditionals - if (code.find("if") != std::string::npos && - code.find("if", code.find("if") + 2) != std::string::npos) { + if (code.find("if") != std::string::npos && code.find("if", code.find("if") + 2) != std::string::npos) { SimpleRefactoringSuggestion suggestion; suggestion.title = "Reduce conditional complexity"; suggestion.description = "Nested conditional statements detected that could be simplified."; suggestion.refactoringType = "reduce_complexity"; suggestion.confidenceScore = 0.7; - suggestion.benefits = { - "Improved readability", - "Reduced cognitive complexity", - "Better error handling" - }; + suggestion.benefits = {"Improved readability", "Reduced cognitive complexity", "Better error handling"}; suggestions.push_back(suggestion); } - + // Check for potential duplication size_t assignmentCount = 0; size_t pos = 0; @@ -154,21 +140,17 @@ class SimpleRefactoringEngine { assignmentCount++; pos++; } - + if (assignmentCount > 5) { SimpleRefactoringSuggestion suggestion; suggestion.title = "Consider extracting common patterns"; suggestion.description = "Multiple similar operations detected that could be consolidated."; suggestion.refactoringType = "remove_duplication"; suggestion.confidenceScore = 0.6; - suggestion.benefits = { - "Reduced code duplication", - "Easier maintenance", - "Improved consistency" - }; + suggestion.benefits = {"Reduced code duplication", "Easier maintenance", "Improved consistency"}; suggestions.push_back(suggestion); } - + return suggestions; } }; @@ -176,13 +158,13 @@ class SimpleRefactoringEngine { int main() { std::cout << "๐Ÿค– Advanced AI Features - Simple Demo\n"; std::cout << "======================================\n\n"; - + // Test code generation std::cout << "๐Ÿ—๏ธ Testing Code Generation:\n"; std::cout << "----------------------------\n"; - + SimpleAICodeGenerator codeGen; - + auto functionResult = codeGen.generateFunction("Calculate the factorial of a number"); std::cout << "Generated Function:\n"; std::cout << functionResult.code << "\n\n"; @@ -191,17 +173,17 @@ int main() { for (const auto& suggestion : functionResult.suggestions) { std::cout << "โ€ข " << suggestion << "\n"; } - + std::cout << "\n"; - + auto classResult = codeGen.generateClass("FileManager", "A class to manage file operations"); std::cout << "Generated Class:\n"; std::cout << classResult.code << "\n\n"; - + // Test documentation generation std::cout << "๐Ÿ“ Testing Documentation Generation:\n"; std::cout << "------------------------------------\n"; - + const std::string sampleCode = R"( int binarySearch(const vector& arr, int target) { int left = 0, right = arr.size() - 1; @@ -214,17 +196,17 @@ int binarySearch(const vector& arr, int target) { return -1; } )"; - + auto documentation = codeGen.generateDocumentation(sampleCode); std::cout << "Generated Documentation:\n"; std::cout << documentation << "\n\n"; - + // Test refactoring suggestions std::cout << "๐Ÿ”ง Testing Refactoring Analysis:\n"; std::cout << "--------------------------------\n"; - + SimpleRefactoringEngine refactoringEngine; - + const std::string complexCode = R"( void processUserData(const string& userData) { if (userData.empty()) { @@ -275,10 +257,10 @@ void processUserData(const string& userData) { cout << "User processed successfully" << endl; } )"; - + auto suggestions = refactoringEngine.analyzeCode(complexCode); std::cout << "Found " << suggestions.size() << " refactoring suggestions:\n\n"; - + for (size_t i = 0; i < suggestions.size(); ++i) { const auto& suggestion = suggestions[i]; std::cout << (i + 1) << ". " << suggestion.title << "\n"; @@ -291,9 +273,9 @@ void processUserData(const string& userData) { } std::cout << "\n"; } - + std::cout << "โœ… Advanced AI Features Demo completed successfully!\n\n"; - + std::cout << "๐ŸŽฏ Features Demonstrated:\n"; std::cout << "โ€ข Function generation from descriptions\n"; std::cout << "โ€ข Class generation with boilerplate code\n"; @@ -301,9 +283,9 @@ void processUserData(const string& userData) { std::cout << "โ€ข Refactoring suggestions with multiple analysis types\n"; std::cout << "โ€ข Pattern-based code analysis\n"; std::cout << "โ€ข Template-driven code generation\n\n"; - + std::cout << "๐Ÿš€ Ready for integration with real AI models (GGML/RWKV)\n"; std::cout << "๐Ÿ“‹ Template-based fallback ensures functionality without AI\n"; - + return 0; -} \ No newline at end of file +} diff --git a/simple_ai_test.cpp b/simple_ai_test.cpp index 0e8cd5dc..a5754b9f 100644 --- a/simple_ai_test.cpp +++ b/simple_ai_test.cpp @@ -1,19 +1,20 @@ -#include "bolt/ai/ai_completion_provider.hpp" #include -using namespace bolt; +#include "bolt/ai/ai_completion_provider.hpp" + +using namespace bolt; // NOLINT(build/namespaces) int main() { std::cout << "Testing AI Code Completion Provider directly...\n"; - + try { // Test the AI code completion engine directly AICodeCompletionEngine& engine = AICodeCompletionEngine::getInstance(); - + std::cout << "1. AI Completion Engine Status:\n"; std::cout << " AI Ready: " << (engine.isAIReady() ? "YES" : "NO") << "\n"; std::cout << " AI Enabled: " << (engine.isAIEnabled() ? "YES" : "NO") << "\n\n"; - + // Test getting completions CodeContext context; context.filePath = "test.cpp"; @@ -22,29 +23,29 @@ int main() { context.line = 1; context.column = 9; context.language = "cpp"; - + std::cout << "2. Testing AI Completions:\n"; auto completions = engine.getCompletions(context, "std::", 5); std::cout << " Found " << completions.size() << " completions for 'std::':\n"; - + for (size_t i = 0; i < completions.size(); ++i) { - std::cout << " " << (i+1) << ". " << completions[i].label - << " (" << completions[i].kind << ", score: " << completions[i].score << ")\n"; + std::cout << " " << (i + 1) << ". " << completions[i].label << " (" << completions[i].kind + << ", score: " << completions[i].score << ")\n"; } - + std::cout << "\n3. Testing Enable/Disable:\n"; engine.setAIEnabled(false); std::cout << " AI Disabled - Ready: " << (engine.isAIReady() ? "YES" : "NO") << "\n"; - + completions = engine.getCompletions(context, "std::", 3); std::cout << " Completions when disabled: " << completions.size() << "\n"; - + engine.setAIEnabled(true); std::cout << " AI Re-enabled - Ready: " << (engine.isAIReady() ? "YES" : "NO") << "\n"; - + completions = engine.getCompletions(context, "std::", 3); std::cout << " Completions when re-enabled: " << completions.size() << "\n"; - + std::cout << "\nโœ… AI Code Completion Provider test successful!\n"; std::cout << "\nThe AI code completion integration includes:\n"; std::cout << " - Mock AI provider with C++ language awareness\n"; @@ -52,10 +53,10 @@ int main() { std::cout << " - Enable/disable functionality\n"; std::cout << " - Scoring system for suggestions\n"; std::cout << " - Integration ready for real AI models\n"; - + return 0; } catch (const std::exception& e) { std::cerr << "โŒ Error: " << e.what() << "\n"; return 1; } -} \ No newline at end of file +} diff --git a/simple_direct_chat.cpp b/simple_direct_chat.cpp index 17a2192f..52c182df 100644 --- a/simple_direct_chat.cpp +++ b/simple_direct_chat.cpp @@ -1,7 +1,7 @@ +#include #include #include #include -#include // Include llama.cpp directly for file access extern "C" { @@ -10,21 +10,23 @@ extern "C" { } class DirectFileChat { -private: + private: llama_model* model = nullptr; llama_context* ctx = nullptr; std::string model_path; -public: + public: ~DirectFileChat() { - if (ctx) llama_free(ctx); - if (model) llama_free_model(model); + if (ctx) + llama_free(ctx); + if (model) + llama_free_model(model); llama_backend_free(); } bool load_model() { model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + if (!std::filesystem::exists(model_path)) { std::cerr << "โŒ Model file not found: " << model_path << std::endl; return false; @@ -40,7 +42,7 @@ class DirectFileChat { llama_model_params model_params = llama_model_default_params(); model_params.n_gpu_layers = 0; // CPU only model_params.use_mmap = true; // Use memory mapping for efficiency - + model = llama_load_model_from_file(model_path.c_str(), model_params); if (!model) { std::cerr << "โŒ Failed to load model from file" << std::endl; @@ -49,10 +51,10 @@ class DirectFileChat { // Create context llama_context_params ctx_params = llama_context_default_params(); - ctx_params.n_ctx = 512; // Small context for simple testing - ctx_params.seed = 42; // Fixed seed for reproducible results - ctx_params.n_threads = 4; // Use 4 threads - + ctx_params.n_ctx = 512; // Small context for simple testing + ctx_params.seed = 42; // Fixed seed for reproducible results + ctx_params.n_threads = 4; // Use 4 threads + ctx = llama_new_context_with_model(model, ctx_params); if (!ctx) { std::cerr << "โŒ Failed to create context" << std::endl; @@ -68,12 +70,13 @@ class DirectFileChat { std::string chat(const std::string& input) { // Simple prompt formatting for TinyLlama std::string prompt = "<|user|>\n" + input + "\n<|assistant|>\n"; - + // Tokenize std::vector tokens; tokens.resize(prompt.length() + 100); - int n_tokens = llama_tokenize(model, prompt.c_str(), prompt.length(), tokens.data(), tokens.size(), true, false); - + int n_tokens = + llama_tokenize(model, prompt.c_str(), prompt.length(), tokens.data(), tokens.size(), true, false); + if (n_tokens < 0) { return "โŒ Failed to tokenize input"; } @@ -83,7 +86,7 @@ class DirectFileChat { // Clear KV cache and evaluate prompt llama_kv_cache_clear(ctx); - + // Process tokens in batch if (llama_decode(ctx, llama_batch_get_one(tokens.data(), n_tokens, 0, 0))) { return "โŒ Failed to process prompt"; @@ -92,27 +95,27 @@ class DirectFileChat { // Generate response std::string response; int max_tokens = 50; // Keep it short for testing - + std::cout << "๐Ÿค– Generating... "; - + for (int i = 0; i < max_tokens; i++) { // Sample next token (simple greedy) auto* logits = llama_get_logits(ctx); llama_token next_token = 0; float max_logit = logits[0]; - + for (llama_token token = 1; token < llama_n_vocab(model); token++) { if (logits[token] > max_logit) { max_logit = logits[token]; next_token = token; } } - + // Check for end of sequence if (next_token == llama_token_eos(model)) { break; } - + // Convert token to text char text_buf[256]; int n_chars = llama_token_to_piece(model, next_token, text_buf, sizeof(text_buf), 0, false); @@ -120,13 +123,13 @@ class DirectFileChat { response.append(text_buf, n_chars); std::cout << std::flush; // Show progress } - + // Feed token back for next iteration if (llama_decode(ctx, llama_batch_get_one(&next_token, 1, n_tokens + i, 0))) { break; } } - + std::cout << " Done!" << std::endl; return response; } @@ -135,30 +138,31 @@ class DirectFileChat { int main() { std::cout << "๐Ÿฆ™ Direct File Access Chat - No Server Required!" << std::endl; std::cout << "=================================================" << std::endl; - + DirectFileChat chat; - + if (!chat.load_model()) { std::cout << "โŒ Failed to load model. Make sure TinyLlama is in the models directory." << std::endl; return 1; } - + std::cout << "\n๐Ÿ’ฌ Direct file chat ready! Type your messages (or 'quit' to exit):" << std::endl; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; - + std::string input; while (true) { std::cout << "\n๐Ÿ‘ค You: "; if (!std::getline(std::cin, input) || input == "quit" || input == "exit") { break; } - - if (input.empty()) continue; - + + if (input.empty()) + continue; + std::cout << "๐Ÿค– AI: " << chat.chat(input) << std::endl; std::cout << "โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€" << std::endl; } - + std::cout << "๐Ÿ‘‹ Goodbye!" << std::endl; return 0; } diff --git a/simple_terminal_ai.cpp b/simple_terminal_ai.cpp index b1619f16..bc552d43 100644 --- a/simple_terminal_ai.cpp +++ b/simple_terminal_ai.cpp @@ -1,17 +1,17 @@ -#include "bolt/ai/direct_gguf_inference.hpp" +#include // For isatty + #include #include -#include // For isatty + +#include "bolt/ai/direct_gguf_inference.hpp" class SimpleBoltTerminalAI { -private: + private: std::unique_ptr direct_ai_; - -public: - SimpleBoltTerminalAI() { - direct_ai_ = std::make_unique(); - } - + + public: + SimpleBoltTerminalAI() { direct_ai_ = std::make_unique(); } + void show_status() { std::cout << "\n๐Ÿ“Š Direct GGUF AI Status:\n"; std::cout << " Model Loaded: " << (direct_ai_->is_loaded() ? "โœ…" : "โŒ") << "\n"; @@ -20,11 +20,11 @@ class SimpleBoltTerminalAI { } std::cout << "\n"; } - + void chat_loop() { std::cout << "๐Ÿค– Simple Bolt AI Terminal Chat (Direct GGUF)\n"; std::cout << "==============================================\n\n"; - + // Try to load a GGUF model std::cout << "๐Ÿ” Searching for GGUF models...\n"; if (!direct_ai_->auto_detect_and_load()) { @@ -32,59 +32,64 @@ class SimpleBoltTerminalAI { } else { std::cout << "โœ… GGUF model loaded successfully!\n"; } - + show_status(); - + // Check if input is from a pipe or terminal bool is_piped = !isatty(fileno(stdin)); - + if (!is_piped) { std::cout << "Commands:\n"; std::cout << " /status - Show AI status\n"; std::cout << " /load - Try to load a GGUF model\n"; std::cout << " /quit - Exit the application\n\n"; - + std::cout << "๐Ÿ’ฌ Start chatting (type your message and press Enter):\n\n"; } - + std::string input; while (std::getline(std::cin, input)) { if (input.empty()) { - if (is_piped) break; // Exit on empty line when piped + if (is_piped) + break; // Exit on empty line when piped continue; } - + if (!is_piped) { std::cout << "You: " << input << "\n"; } - + // Handle commands if (input == "/quit" || input == "/exit") { std::cout << "\n๐Ÿ‘‹ Goodbye!\n"; break; } - + if (input == "/status") { show_status(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + if (input == "/load") { try_load_model(); - if (!is_piped) continue; - else break; + if (!is_piped) + continue; + else + break; } - + // Send to AI std::cout << "AI: "; auto start_time = std::chrono::high_resolution_clock::now(); - + auto response = direct_ai_->generate_text(input, 150, 0.7f); - + auto end_time = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end_time - start_time).count(); - + if (response.success) { std::cout << response.response << "\n"; std::cout << " โฑ๏ธ " << duration << "ms"; @@ -95,17 +100,17 @@ class SimpleBoltTerminalAI { } else { std::cout << "โŒ Error: " << response.error << "\n"; } - + std::cout << "\n"; - + // For piped input, process one question and exit if (is_piped) { break; } } } - -private: + + private: void try_load_model() { std::cout << "๐Ÿ” Attempting to auto-detect GGUF models...\n"; if (direct_ai_->auto_detect_and_load()) { @@ -115,7 +120,8 @@ class SimpleBoltTerminalAI { std::cout << "โŒ No GGUF models found. You can:\n"; std::cout << " 1. Download a small model:\n"; std::cout << " mkdir -p models\n"; - std::cout << " wget -P models/ https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf\n"; + std::cout << " wget -P models/ " + "https://huggingface.co/ggml-org/models/resolve/main/tinyllamas/stories260K.gguf\n"; std::cout << " 2. Or continue using intelligent fallback responses\n\n"; } } @@ -129,6 +135,6 @@ int main() { std::cerr << "โŒ Error: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/src/bolt/ai/ai_completion_provider.cpp b/src/bolt/ai/ai_completion_provider.cpp index b5fe5cd3..4c124b71 100644 --- a/src/bolt/ai/ai_completion_provider.cpp +++ b/src/bolt/ai/ai_completion_provider.cpp @@ -1,106 +1,93 @@ #include "bolt/ai/ai_completion_provider.hpp" -#include "bolt/editor/code_completion.hpp" + #include #include +#include "bolt/editor/code_completion.hpp" + namespace bolt { // Mock AI provider implementation for testing -std::vector MockAICompletionProvider::generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions -) { +std::vector MockAICompletionProvider::generateCompletions(const CodeContext& context, + const std::string& prefix, + size_t maxSuggestions) { if (!initialized_) { return {}; } - + std::vector suggestions; - + // Generate context-aware mock suggestions based on the prefix and file type - if (context.language == "cpp" || context.language == "c++" || - (context.filePath.length() >= 4 && + if (context.language == "cpp" || context.language == "c++" || + (context.filePath.length() >= 4 && (context.filePath.substr(context.filePath.length() - 4) == ".cpp" || context.filePath.substr(context.filePath.length() - 4) == ".hpp" || (context.filePath.length() >= 2 && context.filePath.substr(context.filePath.length() - 2) == ".h")))) { - // C++ specific suggestions if (prefix == "std::") { - suggestions = { - {"vector", "std::vector", "container", 95}, - {"string", "std::string", "type", 90}, - {"unique_ptr", "std::unique_ptr", "smart_pointer", 85}, - {"shared_ptr", "std::shared_ptr", "smart_pointer", 80}, - {"cout", "std::cout", "stream", 75} - }; + suggestions = {{"vector", "std::vector", "container", 95}, + {"string", "std::string", "type", 90}, + {"unique_ptr", "std::unique_ptr", "smart_pointer", 85}, + {"shared_ptr", "std::shared_ptr", "smart_pointer", 80}, + {"cout", "std::cout", "stream", 75}}; } else if (prefix == "class" || prefix == "cla") { suggestions = { - {"class MyClass", "class MyClass {\npublic:\n MyClass();\n ~MyClass();\n};", "snippet", 95} - }; + {"class MyClass", "class MyClass {\npublic:\n MyClass();\n ~MyClass();\n};", "snippet", 95}}; } else if (prefix == "for" || prefix == "fo") { - suggestions = { - {"for loop", "for (size_t i = 0; i < n; ++i) {\n \n}", "snippet", 90}, - {"for range", "for (const auto& item : container) {\n \n}", "snippet", 85} - }; + suggestions = {{"for loop", "for (size_t i = 0; i < n; ++i) {\n \n}", "snippet", 90}, + {"for range", "for (const auto& item : container) {\n \n}", "snippet", 85}}; } else if (prefix == "if" || prefix == "i") { - suggestions = { - {"if statement", "if (condition) {\n \n}", "snippet", 85} - }; + suggestions = {{"if statement", "if (condition) {\n \n}", "snippet", 85}}; } else if (prefix.empty() || prefix.length() == 1) { // General suggestions when typing starts - suggestions = { - {"namespace", "namespace " + prefix, "keyword", 70}, - {"include", "#include <" + prefix, "preprocessor", 65}, - {"auto", "auto " + prefix, "keyword", 60} - }; + suggestions = {{"namespace", "namespace " + prefix, "keyword", 70}, + {"include", "#include <" + prefix, "preprocessor", 65}, + {"auto", "auto " + prefix, "keyword", 60}}; } } else { // Generic suggestions for other languages if (prefix == "function" || prefix == "func") { - suggestions = { - {"function", "function " + prefix + "() {\n \n}", "snippet", 80} - }; + suggestions = {{"function", "function " + prefix + "() {\n \n}", "snippet", 80}}; } else if (prefix == "var" || prefix == "v") { - suggestions = { - {"variable", "var " + prefix, "keyword", 70} - }; + suggestions = {{"variable", "var " + prefix, "keyword", 70}}; } } - + // Add some intelligent context-based suggestions based on surrounding code std::string contextLine = ""; if (context.cursorPosition < context.content.length()) { // Get the current line for context size_t lineStart = context.content.rfind('\n', context.cursorPosition); - if (lineStart == std::string::npos) lineStart = 0; - else lineStart++; - + if (lineStart == std::string::npos) + lineStart = 0; + else + lineStart++; + size_t lineEnd = context.content.find('\n', context.cursorPosition); - if (lineEnd == std::string::npos) lineEnd = context.content.length(); - + if (lineEnd == std::string::npos) + lineEnd = context.content.length(); + contextLine = context.content.substr(lineStart, lineEnd - lineStart); } - + // Add context-specific suggestions if (contextLine.find("return") != std::string::npos && prefix.empty()) { suggestions.push_back({"nullptr", "nullptr", "literal", 85}); suggestions.push_back({"true", "true", "literal", 80}); suggestions.push_back({"false", "false", "literal", 80}); } - + // Limit to requested number of suggestions if (suggestions.size() > maxSuggestions) { suggestions.resize(maxSuggestions); } - + return suggestions; } // AI Code Completion Engine implementation -AICodeCompletionEngine::AICodeCompletionEngine() - : provider_(std::make_unique()) - , baseEngine_(CodeCompletionEngine::getInstance()) { - +AICodeCompletionEngine::AICodeCompletionEngine() + : provider_(std::make_unique()), baseEngine_(CodeCompletionEngine::getInstance()) { // Initialize the mock provider provider_->initialize(); } @@ -115,41 +102,34 @@ void AICodeCompletionEngine::setProvider(std::unique_ptr p } } -std::vector AICodeCompletionEngine::getCompletions( - const CodeContext& context, - const std::string& prefix, - size_t limit -) { +std::vector AICodeCompletionEngine::getCompletions(const CodeContext& context, + const std::string& prefix, size_t limit) { std::vector results; - + // Get AI suggestions if enabled and provider is ready if (aiEnabled_ && provider_ && provider_->isReady()) { auto aiSuggestions = provider_->generateCompletions(context, prefix, limit); results.insert(results.end(), aiSuggestions.begin(), aiSuggestions.end()); } - + // Get base engine suggestions as fallback or supplement auto baseSuggestions = baseEngine_.getCompletions(prefix, limit); results.insert(results.end(), baseSuggestions.begin(), baseSuggestions.end()); - + // Sort by score and deduplicate - std::sort(results.begin(), results.end(), - [](const CompletionItem& a, const CompletionItem& b) { - return a.score > b.score; - }); - + std::sort(results.begin(), results.end(), + [](const CompletionItem& a, const CompletionItem& b) { return a.score > b.score; }); + // Remove duplicates based on label auto last = std::unique(results.begin(), results.end(), - [](const CompletionItem& a, const CompletionItem& b) { - return a.label == b.label; - }); + [](const CompletionItem& a, const CompletionItem& b) { return a.label == b.label; }); results.erase(last, results.end()); - + // Limit to requested number if (results.size() > limit) { results.resize(limit); } - + return results; } @@ -157,4 +137,4 @@ bool AICodeCompletionEngine::isAIReady() const { return provider_ && provider_->isReady(); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/ai/ai_config_manager.cpp b/src/bolt/ai/ai_config_manager.cpp index c42a7605..4902c3f1 100644 --- a/src/bolt/ai/ai_config_manager.cpp +++ b/src/bolt/ai/ai_config_manager.cpp @@ -1,17 +1,19 @@ -#include "bolt/ai/ai_http_client.hpp" -#include -#include #include +#include +#include + +#include "bolt/ai/ai_http_client.hpp" #ifdef BOLT_HAVE_JSONCPP - #include +#include #endif namespace bolt { namespace ai { // AIHttpClientFactory implementation -std::unique_ptr AIHttpClientFactory::create_openai_client(const std::string& api_key, const std::string& model) { +std::unique_ptr AIHttpClientFactory::create_openai_client(const std::string& api_key, + const std::string& model) { AIHttpConfig config; config.base_url = "https://api.openai.com"; config.api_key = api_key; @@ -20,20 +22,23 @@ std::unique_ptr AIHttpClientFactory::create_openai_client(const st config.system_prompt = "You are a helpful AI assistant specializing in software development and programming."; config.max_tokens = 1000; config.temperature = 0.7f; - + return std::make_unique(config); } -std::unique_ptr AIHttpClientFactory::create_anthropic_client(const std::string& api_key, const std::string& model) { +std::unique_ptr AIHttpClientFactory::create_anthropic_client(const std::string& api_key, + const std::string& model) { AIHttpConfig config; config.base_url = "https://api.anthropic.com"; config.api_key = api_key; config.model_name = model; config.api_type = APIType::ANTHROPIC; - config.system_prompt = "You are Claude, a helpful AI assistant created by Anthropic. You're great at helping with programming and development tasks."; + config.system_prompt = + "You are Claude, a helpful AI assistant created by Anthropic. You're great at helping with programming and " + "development tasks."; config.max_tokens = 1000; config.temperature = 0.7f; - + return std::make_unique(config); } @@ -42,24 +47,27 @@ std::unique_ptr AIHttpClientFactory::create_llama_cpp_client(const config.base_url = base_url; config.api_type = APIType::LLAMA_CPP; config.model_name = "local-model"; - config.system_prompt = "You are a helpful AI programming assistant. Help users with code, debugging, and development questions."; + config.system_prompt = + "You are a helpful AI programming assistant. Help users with code, debugging, and development questions."; config.max_tokens = 512; config.temperature = 0.7f; config.verify_ssl = false; // Often local servers don't use SSL - + return std::make_unique(config); } -std::unique_ptr AIHttpClientFactory::create_ollama_client(const std::string& base_url, const std::string& model) { +std::unique_ptr AIHttpClientFactory::create_ollama_client(const std::string& base_url, + const std::string& model) { AIHttpConfig config; config.base_url = base_url; config.model_name = model; config.api_type = APIType::CUSTOM; - config.system_prompt = "You are a helpful AI assistant. Focus on clear, practical advice for programming and development."; + config.system_prompt = + "You are a helpful AI assistant. Focus on clear, practical advice for programming and development."; config.max_tokens = 512; config.temperature = 0.8f; config.verify_ssl = false; - + return std::make_unique(config); } @@ -68,17 +76,17 @@ AIHttpConfig AIHttpClientFactory::detect_local_server() { "http://localhost:8080", "http://localhost:11434", // Ollama default "http://127.0.0.1:8080", - "http://127.0.0.1:5000", // Common Flask/Python server - "http://127.0.0.1:3000", // Common Node.js server + "http://127.0.0.1:5000", // Common Flask/Python server + "http://127.0.0.1:3000", // Common Node.js server }; - + for (const auto& url : common_urls) { AIHttpConfig config; config.base_url = url; config.api_type = APIType::LLAMA_CPP; config.verify_ssl = false; config.timeout_seconds = 5; // Quick timeout for detection - + try { AIHttpClient client(config); if (client.test_connection()) { @@ -90,7 +98,7 @@ AIHttpConfig AIHttpClientFactory::detect_local_server() { // Continue to next URL } } - + // Return default config if nothing found AIHttpConfig default_config; default_config.base_url = "http://localhost:8080"; @@ -101,28 +109,28 @@ AIHttpConfig AIHttpClientFactory::detect_local_server() { std::vector AIHttpClientFactory::get_recommended_configs() { std::vector configs; - + // Local llama.cpp server AIHttpConfig llamacpp; llamacpp.base_url = "http://localhost:8080"; llamacpp.api_type = APIType::LLAMA_CPP; llamacpp.model_name = "local-llama"; configs.push_back(llamacpp); - + // Ollama AIHttpConfig ollama; ollama.base_url = "http://localhost:11434"; ollama.api_type = APIType::CUSTOM; ollama.model_name = "llama2"; configs.push_back(ollama); - + // OpenAI (requires API key) AIHttpConfig openai; openai.base_url = "https://api.openai.com"; openai.api_type = APIType::OPENAI; openai.model_name = "gpt-3.5-turbo"; configs.push_back(openai); - + return configs; } @@ -143,27 +151,27 @@ bool AIConfigManager::load_config(const std::string& config_file) { return false; #else std::string file_path = config_file.empty() ? config_file_path_ : config_file; - + if (!std::filesystem::exists(file_path)) { std::cout << "๐Ÿ“„ Config file not found, creating default: " << file_path << std::endl; load_default_providers(); return save_config(file_path); } - + try { std::ifstream file(file_path); Json::Value root; file >> root; - + if (root.isMember("active_provider")) { active_provider_ = root["active_provider"].asString(); } - + if (root.isMember("providers")) { Json::Value providers = root["providers"]; for (const auto& name : providers.getMemberNames()) { Json::Value provider = providers[name]; - + AIHttpConfig config; config.base_url = provider.get("base_url", "http://localhost:8080").asString(); config.api_key = provider.get("api_key", "").asString(); @@ -173,20 +181,23 @@ bool AIConfigManager::load_config(const std::string& config_file) { config.system_prompt = provider.get("system_prompt", "You are a helpful AI assistant.").asString(); config.timeout_seconds = provider.get("timeout_seconds", 30).asInt(); config.verify_ssl = provider.get("verify_ssl", true).asBool(); - + std::string api_type_str = provider.get("api_type", "llama_cpp").asString(); - if (api_type_str == "openai") config.api_type = APIType::OPENAI; - else if (api_type_str == "anthropic") config.api_type = APIType::ANTHROPIC; - else if (api_type_str == "custom") config.api_type = APIType::CUSTOM; - else config.api_type = APIType::LLAMA_CPP; - + if (api_type_str == "openai") + config.api_type = APIType::OPENAI; + else if (api_type_str == "anthropic") + config.api_type = APIType::ANTHROPIC; + else if (api_type_str == "custom") + config.api_type = APIType::CUSTOM; + else + config.api_type = APIType::LLAMA_CPP; + providers_[name] = config; } } - + std::cout << "โœ… Loaded AI configuration from: " << file_path << std::endl; return true; - } catch (const std::exception& e) { std::cerr << "โŒ Failed to load AI config: " << e.what() << std::endl; load_default_providers(); @@ -201,11 +212,11 @@ bool AIConfigManager::save_config(const std::string& config_file) { return false; #else std::string file_path = config_file.empty() ? config_file_path_ : config_file; - + try { Json::Value root; root["active_provider"] = active_provider_; - + Json::Value providers; for (const auto& [name, config] : providers_) { Json::Value provider; @@ -217,29 +228,36 @@ bool AIConfigManager::save_config(const std::string& config_file) { provider["system_prompt"] = config.system_prompt; provider["timeout_seconds"] = config.timeout_seconds; provider["verify_ssl"] = config.verify_ssl; - + std::string api_type_str; switch (config.api_type) { - case APIType::OPENAI: api_type_str = "openai"; break; - case APIType::ANTHROPIC: api_type_str = "anthropic"; break; - case APIType::CUSTOM: api_type_str = "custom"; break; - default: api_type_str = "llama_cpp"; break; + case APIType::OPENAI: + api_type_str = "openai"; + break; + case APIType::ANTHROPIC: + api_type_str = "anthropic"; + break; + case APIType::CUSTOM: + api_type_str = "custom"; + break; + default: + api_type_str = "llama_cpp"; + break; } provider["api_type"] = api_type_str; - + providers[name] = provider; } root["providers"] = providers; - + std::ofstream file(file_path); Json::StreamWriterBuilder builder; builder["indentation"] = " "; std::unique_ptr writer(builder.newStreamWriter()); writer->write(root, &file); - + std::cout << "๐Ÿ’พ Saved AI configuration to: " << file_path << std::endl; return true; - } catch (const std::exception& e) { std::cerr << "โŒ Failed to save AI config: " << e.what() << std::endl; return false; @@ -250,7 +268,7 @@ bool AIConfigManager::save_config(const std::string& config_file) { void AIConfigManager::add_provider(const std::string& name, const AIHttpConfig& config) { providers_[name] = config; std::cout << "โž• Added AI provider: " << name << " (" << config.base_url << ")" << std::endl; - + if (providers_.size() == 1) { active_provider_ = name; } @@ -261,7 +279,7 @@ void AIConfigManager::remove_provider(const std::string& name) { if (it != providers_.end()) { providers_.erase(it); std::cout << "โž– Removed AI provider: " << name << std::endl; - + if (active_provider_ == name && !providers_.empty()) { active_provider_ = providers_.begin()->first; std::cout << "๐Ÿ”„ Switched active provider to: " << active_provider_ << std::endl; @@ -300,13 +318,13 @@ AIHttpConfig AIConfigManager::get_active_config() const { std::map AIConfigManager::test_all_providers() { std::map results; - + std::cout << "๐Ÿ” Testing all AI providers..." << std::endl; for (const auto& [name, config] : providers_) { std::cout << " Testing " << name << "..." << std::endl; results[name] = test_provider(name); } - + return results; } @@ -316,17 +334,17 @@ bool AIConfigManager::test_provider(const std::string& name) { std::cout << "โŒ Provider not found: " << name << std::endl; return false; } - + try { AIHttpClient client(it->second); bool success = client.test_connection(); - + if (success) { std::cout << "โœ… " << name << " - Connection successful" << std::endl; } else { std::cout << "โŒ " << name << " - Connection failed" << std::endl; } - + return success; } catch (const std::exception& e) { std::cout << "โŒ " << name << " - Error: " << e.what() << std::endl; @@ -336,18 +354,18 @@ bool AIConfigManager::test_provider(const std::string& name) { void AIConfigManager::load_default_providers() { std::cout << "๐Ÿ“‹ Loading default AI providers..." << std::endl; - + // Default local llama.cpp server AIHttpConfig llamacpp = create_default_config(); add_provider("llama_cpp", llamacpp); - + // Try to detect local server AIHttpConfig detected = AIHttpClientFactory::detect_local_server(); if (detected.base_url != llamacpp.base_url) { add_provider("detected_local", detected); active_provider_ = "detected_local"; } - + // Ollama AIHttpConfig ollama; ollama.base_url = "http://localhost:11434"; @@ -355,7 +373,7 @@ void AIConfigManager::load_default_providers() { ollama.model_name = "llama2"; ollama.verify_ssl = false; add_provider("ollama", ollama); - + // OpenAI (template - requires API key) AIHttpConfig openai; openai.base_url = "https://api.openai.com"; @@ -373,12 +391,13 @@ AIHttpConfig AIConfigManager::create_default_config() const { config.model_name = "local-model"; config.max_tokens = 512; config.temperature = 0.7f; - config.system_prompt = "You are a helpful AI programming assistant. Help users with code, debugging, and development questions."; + config.system_prompt = + "You are a helpful AI programming assistant. Help users with code, debugging, and development questions."; config.timeout_seconds = 30; config.verify_ssl = false; - + return config; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/ai_http_client.cpp b/src/bolt/ai/ai_http_client.cpp index 464e7bf9..334269d0 100644 --- a/src/bolt/ai/ai_http_client.cpp +++ b/src/bolt/ai/ai_http_client.cpp @@ -1,8 +1,9 @@ #include "bolt/ai/ai_http_client.hpp" + +#include #include #include #include -#include #ifdef BOLT_HAVE_CURL #include @@ -20,18 +21,18 @@ namespace ai { // Callback function to write HTTP response data size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { size_t total_size = size * nmemb; - userp->append((char*)contents, total_size); + userp->append(static_cast(contents), total_size); return total_size; } AIHttpClient::AIHttpClient(const AIHttpConfig& config) : config_(config) { curl_global_init(CURL_GLOBAL_DEFAULT); curl_ = curl_easy_init(); - + if (!curl_) { throw std::runtime_error("Failed to initialize CURL"); } - + // Set up default options curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl_, CURLOPT_TIMEOUT, config_.timeout_seconds); @@ -39,7 +40,7 @@ AIHttpClient::AIHttpClient(const AIHttpConfig& config) : config_(config) { curl_easy_setopt(curl_, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYPEER, config_.verify_ssl ? 1L : 0L); curl_easy_setopt(curl_, CURLOPT_SSL_VERIFYHOST, config_.verify_ssl ? 2L : 0L); - + std::cout << "โœ… AI HTTP Client initialized for: " << config_.base_url << std::endl; } @@ -60,60 +61,60 @@ drawkern::AIInferenceResponse AIHttpClient::complete_code(const std::string& cod drawkern::AIInferenceResponse AIHttpClient::send_request(const HttpRequest& request) { drawkern::AIInferenceResponse response; - + if (!curl_) { response.error = "HTTP client not initialized"; response.success = false; return response; } - + auto start_time = std::chrono::high_resolution_clock::now(); std::string response_data; - + // Set URL curl_easy_setopt(curl_, CURLOPT_URL, request.url.c_str()); curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &response_data); - + // Set headers struct curl_slist* headers = nullptr; for (const auto& header : request.headers) { headers = curl_slist_append(headers, (header.first + ": " + header.second).c_str()); } curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers); - + // Set POST data if present if (!request.body.empty()) { curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, request.body.c_str()); curl_easy_setopt(curl_, CURLOPT_POSTFIELDSIZE, request.body.length()); } - + // Perform the request CURLcode res = curl_easy_perform(curl_); - + // Clean up headers if (headers) { curl_slist_free_all(headers); } - + auto end_time = std::chrono::high_resolution_clock::now(); response.inference_time_ms = std::chrono::duration(end_time - start_time).count(); - + if (res != CURLE_OK) { response.error = "HTTP request failed: " + std::string(curl_easy_strerror(res)); response.success = false; return response; } - + // Get HTTP response code - long response_code; + long response_code; // NOLINT(runtime/int) the type libcurl writes curl_easy_getinfo(curl_, CURLINFO_RESPONSE_CODE, &response_code); - + if (response_code != 200) { response.error = "HTTP error " + std::to_string(response_code) + ": " + response_data; response.success = false; return response; } - + // Parse response based on API type return parse_response(response_data, request.api_type); } @@ -122,24 +123,24 @@ HttpRequest AIHttpClient::create_chat_request(const std::string& message, const HttpRequest request; request.url = config_.base_url + "/v1/chat/completions"; request.api_type = config_.api_type; - + // Set headers request.headers["Content-Type"] = "application/json"; if (!config_.api_key.empty()) { request.headers["Authorization"] = "Bearer " + config_.api_key; } - + // Create request body based on API type Json::Value root; Json::Value messages(Json::arrayValue); - + if (config_.api_type == APIType::OPENAI || config_.api_type == APIType::ANTHROPIC) { // OpenAI/Anthropic format root["model"] = config_.model_name; root["max_tokens"] = config_.max_tokens; root["temperature"] = config_.temperature; root["stream"] = false; - + // Add system message if configured if (!config_.system_prompt.empty()) { Json::Value system_msg; @@ -147,13 +148,13 @@ HttpRequest AIHttpClient::create_chat_request(const std::string& message, const system_msg["content"] = config_.system_prompt; messages.append(system_msg); } - + // Add user message Json::Value user_msg; user_msg["role"] = "user"; user_msg["content"] = message; messages.append(user_msg); - + root["messages"] = messages; } else if (config_.api_type == APIType::LLAMA_CPP) { // llama.cpp server format @@ -163,53 +164,53 @@ HttpRequest AIHttpClient::create_chat_request(const std::string& message, const root["stop"] = Json::Value(Json::arrayValue); root["stream"] = false; } - + Json::StreamWriterBuilder builder; request.body = Json::writeString(builder, root); - + return request; } HttpRequest AIHttpClient::create_completion_request(const std::string& code, const std::string& language) { HttpRequest request; request.api_type = config_.api_type; - + std::string prompt = "Complete this " + language + " code:\n" + code + "\n\nCompletion:"; - + if (config_.api_type == APIType::OPENAI || config_.api_type == APIType::ANTHROPIC) { request.url = config_.base_url + "/v1/chat/completions"; return create_chat_request(prompt, ""); } else { request.url = config_.base_url + "/completion"; - + Json::Value root; root["prompt"] = prompt; root["n_predict"] = config_.max_tokens; root["temperature"] = config_.temperature; root["stream"] = false; - + Json::StreamWriterBuilder builder; request.body = Json::writeString(builder, root); } - + return request; } drawkern::AIInferenceResponse AIHttpClient::parse_response(const std::string& response_data, APIType api_type) { drawkern::AIInferenceResponse response; - + try { Json::CharReaderBuilder builder; Json::Value root; std::string errors; - + std::istringstream stream(response_data); if (!Json::parseFromStream(builder, stream, &root, &errors)) { response.error = "Failed to parse JSON response: " + errors; response.success = false; return response; } - + if (api_type == APIType::OPENAI || api_type == APIType::ANTHROPIC) { // OpenAI/Anthropic response format if (root.isMember("choices") && root["choices"].isArray() && !root["choices"].empty()) { @@ -218,7 +219,7 @@ drawkern::AIInferenceResponse AIHttpClient::parse_response(const std::string& re response.response = choice["message"]["content"].asString(); response.success = true; } - + // Get usage info if available if (root.isMember("usage")) { Json::Value usage = root["usage"]; @@ -242,7 +243,7 @@ drawkern::AIInferenceResponse AIHttpClient::parse_response(const std::string& re response.error = "llama.cpp Error: " + root["error"].asString(); response.success = false; } - + // Get tokens info if available if (root.isMember("tokens_predicted")) { response.tokens_generated = root["tokens_predicted"].asInt(); @@ -251,32 +252,31 @@ drawkern::AIInferenceResponse AIHttpClient::parse_response(const std::string& re response.tokens_processed = root["tokens_evaluated"].asInt(); } } - + if (!response.success && response.error.empty()) { response.error = "Unknown response format"; response.success = false; } - } catch (const std::exception& e) { response.error = "Exception parsing response: " + std::string(e.what()); response.success = false; } - + return response; } bool AIHttpClient::test_connection() { std::cout << "๐Ÿ” Testing connection to: " << config_.base_url << std::endl; - + HttpRequest request; request.url = config_.base_url + "/v1/models"; request.headers["Content-Type"] = "application/json"; if (!config_.api_key.empty()) { request.headers["Authorization"] = "Bearer " + config_.api_key; } - + drawkern::AIInferenceResponse response = send_request(request); - + if (response.success) { std::cout << "โœ… Connection test successful!" << std::endl; return true; @@ -291,11 +291,11 @@ void AIHttpClient::update_config(const AIHttpConfig& config) { std::cout << "๐Ÿ”„ Updated HTTP client configuration" << std::endl; } -#else // !BOLT_HAVE_CURL +#else // !BOLT_HAVE_CURL // Stub implementations when CURL is not available size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* userp) { - return size * nmemb; // Dummy implementation + return size * nmemb; // Dummy implementation } AIHttpClient::AIHttpClient(const AIHttpConfig& config) : config_(config), curl_(nullptr) { @@ -338,11 +338,11 @@ drawkern::AIInferenceResponse AIHttpClient::send_request(const HttpRequest& requ } HttpRequest AIHttpClient::create_chat_request(const std::string& message, const std::string& session_id) { - return HttpRequest{}; // Return empty request + return HttpRequest{}; // Return empty request } HttpRequest AIHttpClient::create_completion_request(const std::string& code, const std::string& language) { - return HttpRequest{}; // Return empty request + return HttpRequest{}; // Return empty request } drawkern::AIInferenceResponse AIHttpClient::parse_response(const std::string& response_data, APIType api_type) { @@ -352,7 +352,7 @@ drawkern::AIInferenceResponse AIHttpClient::parse_response(const std::string& re return response; } -#endif // BOLT_HAVE_CURL +#endif // BOLT_HAVE_CURL -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/ai_refactoring_engine.cpp b/src/bolt/ai/ai_refactoring_engine.cpp index 5035f1ca..b7efdde8 100644 --- a/src/bolt/ai/ai_refactoring_engine.cpp +++ b/src/bolt/ai/ai_refactoring_engine.cpp @@ -1,7 +1,8 @@ #include "bolt/ai/ai_refactoring_engine.hpp" + #include -#include #include +#include namespace bolt { @@ -15,12 +16,12 @@ void TemplateRefactoringEngine::loadDefaultPatterns() { RefactoringPattern longFunction; longFunction.name = "long_function"; longFunction.description = "Detect long functions that should be extracted"; - longFunction.pattern = std::regex(R"((\w+)\s*\([^)]*\)\s*\{([^}]{200,})\})"); // Functions with 200+ chars + longFunction.pattern = std::regex(R"((\w+)\s*\([^)]*\)\s*\{([^}]{200,})\})"); // Functions with 200+ chars longFunction.suggestionGenerator = [this](const std::smatch& match, const std::string& filePath) { return createExtractMethodSuggestion(match, filePath); }; patterns_.push_back(longFunction); - + // Nested conditional pattern RefactoringPattern nestedConditionals; nestedConditionals.name = "nested_conditionals"; @@ -30,12 +31,12 @@ void TemplateRefactoringEngine::loadDefaultPatterns() { return createComplexityReductionSuggestion(match, filePath); }; patterns_.push_back(nestedConditionals); - + // Duplicate code pattern RefactoringPattern duplicateCode; duplicateCode.name = "duplicate_code"; duplicateCode.description = "Detect potential code duplication"; - duplicateCode.pattern = std::regex(R"((\w+\s*=\s*[^;]+;[\s]*){3,})"); // Similar assignment patterns + duplicateCode.pattern = std::regex(R"((\w+\s*=\s*[^;]+;[\s]*){3,})"); // Similar assignment patterns duplicateCode.suggestionGenerator = [this](const std::smatch& match, const std::string& filePath) { return createDuplicationRemovalSuggestion(match, filePath); }; @@ -50,13 +51,13 @@ bool TemplateRefactoringEngine::initialize() { return initialized_; } -AIRefactoringSuggestion TemplateRefactoringEngine::createExtractMethodSuggestion( - const std::smatch& match, const std::string& filePath) const { - +AIRefactoringSuggestion TemplateRefactoringEngine::createExtractMethodSuggestion(const std::smatch& match, + const std::string& filePath) const { AIRefactoringSuggestion suggestion; suggestion.id = "EXTRACT_METHOD_" + std::to_string(std::hash{}(match.str())); suggestion.title = "Extract method from long function"; - suggestion.description = "This function is quite long and could benefit from being broken down into smaller, more focused methods."; + suggestion.description = + "This function is quite long and could benefit from being broken down into smaller, more focused methods."; suggestion.filePath = filePath; suggestion.originalCode = match.str(); suggestion.refactoringType = "extract_method"; @@ -65,48 +66,51 @@ AIRefactoringSuggestion TemplateRefactoringEngine::createExtractMethodSuggestion suggestion.impact = AIRefactoringSuggestion::Impact::MODERATE; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::MODERATE; suggestion.estimatedTimeMinutes = 45; - - suggestion.benefits = { - "Improved readability and maintainability", - "Better testability of individual components", - "Reduced cognitive complexity", - "Enhanced code reusability" - }; - - suggestion.risks = { - "Potential over-fragmentation if taken too far", - "May introduce slight performance overhead from additional function calls" - }; - - suggestion.aiReasoning = "Large functions are harder to understand, test, and maintain. " - "Breaking them down into smaller, focused methods improves code quality."; - + + suggestion.benefits = {"Improved readability and maintainability", "Better testability of individual components", + "Reduced cognitive complexity", "Enhanced code reusability"}; + + suggestion.risks = {"Potential over-fragmentation if taken too far", + "May introduce slight performance overhead from additional function calls"}; + + suggestion.aiReasoning = + "Large functions are harder to understand, test, and maintain. " + "Breaking them down into smaller, focused methods improves code quality."; + // Generate suggested refactored code std::string functionName = match[1].str(); - suggestion.suggestedCode = "// Extracted methods from " + functionName + "\n" - "void " + functionName + "_step1() {\n" - " // TODO: Move first logical block here\n" - "}\n\n" - "void " + functionName + "_step2() {\n" - " // TODO: Move second logical block here\n" - "}\n\n" - "void " + functionName + "() {\n" - " " + functionName + "_step1();\n" - " " + functionName + "_step2();\n" - "}"; - - suggestion.alternativeApproaches = { - "Use RAII pattern to manage resource lifecycle", - "Apply Strategy pattern if the function has multiple behavioral variations", - "Consider Command pattern for complex operations" - }; - + suggestion.suggestedCode = "// Extracted methods from " + functionName + + "\n" + "void " + + functionName + + "_step1() {\n" + " // TODO: Move first logical block here\n" + "}\n\n" + "void " + + functionName + + "_step2() {\n" + " // TODO: Move second logical block here\n" + "}\n\n" + "void " + + functionName + + "() {\n" + " " + + functionName + + "_step1();\n" + " " + + functionName + + "_step2();\n" + "}"; + + suggestion.alternativeApproaches = {"Use RAII pattern to manage resource lifecycle", + "Apply Strategy pattern if the function has multiple behavioral variations", + "Consider Command pattern for complex operations"}; + return suggestion; } AIRefactoringSuggestion TemplateRefactoringEngine::createComplexityReductionSuggestion( const std::smatch& match, const std::string& filePath) const { - AIRefactoringSuggestion suggestion; suggestion.id = "REDUCE_COMPLEXITY_" + std::to_string(std::hash{}(match.str())); suggestion.title = "Reduce conditional complexity"; @@ -119,43 +123,35 @@ AIRefactoringSuggestion TemplateRefactoringEngine::createComplexityReductionSugg suggestion.impact = AIRefactoringSuggestion::Impact::MODERATE; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::MODERATE; suggestion.estimatedTimeMinutes = 30; - - suggestion.benefits = { - "Improved readability and comprehension", - "Reduced cyclomatic complexity", - "Easier to test individual conditions", - "Better error handling possibilities" - }; - - suggestion.risks = { - "May require restructuring of logic flow", - "Could introduce temporary variables" - }; - - suggestion.aiReasoning = "Nested conditionals increase cognitive load. Using early returns, " - "guard clauses, or extracting conditions into well-named functions improves clarity."; - - suggestion.suggestedCode = "// Refactored with early returns and guard clauses\n" - "if (!condition1) {\n" - " return handleInvalidCondition1();\n" - "}\n" - "if (!condition2) {\n" - " return handleInvalidCondition2();\n" - "}\n" - "// Main logic here with reduced nesting"; - - suggestion.alternativeApproaches = { - "Use polymorphism to replace conditional logic", - "Apply State pattern for complex state-dependent behavior", - "Consider using lookup tables for simple conditional mappings" - }; - + + suggestion.benefits = {"Improved readability and comprehension", "Reduced cyclomatic complexity", + "Easier to test individual conditions", "Better error handling possibilities"}; + + suggestion.risks = {"May require restructuring of logic flow", "Could introduce temporary variables"}; + + suggestion.aiReasoning = + "Nested conditionals increase cognitive load. Using early returns, " + "guard clauses, or extracting conditions into well-named functions improves clarity."; + + suggestion.suggestedCode = + "// Refactored with early returns and guard clauses\n" + "if (!condition1) {\n" + " return handleInvalidCondition1();\n" + "}\n" + "if (!condition2) {\n" + " return handleInvalidCondition2();\n" + "}\n" + "// Main logic here with reduced nesting"; + + suggestion.alternativeApproaches = {"Use polymorphism to replace conditional logic", + "Apply State pattern for complex state-dependent behavior", + "Consider using lookup tables for simple conditional mappings"}; + return suggestion; } AIRefactoringSuggestion TemplateRefactoringEngine::createDuplicationRemovalSuggestion( const std::smatch& match, const std::string& filePath) const { - AIRefactoringSuggestion suggestion; suggestion.id = "REMOVE_DUPLICATION_" + std::to_string(std::hash{}(match.str())); suggestion.title = "Extract common code to eliminate duplication"; @@ -168,134 +164,119 @@ AIRefactoringSuggestion TemplateRefactoringEngine::createDuplicationRemovalSugge suggestion.impact = AIRefactoringSuggestion::Impact::MODERATE; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::MODERATE; suggestion.estimatedTimeMinutes = 25; - - suggestion.benefits = { - "Reduced code duplication (DRY principle)", - "Easier maintenance - changes in one place", - "Smaller codebase and improved consistency", - "Reduced chance of bugs from inconsistent duplicates" - }; - - suggestion.risks = { - "May over-abstract if patterns aren't truly the same", - "Could introduce coupling between previously independent code" - }; - - suggestion.aiReasoning = "Code duplication leads to maintenance issues. Extracting common patterns " - "into reusable functions or templates improves code quality."; - - suggestion.suggestedCode = "// Extract common pattern into helper function\n" - "template\n" - "void setValueIfValid(T& target, const T& value, bool condition) {\n" - " if (condition) {\n" - " target = value;\n" - " }\n" - "}\n\n" - "// Use the helper function to replace duplicated code"; - - suggestion.alternativeApproaches = { - "Use template metaprogramming for type-safe abstractions", - "Apply Builder pattern for complex object construction", - "Consider using factory functions for similar creation logic" - }; - + + suggestion.benefits = {"Reduced code duplication (DRY principle)", "Easier maintenance - changes in one place", + "Smaller codebase and improved consistency", + "Reduced chance of bugs from inconsistent duplicates"}; + + suggestion.risks = {"May over-abstract if patterns aren't truly the same", + "Could introduce coupling between previously independent code"}; + + suggestion.aiReasoning = + "Code duplication leads to maintenance issues. Extracting common patterns " + "into reusable functions or templates improves code quality."; + + suggestion.suggestedCode = + "// Extract common pattern into helper function\n" + "template\n" + "void setValueIfValid(T& target, const T& value, bool condition) {\n" + " if (condition) {\n" + " target = value;\n" + " }\n" + "}\n\n" + "// Use the helper function to replace duplicated code"; + + suggestion.alternativeApproaches = {"Use template metaprogramming for type-safe abstractions", + "Apply Builder pattern for complex object construction", + "Consider using factory functions for similar creation logic"}; + return suggestion; } -std::vector TemplateRefactoringEngine::generateSuggestions( - const std::string& code, - const std::string& filePath, - const std::string& language) { - +std::vector TemplateRefactoringEngine::generateSuggestions(const std::string& code, + const std::string& filePath, + const std::string& language) { std::vector suggestions; - + for (const auto& pattern : patterns_) { std::sregex_iterator iter(code.begin(), code.end(), pattern.pattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { auto suggestion = pattern.suggestionGenerator(*iter, filePath); suggestions.push_back(suggestion); } } - + return suggestions; } std::vector TemplateRefactoringEngine::findExtractMethodOpportunities( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { std::vector suggestions; - + // Look for functions with high line count std::regex functionPattern(R"((\w+)\s*\([^)]*\)\s*\{([^}]*)\})"); std::sregex_iterator iter(code.begin(), code.end(), functionPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { std::string functionBody = (*iter)[2].str(); size_t lineCount = std::count(functionBody.begin(), functionBody.end(), '\n'); - - if (lineCount > 15) { // Threshold for "long" function + + if (lineCount > 15) { // Threshold for "long" function auto suggestion = createExtractMethodSuggestion(*iter, filePath); suggestion.confidenceScore = std::min(1.0, 0.5 + (lineCount - 15) * 0.02); suggestions.push_back(suggestion); } } - + return suggestions; } -std::vector TemplateRefactoringEngine::findComplexityReductions( - const std::string& code, - const std::string& filePath) { - +std::vector TemplateRefactoringEngine::findComplexityReductions(const std::string& code, + const std::string& filePath) { std::vector suggestions; - + // Look for nested conditionals std::regex nestedPattern(R"(if\s*\([^{]*\{[^}]*if\s*\([^{]*\{[^}]*if)"); std::sregex_iterator iter(code.begin(), code.end(), nestedPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { auto suggestion = createComplexityReductionSuggestion(*iter, filePath); suggestions.push_back(suggestion); } - + return suggestions; } -std::vector TemplateRefactoringEngine::findDuplicationRemoval( - const std::string& code, - const std::string& filePath) { - +std::vector TemplateRefactoringEngine::findDuplicationRemoval(const std::string& code, + const std::string& filePath) { std::vector suggestions; - + // Simple pattern for similar code blocks std::regex duplicatePattern(R"((\w+\s*=\s*[^;]+;[\s\n]*){3,})"); std::sregex_iterator iter(code.begin(), code.end(), duplicatePattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { auto suggestion = createDuplicationRemovalSuggestion(*iter, filePath); suggestions.push_back(suggestion); } - + return suggestions; } std::vector TemplateRefactoringEngine::findDesignPatternOpportunities( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { std::vector suggestions; - + // Look for switch statements that could benefit from polymorphism std::regex switchPattern(R"(switch\s*\([^{]*\{([^}]*case[^}]*){3,}\})"); std::sregex_iterator iter(code.begin(), code.end(), switchPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { AIRefactoringSuggestion suggestion; suggestion.id = "DESIGN_PATTERN_" + std::to_string(std::hash{}(iter->str())); @@ -309,39 +290,32 @@ std::vector TemplateRefactoringEngine::findDesignPatter suggestion.impact = AIRefactoringSuggestion::Impact::SIGNIFICANT; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::HARD; suggestion.estimatedTimeMinutes = 120; - - suggestion.benefits = { - "Improved extensibility - easy to add new cases", - "Better adherence to Open-Closed Principle", - "Eliminates need for large switch statements", - "More object-oriented design" - }; - - suggestion.risks = { - "Increased complexity for simple cases", - "May be overkill for small switch statements" - }; - - suggestion.aiReasoning = "Large switch statements often indicate missing polymorphism. " - "Using virtual functions or strategy pattern can improve design."; - + + suggestion.benefits = {"Improved extensibility - easy to add new cases", + "Better adherence to Open-Closed Principle", + "Eliminates need for large switch statements", "More object-oriented design"}; + + suggestion.risks = {"Increased complexity for simple cases", "May be overkill for small switch statements"}; + + suggestion.aiReasoning = + "Large switch statements often indicate missing polymorphism. " + "Using virtual functions or strategy pattern can improve design."; + suggestions.push_back(suggestion); } - + return suggestions; } std::vector TemplateRefactoringEngine::findPerformanceOptimizations( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { std::vector suggestions; - + // Look for potential string concatenation in loops std::regex stringConcatPattern(R"(for\s*\([^{]*\{[^}]*\+\s*=\s*[^}]*std::string)"); std::sregex_iterator iter(code.begin(), code.end(), stringConcatPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { AIRefactoringSuggestion suggestion; suggestion.id = "PERF_OPT_" + std::to_string(std::hash{}(iter->str())); @@ -355,36 +329,32 @@ std::vector TemplateRefactoringEngine::findPerformanceO suggestion.impact = AIRefactoringSuggestion::Impact::MODERATE; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::EASY; suggestion.estimatedTimeMinutes = 15; - - suggestion.benefits = { - "Better performance for large strings", - "Reduced memory allocations", - "More efficient for multiple concatenations" - }; - - suggestion.suggestedCode = "std::ostringstream oss;\n" - "for (...) {\n" - " oss << value;\n" - "}\n" - "std::string result = oss.str();"; - + + suggestion.benefits = {"Better performance for large strings", "Reduced memory allocations", + "More efficient for multiple concatenations"}; + + suggestion.suggestedCode = + "std::ostringstream oss;\n" + "for (...) {\n" + " oss << value;\n" + "}\n" + "std::string result = oss.str();"; + suggestions.push_back(suggestion); } - + return suggestions; } -std::vector TemplateRefactoringEngine::findSecurityImprovements( - const std::string& code, - const std::string& filePath) { - +std::vector TemplateRefactoringEngine::findSecurityImprovements(const std::string& code, + const std::string& filePath) { std::vector suggestions; - + // Look for potential buffer overflow issues std::regex bufferPattern(R"(char\s+\w+\[\d+\].*gets\s*\()"); std::sregex_iterator iter(code.begin(), code.end(), bufferPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { AIRefactoringSuggestion suggestion; suggestion.id = "SECURITY_" + std::to_string(std::hash{}(iter->str())); @@ -398,63 +368,50 @@ std::vector TemplateRefactoringEngine::findSecurityImpr suggestion.impact = AIRefactoringSuggestion::Impact::MAJOR; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::EASY; suggestion.estimatedTimeMinutes = 10; - - suggestion.benefits = { - "Eliminates buffer overflow vulnerability", - "Improves application security", - "Follows modern C++ best practices" - }; - - suggestion.risks = { - "Requires checking return value of safer function" - }; - - suggestion.suggestedCode = "std::string input;\n" - "std::getline(std::cin, input);"; - + + suggestion.benefits = {"Eliminates buffer overflow vulnerability", "Improves application security", + "Follows modern C++ best practices"}; + + suggestion.risks = {"Requires checking return value of safer function"}; + + suggestion.suggestedCode = + "std::string input;\n" + "std::getline(std::cin, input);"; + suggestions.push_back(suggestion); } - + return suggestions; } -std::string TemplateRefactoringEngine::applyRefactoring( - const std::string& code, - const AIRefactoringSuggestion& suggestion) { - +std::string TemplateRefactoringEngine::applyRefactoring(const std::string& code, + const AIRefactoringSuggestion& suggestion) { // Simple string replacement for basic refactoring std::string result = code; - + if (!suggestion.originalCode.empty() && !suggestion.suggestedCode.empty()) { size_t pos = result.find(suggestion.originalCode); if (pos != std::string::npos) { result.replace(pos, suggestion.originalCode.length(), suggestion.suggestedCode); } } - + return result; } -bool TemplateRefactoringEngine::validateRefactoring( - const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion) { - +bool TemplateRefactoringEngine::validateRefactoring(const std::string& originalCode, const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion) { // Basic validation - check that the refactored code is different and not empty - return !refactoredCode.empty() && - refactoredCode != originalCode && - refactoredCode.length() > 10; // Basic sanity check + return !refactoredCode.empty() && refactoredCode != originalCode && + refactoredCode.length() > 10; // Basic sanity check } // AIEnhancedRefactoringEngine implementation AIEnhancedRefactoringEngine::AIEnhancedRefactoringEngine() - : templateEngine_(std::make_unique()) { -} + : templateEngine_(std::make_unique()) {} AIEnhancedRefactoringEngine::AIEnhancedRefactoringEngine(std::unique_ptr provider) - : aiProvider_(std::move(provider)) - , templateEngine_(std::make_unique()) { -} + : aiProvider_(std::move(provider)), templateEngine_(std::make_unique()) {} void AIEnhancedRefactoringEngine::setAIProvider(std::unique_ptr provider) { aiProvider_ = std::move(provider); @@ -462,23 +419,22 @@ void AIEnhancedRefactoringEngine::setAIProvider(std::unique_ptrinitialize(); } - + if (aiProvider_) { result &= aiProvider_->initialize(); } - + initialized_ = result; return result; } bool AIEnhancedRefactoringEngine::isReady() const { - return initialized_ && - ((aiProvider_ && aiProvider_->isReady()) || - (fallbackToTemplate_ && templateEngine_ && templateEngine_->isReady())); + return initialized_ && ((aiProvider_ && aiProvider_->isReady()) || + (fallbackToTemplate_ && templateEngine_ && templateEngine_->isReady())); } void AIEnhancedRefactoringEngine::shutdown() { @@ -491,83 +447,73 @@ void AIEnhancedRefactoringEngine::shutdown() { initialized_ = false; } -std::string AIEnhancedRefactoringEngine::createRefactoringPrompt( - const std::string& code, - const std::string& refactoringType, - const std::string& context) const { - +std::string AIEnhancedRefactoringEngine::createRefactoringPrompt(const std::string& code, + const std::string& refactoringType, + const std::string& context) const { std::ostringstream prompt; prompt << "Analyze this C++ code and suggest refactoring improvements for: " << refactoringType << "\n\n"; prompt << "Code to analyze:\n" << code << "\n\n"; - + if (!context.empty()) { prompt << "Additional context: " << context << "\n\n"; } - + prompt << "Please provide:\n"; prompt << "1. Specific refactoring suggestions\n"; prompt << "2. Improved code examples\n"; prompt << "3. Benefits and potential risks\n"; prompt << "4. Estimated difficulty and time\n"; - + return prompt.str(); } -std::vector AIEnhancedRefactoringEngine::generateSuggestions( - const std::string& code, - const std::string& filePath, - const std::string& language) { - +std::vector AIEnhancedRefactoringEngine::generateSuggestions(const std::string& code, + const std::string& filePath, + const std::string& language) { std::vector suggestions; - + if (aiProvider_ && aiProvider_->isReady()) { std::string prompt = createRefactoringPrompt(code, "general refactoring", ""); - + CodeContext aiContext; aiContext.content = prompt; aiContext.language = language; aiContext.filePath = filePath; aiContext.cursorPosition = prompt.length(); - + auto completions = aiProvider_->generateCompletions(aiContext, prompt, 3); if (!completions.empty()) { auto aiSuggestions = processAIRefactoringResponse(completions, code, filePath, "general"); suggestions.insert(suggestions.end(), aiSuggestions.begin(), aiSuggestions.end()); } } - + // Fallback to template-based suggestions if (fallbackToTemplate_ && templateEngine_) { auto templateSuggestions = templateEngine_->generateSuggestions(code, filePath, language); suggestions.insert(suggestions.end(), templateSuggestions.begin(), templateSuggestions.end()); } - + return suggestions; } std::vector AIEnhancedRefactoringEngine::processAIRefactoringResponse( - const std::vector& completions, - const std::string& originalCode, - const std::string& filePath, + const std::vector& completions, const std::string& originalCode, const std::string& filePath, const std::string& refactoringType) const { - std::vector suggestions; - + for (const auto& completion : completions) { auto suggestion = parseRefactoringSuggestion(completion.label, originalCode, filePath, refactoringType); suggestion.confidenceScore = completion.score; suggestions.push_back(suggestion); } - + return suggestions; } AIRefactoringSuggestion AIEnhancedRefactoringEngine::parseRefactoringSuggestion( - const std::string& response, - const std::string& originalCode, - const std::string& filePath, + const std::string& response, const std::string& originalCode, const std::string& filePath, const std::string& refactoringType) const { - AIRefactoringSuggestion suggestion; suggestion.id = "AI_" + refactoringType + "_" + std::to_string(std::hash{}(response)); suggestion.title = "AI-suggested refactoring"; @@ -580,7 +526,7 @@ AIRefactoringSuggestion AIEnhancedRefactoringEngine::parseRefactoringSuggestion( suggestion.impact = AIRefactoringSuggestion::Impact::MODERATE; suggestion.difficulty = AIRefactoringSuggestion::Difficulty::MODERATE; suggestion.estimatedTimeMinutes = 30; - + // Extract suggested code if present in response std::regex codePattern(R"(```(?:cpp|c\+\+)?\s*(.*?)\s*```)"); std::smatch match; @@ -589,7 +535,7 @@ AIRefactoringSuggestion AIEnhancedRefactoringEngine::parseRefactoringSuggestion( } else { suggestion.suggestedCode = "// See AI reasoning for detailed suggestions"; } - + return suggestion; } @@ -597,35 +543,29 @@ AIRefactoringSuggestion AIEnhancedRefactoringEngine::parseRefactoringSuggestion( // For brevity, implementing key methods and using template engine as fallback std::vector AIEnhancedRefactoringEngine::findExtractMethodOpportunities( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { if (aiProvider_ && aiProvider_->isReady()) { // AI-enhanced analysis would go here // For now, fallback to template engine } - + if (fallbackToTemplate_ && templateEngine_) { return templateEngine_->findExtractMethodOpportunities(code, filePath); } - + return {}; } std::vector AIEnhancedRefactoringEngine::findComplexityReductions( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { if (fallbackToTemplate_ && templateEngine_) { return templateEngine_->findComplexityReductions(code, filePath); } return {}; } -std::vector AIEnhancedRefactoringEngine::findDuplicationRemoval( - const std::string& code, - const std::string& filePath) { - +std::vector AIEnhancedRefactoringEngine::findDuplicationRemoval(const std::string& code, + const std::string& filePath) { if (fallbackToTemplate_ && templateEngine_) { return templateEngine_->findDuplicationRemoval(code, filePath); } @@ -633,9 +573,7 @@ std::vector AIEnhancedRefactoringEngine::findDuplicatio } std::vector AIEnhancedRefactoringEngine::findDesignPatternOpportunities( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { if (fallbackToTemplate_ && templateEngine_) { return templateEngine_->findDesignPatternOpportunities(code, filePath); } @@ -643,9 +581,7 @@ std::vector AIEnhancedRefactoringEngine::findDesignPatt } std::vector AIEnhancedRefactoringEngine::findPerformanceOptimizations( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { if (fallbackToTemplate_ && templateEngine_) { return templateEngine_->findPerformanceOptimizations(code, filePath); } @@ -653,30 +589,24 @@ std::vector AIEnhancedRefactoringEngine::findPerformanc } std::vector AIEnhancedRefactoringEngine::findSecurityImprovements( - const std::string& code, - const std::string& filePath) { - + const std::string& code, const std::string& filePath) { if (fallbackToTemplate_ && templateEngine_) { return templateEngine_->findSecurityImprovements(code, filePath); } return {}; } -std::string AIEnhancedRefactoringEngine::applyRefactoring( - const std::string& code, - const AIRefactoringSuggestion& suggestion) { - +std::string AIEnhancedRefactoringEngine::applyRefactoring(const std::string& code, + const AIRefactoringSuggestion& suggestion) { if (templateEngine_) { return templateEngine_->applyRefactoring(code, suggestion); } return code; } -bool AIEnhancedRefactoringEngine::validateRefactoring( - const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion) { - +bool AIEnhancedRefactoringEngine::validateRefactoring(const std::string& originalCode, + const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion) { if (templateEngine_) { return templateEngine_->validateRefactoring(originalCode, refactoredCode, suggestion); } @@ -701,25 +631,21 @@ void RefactoringService::setEngine(std::unique_ptr engine) } } -std::vector RefactoringService::analyzeCode( - const std::string& code, - const std::string& filePath) { - +std::vector RefactoringService::analyzeCode(const std::string& code, + const std::string& filePath) { stats_.totalSuggestionsGenerated++; - + if (engine_) { return engine_->generateSuggestions(code, filePath); } - + return {}; } -std::vector RefactoringService::findAllOpportunities( - const std::string& code, - const std::string& filePath) { - +std::vector RefactoringService::findAllOpportunities(const std::string& code, + const std::string& filePath) { std::vector allSuggestions; - + if (engine_) { auto extractSuggestions = engine_->findExtractMethodOpportunities(code, filePath); auto complexitySuggestions = engine_->findComplexityReductions(code, filePath); @@ -727,7 +653,7 @@ std::vector RefactoringService::findAllOpportunities( auto designSuggestions = engine_->findDesignPatternOpportunities(code, filePath); auto perfSuggestions = engine_->findPerformanceOptimizations(code, filePath); auto securitySuggestions = engine_->findSecurityImprovements(code, filePath); - + allSuggestions.insert(allSuggestions.end(), extractSuggestions.begin(), extractSuggestions.end()); allSuggestions.insert(allSuggestions.end(), complexitySuggestions.begin(), complexitySuggestions.end()); allSuggestions.insert(allSuggestions.end(), duplicationSuggestions.begin(), duplicationSuggestions.end()); @@ -735,16 +661,13 @@ std::vector RefactoringService::findAllOpportunities( allSuggestions.insert(allSuggestions.end(), perfSuggestions.begin(), perfSuggestions.end()); allSuggestions.insert(allSuggestions.end(), securitySuggestions.begin(), securitySuggestions.end()); } - + stats_.totalSuggestionsGenerated += allSuggestions.size(); - + return allSuggestions; } -std::string RefactoringService::applyRefactoring( - const std::string& code, - const AIRefactoringSuggestion& suggestion) { - +std::string RefactoringService::applyRefactoring(const std::string& code, const AIRefactoringSuggestion& suggestion) { if (engine_) { auto result = engine_->applyRefactoring(code, suggestion); if (result != code) { @@ -755,19 +678,16 @@ std::string RefactoringService::applyRefactoring( } return result; } - + return code; } -bool RefactoringService::validateRefactoring( - const std::string& originalCode, - const std::string& refactoredCode, - const AIRefactoringSuggestion& suggestion) { - +bool RefactoringService::validateRefactoring(const std::string& originalCode, const std::string& refactoredCode, + const AIRefactoringSuggestion& suggestion) { if (engine_) { return engine_->validateRefactoring(originalCode, refactoredCode, suggestion); } - + return false; } @@ -783,4 +703,4 @@ void RefactoringService::resetStatistics() { stats_ = RefactoringStats{}; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/ai/bpe_tokenizer.cpp b/src/bolt/ai/bpe_tokenizer.cpp index a6595ef5..5d54e155 100644 --- a/src/bolt/ai/bpe_tokenizer.cpp +++ b/src/bolt/ai/bpe_tokenizer.cpp @@ -1,26 +1,26 @@ #include "bolt/ai/bpe_tokenizer.hpp" -#include + #include +#include #include namespace bolt { -bool BPETokenizer::loadVocabulary(const std::vector& tokens, - const std::vector& scores) { +bool BPETokenizer::loadVocabulary(const std::vector& tokens, const std::vector& scores) { if (tokens.empty()) { std::cerr << "BPETokenizer: Empty token list" << std::endl; return false; } - + vocab_size_ = tokens.size(); id_to_token_ = tokens; - + // Build reverse mapping token_to_id_.clear(); for (size_t i = 0; i < tokens.size(); i++) { token_to_id_[tokens[i]] = i; } - + // Store scores if provided if (!scores.empty()) { if (scores.size() != tokens.size()) { @@ -32,15 +32,15 @@ bool BPETokenizer::loadVocabulary(const std::vector& tokens, // Default scores (all equal) token_scores_.resize(tokens.size(), 0.0f); } - + // Identify special tokens identifySpecialTokens(); - + std::cout << "BPETokenizer: Loaded vocabulary with " << vocab_size_ << " tokens" << std::endl; std::cout << " BOS: " << bos_token_ << " (" << getTokenString(bos_token_) << ")" << std::endl; std::cout << " EOS: " << eos_token_ << " (" << getTokenString(eos_token_) << ")" << std::endl; std::cout << " PAD: " << pad_token_ << " (" << getTokenString(pad_token_) << ")" << std::endl; - + return true; } @@ -55,29 +55,33 @@ void BPETokenizer::identifySpecialTokens() { } return -1; }; - + // BOS token int bos = find_token({"<|startoftext|>", "", "", "", "[BOS]"}); - if (bos >= 0) bos_token_ = bos; - + if (bos >= 0) + bos_token_ = bos; + // EOS token int eos = find_token({"<|endoftext|>", "", "", "", "[EOS]"}); - if (eos >= 0) eos_token_ = eos; - + if (eos >= 0) + eos_token_ = eos; + // PAD token int pad = find_token({"<|pad|>", "", "", "[PAD]"}); - if (pad >= 0) pad_token_ = pad; - + if (pad >= 0) + pad_token_ = pad; + // UNK token int unk = find_token({"<|unknown|>", "", "", "[UNK]"}); - if (unk >= 0) unk_token_ = unk; + if (unk >= 0) + unk_token_ = unk; } std::vector BPETokenizer::encode(const std::string& text) const { if (text.empty()) { return std::vector(); } - + // Use greedy encoding (longest match first) return greedyEncode(text); } @@ -85,30 +89,30 @@ std::vector BPETokenizer::encode(const std::string& text) const { std::vector BPETokenizer::greedyEncode(const std::string& text) const { std::vector result; size_t pos = 0; - + while (pos < text.length()) { // Try to find the longest matching token int best_token = unk_token_; size_t best_len = 0; - + // Try different lengths, starting from the longest possible for (size_t len = std::min(text.length() - pos, size_t(256)); len > 0; len--) { std::string candidate = text.substr(pos, len); auto it = token_to_id_.find(candidate); - + if (it != token_to_id_.end()) { best_token = it->second; best_len = len; break; } } - + // If no match found, encode as single byte if (best_len == 0) { // Try single character std::string single_char = text.substr(pos, 1); auto it = token_to_id_.find(single_char); - + if (it != token_to_id_.end()) { best_token = it->second; best_len = 1; @@ -118,32 +122,32 @@ std::vector BPETokenizer::greedyEncode(const std::string& text) const { best_len = 1; } } - + result.push_back(best_token); pos += best_len; } - + return result; } std::string BPETokenizer::decode(const std::vector& tokens) const { std::string result; - + for (int token_id : tokens) { // Skip special tokens if (token_id == bos_token_ || token_id == eos_token_ || token_id == pad_token_) { continue; } - + // Check bounds if (token_id < 0 || token_id >= vocab_size_) { std::cerr << "BPETokenizer: Invalid token ID: " << token_id << std::endl; continue; } - + result += id_to_token_[token_id]; } - + return result; } @@ -164,12 +168,12 @@ int BPETokenizer::getTokenId(const std::string& token) const { std::vector BPETokenizer::splitToBytes(const std::string& text) const { std::vector result; - + for (unsigned char c : text) { result.push_back(std::string(1, c)); } - + return result; } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/direct_gguf_inference.cpp b/src/bolt/ai/direct_gguf_inference.cpp index 0bf42db9..06aaab82 100644 --- a/src/bolt/ai/direct_gguf_inference.cpp +++ b/src/bolt/ai/direct_gguf_inference.cpp @@ -1,14 +1,15 @@ #include "bolt/ai/direct_gguf_inference.hpp" -#include -#include -#include -#include + #include +#include +#include #include #include -#include -#include #include +#include +#include +#include +#include #ifdef LLAMA_AVAILABLE #include @@ -29,9 +30,7 @@ struct DirectGGUFInference::ModelData { std::string model_path; }; -DirectGGUFInference::DirectGGUFInference() - : model_data_(std::make_unique()) - , model_loaded_(false) { +DirectGGUFInference::DirectGGUFInference() : model_data_(std::make_unique()), model_loaded_(false) { std::cout << "๐Ÿ“ฆ DirectGGUFInference initialized" << std::endl; } @@ -119,10 +118,8 @@ bool DirectGGUFInference::load_model(const std::string& model_path) { #endif } -drawkern::AIInferenceResponse DirectGGUFInference::generate_text( - const std::string& prompt, - int max_tokens, - float temperature) { +drawkern::AIInferenceResponse DirectGGUFInference::generate_text(const std::string& prompt, int max_tokens, + float temperature) { auto start_time = std::chrono::high_resolution_clock::now(); drawkern::AIInferenceResponse response; @@ -151,9 +148,8 @@ drawkern::AIInferenceResponse DirectGGUFInference::generate_text( return response; } -drawkern::AIInferenceResponse DirectGGUFInference::chat( - const std::string& message, - const std::vector& conversation_history) { +drawkern::AIInferenceResponse DirectGGUFInference::chat(const std::string& message, + const std::vector& conversation_history) { std::string formatted_prompt = format_chat_prompt(message, conversation_history); return generate_text(formatted_prompt, 150, 0.7f); } @@ -183,14 +179,15 @@ std::string DirectGGUFInference::generate_internal(const std::string& prompt, in // Tokenize input using new API (vocab-based) std::vector tokens_in(system_prefix.size() + 8); - int n_in = llama_tokenize(vocab, system_prefix.c_str(), (int)system_prefix.size(), - tokens_in.data(), (int)tokens_in.size(), true, true); - if (n_in < 0) return get_smart_fallback(prompt); + int n_in = llama_tokenize(vocab, system_prefix.c_str(), static_cast(system_prefix.size()), tokens_in.data(), + static_cast(tokens_in.size()), true, true); + if (n_in < 0) + return get_smart_fallback(prompt); tokens_in.resize(n_in); // Create batch for input tokens - llama_batch batch = llama_batch_get_one(tokens_in.data(), (int)tokens_in.size()); - + llama_batch batch = llama_batch_get_one(tokens_in.data(), static_cast(tokens_in.size())); + // Decode input if (llama_decode(ctx, batch) != 0) { return get_smart_fallback(prompt); @@ -198,7 +195,7 @@ std::string DirectGGUFInference::generate_internal(const std::string& prompt, in // Sampling loop using new sampler API std::string out; - out.reserve((size_t)max_tokens * 4); + out.reserve(static_cast(max_tokens) * 4); [[maybe_unused]] int n_vocab = llama_vocab_n_tokens(vocab); llama_token eos_token = llama_vocab_eos(vocab); @@ -206,16 +203,18 @@ std::string DirectGGUFInference::generate_internal(const std::string& prompt, in for (int i = 0; i < max_tokens; ++i) { // Sample next token using the sampler chain llama_token id = llama_sampler_sample(model_data_->sampler, ctx, -1); - + // Accept the token llama_sampler_accept(model_data_->sampler, id); - if (id == eos_token) break; + if (id == eos_token) + break; // Convert token to text char buf[256]; int n = llama_token_to_piece(vocab, id, buf, sizeof(buf), 0, true); - if (n > 0) out.append(buf, n); + if (n > 0) + out.append(buf, n); // Feed back the token llama_batch batch_next = llama_batch_get_one(&id, 1); @@ -231,12 +230,13 @@ std::string DirectGGUFInference::generate_internal(const std::string& prompt, in #endif } -std::string DirectGGUFInference::format_chat_prompt(const std::string& message, const std::vector& history) { +std::string DirectGGUFInference::format_chat_prompt(const std::string& message, + const std::vector& history) { std::ostringstream prompt; prompt << "You are a helpful AI programming assistant specialized in C++ development. "; prompt << "Provide clear, concise answers focused on coding help, debugging, and best practices.\n\n"; - int history_limit = 6; // Last 3 exchanges + int history_limit = 6; // Last 3 exchanges int start_idx = std::max(0, static_cast(history.size()) - history_limit); for (int i = start_idx; i < static_cast(history.size()); i++) { @@ -264,8 +264,8 @@ bolt::drawkern::AIInferenceResponse DirectGGUFInference::get_fallback_response(c return response; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt // Implementation of helper methods as non-member functions in the bolt::ai namespace namespace bolt { @@ -275,24 +275,18 @@ std::string DirectGGUFInference::get_smart_fallback(const std::string& input) { std::string lower_input = input; std::transform(lower_input.begin(), lower_input.end(), lower_input.begin(), ::tolower); - if (lower_input.find("code") != std::string::npos || - lower_input.find("function") != std::string::npos || - lower_input.find("class") != std::string::npos || - lower_input.find("template") != std::string::npos || - lower_input.find("pointer") != std::string::npos || - lower_input.find("c++") != std::string::npos) { + if (lower_input.find("code") != std::string::npos || lower_input.find("function") != std::string::npos || + lower_input.find("class") != std::string::npos || lower_input.find("template") != std::string::npos || + lower_input.find("pointer") != std::string::npos || lower_input.find("c++") != std::string::npos) { return get_coding_help(input); } - if (lower_input.find("algorithm") != std::string::npos || - lower_input.find("sort") != std::string::npos || - lower_input.find("search") != std::string::npos || - lower_input.find("complexity") != std::string::npos) { + if (lower_input.find("algorithm") != std::string::npos || lower_input.find("sort") != std::string::npos || + lower_input.find("search") != std::string::npos || lower_input.find("complexity") != std::string::npos) { return get_algorithm_help(input); } - if (lower_input.find("config") != std::string::npos || - lower_input.find("setup") != std::string::npos || + if (lower_input.find("config") != std::string::npos || lower_input.find("setup") != std::string::npos || lower_input.find("install") != std::string::npos) { return "๐Ÿ”ง **Configuration Help**: To use real AI models:\n\n" "1. **Local GGUF Model**: Download a small model file and load it directly\n" @@ -301,9 +295,10 @@ std::string DirectGGUFInference::get_smart_fallback(const std::string& input) { "Currently using intelligent fallback responses. Load a GGUF model for full AI capabilities!"; } - return "I understand you're asking: \"" + input + "\"\n\n" + return "I understand you're asking: \"" + input + + "\"\n\n" "๐Ÿ’ก I'm currently using smart fallback responses. For full AI capabilities:\n" - "โ€ข Load a GGUF model file directly\n" + "โ€ข Load a GGUF model file directly\n" "โ€ข Start a local llama.cpp server\n" "โ€ข Configure an external AI provider\n\n" "I can still help with C++ coding questions, algorithms, and configuration guidance!"; @@ -313,8 +308,7 @@ std::string DirectGGUFInference::get_coding_help(const std::string& input) { std::string lower = input; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); - if (lower.find("smart pointer") != std::string::npos || - lower.find("unique_ptr") != std::string::npos || + if (lower.find("smart pointer") != std::string::npos || lower.find("unique_ptr") != std::string::npos || lower.find("shared_ptr") != std::string::npos) { return "๐Ÿ“˜ **Smart Pointers in Modern C++**\n\n" "**`std::unique_ptr`** - Exclusive ownership:\n" @@ -410,33 +404,28 @@ std::unique_ptr DirectGGUFFactory::create_from_file(const s std::unique_ptr DirectGGUFFactory::create_auto_detect() { auto models = find_available_models(); - + if (!models.empty()) { auto inference = std::make_unique(); if (inference->load_model(models[0])) { return inference; } } - + // Return a fallback instance that uses smart responses return std::make_unique(); } std::vector DirectGGUFFactory::find_available_models() { std::vector models; - + // Common locations to search for GGUF models - std::vector search_paths = { - "./models", - "../models", - "~/.local/share/bolt/models", - "/usr/local/share/bolt/models", - "~/.cache/huggingface/hub" - }; - + std::vector search_paths = {"./models", "../models", "~/.local/share/bolt/models", + "/usr/local/share/bolt/models", "~/.cache/huggingface/hub"}; + for (const auto& base_path : search_paths) { std::string expanded_path = base_path; - + // Expand ~ to home directory if (!expanded_path.empty() && expanded_path[0] == '~') { const char* home = std::getenv("HOME"); @@ -444,7 +433,7 @@ std::vector DirectGGUFFactory::find_available_models() { expanded_path = std::string(home) + expanded_path.substr(1); } } - + try { if (std::filesystem::exists(expanded_path)) { for (const auto& entry : std::filesystem::recursive_directory_iterator(expanded_path)) { @@ -460,7 +449,7 @@ std::vector DirectGGUFFactory::find_available_models() { // Ignore filesystem errors } } - + return models; } @@ -471,5 +460,5 @@ bool DirectGGUFFactory::download_test_model(const std::string& output_path) { return false; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/ggml.cpp b/src/bolt/ai/ggml.cpp index 07048b99..d79d7ab0 100644 --- a/src/bolt/ai/ggml.cpp +++ b/src/bolt/ai/ggml.cpp @@ -1,5 +1,6 @@ #include "bolt/ai/ggml.hpp" + #include namespace bolt { @@ -7,4 +8,4 @@ namespace bolt { // The implementation is now in the header file with the compatibility layer // This file can contain any additional implementation details if needed -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/ggml_loader.cpp b/src/bolt/ai/ggml_loader.cpp index 0f92f836..cee24db8 100644 --- a/src/bolt/ai/ggml_loader.cpp +++ b/src/bolt/ai/ggml_loader.cpp @@ -1,19 +1,18 @@ #include "bolt/ai/ggml_loader.hpp" -#include -#include + #include +#include +#include namespace bolt { GGMLLoader::GGMLLoader(const std::string& file_path) - : file_path_(file_path) - , loaded_(false) - , magic_(0) - , format_version_(GGMLFormatVersion::UNKNOWN) - , format_version_number_(0) - , tensor_data_offset_(0) -{ -} + : file_path_(file_path), + loaded_(false), + magic_(0), + format_version_(GGMLFormatVersion::UNKNOWN), + format_version_number_(0), + tensor_data_offset_(0) {} GGMLLoader::~GGMLLoader() { if (file_.is_open()) { @@ -28,32 +27,32 @@ bool GGMLLoader::load() { setError("Failed to open file: " + file_path_); return false; } - + // Detect format version if (!detectFormat()) { return false; } - + // Read header based on format if (!readHeader()) { return false; } - + // Read hyperparameters if (!readHyperparameters()) { return false; } - + // Read vocabulary (if present) if (!readVocabulary()) { return false; } - + // Read tensor information if (!readTensorInfo()) { return false; } - + loaded_ = true; return true; } @@ -64,32 +63,30 @@ bool GGMLLoader::detectFormat() { setError("Failed to read magic number"); return false; } - + // Detect format based on magic number if (magic_ == GGML_MAGIC_UNVERSIONED) { format_version_ = GGMLFormatVersion::UNVERSIONED; std::cout << "Detected GGML format: Unversioned" << std::endl; return true; - } - else if (magic_ == GGML_MAGIC_GGMF_V1) { + } else if (magic_ == GGML_MAGIC_GGMF_V1) { format_version_ = GGMLFormatVersion::GGMF_V1; - + // Read version number if (!readValue(format_version_number_)) { setError("Failed to read GGMF version number"); return false; } - + std::cout << "Detected GGML format: GGMF v" << format_version_number_ << std::endl; return true; - } - else if (magic_ == GGML_MAGIC_GGJT_V1) { + } else if (magic_ == GGML_MAGIC_GGJT_V1) { // GGJT format - read version number to determine v1/v2/v3 if (!readValue(format_version_number_)) { setError("Failed to read GGJT version number"); return false; } - + switch (format_version_number_) { case 1: format_version_ = GGMLFormatVersion::GGJT_V1; @@ -104,12 +101,11 @@ bool GGMLLoader::detectFormat() { setError("Unsupported GGJT version: " + std::to_string(format_version_number_)); return false; } - + std::cout << "Detected GGML format: GGJT v" << format_version_number_ << std::endl; return true; - } - else { - setError("Unknown magic number: 0x" + std::to_string(magic_) + + } else { + setError("Unknown magic number: 0x" + std::to_string(magic_) + ". This may not be a GGML format file, or it may be a GGUF file."); return false; } @@ -156,57 +152,55 @@ bool GGMLLoader::readHeaderGGJT() { bool GGMLLoader::readHyperparameters() { // Read common hyperparameters // Order: n_vocab, n_embd, n_mult, n_head, n_layer, n_rot, ftype - + if (!readValue(hparams_.n_vocab)) { setError("Failed to read n_vocab"); return false; } - + if (!readValue(hparams_.n_embd)) { setError("Failed to read n_embd"); return false; } - + if (!readValue(hparams_.n_mult)) { setError("Failed to read n_mult"); return false; } - + if (!readValue(hparams_.n_head)) { setError("Failed to read n_head"); return false; } - + if (!readValue(hparams_.n_layer)) { setError("Failed to read n_layer"); return false; } - + if (!readValue(hparams_.n_rot)) { setError("Failed to read n_rot"); return false; } - + if (!readValue(hparams_.ftype)) { setError("Failed to read ftype"); return false; } - + // Calculate derived parameters hparams_.n_ff = ((2 * (4 * hparams_.n_embd) / 3 + hparams_.n_mult - 1) / hparams_.n_mult) * hparams_.n_mult; - + // For older formats, n_head_kv defaults to n_head (no GQA) hparams_.n_head_kv = hparams_.n_head; - + // Read additional parameters for GGJT v2+ - if (format_version_ == GGMLFormatVersion::GGJT_V2 || - format_version_ == GGMLFormatVersion::GGJT_V3) { - + if (format_version_ == GGMLFormatVersion::GGJT_V2 || format_version_ == GGMLFormatVersion::GGJT_V3) { // GGJT v2+ may have additional hyperparameters // For now, we'll use defaults if not present // In a full implementation, we'd read these conditionally } - + std::cout << "Hyperparameters:" << std::endl; std::cout << " n_vocab: " << hparams_.n_vocab << std::endl; std::cout << " n_embd: " << hparams_.n_embd << std::endl; @@ -216,35 +210,33 @@ bool GGMLLoader::readHyperparameters() { std::cout << " n_rot: " << hparams_.n_rot << std::endl; std::cout << " ftype: " << hparams_.ftype << std::endl; std::cout << " n_ff: " << hparams_.n_ff << std::endl; - + return true; } bool GGMLLoader::readVocabulary() { // Read vocabulary tokens vocabulary_.reserve(hparams_.n_vocab); - + for (uint32_t i = 0; i < hparams_.n_vocab; i++) { GGMLVocabEntry entry; - + // Read token length uint32_t len; if (!readValue(len)) { setError("Failed to read token length at index " + std::to_string(i)); return false; } - + // Read token string if (!readString(entry.token, len)) { setError("Failed to read token at index " + std::to_string(i)); return false; } - + // Read token score (for GGJT formats) - if (format_version_ == GGMLFormatVersion::GGJT_V1 || - format_version_ == GGMLFormatVersion::GGJT_V2 || + if (format_version_ == GGMLFormatVersion::GGJT_V1 || format_version_ == GGMLFormatVersion::GGJT_V2 || format_version_ == GGMLFormatVersion::GGJT_V3) { - if (!readValue(entry.score)) { setError("Failed to read token score at index " + std::to_string(i)); return false; @@ -252,11 +244,11 @@ bool GGMLLoader::readVocabulary() { } else { entry.score = 0.0f; // Default for formats without scores } - + entry.token_type = 0; // Default: normal token vocabulary_.push_back(entry); } - + std::cout << "Loaded " << vocabulary_.size() << " vocabulary tokens" << std::endl; return true; } @@ -265,43 +257,43 @@ bool GGMLLoader::readTensorInfo() { // Read tensor information // In GGML formats, tensors are stored sequentially // Each tensor has: name_len, name, n_dims, dims[], type - + tensor_data_offset_ = file_.tellg(); - + while (file_.good() && !file_.eof()) { GGMLTensorInfo info; - + // Read tensor name length uint32_t name_len; if (!readValue(name_len)) { // End of tensor info section break; } - + // Sanity check on name length if (name_len == 0 || name_len > 1024) { // Likely reached tensor data section break; } - + // Read tensor name if (!readString(info.name, name_len)) { setError("Failed to read tensor name"); return false; } - + // Read number of dimensions if (!readValue(info.n_dims)) { setError("Failed to read tensor dimensions count for: " + info.name); return false; } - + // Sanity check on dimensions if (info.n_dims == 0 || info.n_dims > 4) { setError("Invalid number of dimensions for tensor: " + info.name); return false; } - + // Read dimensions info.dims.resize(info.n_dims); for (uint32_t d = 0; d < info.n_dims; d++) { @@ -310,7 +302,7 @@ bool GGMLLoader::readTensorInfo() { return false; } } - + // Read tensor type uint32_t type_raw; if (!readValue(type_raw)) { @@ -318,36 +310,35 @@ bool GGMLLoader::readTensorInfo() { return false; } info.type = static_cast(type_raw); - + // Store current position as tensor offset info.offset = file_.tellg(); - + // Calculate tensor size size_t n_elements = 1; for (uint32_t dim : info.dims) { n_elements *= dim; } - + // Calculate size based on type size_t type_size = ggml_type_size(info.type); size_t block_size = ggml_blck_size(info.type); info.size = (n_elements * type_size) / block_size; - + // Skip tensor data file_.seekg(info.size, std::ios::cur); - + tensors_[info.name] = info; - - std::cout << "Tensor: " << info.name - << " [" << info.n_dims << "D: "; + + std::cout << "Tensor: " << info.name << " [" << info.n_dims << "D: "; for (uint32_t d = 0; d < info.n_dims; d++) { std::cout << info.dims[d]; - if (d < info.n_dims - 1) std::cout << "x"; + if (d < info.n_dims - 1) + std::cout << "x"; } - std::cout << "] type=" << info.type - << " size=" << info.size << " bytes" << std::endl; + std::cout << "] type=" << info.type << " size=" << info.size << " bytes" << std::endl; } - + std::cout << "Loaded " << tensors_.size() << " tensors" << std::endl; return true; } @@ -378,16 +369,16 @@ ggml_tensor* GGMLLoader::loadTensor(ggml_context* ctx, const std::string& name) setError("Invalid GGML context"); return nullptr; } - + const GGMLTensorInfo* info = getTensorInfo(name); if (!info) { setError("Tensor not found: " + name); return nullptr; } - + // Create tensor in context ggml_tensor* tensor = nullptr; - + switch (info->n_dims) { case 1: tensor = ggml_new_tensor_1d(ctx, info->type, info->dims[0]); @@ -399,31 +390,30 @@ ggml_tensor* GGMLLoader::loadTensor(ggml_context* ctx, const std::string& name) tensor = ggml_new_tensor_3d(ctx, info->type, info->dims[0], info->dims[1], info->dims[2]); break; case 4: - tensor = ggml_new_tensor_4d(ctx, info->type, info->dims[0], info->dims[1], - info->dims[2], info->dims[3]); + tensor = ggml_new_tensor_4d(ctx, info->type, info->dims[0], info->dims[1], info->dims[2], info->dims[3]); break; default: setError("Unsupported number of dimensions: " + std::to_string(info->n_dims)); return nullptr; } - + if (!tensor) { setError("Failed to create tensor in context"); return nullptr; } - + // Set tensor name ggml_set_name(tensor, name.c_str()); - + // Read tensor data from file file_.seekg(info->offset); file_.read(reinterpret_cast(tensor->data), info->size); - + if (!file_.good()) { setError("Failed to read tensor data for: " + name); return nullptr; } - + return tensor; } @@ -432,19 +422,19 @@ bool GGMLLoader::readString(std::string& str, uint32_t len) { str.clear(); return true; } - + str.resize(len); file_.read(&str[0], len); - + if (!file_.good()) { setError("Failed to read string data"); return false; } - + return true; } -template +template bool GGMLLoader::readValue(T& value) { file_.read(reinterpret_cast(&value), sizeof(T)); if (!file_.good()) { @@ -460,22 +450,37 @@ void GGMLLoader::setError(const std::string& message) { ggml_type GGMLLoader::fileTypeToGGMLType(GGMLFileType ftype) const { switch (ftype) { - case GGMLFileType::F32: return GGML_TYPE_F32; - case GGMLFileType::F16: return GGML_TYPE_F16; - case GGMLFileType::Q4_0: return GGML_TYPE_Q4_0; - case GGMLFileType::Q4_1: return GGML_TYPE_Q4_1; - case GGMLFileType::Q5_0: return GGML_TYPE_Q5_0; - case GGMLFileType::Q5_1: return GGML_TYPE_Q5_1; - case GGMLFileType::Q8_0: return GGML_TYPE_Q8_0; - case GGMLFileType::Q8_1: return GGML_TYPE_Q8_1; - case GGMLFileType::Q2_K: return GGML_TYPE_Q2_K; - case GGMLFileType::Q3_K: return GGML_TYPE_Q3_K; - case GGMLFileType::Q4_K: return GGML_TYPE_Q4_K; - case GGMLFileType::Q5_K: return GGML_TYPE_Q5_K; - case GGMLFileType::Q6_K: return GGML_TYPE_Q6_K; - case GGMLFileType::Q8_K: return GGML_TYPE_Q8_K; - default: return GGML_TYPE_F32; + case GGMLFileType::F32: + return GGML_TYPE_F32; + case GGMLFileType::F16: + return GGML_TYPE_F16; + case GGMLFileType::Q4_0: + return GGML_TYPE_Q4_0; + case GGMLFileType::Q4_1: + return GGML_TYPE_Q4_1; + case GGMLFileType::Q5_0: + return GGML_TYPE_Q5_0; + case GGMLFileType::Q5_1: + return GGML_TYPE_Q5_1; + case GGMLFileType::Q8_0: + return GGML_TYPE_Q8_0; + case GGMLFileType::Q8_1: + return GGML_TYPE_Q8_1; + case GGMLFileType::Q2_K: + return GGML_TYPE_Q2_K; + case GGMLFileType::Q3_K: + return GGML_TYPE_Q3_K; + case GGMLFileType::Q4_K: + return GGML_TYPE_Q4_K; + case GGMLFileType::Q5_K: + return GGML_TYPE_Q5_K; + case GGMLFileType::Q6_K: + return GGML_TYPE_Q6_K; + case GGMLFileType::Q8_K: + return GGML_TYPE_Q8_K; + default: + return GGML_TYPE_F32; } } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/gguf_loader.cpp b/src/bolt/ai/gguf_loader.cpp index 59999ebb..bcb8a620 100644 --- a/src/bolt/ai/gguf_loader.cpp +++ b/src/bolt/ai/gguf_loader.cpp @@ -1,21 +1,21 @@ #include "bolt/ai/gguf_loader.hpp" -#include -#include + #include +#include +#include namespace bolt { GGUFLoader::GGUFLoader(const std::string& file_path) - : file_path_(file_path) - , loaded_(false) - , magic_(0) - , version_(0) - , tensor_count_(0) - , metadata_kv_count_(0) - , tensor_data_offset_(0) - , alignment_(32) // Default alignment -{ -} + : file_path_(file_path), + loaded_(false), + magic_(0), + version_(0), + tensor_count_(0), + metadata_kv_count_(0), + tensor_data_offset_(0), + alignment_(32) // Default alignment +{} GGUFLoader::~GGUFLoader() { if (file_.is_open()) { @@ -30,27 +30,27 @@ bool GGUFLoader::load() { setError("Failed to open file: " + file_path_); return false; } - + // Read header if (!readHeader()) { return false; } - + // Read metadata if (!readMetadata()) { return false; } - + // Get alignment from metadata if (hasMetadata("general.alignment")) { alignment_ = getMetadataInt("general.alignment", 32); } - + // Read tensor information if (!readTensorInfo()) { return false; } - + loaded_ = true; return true; } @@ -61,37 +61,35 @@ bool GGUFLoader::readHeader() { setError("Failed to read magic number"); return false; } - + if (magic_ != GGUF_MAGIC) { - setError("Invalid GGUF magic number. Expected 0x46554747, got 0x" + - std::to_string(magic_)); + setError("Invalid GGUF magic number. Expected 0x46554747, got 0x" + std::to_string(magic_)); return false; } - + // Read version if (!readValue(version_)) { setError("Failed to read version"); return false; } - + if (version_ != GGUF_VERSION_V2 && version_ != GGUF_VERSION_V3) { - setError("Unsupported GGUF version: " + std::to_string(version_) + - ". Supported versions: 2, 3"); + setError("Unsupported GGUF version: " + std::to_string(version_) + ". Supported versions: 2, 3"); return false; } - + // Read tensor count if (!readValue(tensor_count_)) { setError("Failed to read tensor count"); return false; } - + // Read metadata count if (!readValue(metadata_kv_count_)) { setError("Failed to read metadata count"); return false; } - + return true; } @@ -100,20 +98,20 @@ bool GGUFLoader::readString(std::string& str) { if (!readValue(len)) { return false; } - + if (len == 0) { str.clear(); return true; } - + str.resize(len); file_.read(&str[0], len); - + if (!file_.good()) { setError("Failed to read string data"); return false; } - + return true; } @@ -121,86 +119,100 @@ bool GGUFLoader::readMetadataValue(GGUFValueType type, MetadataValue& value) { switch (type) { case GGUFValueType::UINT8: { uint8_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::INT8: { int8_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::UINT16: { uint16_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::INT16: { int16_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::UINT32: { uint32_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::INT32: { int32_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::UINT64: { uint64_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::INT64: { int64_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::FLOAT32: { float v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::FLOAT64: { double v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = v; break; } case GGUFValueType::BOOL: { uint8_t v; - if (!readValue(v)) return false; + if (!readValue(v)) + return false; value = static_cast(v); break; } case GGUFValueType::STRING: { std::string v; - if (!readString(v)) return false; + if (!readString(v)) + return false; value = v; break; } case GGUFValueType::ARRAY: { // Read array type uint32_t array_type_raw; - if (!readValue(array_type_raw)) return false; + if (!readValue(array_type_raw)) + return false; GGUFValueType array_type = static_cast(array_type_raw); - + // Read array count uint64_t count; - if (!readValue(count)) return false; - + if (!readValue(count)) + return false; + // Read array elements based on type switch (array_type) { case GGUFValueType::STRING: { @@ -208,7 +220,8 @@ bool GGUFLoader::readMetadataValue(GGUFValueType type, MetadataValue& value) { arr.reserve(count); for (uint64_t i = 0; i < count; i++) { std::string elem; - if (!readString(elem)) return false; + if (!readString(elem)) + return false; arr.push_back(std::move(elem)); } value = arr; @@ -216,19 +229,22 @@ bool GGUFLoader::readMetadataValue(GGUFValueType type, MetadataValue& value) { } case GGUFValueType::FLOAT32: { std::vector arr; - if (!readArray(arr, count)) return false; + if (!readArray(arr, count)) + return false; value = arr; break; } case GGUFValueType::INT32: { std::vector arr; - if (!readArray(arr, count)) return false; + if (!readArray(arr, count)) + return false; value = arr; break; } case GGUFValueType::UINT32: { std::vector arr; - if (!readArray(arr, count)) return false; + if (!readArray(arr, count)) + return false; value = arr; break; } @@ -242,7 +258,7 @@ bool GGUFLoader::readMetadataValue(GGUFValueType type, MetadataValue& value) { setError("Unsupported metadata value type: " + std::to_string(static_cast(type))); return false; } - + return true; } @@ -254,7 +270,7 @@ bool GGUFLoader::readMetadata() { setError("Failed to read metadata key at index " + std::to_string(i)); return false; } - + // Read value type uint32_t type_raw; if (!readValue(type_raw)) { @@ -262,17 +278,17 @@ bool GGUFLoader::readMetadata() { return false; } GGUFValueType type = static_cast(type_raw); - + // Read value MetadataValue value; if (!readMetadataValue(type, value)) { setError("Failed to read metadata value for key: " + key); return false; } - + metadata_[key] = value; } - + return true; } @@ -280,19 +296,19 @@ bool GGUFLoader::readTensorInfo() { // Read tensor information for (uint64_t i = 0; i < tensor_count_; i++) { TensorInfo info; - + // Read tensor name if (!readString(info.name)) { setError("Failed to read tensor name at index " + std::to_string(i)); return false; } - + // Read number of dimensions if (!readValue(info.n_dims)) { setError("Failed to read tensor dimensions count for: " + info.name); return false; } - + // Read dimensions info.dims.resize(info.n_dims); for (uint32_t d = 0; d < info.n_dims; d++) { @@ -301,7 +317,7 @@ bool GGUFLoader::readTensorInfo() { return false; } } - + // Read tensor type uint32_t type_raw; if (!readValue(type_raw)) { @@ -309,26 +325,26 @@ bool GGUFLoader::readTensorInfo() { return false; } info.type = static_cast(type_raw); - + // Read tensor offset if (!readValue(info.offset)) { setError("Failed to read tensor offset for: " + info.name); return false; } - + // Calculate tensor size size_t n_elements = 1; for (uint64_t dim : info.dims) { n_elements *= dim; } info.size = n_elements * ggml_type_size(info.type) / ggml_blck_size(info.type); - + tensors_[info.name] = info; } - + // Calculate tensor data offset (current position, aligned) tensor_data_offset_ = alignOffset(file_.tellg()); - + return true; } @@ -422,9 +438,9 @@ ggml_tensor* GGUFLoader::loadTensor(ggml_context* ctx, const std::string& name) setError("Tensor not found: " + name); return nullptr; } - + const TensorInfo& info = it->second; - + // Create GGML tensor ggml_tensor* tensor = nullptr; switch (info.n_dims) { @@ -444,32 +460,32 @@ ggml_tensor* GGUFLoader::loadTensor(ggml_context* ctx, const std::string& name) setError("Unsupported tensor dimensionality: " + std::to_string(info.n_dims)); return nullptr; } - + if (!tensor) { setError("Failed to create GGML tensor for: " + name); return nullptr; } - + // Set tensor name ggml_set_name(tensor, name.c_str()); - + // Seek to tensor data uint64_t data_offset = tensor_data_offset_ + info.offset; file_.seekg(data_offset); - + if (!file_.good()) { setError("Failed to seek to tensor data for: " + name); return nullptr; } - + // Read tensor data file_.read(static_cast(tensor->data), info.size); - + if (!file_.good()) { setError("Failed to read tensor data for: " + name); return nullptr; } - + return tensor; } @@ -509,7 +525,7 @@ int GGUFLoader::getVocabSize() const { if (!tokens.empty()) { return tokens.size(); } - + // Fallback to metadata if (hasMetadata("rwkv.vocab_size")) { return getMetadataInt("rwkv.vocab_size"); @@ -521,7 +537,7 @@ std::string GGUFLoader::getArchitecture() const { return getMetadataString("general.architecture", "unknown"); } -template +template bool GGUFLoader::readValue(T& value) { file_.read(reinterpret_cast(&value), sizeof(T)); if (!file_.good()) { @@ -531,7 +547,7 @@ bool GGUFLoader::readValue(T& value) { return true; } -template +template bool GGUFLoader::readArray(std::vector& arr, uint64_t count) { arr.resize(count); file_.read(reinterpret_cast(arr.data()), count * sizeof(T)); @@ -551,4 +567,4 @@ uint64_t GGUFLoader::alignOffset(uint64_t offset) const { return (offset + alignment_ - 1) & ~(alignment_ - 1); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/gpu_acceleration.cpp b/src/bolt/ai/gpu_acceleration.cpp index 4fe5c174..296121d0 100644 --- a/src/bolt/ai/gpu_acceleration.cpp +++ b/src/bolt/ai/gpu_acceleration.cpp @@ -1,17 +1,18 @@ #include "bolt/ai/gpu_acceleration.hpp" -#include "bolt/core/logging.hpp" -#include + #include +#include #include #include +#include "bolt/core/logging.hpp" + namespace bolt { namespace ai { // GPUMemoryManager Implementation GPUMemoryManager::GPUMemoryManager(ggml_backend_t backend, ggml_backend_buffer_type_t bufferType) - : backend_(backend), bufferType_(bufferType), totalAllocated_(0), peakUsage_(0) { -} + : backend_(backend), bufferType_(bufferType), totalAllocated_(0), peakUsage_(0) {} GPUMemoryManager::~GPUMemoryManager() { // Cleanup all allocated buffers @@ -49,7 +50,7 @@ void GPUMemoryManager::deallocateBuffer(ggml_backend_buffer_t buffer) { size_t GPUMemoryManager::getTotalMemory() const { // This would need to be implemented per backend - return 0; // Placeholder + return 0; // Placeholder } size_t GPUMemoryManager::getUsedMemory() const { @@ -66,7 +67,7 @@ void GPUMemoryManager::optimizeMemoryUsage() { } void GPUMemoryManager::defragmentMemory() { - // Implementation would depend on specific backend capabilities + // Implementation would depend on specific backend capabilities BOLT_INFO("GPU Memory defragmentation requested"); } @@ -78,17 +79,17 @@ GPUAccelerationManager& GPUAccelerationManager::getInstance() { bool GPUAccelerationManager::initialize(const GPUConfig& config) { std::lock_guard lock(mutex_); - + if (initialized_) { BOLT_WARN("GPU Acceleration Manager already initialized"); return true; } - + config_ = config; - + // Detect available devices first availableDevices_ = detectAvailableDevices(); - + if (availableDevices_.empty()) { BOLT_ERROR("No GPU devices found, falling back to CPU"); if (!initializeCPU()) { @@ -98,7 +99,7 @@ bool GPUAccelerationManager::initialize(const GPUConfig& config) { } else { // Try to initialize preferred backend bool backendInitialized = false; - + // First try the preferred backend if (selectDevice(config_.preferredBackend, config_.preferredDeviceId)) { backendInitialized = true; @@ -111,76 +112,76 @@ bool GPUAccelerationManager::initialize(const GPUConfig& config) { } } } - + if (!backendInitialized) { BOLT_ERROR("Failed to initialize any GPU backend"); return false; } } - + // Initialize memory manager if (currentBackend_ && currentBufferType_) { memoryManager_ = std::make_unique(currentBackend_, currentBufferType_); } - + initialized_ = true; resetPerformanceStats(); - - BOLT_INFO("GPU Acceleration Manager initialized with backend: " + - backendTypeToString(currentBackendType_)); - + + BOLT_INFO("GPU Acceleration Manager initialized with backend: " + backendTypeToString(currentBackendType_)); + return true; } void GPUAccelerationManager::shutdown() { std::lock_guard lock(mutex_); - - if (!initialized_) return; - + + if (!initialized_) + return; + // Cleanup memory manager memoryManager_.reset(); - + // Cleanup backend if (currentBackend_) { ggml_backend_free(currentBackend_); currentBackend_ = nullptr; } - + currentBackendType_ = GPUBackendType::CPU; currentBufferType_ = nullptr; availableDevices_.clear(); - + initialized_ = false; - + BOLT_INFO("GPU Acceleration Manager shutdown complete"); } std::vector GPUAccelerationManager::detectAvailableDevices() { std::vector devices; - + // Detect CUDA devices auto cudaDevices = detectCUDADevices(); devices.insert(devices.end(), cudaDevices.begin(), cudaDevices.end()); - + // Detect OpenCL devices auto openclDevices = detectOpenCLDevices(); devices.insert(devices.end(), openclDevices.begin(), openclDevices.end()); - + // Detect Vulkan devices auto vulkanDevices = detectVulkanDevices(); devices.insert(devices.end(), vulkanDevices.begin(), vulkanDevices.end()); - + // Always add CPU as fallback GPUDeviceInfo cpuDevice; cpuDevice.deviceId = -1; cpuDevice.name = "CPU"; cpuDevice.description = "CPU Fallback"; - cpuDevice.totalMemory = 0; // System RAM + cpuDevice.totalMemory = 0; // System RAM cpuDevice.availableMemory = 0; cpuDevice.backendType = GPUBackendType::CPU; cpuDevice.isAvailable = true; devices.push_back(cpuDevice); - + return devices; } @@ -190,9 +191,9 @@ bool GPUAccelerationManager::selectDevice(GPUBackendType backendType, int device ggml_backend_free(currentBackend_); currentBackend_ = nullptr; } - + bool success = false; - + switch (backendType) { case GPUBackendType::CUDA: success = initializeCUDA(deviceId); @@ -210,23 +211,21 @@ bool GPUAccelerationManager::selectDevice(GPUBackendType backendType, int device BOLT_ERROR("Unknown GPU backend type"); return false; } - + if (success) { currentBackendType_ = backendType; - + // Find and store current device info for (const auto& device : availableDevices_) { - if (device.backendType == backendType && - (deviceId < 0 || device.deviceId == deviceId)) { + if (device.backendType == backendType && (deviceId < 0 || device.deviceId == deviceId)) { currentDevice_ = device; break; } } - - BOLT_INFO("Successfully selected " + backendTypeToString(backendType) + - " device " + std::to_string(deviceId)); + + BOLT_INFO("Successfully selected " + backendTypeToString(backendType) + " device " + std::to_string(deviceId)); } - + return success; } @@ -239,9 +238,9 @@ bool GPUAccelerationManager::loadModelToGPU(ggml_context* ctx, const std::vector BOLT_ERROR("GPU Acceleration Manager not initialized"); return false; } - + auto startTime = std::chrono::high_resolution_clock::now(); - + // Transfer each tensor to GPU size_t totalTransferred = 0; for (auto tensor : tensors) { @@ -251,40 +250,40 @@ bool GPUAccelerationManager::loadModelToGPU(ggml_context* ctx, const std::vector BOLT_WARN("Failed to transfer tensor to GPU"); } } - + auto endTime = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(endTime - startTime); - + performanceStats_.totalMemoryTransfers += totalTransferred; performanceStats_.totalTransferTime += duration.count() / 1000.0; - - BOLT_INFO("Transferred " + std::to_string(totalTransferred) + "/" + - std::to_string(tensors.size()) + " tensors to GPU in " + - std::to_string(duration.count()) + "ms"); - + + BOLT_INFO("Transferred " + std::to_string(totalTransferred) + "/" + std::to_string(tensors.size()) + + " tensors to GPU in " + std::to_string(duration.count()) + "ms"); + return totalTransferred > 0; } bool GPUAccelerationManager::transferTensorToGPU(ggml_tensor* tensor) { - if (!tensor || !memoryManager_) return false; - + if (!tensor || !memoryManager_) + return false; + // Calculate tensor size size_t tensorSize = ggml_nbytes(tensor); - + // Allocate GPU buffer auto buffer = memoryManager_->allocateBuffer(tensorSize); if (!buffer) { BOLT_ERROR("Failed to allocate GPU buffer for tensor"); return false; } - + // Initialize the tensor with the buffer if (ggml_backend_buffer_init_tensor(buffer, tensor) != GGML_STATUS_SUCCESS) { BOLT_ERROR("Failed to initialize tensor on GPU"); memoryManager_->deallocateBuffer(buffer); return false; } - + return true; } @@ -299,27 +298,26 @@ bool GPUAccelerationManager::computeGraph(ggml_cgraph* graph) { BOLT_ERROR("Cannot compute graph: GPU backend not properly initialized"); return false; } - + auto startTime = std::chrono::high_resolution_clock::now(); - + // Compute the graph using the current backend enum ggml_status result = ggml_backend_graph_compute(currentBackend_, graph); - + auto endTime = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(endTime - startTime); - + // Update performance stats performanceStats_.totalComputeOps++; performanceStats_.totalComputeTime += duration.count() / 1000000.0; - performanceStats_.averageOpsPerSecond = - performanceStats_.totalComputeOps / performanceStats_.totalComputeTime; - + performanceStats_.averageOpsPerSecond = performanceStats_.totalComputeOps / performanceStats_.totalComputeTime; + bool success = (result == GGML_STATUS_SUCCESS); - + if (!success) { BOLT_ERROR("Failed to compute graph on GPU"); } - + return success; } @@ -410,7 +408,7 @@ bool GPUAccelerationManager::initializeCPU() { // Device detection implementations std::vector GPUAccelerationManager::detectCUDADevices() { std::vector devices; - + #ifdef GGML_USE_CUDA int deviceCount = ggml_backend_cuda_get_device_count(); for (int i = 0; i < deviceCount; i++) { @@ -418,27 +416,27 @@ std::vector GPUAccelerationManager::detectCUDADevices() { device.deviceId = i; device.backendType = GPUBackendType::CUDA; device.isAvailable = true; - + char description[256]; ggml_backend_cuda_get_device_description(i, description, sizeof(description)); device.description = description; device.name = "CUDA Device " + std::to_string(i); - + size_t free, total; ggml_backend_cuda_get_device_memory(i, &free, &total); device.totalMemory = total; device.availableMemory = free; - + devices.push_back(device); } #endif - + return devices; } std::vector GPUAccelerationManager::detectOpenCLDevices() { std::vector devices; - + #ifdef GGML_USE_OPENCL // OpenCL device detection would require platform-specific code // For now, add a single OpenCL device if available @@ -449,18 +447,18 @@ std::vector GPUAccelerationManager::detectOpenCLDevices() { device.description = "OpenCL Compute Device"; device.backendType = GPUBackendType::OpenCL; device.isAvailable = true; - device.totalMemory = 0; // Would need OpenCL platform query + device.totalMemory = 0; // Would need OpenCL platform query device.availableMemory = 0; devices.push_back(device); } #endif - + return devices; } std::vector GPUAccelerationManager::detectVulkanDevices() { std::vector devices; - + #ifdef GGML_USE_VULKAN int deviceCount = ggml_backend_vk_get_device_count(); for (int i = 0; i < deviceCount; i++) { @@ -468,21 +466,21 @@ std::vector GPUAccelerationManager::detectVulkanDevices() { device.deviceId = i; device.backendType = GPUBackendType::Vulkan; device.isAvailable = true; - + char description[256]; ggml_backend_vk_get_device_description(i, description, sizeof(description)); device.description = description; device.name = "Vulkan Device " + std::to_string(i); - + size_t free, total; ggml_backend_vk_get_device_memory(i, &free, &total); device.totalMemory = total; device.availableMemory = free; - + devices.push_back(device); } #endif - + return devices; } @@ -494,7 +492,7 @@ bool GPUAccelerationManager::isBackendAvailable(GPUBackendType backendType) { #endif #ifdef GGML_USE_OPENCL case GPUBackendType::OpenCL: - return true; // Assume available if compiled with OpenCL + return true; // Assume available if compiled with OpenCL #endif #ifdef GGML_USE_VULKAN case GPUBackendType::Vulkan: @@ -509,19 +507,24 @@ bool GPUAccelerationManager::isBackendAvailable(GPUBackendType backendType) { std::string GPUAccelerationManager::backendTypeToString(GPUBackendType backendType) { switch (backendType) { - case GPUBackendType::CPU: return "CPU"; - case GPUBackendType::CUDA: return "CUDA"; - case GPUBackendType::OpenCL: return "OpenCL"; - case GPUBackendType::Vulkan: return "Vulkan"; - case GPUBackendType::Metal: return "Metal"; - default: return "Unknown"; + case GPUBackendType::CPU: + return "CPU"; + case GPUBackendType::CUDA: + return "CUDA"; + case GPUBackendType::OpenCL: + return "OpenCL"; + case GPUBackendType::Vulkan: + return "Vulkan"; + case GPUBackendType::Metal: + return "Metal"; + default: + return "Unknown"; } } // GPUAcceleratedModel Implementation GPUAcceleratedModel::GPUAcceleratedModel(const std::string& modelPath, const GPUConfig& config) : modelPath_(modelPath), gpuConfig_(config) { - // Initialize GPU acceleration if not already done auto& gpuManager = GPUAccelerationManager::getInstance(); if (!gpuManager.isInitialized()) { @@ -534,7 +537,7 @@ GPUAcceleratedModel::GPUAcceleratedModel(const std::string& modelPath, const GPU } else { gpuAccelerated_ = true; } - + if (threadCount_ == -1) { threadCount_ = std::thread::hardware_concurrency(); } @@ -546,46 +549,44 @@ GPUAcceleratedModel::~GPUAcceleratedModel() { bool GPUAcceleratedModel::loadModel(const std::string& path) { modelPath_ = path; - + // Initialize GGML context struct ggml_init_params params = { - .mem_size = maxContextSize_ * sizeof(float) * 4, - .mem_buffer = nullptr, - .no_alloc = false - }; - - context_ = std::unique_ptr(ggml_init(params), ggml_free); + .mem_size = maxContextSize_ * sizeof(float) * 4, .mem_buffer = nullptr, .no_alloc = false}; + + context_ = std::unique_ptr(ggml_init(params), ggml_free); if (!context_) { BOLT_ERROR("Failed to initialize GGML context"); return false; } - + // Load model weights (simplified implementation) bool success = loadModelWeights(); if (success) { modelLoaded_ = true; - + // Setup GPU context if available if (gpuAccelerated_ && gpuOffloadingEnabled_) { setupGPUContext(); } - + BOLT_INFO("Model loaded successfully from: " + path); } - + return success; } bool GPUAcceleratedModel::setupGPUContext() { - if (!gpuAccelerated_) return false; - + if (!gpuAccelerated_) + return false; + auto& gpuManager = GPUAccelerationManager::getInstance(); - + // Transfer model tensors to GPU if (!modelTensors_.empty()) { return gpuManager.loadModelToGPU(context_.get(), modelTensors_); } - + return true; } @@ -601,24 +602,24 @@ std::string GPUAcceleratedModel::generate(const std::string& prompt, size_t maxT BOLT_ERROR("Model not loaded"); return ""; } - + // Tokenize input auto tokens = tokenize(prompt); - + // Run inference auto outputTensor = runInference(tokens); if (!outputTensor) { BOLT_ERROR("Inference failed"); return ""; } - + // Generate response tokens (simplified) std::vector responseTokens; for (size_t i = 0; i < maxTokens; i++) { // In a real implementation, this would sample from the model output responseTokens.push_back(static_cast('A') + (i % 26)); } - + return detokenize(responseTokens); } @@ -627,30 +628,31 @@ std::vector GPUAcceleratedModel::generateEmbedding(const std::string& inp BOLT_ERROR("Model not loaded"); return {}; } - + // Simplified embedding generation - std::vector embedding(768); // Standard embedding size + std::vector embedding(768); // Standard embedding size std::fill(embedding.begin(), embedding.end(), 0.1f); - + return embedding; } ggml_tensor* GPUAcceleratedModel::runInference(const std::vector& tokens) { - if (!context_ || tokens.empty()) return nullptr; - + if (!context_ || tokens.empty()) + return nullptr; + // Create computation graph ggml_cgraph* graph = ggml_new_graph(context_.get()); - + // Create input tensor (simplified) auto inputTensor = ggml_new_tensor_1d(context_.get(), GGML_TYPE_I32, tokens.size()); - + // Copy token data memcpy(inputTensor->data, tokens.data(), tokens.size() * sizeof(int)); - + // Build forward pass (simplified) auto outputTensor = ggml_new_tensor_1d(context_.get(), GGML_TYPE_F32, tokens.size()); ggml_build_forward_expand(graph, outputTensor); - + // Compute graph if (gpuAccelerated_) { auto& gpuManager = GPUAccelerationManager::getInstance(); @@ -663,7 +665,7 @@ ggml_tensor* GPUAcceleratedModel::runInference(const std::vector& tokens) { ggml_cplan plan = ggml_graph_plan(graph, threadCount_, nullptr); ggml_graph_compute(graph, &plan); } - + return outputTensor; } @@ -694,5 +696,5 @@ GPUAccelerationManager::PerformanceStats GPUAcceleratedModel::getPerformanceStat return {}; } -} // namespace ai -} // namespace bolt \ No newline at end of file +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/llama_completion_provider.cpp b/src/bolt/ai/llama_completion_provider.cpp index 6a830858..621850c0 100644 --- a/src/bolt/ai/llama_completion_provider.cpp +++ b/src/bolt/ai/llama_completion_provider.cpp @@ -1,32 +1,27 @@ #include "bolt/ai/llama_completion_provider.hpp" -#include + #include #include +#include namespace bolt { -LlamaCompletionProvider::LlamaCompletionProvider() - : inference_engine_(std::make_unique()) { -} +LlamaCompletionProvider::LlamaCompletionProvider() : inference_engine_(std::make_unique()) {} LlamaCompletionProvider::LlamaCompletionProvider(const std::string& model_path) - : inference_engine_(std::make_unique()) - , model_path_(model_path) { -} + : inference_engine_(std::make_unique()), model_path_(model_path) {} bool LlamaCompletionProvider::initialize() { if (initialized_) { return true; } - + // If no model path specified, try to auto-detect if (model_path_.empty()) { std::vector search_paths = { - "./models/codellama.gguf", - "./models/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf", - "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf" - }; - + "./models/codellama.gguf", "./models/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf", + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"}; + for (const auto& path : search_paths) { if (std::filesystem::exists(path)) { model_path_ = path; @@ -34,11 +29,11 @@ bool LlamaCompletionProvider::initialize() { } } } - + if (model_path_.empty()) { return false; } - + bool loaded = inference_engine_->load_model(model_path_); initialized_ = loaded; return loaded; @@ -49,17 +44,15 @@ void LlamaCompletionProvider::shutdown() { inference_engine_.reset(); } -std::string LlamaCompletionProvider::buildCompletionPrompt( - const CodeContext& context, - const std::string& prefix) const { - +std::string LlamaCompletionProvider::buildCompletionPrompt(const CodeContext& context, + const std::string& prefix) const { std::ostringstream prompt; - + // System instruction prompt << "You are an expert C++ code completion assistant. "; prompt << "Complete the following code with the most appropriate continuation. "; prompt << "Only provide the completion, no explanations.\n\n"; - + // Context information if (!context.filePath.empty()) { prompt << "File: " << context.filePath << "\n"; @@ -67,40 +60,33 @@ std::string LlamaCompletionProvider::buildCompletionPrompt( if (!context.language.empty()) { prompt << "Language: " << context.language << "\n"; } - + // Code context prompt << "```cpp\n"; - + // Get surrounding context (up to 500 chars before cursor) - size_t context_start = (context.cursorPosition > 500) - ? context.cursorPosition - 500 - : 0; - - std::string before_cursor = context.content.substr( - context_start, - context.cursorPosition - context_start - ); - + size_t context_start = (context.cursorPosition > 500) ? context.cursorPosition - 500 : 0; + + std::string before_cursor = context.content.substr(context_start, context.cursorPosition - context_start); + prompt << before_cursor; - prompt << "โ–ˆ"; // Cursor marker + prompt << "โ–ˆ"; // Cursor marker prompt << "\n```\n\n"; prompt << "Complete the code at the cursor (โ–ˆ):\n"; - + return prompt.str(); } -std::vector LlamaCompletionProvider::parseCompletionResponse( - const std::string& response) const { - +std::vector LlamaCompletionProvider::parseCompletionResponse(const std::string& response) const { std::vector items; - + if (response.empty()) { return items; } - + // Clean up the response std::string cleaned = response; - + // Remove markdown code blocks if present size_t code_start = cleaned.find("```"); if (code_start != std::string::npos) { @@ -114,26 +100,24 @@ std::vector LlamaCompletionProvider::parseCompletionResponse( } } } - + // Trim whitespace cleaned.erase(0, cleaned.find_first_not_of(" \t\n\r")); cleaned.erase(cleaned.find_last_not_of(" \t\n\r") + 1); - + // Create completion item CompletionItem item; item.label = cleaned; item.detail = "AI Suggestion (llama.cpp)"; item.kind = inferCompletionKind(cleaned); item.insertText = cleaned; - + items.push_back(item); - + return items; } -CompletionItemKind LlamaCompletionProvider::inferCompletionKind( - const std::string& completion) const { - +CompletionItemKind LlamaCompletionProvider::inferCompletionKind(const std::string& completion) const { // Simple heuristics to determine completion type if (completion.find("class ") != std::string::npos) { return CompletionItemKind::CLASS; @@ -141,36 +125,33 @@ CompletionItemKind LlamaCompletionProvider::inferCompletionKind( if (completion.find("struct ") != std::string::npos) { return CompletionItemKind::STRUCT; } - if (completion.find("(") != std::string::npos && - completion.find(")") != std::string::npos) { + if (completion.find("(") != std::string::npos && completion.find(")") != std::string::npos) { return CompletionItemKind::FUNCTION; } if (completion.find("::") != std::string::npos) { return CompletionItemKind::METHOD; } - + return CompletionItemKind::TEXT; } -std::vector LlamaCompletionProvider::generateCompletions( - const CodeContext& context, - const std::string& prefix, - size_t maxSuggestions) { - +std::vector LlamaCompletionProvider::generateCompletions(const CodeContext& context, + const std::string& prefix, + size_t maxSuggestions) { if (!isReady()) { return {}; } - + // Build the prompt std::string prompt = buildCompletionPrompt(context, prefix); - + // Generate completion using the inference engine auto response = inference_engine_->generate_text(prompt, max_tokens_, temperature_); - + if (!response.success) { return {}; } - + // Parse and return completions return parseCompletionResponse(response.response); } @@ -182,4 +163,4 @@ std::string LlamaCompletionProvider::getModelInfo() const { return inference_engine_->get_model_info(); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/model_loader.cpp b/src/bolt/ai/model_loader.cpp index a06886e7..17cdbd4f 100644 --- a/src/bolt/ai/model_loader.cpp +++ b/src/bolt/ai/model_loader.cpp @@ -1,50 +1,45 @@ #include "bolt/ai/model_loader.hpp" -#include + #include +#include namespace bolt { ModelLoader::ModelLoader(const std::string& file_path) - : file_path_(file_path) - , loaded_(false) - , format_type_(FormatType::UNKNOWN) -{ -} + : file_path_(file_path), loaded_(false), format_type_(FormatType::UNKNOWN) {} -ModelLoader::~ModelLoader() { -} +ModelLoader::~ModelLoader() {} bool ModelLoader::load() { // Detect format format_type_ = detectFormat(); - + if (format_type_ == FormatType::UNKNOWN) { setError("Unable to detect file format for: " + file_path_); return false; } - + // Load using appropriate loader bool success = false; - + if (format_type_ == FormatType::GGUF) { std::cout << "Loading as GGUF format..." << std::endl; gguf_loader_ = std::make_unique(file_path_); success = gguf_loader_->load(); - + if (!success) { setError("GGUF loader failed: " + gguf_loader_->getError()); } - } - else if (format_type_ == FormatType::GGML_LEGACY) { + } else if (format_type_ == FormatType::GGML_LEGACY) { std::cout << "Loading as legacy GGML format..." << std::endl; ggml_loader_ = std::make_unique(file_path_); success = ggml_loader_->load(); - + if (!success) { setError("GGML loader failed: " + ggml_loader_->getError()); } } - + loaded_ = success; return success; } @@ -55,30 +50,28 @@ ModelLoader::FormatType ModelLoader::detectFormat() { setError("Failed to open file: " + file_path_); return FormatType::UNKNOWN; } - + // Read magic number uint32_t magic; file.read(reinterpret_cast(&magic), sizeof(magic)); - + if (!file.good()) { setError("Failed to read magic number"); return FormatType::UNKNOWN; } - + file.close(); - + // Check for GGUF magic if (magic == GGUF_MAGIC) { return FormatType::GGUF; } - + // Check for legacy GGML formats - if (magic == GGML_MAGIC_UNVERSIONED || - magic == GGML_MAGIC_GGMF_V1 || - magic == GGML_MAGIC_GGJT_V1) { + if (magic == GGML_MAGIC_UNVERSIONED || magic == GGML_MAGIC_GGMF_V1 || magic == GGML_MAGIC_GGJT_V1) { return FormatType::GGML_LEGACY; } - + return FormatType::UNKNOWN; } @@ -89,7 +82,7 @@ std::string ModelLoader::getFormatName() const { return "GGUF v" + std::to_string(gguf_loader_->getVersion()); } return "GGUF"; - + case FormatType::GGML_LEGACY: if (ggml_loader_) { switch (ggml_loader_->getFormatVersion()) { @@ -108,7 +101,7 @@ std::string ModelLoader::getFormatName() const { } } return "GGML Legacy"; - + default: return "Unknown"; } @@ -117,8 +110,7 @@ std::string ModelLoader::getFormatName() const { std::string ModelLoader::getArchitecture() const { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->getArchitecture(); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->getArchitecture(); } return "unknown"; @@ -127,8 +119,7 @@ std::string ModelLoader::getArchitecture() const { uint32_t ModelLoader::getVocabSize() const { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->getVocabSize(); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->getHyperparameters().n_vocab; } return 0; @@ -137,8 +128,7 @@ uint32_t ModelLoader::getVocabSize() const { uint32_t ModelLoader::getEmbeddingDim() const { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->getEmbedDim(); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->getHyperparameters().n_embd; } return 0; @@ -147,8 +137,7 @@ uint32_t ModelLoader::getEmbeddingDim() const { uint32_t ModelLoader::getNumLayers() const { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->getNumLayers(); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->getHyperparameters().n_layer; } return 0; @@ -158,8 +147,7 @@ uint32_t ModelLoader::getNumHeads() const { if (format_type_ == FormatType::GGUF && gguf_loader_) { // GGUF stores this in metadata return gguf_loader_->getMetadataInt(getArchitecture() + ".attention.head_count", 0); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->getHyperparameters().n_head; } return 0; @@ -168,8 +156,7 @@ uint32_t ModelLoader::getNumHeads() const { bool ModelLoader::hasTensor(const std::string& name) const { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->hasTensor(name); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->hasTensor(name); } return false; @@ -178,8 +165,7 @@ bool ModelLoader::hasTensor(const std::string& name) const { std::vector ModelLoader::getTensorNames() const { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->getTensorNames(); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->getTensorNames(); } return {}; @@ -188,8 +174,7 @@ std::vector ModelLoader::getTensorNames() const { ggml_tensor* ModelLoader::loadTensor(ggml_context* ctx, const std::string& name) { if (format_type_ == FormatType::GGUF && gguf_loader_) { return gguf_loader_->loadTensor(ctx, name); - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { return ggml_loader_->loadTensor(ctx, name); } return nullptr; @@ -200,7 +185,7 @@ void ModelLoader::printModelInfo() const { std::cout << "Model not loaded" << std::endl; return; } - + std::cout << "\n=== Model Information ===" << std::endl; std::cout << "File: " << file_path_ << std::endl; std::cout << "Format: " << getFormatName() << std::endl; @@ -209,26 +194,25 @@ void ModelLoader::printModelInfo() const { std::cout << "Embedding Dimension: " << getEmbeddingDim() << std::endl; std::cout << "Number of Layers: " << getNumLayers() << std::endl; std::cout << "Number of Heads: " << getNumHeads() << std::endl; - + auto tensor_names = getTensorNames(); std::cout << "Number of Tensors: " << tensor_names.size() << std::endl; - + if (format_type_ == FormatType::GGUF && gguf_loader_) { std::cout << "GGUF Version: " << gguf_loader_->getVersion() << std::endl; std::cout << "Metadata Count: " << gguf_loader_->getMetadataCount() << std::endl; - } - else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { + } else if (format_type_ == FormatType::GGML_LEGACY && ggml_loader_) { const auto& hparams = ggml_loader_->getHyperparameters(); std::cout << "File Type (Quantization): " << hparams.ftype << std::endl; std::cout << "Feedforward Dimension: " << hparams.n_ff << std::endl; std::cout << "Rotary Dimension: " << hparams.n_rot << std::endl; - + const auto& vocab = ggml_loader_->getVocabulary(); if (!vocab.empty()) { std::cout << "Vocabulary loaded: " << vocab.size() << " tokens" << std::endl; } } - + std::cout << "========================\n" << std::endl; } @@ -237,4 +221,4 @@ void ModelLoader::setError(const std::string& message) { std::cerr << "Model Loader Error: " << message << std::endl; } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/rag_router.cpp b/src/bolt/ai/rag_router.cpp index c790fa5a..4a99db8e 100644 --- a/src/bolt/ai/rag_router.cpp +++ b/src/bolt/ai/rag_router.cpp @@ -1,8 +1,9 @@ #include "bolt/ai/rag_router.hpp" + #include #include -#include #include +#include namespace bolt { namespace ai { @@ -12,8 +13,7 @@ RAGRouter::RAGRouter() { initializePatterns(); } -RAGRouter::RAGRouter(const RAGRouterConfig& config) - : config_(config) { +RAGRouter::RAGRouter(const RAGRouterConfig& config) : config_(config) { initializeKeywords(); initializePatterns(); } @@ -24,119 +24,96 @@ void RAGRouter::setConfig(const RAGRouterConfig& config) { void RAGRouter::initializeKeywords() { // Narrative keywords - narrative_keywords_ = { - "story", "narrative", "plot", "character", "protagonist", "antagonist", - "hero", "villain", "dialogue", "scene", "chapter", "tale", "legend", - "adventure", "quest", "journey", "epic", "saga", "chronicle", - "happened", "told", "said", "spoke", "whispered", "shouted", - "castle", "kingdom", "forest", "dungeon", "tower", "village", - "sword", "magic", "spell", "potion", "artifact", "treasure", - "battle", "fight", "encounter", "meeting", "discovery" - }; - + narrative_keywords_ = {"story", "narrative", "plot", "character", "protagonist", "antagonist", "hero", + "villain", "dialogue", "scene", "chapter", "tale", "legend", "adventure", + "quest", "journey", "epic", "saga", "chronicle", "happened", "told", + "said", "spoke", "whispered", "shouted", "castle", "kingdom", "forest", + "dungeon", "tower", "village", "sword", "magic", "spell", "potion", + "artifact", "treasure", "battle", "fight", "encounter", "meeting", "discovery"}; + // Temporal keywords - temporal_keywords_ = { - "trend", "forecast", "predict", "prediction", "time series", "temporal", - "historical", "history", "pattern", "anomaly", "outlier", "spike", - "correlation", "causation", "regression", "seasonality", - "price", "stock", "market", "trading", "volume", "volatility", - "sensor", "metric", "measurement", "reading", "data point", - "yesterday", "today", "tomorrow", "last week", "next month", - "hour", "day", "week", "month", "year", "quarter", - "increase", "decrease", "rise", "fall", "growth", "decline", - "over time", "through time", "across time", "time period", - "from", "to", "between", "during", "since", "until" - }; - + temporal_keywords_ = {"trend", "forecast", "predict", "prediction", "time series", "temporal", + "historical", "history", "pattern", "anomaly", "outlier", "spike", + "correlation", "causation", "regression", "seasonality", "price", "stock", + "market", "trading", "volume", "volatility", "sensor", "metric", + "measurement", "reading", "data point", "yesterday", "today", "tomorrow", + "last week", "next month", "hour", "day", "week", "month", + "year", "quarter", "increase", "decrease", "rise", "fall", + "growth", "decline", "over time", "through time", "across time", "time period", + "from", "to", "between", "during", "since", "until"}; + // Character-related keywords - character_keywords_ = { - "character", "person", "people", "hero", "villain", "protagonist", - "antagonist", "ally", "enemy", "friend", "companion", "npc" - }; - + character_keywords_ = {"character", "person", "people", "hero", "villain", "protagonist", + "antagonist", "ally", "enemy", "friend", "companion", "npc"}; + // Event-related keywords - event_keywords_ = { - "event", "happened", "occurred", "took place", "incident", - "encounter", "meeting", "battle", "discovery", "revelation" - }; - + event_keywords_ = {"event", "happened", "occurred", "took place", "incident", + "encounter", "meeting", "battle", "discovery", "revelation"}; + // Metric-related keywords - metric_keywords_ = { - "metric", "measurement", "value", "number", "statistic", - "price", "cost", "rate", "percentage", "ratio" - }; - + metric_keywords_ = {"metric", "measurement", "value", "number", "statistic", + "price", "cost", "rate", "percentage", "ratio"}; + // Trend-related keywords - trend_keywords_ = { - "trend", "pattern", "tendency", "direction", "movement", - "increase", "decrease", "growth", "decline", "change" - }; + trend_keywords_ = {"trend", "pattern", "tendency", "direction", "movement", + "increase", "decrease", "growth", "decline", "change"}; } void RAGRouter::initializePatterns() { // Temporal patterns temporal_patterns_ = { // Date patterns: YYYY, YYYY-MM-DD, MM/DD/YYYY - std::regex(R"(\b\d{4}\b)"), - std::regex(R"(\b\d{4}-\d{2}-\d{2}\b)"), + std::regex(R"(\b\d{4}\b)"), std::regex(R"(\b\d{4}-\d{2}-\d{2}\b)"), std::regex(R"(\b\d{1,2}/\d{1,2}/\d{2,4}\b)"), - + // Time patterns: HH:MM, HH:MM:SS std::regex(R"(\b\d{1,2}:\d{2}(:\d{2})?\b)"), - + // Relative time: "last X", "next X", "past X" - std::regex(R"(\b(last|next|past|previous|following)\s+(hour|day|week|month|year|quarter)s?\b)", - std::regex::icase), - + std::regex(R"(\b(last|next|past|previous|following)\s+(hour|day|week|month|year|quarter)s?\b)", + std::regex::icase), + // Time ranges: "from X to Y", "between X and Y" std::regex(R"(\b(from|between)\b.*\b(to|and)\b)", std::regex::icase), - + // Temporal quantifiers: "X days ago", "in X hours" - std::regex(R"(\b\d+\s+(hour|day|week|month|year)s?\s+(ago|later)\b)", - std::regex::icase) - }; - + std::regex(R"(\b\d+\s+(hour|day|week|month|year)s?\s+(ago|later)\b)", std::regex::icase)}; + // Narrative patterns - narrative_patterns_ = { - // Story-related phrases - std::regex(R"(\b(tell me|what happened|the story|once upon)\b)", - std::regex::icase), - - // Character mentions: "the hero", "a character named" - std::regex(R"(\b(the|a)\s+(hero|villain|character|protagonist)\b)", - std::regex::icase), - - // Location mentions: "in the castle", "at the village" - std::regex(R"(\b(in|at|near|by)\s+the\s+\w+\b)", std::regex::icase), - - // Action phrases: "when X did Y", "after X happened" - std::regex(R"(\b(when|after|before)\s+\w+\s+(did|happened|occurred)\b)", - std::regex::icase) - }; + narrative_patterns_ = {// Story-related phrases + std::regex(R"(\b(tell me|what happened|the story|once upon)\b)", std::regex::icase), + + // Character mentions: "the hero", "a character named" + std::regex(R"(\b(the|a)\s+(hero|villain|character|protagonist)\b)", std::regex::icase), + + // Location mentions: "in the castle", "at the village" + std::regex(R"(\b(in|at|near|by)\s+the\s+\w+\b)", std::regex::icase), + + // Action phrases: "when X did Y", "after X happened" + std::regex(R"(\b(when|after|before)\s+\w+\s+(did|happened|occurred)\b)", std::regex::icase)}; } QueryFeatures RAGRouter::extractFeatures(const std::string& query) const { QueryFeatures features; - + // Convert to lowercase for case-insensitive matching std::string lower_query = query; - std::transform(lower_query.begin(), lower_query.end(), - lower_query.begin(), ::tolower); - + std::transform(lower_query.begin(), lower_query.end(), lower_query.begin(), ::tolower); + // Count narrative keywords for (const auto& keyword : narrative_keywords_) { if (lower_query.find(keyword) != std::string::npos) { features.narrative_keyword_count++; } } - + // Count temporal keywords for (const auto& keyword : temporal_keywords_) { if (lower_query.find(keyword) != std::string::npos) { features.temporal_keyword_count++; } } - + // Check for temporal patterns for (const auto& pattern : temporal_patterns_) { if (std::regex_search(query, pattern)) { @@ -144,7 +121,7 @@ QueryFeatures RAGRouter::extractFeatures(const std::string& query) const { break; } } - + // Check for narrative patterns for (const auto& pattern : narrative_patterns_) { if (std::regex_search(query, pattern)) { @@ -152,18 +129,14 @@ QueryFeatures RAGRouter::extractFeatures(const std::string& query) const { break; } } - + // Check for question patterns - if (query.find('?') != std::string::npos || - lower_query.find("what") == 0 || - lower_query.find("when") == 0 || - lower_query.find("where") == 0 || - lower_query.find("who") == 0 || - lower_query.find("how") == 0 || + if (query.find('?') != std::string::npos || lower_query.find("what") == 0 || lower_query.find("when") == 0 || + lower_query.find("where") == 0 || lower_query.find("who") == 0 || lower_query.find("how") == 0 || lower_query.find("why") == 0) { features.has_question_pattern = true; } - + // Check contextual features for (const auto& keyword : character_keywords_) { if (lower_query.find(keyword) != std::string::npos) { @@ -171,42 +144,42 @@ QueryFeatures RAGRouter::extractFeatures(const std::string& query) const { break; } } - + for (const auto& keyword : event_keywords_) { if (lower_query.find(keyword) != std::string::npos) { features.mentions_events = true; break; } } - + for (const auto& keyword : metric_keywords_) { if (lower_query.find(keyword) != std::string::npos) { features.mentions_metrics = true; break; } } - + for (const auto& keyword : trend_keywords_) { if (lower_query.find(keyword) != std::string::npos) { features.mentions_trends = true; break; } } - + return features; } float RAGRouter::calculateNarrativeScore(const QueryFeatures& features) const { float score = 0.0f; - + // Keyword contribution score += features.narrative_keyword_count * config_.keyword_weight; - + // Pattern contribution if (features.has_narrative_pattern) { score += 2.0f * config_.pattern_weight; } - + // Context contribution if (features.mentions_characters) { score += 1.5f * config_.context_weight; @@ -214,24 +187,24 @@ float RAGRouter::calculateNarrativeScore(const QueryFeatures& features) const { if (features.mentions_events) { score += 1.5f * config_.context_weight; } - + // Normalize to 0-1 range (using sigmoid-like function) features.narrative_score = 1.0f / (1.0f + std::exp(-score / 5.0f)); - + return features.narrative_score; } float RAGRouter::calculateTemporalScore(const QueryFeatures& features) const { float score = 0.0f; - + // Keyword contribution score += features.temporal_keyword_count * config_.keyword_weight; - + // Pattern contribution (time patterns are strong indicators) if (features.has_time_pattern) { score += 3.0f * config_.pattern_weight; } - + // Context contribution if (features.mentions_metrics) { score += 1.5f * config_.context_weight; @@ -239,43 +212,39 @@ float RAGRouter::calculateTemporalScore(const QueryFeatures& features) const { if (features.mentions_trends) { score += 1.5f * config_.context_weight; } - + // Normalize to 0-1 range features.temporal_score = 1.0f / (1.0f + std::exp(-score / 5.0f)); - + return features.temporal_score; } float RAGRouter::calculateGeneralScore(const QueryFeatures& features) const { // General score is inversely related to specialized scores float specialized_score = std::max(features.narrative_score, features.temporal_score); - + // If the query doesn't strongly match any specialized category, // it's likely a general query features.general_score = 1.0f - specialized_score; - + // Boost general score if it's a question without specific context - if (features.has_question_pattern && - features.narrative_keyword_count == 0 && + if (features.has_question_pattern && features.narrative_keyword_count == 0 && features.temporal_keyword_count == 0) { features.general_score = std::min(1.0f, features.general_score + 0.3f); } - + return features.general_score; } -RAGQueryType RAGRouter::classifyFromScores(float narrative_score, - float temporal_score, - float general_score) const { +RAGQueryType RAGRouter::classifyFromScores(float narrative_score, float temporal_score, float general_score) const { // Check for hybrid queries - if (narrative_score >= config_.hybrid_threshold && - temporal_score >= config_.hybrid_threshold) { + if (narrative_score >= config_.hybrid_threshold && temporal_score >= config_.hybrid_threshold) { return RAGQueryType::HYBRID; } - + // Find the highest score float max_score = std::max({narrative_score, temporal_score, general_score}); - + // Classify based on highest score and thresholds if (narrative_score == max_score && narrative_score >= config_.narrative_threshold) { return RAGQueryType::NARRATIVE; @@ -287,10 +256,9 @@ RAGQueryType RAGRouter::classifyFromScores(float narrative_score, } } -float RAGRouter::calculateConfidence(const QueryFeatures& features, - RAGQueryType type) const { +float RAGRouter::calculateConfidence(const QueryFeatures& features, RAGQueryType type) const { float confidence = 0.0f; - + switch (type) { case RAGQueryType::NARRATIVE: confidence = features.narrative_score; @@ -299,7 +267,7 @@ float RAGRouter::calculateConfidence(const QueryFeatures& features, confidence = std::min(1.0f, confidence + 0.1f); } break; - + case RAGQueryType::TEMPORAL: confidence = features.temporal_score; // Time patterns are strong indicators @@ -307,31 +275,28 @@ float RAGRouter::calculateConfidence(const QueryFeatures& features, confidence = std::min(1.0f, confidence + 0.15f); } break; - + case RAGQueryType::HYBRID: // Confidence for hybrid is the average of both scores confidence = (features.narrative_score + features.temporal_score) / 2.0f; break; - + case RAGQueryType::GENERAL_SEMANTIC: confidence = features.general_score; break; } - + return confidence; } -std::string RAGRouter::generateReasoning(const QueryFeatures& features, - RAGQueryType type) const { +std::string RAGRouter::generateReasoning(const QueryFeatures& features, RAGQueryType type) const { std::ostringstream reasoning; - + switch (type) { case RAGQueryType::NARRATIVE: - reasoning << "Query classified as NARRATIVE (score: " - << std::fixed << std::setprecision(2) - << features.narrative_score << "). "; - reasoning << "Found " << features.narrative_keyword_count - << " narrative keywords. "; + reasoning << "Query classified as NARRATIVE (score: " << std::fixed << std::setprecision(2) + << features.narrative_score << "). "; + reasoning << "Found " << features.narrative_keyword_count << " narrative keywords. "; if (features.has_narrative_pattern) { reasoning << "Detected narrative patterns. "; } @@ -342,12 +307,10 @@ std::string RAGRouter::generateReasoning(const QueryFeatures& features, reasoning << "Mentions events. "; } break; - + case RAGQueryType::TEMPORAL: - reasoning << "Query classified as TEMPORAL (score: " - << features.temporal_score << "). "; - reasoning << "Found " << features.temporal_keyword_count - << " temporal keywords. "; + reasoning << "Query classified as TEMPORAL (score: " << features.temporal_score << "). "; + reasoning << "Found " << features.temporal_keyword_count << " temporal keywords. "; if (features.has_time_pattern) { reasoning << "Detected time patterns. "; } @@ -358,82 +321,74 @@ std::string RAGRouter::generateReasoning(const QueryFeatures& features, reasoning << "Mentions trends. "; } break; - + case RAGQueryType::HYBRID: reasoning << "Query classified as HYBRID. "; reasoning << "Narrative score: " << features.narrative_score << ", "; reasoning << "Temporal score: " << features.temporal_score << ". "; reasoning << "Requires multiple backends."; break; - + case RAGQueryType::GENERAL_SEMANTIC: - reasoning << "Query classified as GENERAL (score: " - << features.general_score << "). "; + reasoning << "Query classified as GENERAL (score: " << features.general_score << "). "; reasoning << "No strong specialized indicators found."; break; } - + return reasoning.str(); } -std::vector> RAGRouter::generateAlternatives( - const QueryFeatures& features, - RAGQueryType primary_type) const { - +std::vector> RAGRouter::generateAlternatives(const QueryFeatures& features, + RAGQueryType primary_type) const { std::vector> alternatives; - + // Add all backends with their scores (except the primary) if (primary_type != RAGQueryType::NARRATIVE && features.narrative_score > 0.2f) { alternatives.emplace_back("NarrativeRAG", features.narrative_score); } - + if (primary_type != RAGQueryType::TEMPORAL && features.temporal_score > 0.2f) { alternatives.emplace_back("TemporalRAG", features.temporal_score); } - + if (primary_type != RAGQueryType::GENERAL_SEMANTIC && features.general_score > 0.2f) { alternatives.emplace_back("GeneralRAG", features.general_score); } - + // Sort by score (descending) std::sort(alternatives.begin(), alternatives.end(), - [](const auto& a, const auto& b) { - return a.second > b.second; - }); - + [](const auto& a, const auto& b) { return a.second > b.second; }); + return alternatives; } RoutingDecision RAGRouter::route(const std::string& query) const { RoutingDecision decision; - + // Extract features decision.features = extractFeatures(query); - + // Calculate scores calculateNarrativeScore(decision.features); calculateTemporalScore(decision.features); calculateGeneralScore(decision.features); - + // Classify query - decision.query_type = classifyFromScores( - decision.features.narrative_score, - decision.features.temporal_score, - decision.features.general_score - ); - + decision.query_type = classifyFromScores(decision.features.narrative_score, decision.features.temporal_score, + decision.features.general_score); + // Set backend name decision.backend_name = backendNameFromType(decision.query_type); - + // Calculate confidence decision.confidence = calculateConfidence(decision.features, decision.query_type); - + // Generate reasoning decision.reasoning = generateReasoning(decision.features, decision.query_type); - + // Generate alternatives decision.alternatives = generateAlternatives(decision.features, decision.query_type); - + return decision; } @@ -447,30 +402,36 @@ QueryFeatures RAGRouter::analyzeQuery(const std::string& query) const { RAGQueryType RAGRouter::classifyQuery(const std::string& query) const { auto features = analyzeQuery(query); - return classifyFromScores( - features.narrative_score, - features.temporal_score, - features.general_score - ); + return classifyFromScores(features.narrative_score, features.temporal_score, features.general_score); } std::string RAGRouter::queryTypeToString(RAGQueryType type) const { switch (type) { - case RAGQueryType::NARRATIVE: return "NARRATIVE"; - case RAGQueryType::TEMPORAL: return "TEMPORAL"; - case RAGQueryType::HYBRID: return "HYBRID"; - case RAGQueryType::GENERAL_SEMANTIC: return "GENERAL_SEMANTIC"; - default: return "UNKNOWN"; + case RAGQueryType::NARRATIVE: + return "NARRATIVE"; + case RAGQueryType::TEMPORAL: + return "TEMPORAL"; + case RAGQueryType::HYBRID: + return "HYBRID"; + case RAGQueryType::GENERAL_SEMANTIC: + return "GENERAL_SEMANTIC"; + default: + return "UNKNOWN"; } } std::string RAGRouter::backendNameFromType(RAGQueryType type) const { switch (type) { - case RAGQueryType::NARRATIVE: return "NarrativeRAG"; - case RAGQueryType::TEMPORAL: return "TemporalRAG"; - case RAGQueryType::HYBRID: return "Hybrid (Multiple Backends)"; - case RAGQueryType::GENERAL_SEMANTIC: return "GeneralRAG"; - default: return "Unknown"; + case RAGQueryType::NARRATIVE: + return "NarrativeRAG"; + case RAGQueryType::TEMPORAL: + return "TemporalRAG"; + case RAGQueryType::HYBRID: + return "Hybrid (Multiple Backends)"; + case RAGQueryType::GENERAL_SEMANTIC: + return "GeneralRAG"; + default: + return "Unknown"; } } @@ -487,5 +448,5 @@ void RAGRouter::clearCustomKeywords() { initializeKeywords(); } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/rwkv_improved.cpp b/src/bolt/ai/rwkv_improved.cpp index 8607e1b9..a6408a2e 100644 --- a/src/bolt/ai/rwkv_improved.cpp +++ b/src/bolt/ai/rwkv_improved.cpp @@ -1,47 +1,49 @@ -#include "bolt/ai/rwkv_wrapper.hpp" -#include #include -#include -#include -#include #include +#include +#include +#include +#include + +#include "bolt/ai/rwkv_wrapper.hpp" namespace bolt { // Improved RWKV implementation with proper token generation -std::string RWKVWrapper::generateImproved(const std::string& prompt, size_t max_tokens, float temperature, float top_p) { +std::string RWKVWrapper::generateImproved(const std::string& prompt, size_t max_tokens, float temperature, + float top_p) { if (!model_loaded_) { throw std::runtime_error("RWKV model not initialized"); } - + // Tokenize the prompt auto prompt_tokens = tokenize(prompt); - + std::vector generated_tokens = prompt_tokens; std::random_device rd; std::mt19937 gen(rd()); - + // Generation loop for (size_t i = 0; i < max_tokens; ++i) { // Create input tensor from current tokens auto* input = ggml_new_tensor_1d(context_->get(), GGML_TYPE_I32, generated_tokens.size()); memcpy(input->data, generated_tokens.data(), generated_tokens.size() * sizeof(int)); - + // Forward pass through the model auto* logits = forwardWithLogits(input); - + // Sample next token int next_token = sampleToken(logits, temperature, top_p, gen); - + // Check for end of sequence - if (next_token == 0 || next_token == 2) { // EOS or padding + if (next_token == 0 || next_token == 2) { // EOS or padding break; } - + generated_tokens.push_back(next_token); } - + // Remove prompt tokens and return only generated text std::vector output_tokens(generated_tokens.begin() + prompt_tokens.size(), generated_tokens.end()); return detokenize(output_tokens); @@ -51,95 +53,95 @@ ggml_tensor* RWKVWrapper::forwardWithLogits(ggml_tensor* input) { if (!model_loaded_) { throw std::runtime_error("RWKV model not initialized"); } - + // Build computation graph for RWKV forward pass auto* gf = ggml_new_graph_custom(context_->get(), GGML_DEFAULT_GRAPH_SIZE, true); - + // Get input embeddings auto* current = getEmbeddings(input); - + // Process through RWKV layers for (int i = 0; i < n_layers_; i++) { current = rwkvLayer(current, i); } - + // Final layer norm current = layerNorm(current); - + // Project to vocabulary logits auto* logits = projectToVocab(current); - + // Build and compute graph ggml_build_forward_expand(gf, logits); - + // In a real implementation, we would compute the graph here // ggml_graph_compute_with_ctx(context_->get(), gf, n_threads_); - + return logits; } ggml_tensor* RWKVWrapper::rwkvLayer(ggml_tensor* x, int layer_idx) { // RWKV layer: Time-mixing + Channel-mixing - + // Time-mixing (attention-like mechanism) auto* tm_out = timeMixing(x, layer_idx); - + // Residual connection auto* x1 = ggml_add(context_->get(), x, tm_out); - + // Layer norm x1 = layerNorm(x1); - + // Channel-mixing (FFN-like mechanism) auto* cm_out = channelMixing(x1, layer_idx); - + // Residual connection auto* output = ggml_add(context_->get(), x1, cm_out); - + return output; } ggml_tensor* RWKVWrapper::timeMixing(ggml_tensor* x, int layer_idx) { std::string prefix = "layer_" + std::to_string(layer_idx) + "_"; - + // Get time-mixing weights auto* w_k = weights_[prefix + "tm_w_k"]; auto* w_v = weights_[prefix + "tm_w_v"]; auto* w_r = weights_[prefix + "tm_w_r"]; - + // Compute key, value, receptance auto* k = ggml_mul_mat(context_->get(), w_k, x); auto* v = ggml_mul_mat(context_->get(), w_v, x); auto* r = ggml_mul_mat(context_->get(), w_r, x); - + // Apply sigmoid to receptance r = ggml_sigmoid(context_->get(), r); - + // Compute attention-like output auto* kv = ggml_mul(context_->get(), k, v); auto* output = ggml_mul(context_->get(), r, kv); - + return output; } ggml_tensor* RWKVWrapper::channelMixing(ggml_tensor* x, int layer_idx) { std::string prefix = "layer_" + std::to_string(layer_idx) + "_"; - + // Get channel-mixing weights auto* w_k = weights_[prefix + "cm_w_k"]; auto* w_v = weights_[prefix + "cm_w_v"]; - + // Compute key and value auto* k = ggml_mul_mat(context_->get(), w_k, x); auto* v = ggml_mul_mat(context_->get(), w_v, x); - + // Apply ReLU squared to key k = ggml_relu(context_->get(), k); k = ggml_sqr(context_->get(), k); - + // Compute output auto* output = ggml_mul(context_->get(), k, v); - + return output; } @@ -149,27 +151,27 @@ ggml_tensor* RWKVWrapper::layerNorm(ggml_tensor* x) { auto* centered = ggml_sub(context_->get(), x, mean); auto* variance = ggml_sqr(context_->get(), centered); auto* var_mean = ggml_mean(context_->get(), variance); - + // Add epsilon for numerical stability float eps = 1e-5f; auto* eps_tensor = ggml_new_f32(context_->get(), eps); auto* var_eps = ggml_add(context_->get(), var_mean, eps_tensor); auto* std_dev = ggml_sqrt(context_->get(), var_eps); - + // Normalize auto* normalized = ggml_div(context_->get(), centered, std_dev); - + return normalized; } ggml_tensor* RWKVWrapper::getEmbeddings(ggml_tensor* tokens) { // Get token embeddings auto* emb_weight = weights_["emb_weight"]; - + // In a real implementation, this would do proper embedding lookup // For now, return a placeholder auto* embeddings = ggml_mul_mat(context_->get(), emb_weight, tokens); - + return embeddings; } @@ -177,54 +179,56 @@ ggml_tensor* RWKVWrapper::projectToVocab(ggml_tensor* x) { // Project hidden states to vocabulary logits auto* lm_head = weights_["lm_head"]; auto* logits = ggml_mul_mat(context_->get(), lm_head, x); - + return logits; } int RWKVWrapper::sampleToken(ggml_tensor* logits, float temperature, float top_p, std::mt19937& gen) { // Get logits data (in real implementation, would extract from computed tensor) // For now, use a simplified sampling approach - - int vocab_size = 50000; // Typical vocab size + + int vocab_size = 50000; // Typical vocab size std::vector probs(vocab_size); - + // Apply temperature float max_logit = -INFINITY; for (int i = 0; i < vocab_size; ++i) { - probs[i] = static_cast(i % 100) / 100.0f; // Placeholder - if (probs[i] > max_logit) max_logit = probs[i]; + probs[i] = static_cast(i % 100) / 100.0f; // Placeholder + if (probs[i] > max_logit) + max_logit = probs[i]; } - + // Softmax with temperature float sum = 0.0f; for (int i = 0; i < vocab_size; ++i) { probs[i] = std::exp((probs[i] - max_logit) / temperature); sum += probs[i]; } - + for (int i = 0; i < vocab_size; ++i) { probs[i] /= sum; } - + // Top-p (nucleus) sampling std::vector> sorted_probs; for (int i = 0; i < vocab_size; ++i) { sorted_probs.push_back({probs[i], i}); } std::sort(sorted_probs.begin(), sorted_probs.end(), std::greater<>()); - + float cumsum = 0.0f; std::vector> nucleus; for (const auto& [prob, idx] : sorted_probs) { cumsum += prob; nucleus.push_back({prob, idx}); - if (cumsum >= top_p) break; + if (cumsum >= top_p) + break; } - + // Sample from nucleus std::uniform_real_distribution dist(0.0f, cumsum); float r = dist(gen); - + cumsum = 0.0f; for (const auto& [prob, idx] : nucleus) { cumsum += prob; @@ -232,36 +236,36 @@ int RWKVWrapper::sampleToken(ggml_tensor* logits, float temperature, float top_p return idx; } } - + return nucleus.back().second; } void RWKVWrapper::loadModelWeights(const std::string& path) { // Enhanced model loading with proper weight initialization - + std::cout << "Loading RWKV model from: " << path << std::endl; - + // Create embedding weight weights_["emb_weight"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, n_embd_, 50000); ggml_set_zero(weights_["emb_weight"]); - + // Create language model head weights_["lm_head"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, 50000, n_embd_); ggml_set_zero(weights_["lm_head"]); - + // Create layer weights for (int i = 0; i < n_layers_; i++) { std::string prefix = "layer_" + std::to_string(i) + "_"; - + // Time-mixing weights weights_[prefix + "tm_w_k"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, n_embd_, n_embd_); weights_[prefix + "tm_w_v"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, n_embd_, n_embd_); weights_[prefix + "tm_w_r"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, n_embd_, n_embd_); - + // Channel-mixing weights weights_[prefix + "cm_w_k"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, n_embd_ * 4, n_embd_); weights_[prefix + "cm_w_v"] = ggml_new_tensor_2d(context_->get(), GGML_TYPE_F32, n_embd_, n_embd_ * 4); - + // Initialize to small random values ggml_set_zero(weights_[prefix + "tm_w_k"]); ggml_set_zero(weights_[prefix + "tm_w_v"]); @@ -269,15 +273,15 @@ void RWKVWrapper::loadModelWeights(const std::string& path) { ggml_set_zero(weights_[prefix + "cm_w_k"]); ggml_set_zero(weights_[prefix + "cm_w_v"]); } - + // In a real implementation, load actual weights from file // This would involve: // 1. Opening the model file // 2. Reading weight tensors // 3. Copying data to GGML tensors // 4. Handling quantization if needed - + std::cout << "Model loaded successfully (placeholder weights)" << std::endl; } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/ai/semantic_search_manager.cpp b/src/bolt/ai/semantic_search_manager.cpp index 3221a833..5d0f4b31 100644 --- a/src/bolt/ai/semantic_search_manager.cpp +++ b/src/bolt/ai/semantic_search_manager.cpp @@ -1,10 +1,11 @@ #include "bolt/ai/semantic_search_manager.hpp" -#include -#include -#include + #include #include +#include +#include #include +#include namespace bolt { namespace ai { @@ -13,8 +14,7 @@ SemanticSearchManager::SemanticSearchManager() { inference_engine_ = std::make_unique(); } -SemanticSearchManager::SemanticSearchManager(const IndexingConfig& config) - : config_(config) { +SemanticSearchManager::SemanticSearchManager(const IndexingConfig& config) : config_(config) { inference_engine_ = std::make_unique(); } @@ -22,16 +22,15 @@ bool SemanticSearchManager::initialize(const std::string& model_path) { if (initialized_) { return true; } - + std::string actual_model_path = model_path; - + // Auto-detect model if not specified if (actual_model_path.empty()) { std::vector search_paths = { "./models/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf", - "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf" - }; - + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"}; + for (const auto& path : search_paths) { if (std::filesystem::exists(path)) { actual_model_path = path; @@ -39,12 +38,12 @@ bool SemanticSearchManager::initialize(const std::string& model_path) { } } } - + if (actual_model_path.empty()) { std::cerr << "No model found for semantic search" << std::endl; return false; } - + initialized_ = inference_engine_->load_model(actual_model_path); return initialized_; } @@ -57,52 +56,52 @@ void SemanticSearchManager::shutdown() { std::vector SemanticSearchManager::chunkText(const std::string& text) const { std::vector chunks; - + if (text.length() <= config_.max_chunk_size) { chunks.push_back(text); return chunks; } - + size_t pos = 0; while (pos < text.length()) { size_t chunk_size = std::min(config_.max_chunk_size, text.length() - pos); chunks.push_back(text.substr(pos, chunk_size)); - + // Move position forward, accounting for overlap pos += chunk_size - config_.chunk_overlap; - if (pos >= text.length()) break; + if (pos >= text.length()) + break; } - + return chunks; } bool SemanticSearchManager::shouldIndexFile(const std::string& file_path) const { namespace fs = std::filesystem; - + // Check if file exists if (!fs::exists(file_path)) { return false; } - + // Check if it's a regular file if (!fs::is_regular_file(file_path)) { return false; } - + // Check file size auto file_size = fs::file_size(file_path); if (file_size > config_.max_file_size) { return false; } - + // Check extension std::string extension = fs::path(file_path).extension().string(); - if (std::find(config_.file_extensions.begin(), - config_.file_extensions.end(), - extension) == config_.file_extensions.end()) { + if (std::find(config_.file_extensions.begin(), config_.file_extensions.end(), extension) == + config_.file_extensions.end()) { return false; } - + // Check hidden files if (!config_.index_hidden_files) { std::string filename = fs::path(file_path).filename().string(); @@ -110,7 +109,7 @@ bool SemanticSearchManager::shouldIndexFile(const std::string& file_path) const return false; } } - + return true; } @@ -119,7 +118,7 @@ std::string SemanticSearchManager::readFileContent(const std::string& file_path) if (!file.is_open()) { return ""; } - + std::stringstream buffer; buffer << file.rdbuf(); return buffer.str(); @@ -129,33 +128,33 @@ std::vector SemanticSearchManager::generateEmbedding(const std::string& t if (!initialized_ || !inference_engine_) { return {}; } - + // For now, use a simple prompt-based approach // In a production system, you'd use a dedicated embedding model std::string prompt = "Summarize the following text in a semantic vector: " + text; - + // This is a placeholder - the actual implementation would use // llama_get_embeddings() from llama.cpp // For now, we'll generate a simple hash-based pseudo-embedding - std::vector embedding(384, 0.0f); // Common embedding dimension - + std::vector embedding(384, 0.0f); // Common embedding dimension + for (size_t i = 0; i < text.length() && i < embedding.size(); ++i) { embedding[i % embedding.size()] += static_cast(text[i]) / 255.0f; } - + // Normalize float norm = 0.0f; for (float val : embedding) { norm += val * val; } norm = std::sqrt(norm); - + if (norm > 0.0f) { for (float& val : embedding) { val /= norm; } } - + return embedding; } @@ -163,28 +162,28 @@ bool SemanticSearchManager::indexFile(const std::string& file_path) { if (!initialized_) { return false; } - + if (!shouldIndexFile(file_path)) { stats_.files_skipped++; return false; } - + auto start_time = std::chrono::high_resolution_clock::now(); - + try { std::string content = readFileContent(file_path); if (content.empty()) { stats_.errors++; return false; } - + // Chunk the content auto chunks = chunkText(content); - + // Generate embeddings for each chunk for (size_t i = 0; i < chunks.size(); ++i) { auto embedding = generateEmbedding(chunks[i]); - + if (!embedding.empty()) { VectorRecord record; record.id = file_path + "#chunk" + std::to_string(i); @@ -193,20 +192,19 @@ bool SemanticSearchManager::indexFile(const std::string& file_path) { record.file_type = std::filesystem::path(file_path).extension().string(); record.file_size = std::filesystem::file_size(file_path); record.last_modified = std::filesystem::last_write_time(file_path).time_since_epoch().count(); - + vector_db_.addOrUpdateRecord(record); stats_.total_chunks++; } } - + stats_.files_indexed++; - + auto end_time = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration(end_time - start_time); stats_.total_time_seconds += duration.count(); - + return true; - } catch (const std::exception& e) { std::cerr << "Error indexing file " << file_path << ": " << e.what() << std::endl; stats_.errors++; @@ -218,42 +216,39 @@ bool SemanticSearchManager::indexDirectory(const std::string& directory_path, bo if (!initialized_) { return false; } - + indexing_in_progress_ = true; namespace fs = std::filesystem; - + try { - auto iterator = recursive - ? fs::recursive_directory_iterator(directory_path) - : fs::directory_iterator(directory_path); - + auto iterator = + recursive ? fs::recursive_directory_iterator(directory_path) : fs::directory_iterator(directory_path); + size_t total_files = 0; size_t processed = 0; - + for (const auto& entry : iterator) { if (entry.is_regular_file()) { total_files++; } } - - iterator = recursive - ? fs::recursive_directory_iterator(directory_path) - : fs::directory_iterator(directory_path); - + + iterator = + recursive ? fs::recursive_directory_iterator(directory_path) : fs::directory_iterator(directory_path); + for (const auto& entry : iterator) { if (entry.is_regular_file()) { indexFile(entry.path().string()); processed++; - + if (progress_callback_) { progress_callback_(entry.path().string(), processed, total_files); } } } - + indexing_in_progress_ = false; return true; - } catch (const std::exception& e) { std::cerr << "Error indexing directory: " << e.what() << std::endl; indexing_in_progress_ = false; @@ -265,14 +260,14 @@ bool SemanticSearchManager::removeFileFromIndex(const std::string& file_path) { // Remove all chunks for this file auto all_ids = vector_db_.getAllIds(); bool removed_any = false; - + for (const auto& id : all_ids) { if (id.find(file_path) == 0) { vector_db_.removeRecord(id); removed_any = true; } } - + return removed_any; } @@ -281,30 +276,23 @@ void SemanticSearchManager::clearIndex() { stats_ = IndexingStats(); } -std::vector SemanticSearchManager::search( - const std::string& query, - int top_k, - float min_similarity) { - +std::vector SemanticSearchManager::search(const std::string& query, int top_k, float min_similarity) { if (!initialized_) { return {}; } - + auto query_embedding = generateEmbedding(query); if (query_embedding.empty()) { return {}; } - + return vector_db_.searchSimilar(query_embedding, top_k, min_similarity); } -std::vector SemanticSearchManager::searchInDirectory( - const std::string& query, - const std::string& directory_path, - int top_k) { - - auto all_results = search(query, top_k * 2); // Get more results to filter - +std::vector SemanticSearchManager::searchInDirectory(const std::string& query, + const std::string& directory_path, int top_k) { + auto all_results = search(query, top_k * 2); // Get more results to filter + std::vector filtered_results; for (const auto& result : all_results) { if (result.file_path.find(directory_path) == 0) { @@ -314,7 +302,7 @@ std::vector SemanticSearchManager::searchInDirectory( } } } - + return filtered_results; } @@ -322,5 +310,5 @@ size_t SemanticSearchManager::getIndexedFileCount() const { return stats_.files_indexed; } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/ai/vector_database.cpp b/src/bolt/ai/vector_database.cpp index acfef169..c6f30f81 100644 --- a/src/bolt/ai/vector_database.cpp +++ b/src/bolt/ai/vector_database.cpp @@ -1,8 +1,9 @@ #include "bolt/ai/vector_database.hpp" -#include + #include -#include +#include #include +#include #include namespace bolt { @@ -32,85 +33,69 @@ VectorRecord VectorDatabase::getRecord(const std::string& id) const { return VectorRecord(); } -float VectorDatabase::cosineSimilarity( - const std::vector& a, - const std::vector& b) { - +float VectorDatabase::cosineSimilarity(const std::vector& a, const std::vector& b) { if (a.size() != b.size() || a.empty()) { return 0.0f; } - + float dot_product = 0.0f; float norm_a = 0.0f; float norm_b = 0.0f; - + for (size_t i = 0; i < a.size(); ++i) { dot_product += a[i] * b[i]; norm_a += a[i] * a[i]; norm_b += b[i] * b[i]; } - + if (norm_a == 0.0f || norm_b == 0.0f) { return 0.0f; } - + return dot_product / (std::sqrt(norm_a) * std::sqrt(norm_b)); } -float VectorDatabase::euclideanDistance( - const std::vector& a, - const std::vector& b) { - +float VectorDatabase::euclideanDistance(const std::vector& a, const std::vector& b) { if (a.size() != b.size() || a.empty()) { return std::numeric_limits::max(); } - + float sum = 0.0f; for (size_t i = 0; i < a.size(); ++i) { float diff = a[i] - b[i]; sum += diff * diff; } - + return std::sqrt(sum); } -std::vector VectorDatabase::searchSimilar( - const std::vector& query_embedding, - int top_k, - float min_similarity) const { - +std::vector VectorDatabase::searchSimilar(const std::vector& query_embedding, int top_k, + float min_similarity) const { std::lock_guard lock(mutex_); - + std::vector results; results.reserve(records_.size()); - + // Calculate similarity for each record for (const auto& pair : records_) { const VectorRecord& record = pair.second; - + float similarity = cosineSimilarity(query_embedding, record.embedding); - + if (similarity >= min_similarity) { - results.emplace_back( - record.id, - similarity, - record.content_preview, - record.file_type - ); + results.emplace_back(record.id, similarity, record.content_preview, record.file_type); } } - + // Sort by similarity (descending) - std::sort(results.begin(), results.end(), - [](const SearchResult& a, const SearchResult& b) { - return a.similarity_score > b.similarity_score; - }); - + std::sort(results.begin(), results.end(), + [](const SearchResult& a, const SearchResult& b) { return a.similarity_score > b.similarity_score; }); + // Return top K results if (results.size() > static_cast(top_k)) { results.resize(top_k); } - + return results; } @@ -123,11 +108,11 @@ std::vector VectorDatabase::getAllIds() const { std::lock_guard lock(mutex_); std::vector ids; ids.reserve(records_.size()); - + for (const auto& pair : records_) { ids.push_back(pair.first); } - + return ids; } @@ -138,64 +123,62 @@ void VectorDatabase::clear() { bool VectorDatabase::saveToFile(const std::string& file_path) const { std::lock_guard lock(mutex_); - + try { std::ofstream file(file_path, std::ios::binary); if (!file.is_open()) { return false; } - + // Write file header const char* magic = "BVDB"; // Bolt Vector DataBase file.write(magic, 4); - + uint32_t version = 1; file.write(reinterpret_cast(&version), sizeof(version)); - + // Write number of records uint64_t num_records = records_.size(); file.write(reinterpret_cast(&num_records), sizeof(num_records)); - + // Write each record for (const auto& [id, record] : records_) { // Write ID length and ID uint32_t id_len = id.size(); file.write(reinterpret_cast(&id_len), sizeof(id_len)); file.write(id.c_str(), id_len); - + // Write content length and content uint32_t content_len = record.content.size(); file.write(reinterpret_cast(&content_len), sizeof(content_len)); file.write(record.content.c_str(), content_len); - + // Write embedding dimension and embedding data uint32_t embedding_dim = record.embedding.size(); file.write(reinterpret_cast(&embedding_dim), sizeof(embedding_dim)); - file.write(reinterpret_cast(record.embedding.data()), - embedding_dim * sizeof(float)); - + file.write(reinterpret_cast(record.embedding.data()), embedding_dim * sizeof(float)); + // Write metadata size uint32_t metadata_size = record.metadata.size(); file.write(reinterpret_cast(&metadata_size), sizeof(metadata_size)); - + // Write each metadata key-value pair for (const auto& [key, value] : record.metadata) { uint32_t key_len = key.size(); file.write(reinterpret_cast(&key_len), sizeof(key_len)); file.write(key.c_str(), key_len); - + uint32_t value_len = value.size(); file.write(reinterpret_cast(&value_len), sizeof(value_len)); file.write(value.c_str(), value_len); } - + // Write timestamp file.write(reinterpret_cast(&record.timestamp), sizeof(record.timestamp)); } - + file.close(); return true; - } catch (const std::exception& e) { return false; } @@ -203,90 +186,88 @@ bool VectorDatabase::saveToFile(const std::string& file_path) const { bool VectorDatabase::loadFromFile(const std::string& file_path) { std::lock_guard lock(mutex_); - + try { std::ifstream file(file_path, std::ios::binary); if (!file.is_open()) { return false; } - + // Read and verify file header char magic[4]; file.read(magic, 4); if (std::string(magic, 4) != "BVDB") { return false; // Invalid file format } - + uint32_t version; file.read(reinterpret_cast(&version), sizeof(version)); if (version != 1) { return false; // Unsupported version } - + // Clear existing records records_.clear(); - + // Read number of records uint64_t num_records; file.read(reinterpret_cast(&num_records), sizeof(num_records)); - + // Read each record for (uint64_t i = 0; i < num_records; ++i) { VectorRecord record; - + // Read ID uint32_t id_len; file.read(reinterpret_cast(&id_len), sizeof(id_len)); std::string id(id_len, '\0'); file.read(&id[0], id_len); record.id = id; - + // Read content uint32_t content_len; file.read(reinterpret_cast(&content_len), sizeof(content_len)); record.content.resize(content_len); file.read(&record.content[0], content_len); - + // Read embedding uint32_t embedding_dim; file.read(reinterpret_cast(&embedding_dim), sizeof(embedding_dim)); record.embedding.resize(embedding_dim); - file.read(reinterpret_cast(record.embedding.data()), - embedding_dim * sizeof(float)); - + file.read(reinterpret_cast(record.embedding.data()), embedding_dim * sizeof(float)); + // Read metadata uint32_t metadata_size; file.read(reinterpret_cast(&metadata_size), sizeof(metadata_size)); - + for (uint32_t j = 0; j < metadata_size; ++j) { uint32_t key_len; file.read(reinterpret_cast(&key_len), sizeof(key_len)); std::string key(key_len, '\0'); file.read(&key[0], key_len); - + uint32_t value_len; file.read(reinterpret_cast(&value_len), sizeof(value_len)); std::string value(value_len, '\0'); file.read(&value[0], value_len); - + record.metadata[key] = value; } - + // Read timestamp file.read(reinterpret_cast(&record.timestamp), sizeof(record.timestamp)); - + // Add record to database records_[record.id] = record; } - + file.close(); return true; - } catch (const std::exception& e) { records_.clear(); // Clear partial data on error return false; } } -} // namespace ai -} // namespace bolt +} // namespace ai +} // namespace bolt diff --git a/src/bolt/benchmarks/core_benchmarks.cpp b/src/bolt/benchmarks/core_benchmarks.cpp index a3423671..c360ef15 100644 --- a/src/bolt/benchmarks/core_benchmarks.cpp +++ b/src/bolt/benchmarks/core_benchmarks.cpp @@ -1,27 +1,26 @@ -#include "../../include/bolt/core/benchmark_suite.hpp" -#include "../../include/bolt/core/performance_profiler.hpp" -#include "../../include/bolt/core/memory_manager.hpp" -#include "../../include/bolt/core/memory_pool.hpp" -#include "../../include/bolt/core/logging.hpp" -#include -#include -#include -#include -#include #include +#include #include +#include +#include +#include #include +#include + +#include "../../include/bolt/core/benchmark_suite.hpp" +#include "../../include/bolt/core/logging.hpp" +#include "../../include/bolt/core/memory_manager.hpp" +#include "../../include/bolt/core/memory_pool.hpp" +#include "../../include/bolt/core/performance_profiler.hpp" -using namespace bolt; +using namespace bolt; // NOLINT(build/namespaces) // Memory Management Benchmarks -BOLT_BENCHMARK_CONFIG(memory_allocation_basic, "CORE", - "Basic memory allocation and deallocation performance", 100) { - +BOLT_BENCHMARK_CONFIG(memory_allocation_basic, "CORE", "Basic memory allocation and deallocation performance", 100) { std::vector allocations; const size_t numAllocations = 1000; const size_t allocationSize = 1024; - + // Allocate for (size_t i = 0; i < numAllocations; ++i) { void* ptr = malloc(allocationSize); @@ -29,7 +28,7 @@ BOLT_BENCHMARK_CONFIG(memory_allocation_basic, "CORE", allocations.push_back(ptr); } } - + // Deallocate for (void* ptr : allocations) { if (ptr) { @@ -38,23 +37,21 @@ BOLT_BENCHMARK_CONFIG(memory_allocation_basic, "CORE", } } -BOLT_BENCHMARK_CONFIG(memory_pool_performance, "CORE", - "Memory pool allocation vs standard allocation", 50) { - +BOLT_BENCHMARK_CONFIG(memory_pool_performance, "CORE", "Memory pool allocation vs standard allocation", 50) { const size_t numAllocations = 500; const size_t blockSize = 512; - + // Test memory pool MemoryPool pool(blockSize, numAllocations); std::vector poolAllocations; - + for (size_t i = 0; i < numAllocations; ++i) { void* ptr = pool.allocate(); if (ptr) { poolAllocations.push_back(ptr); } } - + for (void* ptr : poolAllocations) { if (ptr) { pool.deallocate(ptr); @@ -63,32 +60,28 @@ BOLT_BENCHMARK_CONFIG(memory_pool_performance, "CORE", } // Performance Profiler Benchmarks -BOLT_BENCHMARK_CONFIG(profiler_overhead, "CORE", - "Measure performance profiler overhead", 1000) { - +BOLT_BENCHMARK_CONFIG(profiler_overhead, "CORE", "Measure performance profiler overhead", 1000) { auto& profiler = PerformanceProfiler::getInstance(); - + // Simple operation with profiling for (int i = 0; i < 100; ++i) { auto metric = profiler.startMetric("test_operation", "BENCHMARK"); - + // Simulate some work volatile int sum = 0; for (int j = 0; j < 1000; ++j) { sum += j; } - + profiler.endMetric(metric); } } // Threading Benchmarks -BOLT_BENCHMARK_CONFIG(thread_creation_overhead, "CORE", - "Thread creation and destruction overhead", 20) { - +BOLT_BENCHMARK_CONFIG(thread_creation_overhead, "CORE", "Thread creation and destruction overhead", 20) { const int numThreads = 10; std::vector threads; - + // Create threads for (int i = 0; i < numThreads; ++i) { threads.emplace_back([]() { @@ -96,7 +89,7 @@ BOLT_BENCHMARK_CONFIG(thread_creation_overhead, "CORE", std::this_thread::sleep_for(std::chrono::milliseconds(1)); }); } - + // Join threads for (auto& thread : threads) { if (thread.joinable()) { @@ -105,16 +98,14 @@ BOLT_BENCHMARK_CONFIG(thread_creation_overhead, "CORE", } } -BOLT_BENCHMARK_CONFIG(mutex_contention, "CORE", - "Mutex contention performance with multiple threads", 10) { - +BOLT_BENCHMARK_CONFIG(mutex_contention, "CORE", "Mutex contention performance with multiple threads", 10) { const int numThreads = 4; const int operationsPerThread = 1000; std::mutex testMutex; int sharedCounter = 0; - + std::vector threads; - + for (int i = 0; i < numThreads; ++i) { threads.emplace_back([&]() { for (int j = 0; j < operationsPerThread; ++j) { @@ -123,7 +114,7 @@ BOLT_BENCHMARK_CONFIG(mutex_contention, "CORE", } }); } - + for (auto& thread : threads) { if (thread.joinable()) { thread.join(); @@ -132,24 +123,22 @@ BOLT_BENCHMARK_CONFIG(mutex_contention, "CORE", } // String Processing Benchmarks -BOLT_BENCHMARK_CONFIG(string_operations, "CORE", - "String creation, manipulation, and destruction", 100) { - +BOLT_BENCHMARK_CONFIG(string_operations, "CORE", "String creation, manipulation, and destruction", 100) { const int numStrings = 1000; std::vector strings; - + // String creation for (int i = 0; i < numStrings; ++i) { strings.emplace_back("Test string " + std::to_string(i) + " with some content"); } - + // String manipulation for (auto& str : strings) { str += " appended"; str = str.substr(0, str.length() / 2); std::transform(str.begin(), str.end(), str.begin(), ::toupper); } - + // String searching int found = 0; for (const auto& str : strings) { @@ -160,44 +149,40 @@ BOLT_BENCHMARK_CONFIG(string_operations, "CORE", } // Container Benchmarks -BOLT_BENCHMARK_CONFIG(vector_operations, "CORE", - "Vector push_back, insert, and erase operations", 50) { - +BOLT_BENCHMARK_CONFIG(vector_operations, "CORE", "Vector push_back, insert, and erase operations", 50) { std::vector vec; const int numElements = 10000; - + // Push back for (int i = 0; i < numElements; ++i) { vec.push_back(i); } - + // Random access std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(0, numElements - 1); - + int sum = 0; for (int i = 0; i < 1000; ++i) { sum += vec[dis(gen)]; } - + // Erase elements while (!vec.empty() && vec.size() > numElements / 2) { vec.erase(vec.begin() + vec.size() / 2); } } -BOLT_BENCHMARK_CONFIG(map_operations, "CORE", - "Map insertion, lookup, and deletion operations", 30) { - +BOLT_BENCHMARK_CONFIG(map_operations, "CORE", "Map insertion, lookup, and deletion operations", 30) { std::unordered_map map; const int numElements = 5000; - + // Insertion for (int i = 0; i < numElements; ++i) { map["key_" + std::to_string(i)] = i; } - + // Lookup int sum = 0; for (int i = 0; i < numElements; ++i) { @@ -206,7 +191,7 @@ BOLT_BENCHMARK_CONFIG(map_operations, "CORE", sum += it->second; } } - + // Deletion for (int i = 0; i < numElements / 2; ++i) { map.erase("key_" + std::to_string(i)); @@ -214,13 +199,11 @@ BOLT_BENCHMARK_CONFIG(map_operations, "CORE", } // File I/O Benchmarks -BOLT_BENCHMARK_CONFIG(file_io_operations, "CORE", - "File creation, writing, reading, and deletion", 10) { - +BOLT_BENCHMARK_CONFIG(file_io_operations, "CORE", "File creation, writing, reading, and deletion", 10) { const std::string filename = "/tmp/benchmark_test_file.txt"; const std::string content = "This is test content for file I/O benchmark. "; const int numLines = 1000; - + // Write file { std::ofstream file(filename); @@ -228,7 +211,7 @@ BOLT_BENCHMARK_CONFIG(file_io_operations, "CORE", file << content << "Line " << i << std::endl; } } - + // Read file { std::ifstream file(filename); @@ -238,20 +221,18 @@ BOLT_BENCHMARK_CONFIG(file_io_operations, "CORE", lineCount++; } } - + // Clean up std::remove(filename.c_str()); } // Logging Performance Benchmark -BOLT_BENCHMARK_CONFIG(logging_performance, "CORE", - "Logging system performance with different levels", 50) { - +BOLT_BENCHMARK_CONFIG(logging_performance, "CORE", "Logging system performance with different levels", 50) { const int numLogs = 1000; - + // Configure logging for benchmark LogManager::configureConsoleLogging(LogLevel::WARN, false); - + // Test different log levels for (int i = 0; i < numLogs; ++i) { BOLT_LOG_DEBUG("Debug message {}", i); @@ -261,4 +242,4 @@ BOLT_BENCHMARK_CONFIG(logging_performance, "CORE", BOLT_LOG_ERROR("Error message {}", i); } } -} \ No newline at end of file +} diff --git a/src/bolt/collaboration/collaboration_protocol.cpp b/src/bolt/collaboration/collaboration_protocol.cpp index dd89bab9..adf76c5b 100644 --- a/src/bolt/collaboration/collaboration_protocol.cpp +++ b/src/bolt/collaboration/collaboration_protocol.cpp @@ -6,5 +6,5 @@ namespace collaboration { // All implementation is in the header for template-heavy classes // This file exists to ensure proper compilation and linking -} // namespace collaboration -} // namespace bolt \ No newline at end of file +} // namespace collaboration +} // namespace bolt diff --git a/src/bolt/collaboration/collaborative_editor_integration.cpp b/src/bolt/collaboration/collaborative_editor_integration.cpp index 9e6491fa..e3a4b2fc 100644 --- a/src/bolt/collaboration/collaborative_editor_integration.cpp +++ b/src/bolt/collaboration/collaborative_editor_integration.cpp @@ -6,5 +6,5 @@ namespace collaboration { // All implementation is in the header for template-heavy classes // This file exists to ensure proper compilation and linking -} // namespace collaboration -} // namespace bolt \ No newline at end of file +} // namespace collaboration +} // namespace bolt diff --git a/src/bolt/collaboration/collaborative_session.cpp b/src/bolt/collaboration/collaborative_session.cpp index 44832436..429d628b 100644 --- a/src/bolt/collaboration/collaborative_session.cpp +++ b/src/bolt/collaboration/collaborative_session.cpp @@ -6,5 +6,5 @@ namespace collaboration { // All implementation is in the header for template-heavy classes // This file exists to ensure proper compilation and linking -} // namespace collaboration -} // namespace bolt \ No newline at end of file +} // namespace collaboration +} // namespace bolt diff --git a/src/bolt/collaboration/document_operation.cpp b/src/bolt/collaboration/document_operation.cpp index 7f9d4fb4..67a94dd2 100644 --- a/src/bolt/collaboration/document_operation.cpp +++ b/src/bolt/collaboration/document_operation.cpp @@ -6,5 +6,5 @@ namespace collaboration { // All implementation is in the header for template-heavy classes // This file exists to ensure proper compilation and linking -} // namespace collaboration -} // namespace bolt \ No newline at end of file +} // namespace collaboration +} // namespace bolt diff --git a/src/bolt/collaboration/operational_transform.cpp b/src/bolt/collaboration/operational_transform.cpp index b3e2fd47..4b2d4630 100644 --- a/src/bolt/collaboration/operational_transform.cpp +++ b/src/bolt/collaboration/operational_transform.cpp @@ -6,5 +6,5 @@ namespace collaboration { // All implementation is in the header for template-heavy classes // This file exists to ensure proper compilation and linking -} // namespace collaboration -} // namespace bolt \ No newline at end of file +} // namespace collaboration +} // namespace bolt diff --git a/src/bolt/core/benchmark_suite.cpp b/src/bolt/core/benchmark_suite.cpp index 7a2ae009..569f4308 100644 --- a/src/bolt/core/benchmark_suite.cpp +++ b/src/bolt/core/benchmark_suite.cpp @@ -1,14 +1,16 @@ #include "bolt/core/benchmark_suite.hpp" -#include "bolt/core/performance_profiler.hpp" -#include "bolt/core/logging.hpp" + #include -#include #include -#include -#include #include -#include +#include +#include #include +#include +#include + +#include "bolt/core/logging.hpp" +#include "bolt/core/performance_profiler.hpp" namespace bolt { @@ -31,7 +33,7 @@ BenchmarkSuite& BenchmarkSuite::getInstance() { void BenchmarkSuite::registerBenchmark(const BenchmarkConfig& config, BenchmarkFunction function) { std::lock_guard lock(benchmarksMutex_); benchmarks_[config.name] = std::make_pair(config, function); - + if (verboseOutput_) { BOLT_INFO("Registered benchmark '" + config.name + "' in category '" + config.category + "'"); } @@ -39,39 +41,40 @@ void BenchmarkSuite::registerBenchmark(const BenchmarkConfig& config, BenchmarkF std::vector BenchmarkSuite::runAllBenchmarks() { std::vector results; - + std::lock_guard lock(benchmarksMutex_); for (const auto& benchmark : benchmarks_) { if (verboseOutput_) { BOLT_INFO("Running benchmark '" + benchmark.first + "'..."); } - + BenchmarkResult result = executeBenchmark(benchmark.second.first, benchmark.second.second); results.push_back(result); - + if (verboseOutput_) { - BOLT_INFO("Benchmark '" + result.name + "' completed: " + std::to_string(result.averageDurationMs) + "ms avg (" + std::to_string(result.successfulRuns) + " runs)"); + BOLT_INFO("Benchmark '" + result.name + "' completed: " + std::to_string(result.averageDurationMs) + + "ms avg (" + std::to_string(result.successfulRuns) + " runs)"); } } - + return results; } std::vector BenchmarkSuite::runBenchmarksByCategory(const std::string& category) { std::vector results; - + std::lock_guard lock(benchmarksMutex_); for (const auto& benchmark : benchmarks_) { if (benchmark.second.first.category == category) { if (verboseOutput_) { BOLT_INFO("Running benchmark '" + benchmark.first + "' in category '" + category + "'..."); } - + BenchmarkResult result = executeBenchmark(benchmark.second.first, benchmark.second.second); results.push_back(result); } } - + return results; } @@ -84,7 +87,7 @@ BenchmarkResult BenchmarkSuite::runBenchmark(const std::string& name) { result.errorMessage = "Benchmark not found"; return result; } - + return executeBenchmark(it->second.first, it->second.second); } @@ -95,18 +98,18 @@ BenchmarkResult BenchmarkSuite::executeBenchmark(const BenchmarkConfig& config, result.description = config.description; result.timestamp = std::chrono::steady_clock::now(); result.totalIterations = config.iterations; - + auto& profiler = PerformanceProfiler::getInstance(); profiler.enable(); - + // Create a benchmark session auto session = profiler.createSession("benchmark_" + config.name); profiler.setCurrentSession("benchmark_" + config.name); - + std::vector durations; std::vector memoryUsages; std::vector cpuUsages; - + try { // Warmup runs for (int i = 0; i < config.warmupRuns; ++i) { @@ -118,27 +121,28 @@ BenchmarkResult BenchmarkSuite::executeBenchmark(const BenchmarkConfig& config, } } } - + // Actual benchmark runs for (int i = 0; i < config.iterations; ++i) { auto runStart = std::chrono::steady_clock::now(); size_t memoryBefore = getCurrentMemoryUsage(); - + try { auto metric = profiler.startMetric(config.name + "_run_" + std::to_string(i), config.category); - + function(config); - + profiler.endMetric(metric); - + auto runEnd = std::chrono::steady_clock::now(); double duration = std::chrono::duration(runEnd - runStart).count(); size_t memoryAfter = getCurrentMemoryUsage(); - + durations.push_back(duration); - memoryUsages.push_back(static_cast(memoryAfter - memoryBefore) / (1024 * 1024)); // Convert to MB + memoryUsages.push_back(static_cast(memoryAfter - memoryBefore) / + (1024 * 1024)); // Convert to MB cpuUsages.push_back(getCurrentCpuUsage()); - + result.successfulRuns++; } catch (const std::exception& e) { result.failedRuns++; @@ -150,7 +154,7 @@ BenchmarkResult BenchmarkSuite::executeBenchmark(const BenchmarkConfig& config, } } } - + // Calculate statistics if (!durations.empty()) { result.rawDurations = durations; @@ -159,44 +163,42 @@ BenchmarkResult BenchmarkSuite::executeBenchmark(const BenchmarkConfig& config, result.maxDurationMs = *std::max_element(durations.begin(), durations.end()); result.standardDeviationMs = calculateStandardDeviation(durations, result.averageDurationMs); } - + if (!memoryUsages.empty()) { - result.averageMemoryUsageMB = std::accumulate(memoryUsages.begin(), memoryUsages.end(), 0.0) / memoryUsages.size(); + result.averageMemoryUsageMB = + std::accumulate(memoryUsages.begin(), memoryUsages.end(), 0.0) / memoryUsages.size(); result.maxMemoryUsageMB = *std::max_element(memoryUsages.begin(), memoryUsages.end()); } - + if (!cpuUsages.empty()) { result.averageCpuUsagePercent = std::accumulate(cpuUsages.begin(), cpuUsages.end(), 0.0) / cpuUsages.size(); } - + // Add session metadata if (session) { result.metadata["session_metrics"] = std::to_string(session->getMetricsCount()); result.metadata["session_duration"] = std::to_string(session->getTotalDurationMs()); } - } catch (const std::exception& e) { result.errorMessage = "Benchmark execution failed: " + std::string(e.what()); BOLT_ERROR("Benchmark '" + config.name + "' failed: " + e.what()); } - + profiler.endSession("benchmark_" + config.name); - + return result; } -std::vector BenchmarkSuite::compareWithBaseline( - const std::vector& current, - const std::vector& baseline -) { +std::vector BenchmarkSuite::compareWithBaseline(const std::vector& current, + const std::vector& baseline) { std::vector comparisons; - + // Create a map for quick baseline lookup std::unordered_map baselineMap; for (const auto& result : baseline) { baselineMap[result.name] = result; } - + for (const auto& currentResult : current) { auto baselineIt = baselineMap.find(currentResult.name); if (baselineIt != baselineMap.end()) { @@ -204,33 +206,36 @@ std::vector BenchmarkSuite::compareWithBaseline( comparison.benchmarkName = currentResult.name; comparison.current = currentResult; comparison.baseline = baselineIt->second; - + // Calculate performance changes if (baselineIt->second.averageDurationMs > 0) { - comparison.durationChangePercent = - ((currentResult.averageDurationMs - baselineIt->second.averageDurationMs) / - baselineIt->second.averageDurationMs) * 100.0; + comparison.durationChangePercent = + ((currentResult.averageDurationMs - baselineIt->second.averageDurationMs) / + baselineIt->second.averageDurationMs) * + 100.0; } - + if (baselineIt->second.averageMemoryUsageMB > 0) { - comparison.memoryChangePercent = - ((currentResult.averageMemoryUsageMB - baselineIt->second.averageMemoryUsageMB) / - baselineIt->second.averageMemoryUsageMB) * 100.0; + comparison.memoryChangePercent = + ((currentResult.averageMemoryUsageMB - baselineIt->second.averageMemoryUsageMB) / + baselineIt->second.averageMemoryUsageMB) * + 100.0; } - + if (baselineIt->second.averageCpuUsagePercent > 0) { - comparison.cpuChangePercent = - ((currentResult.averageCpuUsagePercent - baselineIt->second.averageCpuUsagePercent) / - baselineIt->second.averageCpuUsagePercent) * 100.0; + comparison.cpuChangePercent = + ((currentResult.averageCpuUsagePercent - baselineIt->second.averageCpuUsagePercent) / + baselineIt->second.averageCpuUsagePercent) * + 100.0; } - + // Determine performance status comparison.performanceStatus = determinePerformanceStatus(baselineIt->second, currentResult); - + comparisons.push_back(comparison); } } - + return comparisons; } @@ -240,13 +245,15 @@ void BenchmarkSuite::generateJsonReport(const std::vector& resu BOLT_ERROR("Failed to open file for JSON report: " + filename); return; } - + file << "{\n"; file << " \"benchmark_suite_version\": \"1.0.0\",\n"; - file << " \"timestamp\": \"" << std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count() << "\",\n"; + file + << " \"timestamp\": \"" + << std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() + << "\",\n"; file << " \"results\": [\n"; - + for (size_t i = 0; i < results.size(); ++i) { const auto& result = results[i]; file << " {\n"; @@ -266,13 +273,14 @@ void BenchmarkSuite::generateJsonReport(const std::vector& resu file << " \"success_rate\": " << result.getSuccessRate() << ",\n"; file << " \"error_message\": \"" << result.errorMessage << "\"\n"; file << " }"; - if (i < results.size() - 1) file << ","; + if (i < results.size() - 1) + file << ","; file << "\n"; } - + file << " ]\n"; file << "}\n"; - + file.close(); BOLT_INFO("JSON report generated: " + filename); } @@ -283,30 +291,23 @@ void BenchmarkSuite::generateCsvReport(const std::vector& resul BOLT_ERROR("Failed to open file for CSV report: " + filename); return; } - + // Header - file << "Name,Category,Description,AvgDurationMs,MinDurationMs,MaxDurationMs,StdDevMs," - << "AvgMemoryMB,MaxMemoryMB,AvgCpuPercent,TotalIterations,SuccessfulRuns,FailedRuns,SuccessRate,ErrorMessage\n"; - + file + << "Name,Category,Description,AvgDurationMs,MinDurationMs,MaxDurationMs,StdDevMs," + << "AvgMemoryMB,MaxMemoryMB,AvgCpuPercent,TotalIterations,SuccessfulRuns,FailedRuns,SuccessRate,ErrorMessage\n"; + // Data rows for (const auto& result : results) { file << "\"" << result.name << "\"," << "\"" << result.category << "\"," - << "\"" << result.description << "\"," - << result.averageDurationMs << "," - << result.minDurationMs << "," - << result.maxDurationMs << "," - << result.standardDeviationMs << "," - << result.averageMemoryUsageMB << "," - << result.maxMemoryUsageMB << "," - << result.averageCpuUsagePercent << "," - << result.totalIterations << "," - << result.successfulRuns << "," - << result.failedRuns << "," - << result.getSuccessRate() << "," + << "\"" << result.description << "\"," << result.averageDurationMs << "," << result.minDurationMs << "," + << result.maxDurationMs << "," << result.standardDeviationMs << "," << result.averageMemoryUsageMB << "," + << result.maxMemoryUsageMB << "," << result.averageCpuUsagePercent << "," << result.totalIterations << "," + << result.successfulRuns << "," << result.failedRuns << "," << result.getSuccessRate() << "," << "\"" << result.errorMessage << "\"\n"; } - + file.close(); BOLT_INFO("CSV report generated: " + filename); } @@ -317,8 +318,9 @@ void BenchmarkSuite::generateHtmlReport(const std::vector& resu BOLT_ERROR("Failed to open file for HTML report: " + filename); return; } - - file << R"( + + file + << R"( @@ -340,12 +342,14 @@ void BenchmarkSuite::generateHtmlReport(const std::vector& resu

Bolt Performance Benchmark Report

-

Generated: )" << std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()).count() << R"(

-

Total Benchmarks: )" << results.size() << R"(

+

Generated: )" + << std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() + << R"(

+

Total Benchmarks: )" + << results.size() << R"(

)"; - + // Summary statistics int totalSuccessful = 0, totalFailed = 0; double averageTime = 0.0; @@ -357,31 +361,43 @@ void BenchmarkSuite::generateHtmlReport(const std::vector& resu if (!results.empty()) { averageTime /= results.size(); } - + file << R"(

Summary Statistics

-
Successful Runs: )" << totalSuccessful << R"(
-
Failed Runs: )" << totalFailed << R"(
-
Average Duration: )" << formatDuration(averageTime) << R"(
+
Successful Runs: )" + << totalSuccessful << R"(
+
Failed Runs: )" + << totalFailed << R"(
+
Average Duration: )" + << formatDuration(averageTime) << R"(
)"; - + // Individual benchmark results for (const auto& result : results) { std::string cssClass = result.isValid() ? "success" : "failure"; file << R"(
-

)" << result.name << R"( ()" << result.category << R"()

-

)" << result.description << R"(

+

)" + << result.name << R"( ()" << result.category << R"()

+

)" << result.description + << R"(

-
Avg: )" << formatDuration(result.averageDurationMs) << R"(
-
Min: )" << formatDuration(result.minDurationMs) << R"(
-
Max: )" << formatDuration(result.maxDurationMs) << R"(
-
StdDev: )" << formatDuration(result.standardDeviationMs) << R"(
-
Memory: )" << formatMemory(result.averageMemoryUsageMB) << R"(
-
CPU: )" << formatPercentage(result.averageCpuUsagePercent) << R"(
-
Success Rate: )" << formatPercentage(result.getSuccessRate() * 100) << R"(
+
Avg: )" + << formatDuration(result.averageDurationMs) << R"(
+
Min: )" + << formatDuration(result.minDurationMs) << R"(
+
Max: )" + << formatDuration(result.maxDurationMs) << R"(
+
StdDev: )" + << formatDuration(result.standardDeviationMs) << R"(
+
Memory: )" + << formatMemory(result.averageMemoryUsageMB) << R"(
+
CPU: )" + << formatPercentage(result.averageCpuUsagePercent) << R"(
+
Success Rate: )" + << formatPercentage(result.getSuccessRate() * 100) << R"(
)"; if (!result.errorMessage.empty()) { @@ -390,10 +406,10 @@ void BenchmarkSuite::generateHtmlReport(const std::vector& resu file << R"(
)"; } - + file << R"( )"; - + file.close(); BOLT_INFO("HTML report generated: " + filename); } @@ -429,8 +445,9 @@ std::vector BenchmarkSuite::getAvailableCategories() const { } double BenchmarkSuite::calculateStandardDeviation(const std::vector& values, double mean) { - if (values.empty()) return 0.0; - + if (values.empty()) + return 0.0; + double variance = 0.0; for (double value : values) { variance += (value - mean) * (value - mean); @@ -439,16 +456,14 @@ double BenchmarkSuite::calculateStandardDeviation(const std::vector& val return std::sqrt(variance); } -BenchmarkComparison::Status BenchmarkSuite::determinePerformanceStatus( - const BenchmarkResult& baseline, const BenchmarkResult& current) { - +BenchmarkComparison::Status BenchmarkSuite::determinePerformanceStatus(const BenchmarkResult& baseline, + const BenchmarkResult& current) { if (!baseline.isValid() || !current.isValid()) { return BenchmarkComparison::Status::INCONCLUSIVE; } - - double change = ((current.averageDurationMs - baseline.averageDurationMs) / - baseline.averageDurationMs) * 100.0; - + + double change = ((current.averageDurationMs - baseline.averageDurationMs) / baseline.averageDurationMs) * 100.0; + if (change <= IMPROVEMENT_THRESHOLD) { return BenchmarkComparison::Status::IMPROVED; } else if (change >= REGRESSION_THRESHOLD) { @@ -486,7 +501,7 @@ size_t getCurrentMemoryUsage() { std::istringstream iss(line); std::string label, value, unit; iss >> label >> value >> unit; - return std::stoul(value) * 1024; // Convert from KB to bytes + return std::stoul(value) * 1024; // Convert from KB to bytes } } return 0; @@ -498,4 +513,4 @@ double getCurrentCpuUsage() { return 0.0; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/core/chat_store.cpp b/src/bolt/core/chat_store.cpp index 453ab852..dc2cea4a 100644 --- a/src/bolt/core/chat_store.cpp +++ b/src/bolt/core/chat_store.cpp @@ -3,4 +3,4 @@ namespace bolt { // All implementation is in the header -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/core/code_analyzer.cpp b/src/bolt/core/code_analyzer.cpp index 67eba9c2..b5902c56 100644 --- a/src/bolt/core/code_analyzer.cpp +++ b/src/bolt/core/code_analyzer.cpp @@ -1,13 +1,14 @@ #include "bolt/core/code_analyzer.hpp" -#include -#include + #include -#include +#include #include +#include +#include #include +#include +#include #include -#include -#include namespace bolt { @@ -16,84 +17,79 @@ std::vector ComplexityAnalyzer::getSupportedExtensions() const { return {".cpp", ".hpp", ".c", ".h", ".cc", ".cxx", ".hxx"}; } -std::vector ComplexityAnalyzer::analyzeFile(const std::string& filePath, - const std::string& content) { +std::vector ComplexityAnalyzer::analyzeFile(const std::string& filePath, const std::string& content) { std::vector issues; - + auto metrics = getMetrics(filePath, content); - + // Check cyclomatic complexity if (metrics.cyclomaticComplexity > 10) { - AnalysisIssue issue("COMPLEX_FUNCTION", - "High cyclomatic complexity: " + std::to_string(metrics.cyclomaticComplexity), - AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("COMPLEX_FUNCTION", + "High cyclomatic complexity: " + std::to_string(metrics.cyclomaticComplexity), + AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Consider breaking down complex functions into smaller ones"); issue.suggestions.push_back("Use early returns to reduce nesting"); issues.push_back(issue); } - + // Check nesting depth if (metrics.nestingDepth > 4) { - AnalysisIssue issue("DEEP_NESTING", - "Deep nesting detected: " + std::to_string(metrics.nestingDepth) + " levels", - AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("DEEP_NESTING", + "Deep nesting detected: " + std::to_string(metrics.nestingDepth) + " levels", + AnalysisSeverity::WARNING, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Extract nested logic into separate functions"); issue.suggestions.push_back("Use guard clauses to reduce nesting"); issues.push_back(issue); } - + // Check function count per file if (metrics.functionCount > 50) { - AnalysisIssue issue("TOO_MANY_FUNCTIONS", - "Too many functions in file: " + std::to_string(metrics.functionCount), - AnalysisSeverity::INFO, AnalysisCategory::COMPLEXITY); + AnalysisIssue issue("TOO_MANY_FUNCTIONS", + "Too many functions in file: " + std::to_string(metrics.functionCount), + AnalysisSeverity::INFO, AnalysisCategory::COMPLEXITY); issue.filePath = filePath; issue.suggestions.push_back("Consider splitting the file into smaller modules"); issues.push_back(issue); } - + return issues; } std::vector ComplexityAnalyzer::analyzeProject(const std::string& projectPath) { std::vector allIssues; - + for (const auto& ext : getSupportedExtensions()) { for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { if (entry.is_regular_file() && entry.path().extension() == ext) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto fileIssues = analyzeFile(entry.path().string(), content); allIssues.insert(allIssues.end(), fileIssues.begin(), fileIssues.end()); } } } - + return allIssues; } -CodeMetrics ComplexityAnalyzer::getMetrics(const std::string& filePath, - const std::string& content) { +CodeMetrics ComplexityAnalyzer::getMetrics(const std::string& filePath, const std::string& content) { CodeMetrics metrics; - + std::istringstream stream(content); std::string line; - + while (std::getline(stream, line)) { metrics.physicalLines++; - + // Remove leading/trailing whitespace - line.erase(line.begin(), std::find_if(line.begin(), line.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); - line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { - return !std::isspace(ch); - }).base(), line.end()); - + line.erase(line.begin(), + std::find_if(line.begin(), line.end(), [](unsigned char ch) { return !std::isspace(ch); })); + line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), + line.end()); + if (line.empty()) { metrics.blankLines++; } else if (line.find("//") == 0 || line.find("/*") == 0) { @@ -102,49 +98,50 @@ CodeMetrics ComplexityAnalyzer::getMetrics(const std::string& filePath, metrics.linesOfCode++; } } - + metrics.cyclomaticComplexity = calculateCyclomaticComplexity(content); metrics.nestingDepth = calculateNestingDepth(content); metrics.functionCount = countFunctions(content); metrics.classCount = countClasses(content); - + // Calculate maintainability index (simplified version) if (metrics.linesOfCode > 0) { double complexity = static_cast(metrics.cyclomaticComplexity); double loc = static_cast(metrics.linesOfCode); - metrics.maintainabilityIndex = std::max(0.0, - 171.0 - 5.2 * std::log(complexity) - 0.23 * complexity - 16.2 * std::log(loc)); + metrics.maintainabilityIndex = + std::max(0.0, 171.0 - 5.2 * std::log(complexity) - 0.23 * complexity - 16.2 * std::log(loc)); } - + return metrics; } size_t ComplexityAnalyzer::calculateCyclomaticComplexity(const std::string& content) { - size_t complexity = 1; // Base complexity - + size_t complexity = 1; // Base complexity + // Count decision points std::regex decisionPoints(R"(\b(if|else\s+if|while|for|do|switch|case|catch|\?)\b)"); std::sregex_iterator iter(content.begin(), content.end(), decisionPoints); std::sregex_iterator end; - + complexity += std::distance(iter, end); - + return complexity; } size_t ComplexityAnalyzer::calculateNestingDepth(const std::string& content) { size_t maxDepth = 0; size_t currentDepth = 0; - + for (char c : content) { if (c == '{') { currentDepth++; maxDepth = std::max(maxDepth, currentDepth); } else if (c == '}') { - if (currentDepth > 0) currentDepth--; + if (currentDepth > 0) + currentDepth--; } } - + return maxDepth; } @@ -152,7 +149,7 @@ size_t ComplexityAnalyzer::countFunctions(const std::string& content) { std::regex functionPattern(R"(\b\w+\s*\([^)]*\)\s*\{)"); std::sregex_iterator iter(content.begin(), content.end(), functionPattern); std::sregex_iterator end; - + return std::distance(iter, end); } @@ -160,7 +157,7 @@ size_t ComplexityAnalyzer::countClasses(const std::string& content) { std::regex classPattern(R"(\bclass\s+\w+)"); std::sregex_iterator iter(content.begin(), content.end(), classPattern); std::sregex_iterator end; - + return std::distance(iter, end); } @@ -169,11 +166,11 @@ std::vector ComplexityAnalyzer::extractFunctions(const std::string& std::regex functionPattern(R"(\b(\w+)\s*\([^)]*\)\s*\{)"); std::sregex_iterator iter(content.begin(), content.end(), functionPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { functions.push_back((*iter)[1].str()); } - + return functions; } @@ -182,136 +179,128 @@ std::vector SecurityAnalyzer::getSupportedExtensions() const { return {".cpp", ".c", ".cc", ".cxx"}; } -std::vector SecurityAnalyzer::analyzeFile(const std::string& filePath, - const std::string& content) { +std::vector SecurityAnalyzer::analyzeFile(const std::string& filePath, const std::string& content) { std::vector issues; - + auto bufferIssues = checkBufferOverflows(content, filePath); auto memoryIssues = checkMemoryLeaks(content, filePath); auto unsafeIssues = checkUnsafeFunctions(content, filePath); - + issues.insert(issues.end(), bufferIssues.begin(), bufferIssues.end()); issues.insert(issues.end(), memoryIssues.begin(), memoryIssues.end()); issues.insert(issues.end(), unsafeIssues.begin(), unsafeIssues.end()); - + return issues; } std::vector SecurityAnalyzer::analyzeProject(const std::string& projectPath) { std::vector allIssues; - + for (const auto& ext : getSupportedExtensions()) { for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { if (entry.is_regular_file() && entry.path().extension() == ext) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto fileIssues = analyzeFile(entry.path().string(), content); allIssues.insert(allIssues.end(), fileIssues.begin(), fileIssues.end()); } } } - + return allIssues; } -CodeMetrics SecurityAnalyzer::getMetrics(const std::string& filePath, - const std::string& content) { +CodeMetrics SecurityAnalyzer::getMetrics(const std::string& filePath, const std::string& content) { CodeMetrics metrics; - + // Count potential security issues as custom metrics auto bufferIssues = checkBufferOverflows(content, filePath); auto memoryIssues = checkMemoryLeaks(content, filePath); auto unsafeIssues = checkUnsafeFunctions(content, filePath); - + metrics.customMetrics["buffer_overflow_risks"] = bufferIssues.size(); metrics.customMetrics["memory_leak_risks"] = memoryIssues.size(); metrics.customMetrics["unsafe_function_uses"] = unsafeIssues.size(); - + return metrics; } -std::vector SecurityAnalyzer::checkBufferOverflows(const std::string& content, +std::vector SecurityAnalyzer::checkBufferOverflows(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for unsafe buffer operations std::regex unsafeBufferOps(R"(\b(strcpy|strcat|sprintf|gets)\s*\()"); std::sregex_iterator iter(content.begin(), content.end(), unsafeBufferOps); std::sregex_iterator end; - + for (; iter != end; ++iter) { - AnalysisIssue issue("UNSAFE_BUFFER_OP", - "Unsafe buffer operation: " + (*iter)[1].str(), - AnalysisSeverity::ERROR, AnalysisCategory::SECURITY); + AnalysisIssue issue("UNSAFE_BUFFER_OP", "Unsafe buffer operation: " + (*iter)[1].str(), AnalysisSeverity::ERROR, + AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back("Use safer alternatives like strncpy, strncat, snprintf"); issue.suggestions.push_back("Consider using std::string for better safety"); issues.push_back(issue); } - + return issues; } -std::vector SecurityAnalyzer::checkMemoryLeaks(const std::string& content, - const std::string& filePath) { +std::vector SecurityAnalyzer::checkMemoryLeaks(const std::string& content, const std::string& filePath) { std::vector issues; - + // Simple heuristic: count new/delete and malloc/free pairs std::regex newPattern(R"(\bnew\b)"); std::regex deletePattern(R"(\bdelete\b)"); std::regex mallocPattern(R"(\bmalloc\s*\()"); std::regex freePattern(R"(\bfree\s*\()"); - - size_t newCount = std::distance(std::sregex_iterator(content.begin(), content.end(), newPattern), - std::sregex_iterator()); - size_t deleteCount = std::distance(std::sregex_iterator(content.begin(), content.end(), deletePattern), - std::sregex_iterator()); - size_t mallocCount = std::distance(std::sregex_iterator(content.begin(), content.end(), mallocPattern), - std::sregex_iterator()); - size_t freeCount = std::distance(std::sregex_iterator(content.begin(), content.end(), freePattern), - std::sregex_iterator()); - + + size_t newCount = + std::distance(std::sregex_iterator(content.begin(), content.end(), newPattern), std::sregex_iterator()); + size_t deleteCount = + std::distance(std::sregex_iterator(content.begin(), content.end(), deletePattern), std::sregex_iterator()); + size_t mallocCount = + std::distance(std::sregex_iterator(content.begin(), content.end(), mallocPattern), std::sregex_iterator()); + size_t freeCount = + std::distance(std::sregex_iterator(content.begin(), content.end(), freePattern), std::sregex_iterator()); + if (newCount > deleteCount || mallocCount > freeCount) { - AnalysisIssue issue("POTENTIAL_MEMORY_LEAK", - "Potential memory leak detected (unmatched allocations)", - AnalysisSeverity::WARNING, AnalysisCategory::SECURITY); + AnalysisIssue issue("POTENTIAL_MEMORY_LEAK", "Potential memory leak detected (unmatched allocations)", + AnalysisSeverity::WARNING, AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back("Ensure all allocations have corresponding deallocations"); issue.suggestions.push_back("Consider using smart pointers for automatic memory management"); issues.push_back(issue); } - + return issues; } -std::vector SecurityAnalyzer::checkUnsafeFunctions(const std::string& content, +std::vector SecurityAnalyzer::checkUnsafeFunctions(const std::string& content, const std::string& filePath) { std::vector issues; - + std::vector> unsafeFunctions = { {"scanf", "Use cin or safer input methods"}, {"printf", "Consider using cout or safer output methods"}, {"system", "Avoid system calls, use safer alternatives"}, - {"popen", "Use safer process execution methods"} - }; - + {"popen", "Use safer process execution methods"}}; + for (const auto& [func, suggestion] : unsafeFunctions) { std::regex pattern("\\b" + func + "\\s*\\("); std::sregex_iterator iter(content.begin(), content.end(), pattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { - AnalysisIssue issue("UNSAFE_FUNCTION", - "Unsafe function usage: " + func, - AnalysisSeverity::WARNING, AnalysisCategory::SECURITY); + AnalysisIssue issue("UNSAFE_FUNCTION", "Unsafe function usage: " + func, AnalysisSeverity::WARNING, + AnalysisCategory::SECURITY); issue.filePath = filePath; issue.suggestions.push_back(suggestion); issues.push_back(issue); } } - + return issues; } @@ -320,79 +309,74 @@ std::vector DependencyAnalyzer::getSupportedExtensions() const { return {".cpp", ".hpp", ".c", ".h", ".cc", ".cxx", ".hxx"}; } -std::vector DependencyAnalyzer::analyzeFile(const std::string& filePath, - const std::string& content) { +std::vector DependencyAnalyzer::analyzeFile(const std::string& filePath, const std::string& content) { std::vector issues; - + auto includes = extractIncludes(content); - + // Check for too many dependencies if (includes.size() > 20) { - AnalysisIssue issue("TOO_MANY_DEPENDENCIES", - "Too many includes: " + std::to_string(includes.size()), - AnalysisSeverity::WARNING, AnalysisCategory::DEPENDENCIES); + AnalysisIssue issue("TOO_MANY_DEPENDENCIES", "Too many includes: " + std::to_string(includes.size()), + AnalysisSeverity::WARNING, AnalysisCategory::DEPENDENCIES); issue.filePath = filePath; issue.suggestions.push_back("Consider reducing dependencies"); issue.suggestions.push_back("Use forward declarations where possible"); issues.push_back(issue); } - + return issues; } std::vector DependencyAnalyzer::analyzeProject(const std::string& projectPath) { std::vector allIssues; - + // Analyze individual files for (const auto& ext : getSupportedExtensions()) { for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { if (entry.is_regular_file() && entry.path().extension() == ext) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto fileIssues = analyzeFile(entry.path().string(), content); allIssues.insert(allIssues.end(), fileIssues.begin(), fileIssues.end()); } } } - + // Check for circular dependencies auto circularDeps = findCircularDependencies(projectPath); for (const auto& dep : circularDeps) { if (dep.isCircular) { - AnalysisIssue issue("CIRCULAR_DEPENDENCY", - "Circular dependency detected: " + dep.fromFile + " <-> " + dep.toFile, - AnalysisSeverity::ERROR, AnalysisCategory::DEPENDENCIES); + AnalysisIssue issue("CIRCULAR_DEPENDENCY", + "Circular dependency detected: " + dep.fromFile + " <-> " + dep.toFile, + AnalysisSeverity::ERROR, AnalysisCategory::DEPENDENCIES); issue.suggestions.push_back("Break circular dependency by introducing interfaces"); issue.suggestions.push_back("Reorganize code to eliminate circular references"); allIssues.push_back(issue); } } - + return allIssues; } -CodeMetrics DependencyAnalyzer::getMetrics(const std::string& filePath, - const std::string& content) { +CodeMetrics DependencyAnalyzer::getMetrics(const std::string& filePath, const std::string& content) { CodeMetrics metrics; - + auto includes = extractIncludes(content); metrics.customMetrics["include_count"] = includes.size(); - + return metrics; } std::vector DependencyAnalyzer::getDependencies(const std::string& projectPath) { std::vector dependencies; - + for (const auto& ext : getSupportedExtensions()) { for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { if (entry.is_regular_file() && entry.path().extension() == ext) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto includes = extractIncludes(content); for (const auto& include : includes) { DependencyInfo dep; @@ -404,16 +388,16 @@ std::vector DependencyAnalyzer::getDependencies(const std::strin } } } - + return dependencies; } std::vector DependencyAnalyzer::findCircularDependencies(const std::string& projectPath) { std::vector circularDeps; - + auto depGraph = buildDependencyGraph(projectPath); auto cycles = findCycles(depGraph); - + for (const auto& cycle : cycles) { for (size_t i = 0; i < cycle.size(); ++i) { DependencyInfo dep; @@ -423,7 +407,7 @@ std::vector DependencyAnalyzer::findCircularDependencies(const s circularDeps.push_back(dep); } } - + return circularDeps; } @@ -432,23 +416,23 @@ std::vector DependencyAnalyzer::extractIncludes(const std::string& std::regex includePattern(R"(#include\s*[<"](.*?)[>"])"); std::sregex_iterator iter(content.begin(), content.end(), includePattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { includes.push_back((*iter)[1].str()); } - + return includes; } std::unordered_map> DependencyAnalyzer::buildDependencyGraph( const std::string& projectPath) { std::unordered_map> graph; - + auto dependencies = getDependencies(projectPath); for (const auto& dep : dependencies) { graph[dep.fromFile].push_back(dep.toFile); } - + return graph; } @@ -457,13 +441,13 @@ std::vector> DependencyAnalyzer::findCycles( std::vector> cycles; std::unordered_set visited; std::unordered_set recStack; - - std::function&)> dfs = + + std::function&)> dfs = [&](const std::string& node, std::vector& path) -> bool { visited.insert(node); recStack.insert(node); path.push_back(node); - + auto it = graph.find(node); if (it != graph.end()) { for (const auto& neighbor : it->second) { @@ -479,19 +463,19 @@ std::vector> DependencyAnalyzer::findCycles( } } } - + recStack.erase(node); path.pop_back(); return false; }; - + for (const auto& [node, _] : graph) { if (!visited.count(node)) { std::vector path; dfs(node, path); } } - + return cycles; } @@ -500,136 +484,123 @@ std::vector PerformanceAnalyzer::getSupportedExtensions() const { return {".cpp", ".c", ".cc", ".cxx"}; } -std::vector PerformanceAnalyzer::analyzeFile(const std::string& filePath, - const std::string& content) { +std::vector PerformanceAnalyzer::analyzeFile(const std::string& filePath, const std::string& content) { std::vector issues; - + auto inefficiencyIssues = detectInefficiencies(content, filePath); auto memoryIssues = detectMemoryIssues(content, filePath); auto algorithmicIssues = detectAlgorithmicIssues(content, filePath); - + issues.insert(issues.end(), inefficiencyIssues.begin(), inefficiencyIssues.end()); issues.insert(issues.end(), memoryIssues.begin(), memoryIssues.end()); issues.insert(issues.end(), algorithmicIssues.begin(), algorithmicIssues.end()); - + return issues; } std::vector PerformanceAnalyzer::analyzeProject(const std::string& projectPath) { std::vector allIssues; - + for (const auto& ext : getSupportedExtensions()) { for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { if (entry.is_regular_file() && entry.path().extension() == ext) { std::ifstream file(entry.path()); - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + auto fileIssues = analyzeFile(entry.path().string(), content); allIssues.insert(allIssues.end(), fileIssues.begin(), fileIssues.end()); } } } - + return allIssues; } -CodeMetrics PerformanceAnalyzer::getMetrics(const std::string& filePath, - const std::string& content) { +CodeMetrics PerformanceAnalyzer::getMetrics(const std::string& filePath, const std::string& content) { CodeMetrics metrics; - + auto inefficiencyIssues = detectInefficiencies(content, filePath); auto memoryIssues = detectMemoryIssues(content, filePath); auto algorithmicIssues = detectAlgorithmicIssues(content, filePath); - - metrics.customMetrics["performance_issues"] = inefficiencyIssues.size() + - memoryIssues.size() + - algorithmicIssues.size(); - + + metrics.customMetrics["performance_issues"] = + inefficiencyIssues.size() + memoryIssues.size() + algorithmicIssues.size(); + return metrics; } -std::vector PerformanceAnalyzer::detectInefficiencies(const std::string& content, +std::vector PerformanceAnalyzer::detectInefficiencies(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for string concatenation in loops std::regex stringConcatInLoop(R"(for\s*\([^}]*\+\s*=\s*[^;]*string)"); if (std::regex_search(content, stringConcatInLoop)) { - AnalysisIssue issue("STRING_CONCAT_IN_LOOP", - "String concatenation in loop detected", - AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("STRING_CONCAT_IN_LOOP", "String concatenation in loop detected", AnalysisSeverity::WARNING, + AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Use stringstream or reserve space for better performance"); issues.push_back(issue); } - + return issues; } -std::vector PerformanceAnalyzer::detectMemoryIssues(const std::string& content, +std::vector PerformanceAnalyzer::detectMemoryIssues(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for frequent allocations std::regex frequentAlloc(R"(\bnew\b.*\bfor\b|\bfor\b.*\bnew\b)"); if (std::regex_search(content, frequentAlloc)) { - AnalysisIssue issue("FREQUENT_ALLOCATION", - "Frequent memory allocation in loop detected", - AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("FREQUENT_ALLOCATION", "Frequent memory allocation in loop detected", + AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Pre-allocate memory outside the loop"); issue.suggestions.push_back("Use object pools for frequent allocations"); issues.push_back(issue); } - + return issues; } -std::vector PerformanceAnalyzer::detectAlgorithmicIssues(const std::string& content, +std::vector PerformanceAnalyzer::detectAlgorithmicIssues(const std::string& content, const std::string& filePath) { std::vector issues; - + // Check for nested loops (potential O(nยฒ) or worse) std::regex nestedLoops(R"(for\s*\([^}]*for\s*\()"); std::sregex_iterator iter(content.begin(), content.end(), nestedLoops); std::sregex_iterator end; - + size_t nestedLoopCount = std::distance(iter, end); if (nestedLoopCount > 0) { - AnalysisIssue issue("NESTED_LOOPS", - "Nested loops detected (" + std::to_string(nestedLoopCount) + ")", - AnalysisSeverity::INFO, AnalysisCategory::PERFORMANCE); + AnalysisIssue issue("NESTED_LOOPS", "Nested loops detected (" + std::to_string(nestedLoopCount) + ")", + AnalysisSeverity::INFO, AnalysisCategory::PERFORMANCE); issue.filePath = filePath; issue.suggestions.push_back("Consider algorithmic improvements to reduce complexity"); issue.suggestions.push_back("Look for opportunities to break or optimize inner loops"); issues.push_back(issue); } - + return issues; } // AnalysisResult implementation size_t AnalysisResult::getIssueCount(AnalysisSeverity severity) const { return std::count_if(issues.begin(), issues.end(), - [severity](const AnalysisIssue& issue) { - return issue.severity == severity; - }); + [severity](const AnalysisIssue& issue) { return issue.severity == severity; }); } size_t AnalysisResult::getIssueCount(AnalysisCategory category) const { return std::count_if(issues.begin(), issues.end(), - [category](const AnalysisIssue& issue) { - return issue.category == category; - }); + [category](const AnalysisIssue& issue) { return issue.category == category; }); } std::vector AnalysisResult::getIssuesForFile(const std::string& filePath) const { std::vector fileIssues; std::copy_if(issues.begin(), issues.end(), std::back_inserter(fileIssues), - [&filePath](const AnalysisIssue& issue) { - return issue.filePath == filePath; - }); + [&filePath](const AnalysisIssue& issue) { return issue.filePath == filePath; }); return fileIssues; } @@ -670,18 +641,17 @@ AnalysisResult CodeAnalyzer::analyzeFile(const std::string& filePath) { AnalysisResult result; result.projectPath = filePath; result.analysisTime = std::chrono::steady_clock::now(); - + auto startTime = std::chrono::steady_clock::now(); - + std::ifstream file(filePath); if (!file.is_open()) { LogManager::getInstance().error("Failed to open file for analysis: " + filePath); return result; } - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + // Run enabled analyzers for (const auto& [name, analyzer] : analyzers_) { if (analyzerEnabled_[name] && analyzer->isEnabled()) { @@ -689,30 +659,29 @@ AnalysisResult CodeAnalyzer::analyzeFile(const std::string& filePath) { auto extensions = analyzer->getSupportedExtensions(); std::filesystem::path path(filePath); if (std::find(extensions.begin(), extensions.end(), path.extension().string()) != extensions.end()) { - std::unique_ptr profiler; if (performanceProfilingEnabled_) { profiler = std::make_unique("analyzer_" + name, "analysis"); } - + auto issues = analyzer->analyzeFile(filePath, content); result.issues.insert(result.issues.end(), issues.begin(), issues.end()); - + auto metrics = analyzer->getMetrics(filePath, content); result.fileMetrics[filePath] = metrics; } } } - + auto endTime = std::chrono::steady_clock::now(); - result.analysisTimeMs = std::chrono::duration_cast>( - endTime - startTime).count(); - + result.analysisTimeMs = + std::chrono::duration_cast>(endTime - startTime).count(); + if (metricsCallback_) { metricsCallback_("analysis_time_ms", result.analysisTimeMs); metricsCallback_("issues_found", static_cast(result.issues.size())); } - + return result; } @@ -720,14 +689,14 @@ AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath) { return analyzeProject(projectPath, getRegisteredAnalyzers()); } -AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath, - const std::vector& enabledAnalyzers) { +AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath, + const std::vector& enabledAnalyzers) { AnalysisResult result; result.projectPath = projectPath; result.analysisTime = std::chrono::steady_clock::now(); - + auto startTime = std::chrono::steady_clock::now(); - + // Collect all supported file extensions std::unordered_set allExtensions; for (const auto& analyzerName : enabledAnalyzers) { @@ -737,35 +706,35 @@ AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath, allExtensions.insert(extensions.begin(), extensions.end()); } } - + // Find all relevant files - auto relevantFiles = findFilesWithExtensions(projectPath, - std::vector(allExtensions.begin(), allExtensions.end())); - + auto relevantFiles = + findFilesWithExtensions(projectPath, std::vector(allExtensions.begin(), allExtensions.end())); + // Run analyzers on each file std::vector allMetrics; for (const auto& filePath : relevantFiles) { std::ifstream file(filePath); - if (!file.is_open()) continue; - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); - + if (!file.is_open()) + continue; + + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + for (const auto& analyzerName : enabledAnalyzers) { auto it = analyzers_.find(analyzerName); if (it != analyzers_.end() && analyzerEnabled_[analyzerName] && it->second->isEnabled()) { auto extensions = it->second->getSupportedExtensions(); std::filesystem::path path(filePath); - + if (std::find(extensions.begin(), extensions.end(), path.extension().string()) != extensions.end()) { std::unique_ptr profiler; if (performanceProfilingEnabled_) { profiler = std::make_unique("analyzer_" + analyzerName, "analysis"); } - + auto issues = it->second->analyzeFile(filePath, content); result.issues.insert(result.issues.end(), issues.begin(), issues.end()); - + auto metrics = it->second->getMetrics(filePath, content); result.fileMetrics[filePath] = metrics; allMetrics.push_back(metrics); @@ -773,7 +742,7 @@ AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath, } } } - + // Run project-level analysis for (const auto& analyzerName : enabledAnalyzers) { auto it = analyzers_.find(analyzerName); @@ -782,12 +751,12 @@ AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath, if (performanceProfilingEnabled_) { profiler = std::make_unique("project_analyzer_" + analyzerName, "analysis"); } - + auto projectIssues = it->second->analyzeProject(projectPath); result.issues.insert(result.issues.end(), projectIssues.begin(), projectIssues.end()); } } - + // Get dependency information if (std::find(enabledAnalyzers.begin(), enabledAnalyzers.end(), "DependencyAnalyzer") != enabledAnalyzers.end()) { auto depAnalyzer = dynamic_cast(analyzers_["DependencyAnalyzer"].get()); @@ -795,32 +764,31 @@ AnalysisResult CodeAnalyzer::analyzeProject(const std::string& projectPath, result.dependencies = depAnalyzer->getDependencies(projectPath); } } - + // Aggregate metrics aggregateMetrics(allMetrics, result.overallMetrics); - + auto endTime = std::chrono::steady_clock::now(); - result.analysisTimeMs = std::chrono::duration_cast>( - endTime - startTime).count(); - + result.analysisTimeMs = + std::chrono::duration_cast>(endTime - startTime).count(); + if (metricsCallback_) { metricsCallback_("project_analysis_time_ms", result.analysisTimeMs); metricsCallback_("total_issues_found", static_cast(result.issues.size())); metricsCallback_("files_analyzed", static_cast(relevantFiles.size())); } - - LogManager::getInstance().info("Code analysis completed: " + - std::to_string(result.issues.size()) + " issues found in " + - std::to_string(relevantFiles.size()) + " files (" + - std::to_string(result.analysisTimeMs) + "ms)"); - + + LogManager::getInstance().info("Code analysis completed: " + std::to_string(result.issues.size()) + + " issues found in " + std::to_string(relevantFiles.size()) + " files (" + + std::to_string(result.analysisTimeMs) + "ms)"); + return result; } -void CodeAnalyzer::configure(const std::string& analyzerName, - const std::unordered_map& config) { +void CodeAnalyzer::configure(const std::string& analyzerName, + const std::unordered_map& config) { analyzerConfigs_[analyzerName] = config; - + auto it = analyzers_.find(analyzerName); if (it != analyzers_.end()) { it->second->configure(config); @@ -836,10 +804,10 @@ bool CodeAnalyzer::isAnalyzerEnabled(const std::string& analyzerName) const { return it != analyzerEnabled_.end() ? it->second : false; } -void CodeAnalyzer::exportResults(const AnalysisResult& result, const std::string& format, +void CodeAnalyzer::exportResults(const AnalysisResult& result, const std::string& format, const std::string& outputPath) { std::string reportContent = generateReport(result, format); - + std::ofstream file(outputPath); if (file.is_open()) { file << reportContent; @@ -851,16 +819,17 @@ void CodeAnalyzer::exportResults(const AnalysisResult& result, const std::string std::string CodeAnalyzer::generateReport(const AnalysisResult& result, const std::string& format) { std::ostringstream report; - + if (format == "json") { report << "{\n"; report << " \"projectPath\": \"" << result.projectPath << "\",\n"; - report << " \"analysisTime\": \"" << std::chrono::duration_cast( - result.analysisTime.time_since_epoch()).count() << "\",\n"; + report << " \"analysisTime\": \"" + << std::chrono::duration_cast(result.analysisTime.time_since_epoch()).count() + << "\",\n"; report << " \"analysisTimeMs\": " << result.analysisTimeMs << ",\n"; report << " \"totalIssues\": " << result.issues.size() << ",\n"; report << " \"issues\": [\n"; - + for (size_t i = 0; i < result.issues.size(); ++i) { const auto& issue = result.issues[i]; report << " {\n"; @@ -871,10 +840,11 @@ std::string CodeAnalyzer::generateReport(const AnalysisResult& result, const std report << " \"filePath\": \"" << issue.filePath << "\",\n"; report << " \"lineNumber\": " << issue.lineNumber << "\n"; report << " }"; - if (i < result.issues.size() - 1) report << ","; + if (i < result.issues.size() - 1) + report << ","; report << "\n"; } - + report << " ]\n"; report << "}\n"; } else { @@ -883,38 +853,36 @@ std::string CodeAnalyzer::generateReport(const AnalysisResult& result, const std report << "Project: " << result.projectPath << "\n"; report << "Analysis Time: " << result.analysisTimeMs << " ms\n"; report << "Total Issues: " << result.issues.size() << "\n\n"; - + // Group issues by severity - for (auto severity : {AnalysisSeverity::CRITICAL, AnalysisSeverity::ERROR, - AnalysisSeverity::WARNING, AnalysisSeverity::INFO}) { + for (auto severity : + {AnalysisSeverity::CRITICAL, AnalysisSeverity::ERROR, AnalysisSeverity::WARNING, AnalysisSeverity::INFO}) { auto count = result.getIssueCount(severity); if (count > 0) { report << formatSeverity(severity) << " Issues: " << count << "\n"; } } - + report << "\n=== Issues by Category ===\n"; - for (auto category : {AnalysisCategory::SECURITY, AnalysisCategory::PERFORMANCE, - AnalysisCategory::COMPLEXITY, AnalysisCategory::MAINTAINABILITY, - AnalysisCategory::DEPENDENCIES}) { + for (auto category : {AnalysisCategory::SECURITY, AnalysisCategory::PERFORMANCE, AnalysisCategory::COMPLEXITY, + AnalysisCategory::MAINTAINABILITY, AnalysisCategory::DEPENDENCIES}) { auto count = result.getIssueCount(category); if (count > 0) { report << formatCategory(category) << ": " << count << "\n"; } } - + report << "\n=== Detailed Issues ===\n"; for (const auto& issue : result.issues) { - report << "[" << formatSeverity(issue.severity) << "] " - << issue.filePath << ":" << issue.lineNumber << " - " - << issue.message << "\n"; + report << "[" << formatSeverity(issue.severity) << "] " << issue.filePath << ":" << issue.lineNumber + << " - " << issue.message << "\n"; for (const auto& suggestion : issue.suggestions) { report << " Suggestion: " << suggestion << "\n"; } report << "\n"; } } - + return report.str(); } @@ -926,10 +894,10 @@ void CodeAnalyzer::enablePerformanceProfiling(bool enabled) { performanceProfilingEnabled_ = enabled; } -std::vector CodeAnalyzer::findFilesWithExtensions(const std::string& path, - const std::vector& extensions) { +std::vector CodeAnalyzer::findFilesWithExtensions(const std::string& path, + const std::vector& extensions) { std::vector files; - + for (const auto& entry : std::filesystem::recursive_directory_iterator(path)) { if (entry.is_regular_file()) { auto ext = entry.path().extension().string(); @@ -938,7 +906,7 @@ std::vector CodeAnalyzer::findFilesWithExtensions(const std::string } } } - + return files; } @@ -953,12 +921,12 @@ void CodeAnalyzer::aggregateMetrics(const std::vector& fileMetrics, overall.functionCount += metrics.functionCount; overall.classCount += metrics.classCount; overall.namespaceCount += metrics.namespaceCount; - + for (const auto& [key, value] : metrics.customMetrics) { overall.customMetrics[key] += value; } } - + // Calculate averages if (!fileMetrics.empty()) { double totalMaintainability = 0.0; @@ -971,84 +939,96 @@ void CodeAnalyzer::aggregateMetrics(const std::vector& fileMetrics, std::string CodeAnalyzer::formatSeverity(AnalysisSeverity severity) const { switch (severity) { - case AnalysisSeverity::INFO: return "INFO"; - case AnalysisSeverity::WARNING: return "WARNING"; - case AnalysisSeverity::ERROR: return "ERROR"; - case AnalysisSeverity::CRITICAL: return "CRITICAL"; - default: return "UNKNOWN"; + case AnalysisSeverity::INFO: + return "INFO"; + case AnalysisSeverity::WARNING: + return "WARNING"; + case AnalysisSeverity::ERROR: + return "ERROR"; + case AnalysisSeverity::CRITICAL: + return "CRITICAL"; + default: + return "UNKNOWN"; } } std::string CodeAnalyzer::formatCategory(AnalysisCategory category) const { switch (category) { - case AnalysisCategory::COMPLEXITY: return "COMPLEXITY"; - case AnalysisCategory::MAINTAINABILITY: return "MAINTAINABILITY"; - case AnalysisCategory::PERFORMANCE: return "PERFORMANCE"; - case AnalysisCategory::SECURITY: return "SECURITY"; - case AnalysisCategory::STYLE: return "STYLE"; - case AnalysisCategory::DEPENDENCIES: return "DEPENDENCIES"; - case AnalysisCategory::MEMORY: return "MEMORY"; - case AnalysisCategory::TESTING: return "TESTING"; - case AnalysisCategory::ARCHITECTURE: return "ARCHITECTURE"; - default: return "UNKNOWN"; + case AnalysisCategory::COMPLEXITY: + return "COMPLEXITY"; + case AnalysisCategory::MAINTAINABILITY: + return "MAINTAINABILITY"; + case AnalysisCategory::PERFORMANCE: + return "PERFORMANCE"; + case AnalysisCategory::SECURITY: + return "SECURITY"; + case AnalysisCategory::STYLE: + return "STYLE"; + case AnalysisCategory::DEPENDENCIES: + return "DEPENDENCIES"; + case AnalysisCategory::MEMORY: + return "MEMORY"; + case AnalysisCategory::TESTING: + return "TESTING"; + case AnalysisCategory::ARCHITECTURE: + return "ARCHITECTURE"; + default: + return "UNKNOWN"; } } // RefactoringSuggestionEngine implementation -std::vector -RefactoringSuggestionEngine::generateSuggestions(const AnalysisResult& result) { +std::vector RefactoringSuggestionEngine::generateSuggestions( + const AnalysisResult& result) { std::vector suggestions; - + for (const auto& [filePath, metrics] : result.fileMetrics) { 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()); + auto fileSuggestions = generateSuggestionsForFile(filePath, content); suggestions.insert(suggestions.end(), fileSuggestions.begin(), fileSuggestions.end()); } } - + return suggestions; } -std::vector -RefactoringSuggestionEngine::generateSuggestionsForFile(const std::string& filePath, - const std::string& content) { +std::vector RefactoringSuggestionEngine::generateSuggestionsForFile( + const std::string& filePath, const std::string& content) { std::vector suggestions; - + auto extractMethodSuggestions = suggestExtractMethod(content, filePath); auto complexitySuggestions = suggestReduceComplexity(content, filePath); auto duplicationSuggestions = suggestRemoveDuplication(content, filePath); - + suggestions.insert(suggestions.end(), extractMethodSuggestions.begin(), extractMethodSuggestions.end()); suggestions.insert(suggestions.end(), complexitySuggestions.begin(), complexitySuggestions.end()); suggestions.insert(suggestions.end(), duplicationSuggestions.begin(), duplicationSuggestions.end()); - + return suggestions; } -std::vector -RefactoringSuggestionEngine::suggestExtractMethod(const std::string& content, - const std::string& filePath) { +std::vector RefactoringSuggestionEngine::suggestExtractMethod( + const std::string& content, const std::string& filePath) { std::vector suggestions; - + // Look for long functions that could be extracted std::regex functionPattern(R"((\w+)\s*\([^)]*\)\s*\{([^}]*)\})"); std::sregex_iterator iter(content.begin(), content.end(), functionPattern); std::sregex_iterator end; - + for (; iter != end; ++iter) { std::string functionBody = (*iter)[2].str(); size_t lineCount = std::count(functionBody.begin(), functionBody.end(), '\n'); - + if (lineCount > 20) { RefactoringSuggestion suggestion; suggestion.id = "EXTRACT_METHOD_" + (*iter)[1].str(); suggestion.title = "Extract method from long function"; - suggestion.description = "Function " + (*iter)[1].str() + " is " + - std::to_string(lineCount) + " lines long and could be broken down"; + suggestion.description = "Function " + (*iter)[1].str() + " is " + std::to_string(lineCount) + + " lines long and could be broken down"; suggestion.filePath = filePath; suggestion.confidenceScore = 0.8; suggestion.benefits.push_back("Improved readability"); @@ -1057,15 +1037,14 @@ RefactoringSuggestionEngine::suggestExtractMethod(const std::string& content, suggestions.push_back(suggestion); } } - + return suggestions; } -std::vector -RefactoringSuggestionEngine::suggestReduceComplexity(const std::string& content, - const std::string& filePath) { +std::vector RefactoringSuggestionEngine::suggestReduceComplexity( + const std::string& content, const std::string& filePath) { std::vector suggestions; - + // Look for nested if statements std::regex nestedIfs(R"(if\s*\([^{]*\{\s*if\s*\()"); if (std::regex_search(content, nestedIfs)) { @@ -1079,34 +1058,31 @@ RefactoringSuggestionEngine::suggestReduceComplexity(const std::string& content, suggestion.benefits.push_back("Reduced cognitive complexity"); suggestions.push_back(suggestion); } - + return suggestions; } -std::vector -RefactoringSuggestionEngine::suggestRemoveDuplication(const std::string& content, - const std::string& filePath) { +std::vector RefactoringSuggestionEngine::suggestRemoveDuplication( + const std::string& content, const std::string& filePath) { std::vector suggestions; - + // Simple duplication detection (this could be much more sophisticated) std::vector lines; std::istringstream stream(content); std::string line; - + while (std::getline(stream, line)) { // Remove leading/trailing whitespace - line.erase(line.begin(), std::find_if(line.begin(), line.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); - line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { - return !std::isspace(ch); - }).base(), line.end()); - + line.erase(line.begin(), + std::find_if(line.begin(), line.end(), [](unsigned char ch) { return !std::isspace(ch); })); + line.erase(std::find_if(line.rbegin(), line.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), + line.end()); + if (!line.empty() && line.find("//") != 0) { lines.push_back(line); } } - + // Look for repeated sequences of 3+ lines for (size_t i = 0; i < lines.size() - 2; ++i) { for (size_t j = i + 3; j < lines.size() - 2; ++j) { @@ -1117,13 +1093,13 @@ RefactoringSuggestionEngine::suggestRemoveDuplication(const std::string& content break; } } - + if (isDuplicate) { RefactoringSuggestion suggestion; suggestion.id = "REMOVE_DUPLICATION_" + std::to_string(i) + "_" + std::to_string(j); suggestion.title = "Remove code duplication"; - suggestion.description = "Duplicate code sequences found at lines " + - std::to_string(i + 1) + " and " + std::to_string(j + 1); + suggestion.description = "Duplicate code sequences found at lines " + std::to_string(i + 1) + " and " + + std::to_string(j + 1); suggestion.filePath = filePath; suggestion.startLine = i + 1; suggestion.endLine = i + 4; @@ -1131,12 +1107,12 @@ RefactoringSuggestionEngine::suggestRemoveDuplication(const std::string& content suggestion.benefits.push_back("Reduced maintenance burden"); suggestion.benefits.push_back("Improved consistency"); suggestions.push_back(suggestion); - break; // Avoid too many duplication reports + break; // Avoid too many duplication reports } } } - + return suggestions; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/core/editor_store.cpp b/src/bolt/core/editor_store.cpp index 83ea47fc..1b6d127a 100644 --- a/src/bolt/core/editor_store.cpp +++ b/src/bolt/core/editor_store.cpp @@ -3,4 +3,4 @@ namespace bolt { // All implementation is in the header -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/core/logging.cpp b/src/bolt/core/logging.cpp index cc32b456..07037118 100644 --- a/src/bolt/core/logging.cpp +++ b/src/bolt/core/logging.cpp @@ -1,8 +1,9 @@ #include "bolt/core/logging.hpp" -#include -#include + #include #include +#include +#include namespace bolt { @@ -15,9 +16,8 @@ std::string extractFilename(const std::string& filepath) { // Helper function to format timestamp std::string formatTimestamp(const std::chrono::system_clock::time_point& timestamp) { auto time_t = std::chrono::system_clock::to_time_t(timestamp); - auto ms = std::chrono::duration_cast( - timestamp.time_since_epoch()) % 1000; - + auto ms = std::chrono::duration_cast(timestamp.time_since_epoch()) % 1000; + std::stringstream ss; ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S"); ss << '.' << std::setfill('0') << std::setw(3) << ms.count(); @@ -35,26 +35,25 @@ std::string formatThreadId(const std::thread::id& threadId) { std::string SimpleFormatter::format(const LogEntry& entry) { std::stringstream ss; ss << "[" << Logger::levelToString(entry.level) << "] " - << "[" << Logger::categoryToString(entry.category) << "] " - << entry.message; + << "[" << Logger::categoryToString(entry.category) << "] " << entry.message; return ss.str(); } // DetailedFormatter implementation std::string DetailedFormatter::format(const LogEntry& entry) { std::stringstream ss; - + if (includeTimestamp_) { ss << "[" << formatTimestamp(entry.timestamp) << "] "; } - + ss << "[" << Logger::levelToString(entry.level) << "] "; ss << "[" << Logger::categoryToString(entry.category) << "] "; - + if (includeThreadId_) { ss << "[T:" << formatThreadId(entry.threadId) << "] "; } - + if (includeLocation_ && !entry.file.empty()) { ss << "[" << extractFilename(entry.file) << ":" << entry.line; if (!entry.function.empty()) { @@ -62,7 +61,7 @@ std::string DetailedFormatter::format(const LogEntry& entry) { } ss << "] "; } - + ss << entry.message; return ss.str(); } @@ -76,16 +75,16 @@ std::string JsonFormatter::format(const LogEntry& entry) { << "\"category\":\"" << Logger::categoryToString(entry.category) << "\"," << "\"thread\":\"" << formatThreadId(entry.threadId) << "\"," << "\"message\":\"" << entry.message << "\""; - + if (!entry.file.empty()) { ss << ",\"file\":\"" << extractFilename(entry.file) << "\"" << ",\"line\":" << entry.line; } - + if (!entry.function.empty()) { ss << ",\"function\":\"" << entry.function << "\""; } - + ss << "}"; return ss.str(); } @@ -93,16 +92,16 @@ std::string JsonFormatter::format(const LogEntry& entry) { // ConsoleSink implementation void ConsoleSink::write(const LogEntry& entry, const std::string& formattedMessage) { std::ostream& stream = useStderr_ ? std::cerr : std::cout; - + // Use different colors based on log level (if terminal supports it) if (entry.level >= LogLevel::ERROR) { - stream << "\033[31m" << formattedMessage << "\033[0m" << std::endl; // Red + stream << "\033[31m" << formattedMessage << "\033[0m" << std::endl; // Red } else if (entry.level == LogLevel::WARN) { - stream << "\033[33m" << formattedMessage << "\033[0m" << std::endl; // Yellow + stream << "\033[33m" << formattedMessage << "\033[0m" << std::endl; // Yellow } else if (entry.level == LogLevel::DEBUG) { - stream << "\033[36m" << formattedMessage << "\033[0m" << std::endl; // Cyan + stream << "\033[36m" << formattedMessage << "\033[0m" << std::endl; // Cyan } else { - stream << formattedMessage << std::endl; // Default color + stream << formattedMessage << std::endl; // Default color } } @@ -118,7 +117,7 @@ FileSink::FileSink(const std::string& filename) : filename_(filename) { if (filepath.has_parent_path()) { std::filesystem::create_directories(filepath.parent_path()); } - + file_.open(filename, std::ios::app); if (!file_.is_open()) { throw std::runtime_error("Failed to open log file: " + filename); @@ -152,18 +151,17 @@ bool FileSink::isOpen() const { // RotatingFileSink implementation RotatingFileSink::RotatingFileSink(const std::string& baseFilename, size_t maxFileSize, size_t maxFiles) : baseFilename_(baseFilename), maxFileSize_(maxFileSize), maxFiles_(maxFiles), currentFileSize_(0) { - // Create directory if it doesn't exist std::filesystem::path filepath(baseFilename); if (filepath.has_parent_path()) { std::filesystem::create_directories(filepath.parent_path()); } - + currentFile_ = std::make_unique(baseFilename, std::ios::app); if (!currentFile_->is_open()) { throw std::runtime_error("Failed to open rotating log file: " + baseFilename); } - + // Get current file size std::filesystem::path path(baseFilename); if (std::filesystem::exists(path)) { @@ -181,22 +179,22 @@ void RotatingFileSink::rotateFile() { if (currentFile_ && currentFile_->is_open()) { currentFile_->close(); } - + // Move existing files for (int i = maxFiles_ - 1; i >= 1; --i) { std::string oldFile = getRotatedFilename(i - 1); std::string newFile = getRotatedFilename(i); - + if (std::filesystem::exists(oldFile)) { std::filesystem::rename(oldFile, newFile); } } - + // Move current file to .1 if (std::filesystem::exists(baseFilename_)) { std::filesystem::rename(baseFilename_, getRotatedFilename(1)); } - + // Open new current file currentFile_ = std::make_unique(baseFilename_, std::ios::app); currentFileSize_ = 0; @@ -208,17 +206,17 @@ std::string RotatingFileSink::getRotatedFilename(size_t index) { void RotatingFileSink::write(const LogEntry& entry, const std::string& formattedMessage) { std::lock_guard lock(mutex_); - + if (!currentFile_ || !currentFile_->is_open()) { return; } - + // Check if we need to rotate - size_t messageSize = formattedMessage.length() + 1; // +1 for newline + size_t messageSize = formattedMessage.length() + 1; // +1 for newline if (currentFileSize_ + messageSize > maxFileSize_) { rotateFile(); } - + if (currentFile_ && currentFile_->is_open()) { *currentFile_ << formattedMessage << std::endl; currentFileSize_ += messageSize; @@ -245,9 +243,7 @@ bool CategoryFilter::shouldLog(const LogEntry& entry) { // Logger implementation Logger::Logger(LogLevel level, LogCategory defaultCategory) - : level_(level), defaultCategory_(defaultCategory), enabled_(true), - totalMessages_(0), droppedMessages_(0) { - + : level_(level), defaultCategory_(defaultCategory), enabled_(true), totalMessages_(0), droppedMessages_(0) { // Set default formatter formatter_ = std::make_unique(); } @@ -261,19 +257,19 @@ bool Logger::shouldLog(const LogEntry& entry) const { if (!enabled_.read([](const bool& e) { return e; })) { return false; } - + // Check level if (entry.level < level_) { return false; } - + // Check filters for (const auto& filter : filters_) { if (!filter->shouldLog(entry)) { return false; } } - + return true; } @@ -281,9 +277,9 @@ void Logger::writeToSinks(const LogEntry& entry) { if (sinks_.empty()) { return; } - + std::string formattedMessage = formatter_->format(entry); - + for (const auto& sink : sinks_) { try { if (sink->isOpen()) { @@ -297,17 +293,17 @@ void Logger::writeToSinks(const LogEntry& entry) { } } -void Logger::log(LogLevel level, LogCategory category, const std::string& message, - const std::string& file, int line, const std::string& function) { +void Logger::log(LogLevel level, LogCategory category, const std::string& message, const std::string& file, int line, + const std::string& function) { LogEntry entry(level, category, message, file, line, function); - + totalMessages_++; - + if (!shouldLog(entry)) { droppedMessages_++; return; } - + std::lock_guard lock(mutex_); writeToSinks(entry); } @@ -360,64 +356,101 @@ void Logger::flush() { std::string Logger::levelToString(LogLevel level) { switch (level) { - case LogLevel::TRACE: return "TRACE"; - case LogLevel::DEBUG: return "DEBUG"; - case LogLevel::INFO: return "INFO"; - case LogLevel::WARN: return "WARN"; - case LogLevel::ERROR: return "ERROR"; - case LogLevel::FATAL: return "FATAL"; - case LogLevel::OFF: return "OFF"; - default: return "UNKNOWN"; + case LogLevel::TRACE: + return "TRACE"; + case LogLevel::DEBUG: + return "DEBUG"; + case LogLevel::INFO: + return "INFO"; + case LogLevel::WARN: + return "WARN"; + case LogLevel::ERROR: + return "ERROR"; + case LogLevel::FATAL: + return "FATAL"; + case LogLevel::OFF: + return "OFF"; + default: + return "UNKNOWN"; } } std::string Logger::categoryToString(LogCategory category) { switch (category) { - case LogCategory::CORE: return "CORE"; - case LogCategory::MEMORY: return "MEMORY"; - case LogCategory::EDITOR: return "EDITOR"; - case LogCategory::AI: return "AI"; - case LogCategory::GUI: return "GUI"; - case LogCategory::NETWORK: return "NETWORK"; - case LogCategory::PLUGIN: return "PLUGIN"; - case LogCategory::COLLABORATION: return "COLLABORATION"; - case LogCategory::DEBUGGER: return "DEBUGGER"; - case LogCategory::TESTING: return "TESTING"; - case LogCategory::UNKNOWN: return "UNKNOWN"; - default: return "UNKNOWN"; + case LogCategory::CORE: + return "CORE"; + case LogCategory::MEMORY: + return "MEMORY"; + case LogCategory::EDITOR: + return "EDITOR"; + case LogCategory::AI: + return "AI"; + case LogCategory::GUI: + return "GUI"; + case LogCategory::NETWORK: + return "NETWORK"; + case LogCategory::PLUGIN: + return "PLUGIN"; + case LogCategory::COLLABORATION: + return "COLLABORATION"; + case LogCategory::DEBUGGER: + return "DEBUGGER"; + case LogCategory::TESTING: + return "TESTING"; + case LogCategory::UNKNOWN: + return "UNKNOWN"; + default: + return "UNKNOWN"; } } LogLevel Logger::stringToLevel(const std::string& levelStr) { std::string upper = levelStr; std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper); - - if (upper == "TRACE") return LogLevel::TRACE; - if (upper == "DEBUG") return LogLevel::DEBUG; - if (upper == "INFO") return LogLevel::INFO; - if (upper == "WARN" || upper == "WARNING") return LogLevel::WARN; - if (upper == "ERROR") return LogLevel::ERROR; - if (upper == "FATAL") return LogLevel::FATAL; - if (upper == "OFF") return LogLevel::OFF; - - return LogLevel::INFO; // Default + + if (upper == "TRACE") + return LogLevel::TRACE; + if (upper == "DEBUG") + return LogLevel::DEBUG; + if (upper == "INFO") + return LogLevel::INFO; + if (upper == "WARN" || upper == "WARNING") + return LogLevel::WARN; + if (upper == "ERROR") + return LogLevel::ERROR; + if (upper == "FATAL") + return LogLevel::FATAL; + if (upper == "OFF") + return LogLevel::OFF; + + return LogLevel::INFO; // Default } LogCategory Logger::stringToCategory(const std::string& categoryStr) { std::string upper = categoryStr; std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper); - - if (upper == "CORE") return LogCategory::CORE; - if (upper == "MEMORY") return LogCategory::MEMORY; - if (upper == "EDITOR") return LogCategory::EDITOR; - if (upper == "AI") return LogCategory::AI; - if (upper == "GUI") return LogCategory::GUI; - if (upper == "NETWORK") return LogCategory::NETWORK; - if (upper == "PLUGIN") return LogCategory::PLUGIN; - if (upper == "COLLABORATION") return LogCategory::COLLABORATION; - if (upper == "DEBUGGER") return LogCategory::DEBUGGER; - if (upper == "TESTING") return LogCategory::TESTING; - + + if (upper == "CORE") + return LogCategory::CORE; + if (upper == "MEMORY") + return LogCategory::MEMORY; + if (upper == "EDITOR") + return LogCategory::EDITOR; + if (upper == "AI") + return LogCategory::AI; + if (upper == "GUI") + return LogCategory::GUI; + if (upper == "NETWORK") + return LogCategory::NETWORK; + if (upper == "PLUGIN") + return LogCategory::PLUGIN; + if (upper == "COLLABORATION") + return LogCategory::COLLABORATION; + if (upper == "DEBUGGER") + return LogCategory::DEBUGGER; + if (upper == "TESTING") + return LogCategory::TESTING; + return LogCategory::UNKNOWN; } @@ -448,68 +481,68 @@ void LogManager::reset() { void LogManager::configureConsoleLogging(LogLevel level, bool useDetailedFormat) { auto logger = std::make_unique(level); logger->addSink(std::make_unique()); - + if (useDetailedFormat) { logger->setFormatter(std::make_unique(true, true, false)); } else { logger->setFormatter(std::make_unique()); } - + setGlobalLogger(std::move(logger)); } void LogManager::configureFileLogging(const std::string& filename, LogLevel level, bool useDetailedFormat) { auto logger = std::make_unique(level); logger->addSink(std::make_unique(filename)); - + if (useDetailedFormat) { logger->setFormatter(std::make_unique(true, true, true)); } else { logger->setFormatter(std::make_unique()); } - + setGlobalLogger(std::move(logger)); } -void LogManager::configureRotatingFileLogging(const std::string& baseFilename, size_t maxFileSize, size_t maxFiles, LogLevel level) { +void LogManager::configureRotatingFileLogging(const std::string& baseFilename, size_t maxFileSize, size_t maxFiles, + LogLevel level) { auto logger = std::make_unique(level); logger->addSink(std::make_unique(baseFilename, maxFileSize, maxFiles)); logger->setFormatter(std::make_unique(true, true, true)); - + setGlobalLogger(std::move(logger)); } void LogManager::configureDualLogging(const std::string& filename, LogLevel consoleLevel, LogLevel fileLevel) { auto logger = std::make_unique(std::min(consoleLevel, fileLevel)); - + // Add console sink with level filter logger->addSink(std::make_unique()); logger->addFilter(std::make_unique(consoleLevel)); - + // Add file sink logger->addSink(std::make_unique(filename)); - + // Use detailed formatter for file logging logger->setFormatter(std::make_unique(true, true, true)); - + setGlobalLogger(std::move(logger)); } // ScopedLogger implementation ScopedLogger::ScopedLogger(const std::string& function, LogCategory category) : function_(function), category_(category), startTime_(std::chrono::steady_clock::now()) { - LogManager::getInstance().log(LogLevel::TRACE, category_, "Entering " + function_); } ScopedLogger::~ScopedLogger() { auto endTime = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast(endTime - startTime_); - + std::stringstream ss; ss << "Exiting " << function_ << " (took " << duration.count() << "ฮผs)"; - + LogManager::getInstance().log(LogLevel::TRACE, category_, ss.str()); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/core/memory_leak_detector.cpp b/src/bolt/core/memory_leak_detector.cpp index 3b3ec3c8..20fe6029 100644 --- a/src/bolt/core/memory_leak_detector.cpp +++ b/src/bolt/core/memory_leak_detector.cpp @@ -1,4 +1,5 @@ #include "bolt/core/memory_leak_detector.hpp" + #include namespace bolt { @@ -6,4 +7,4 @@ namespace bolt { // Implementation is mostly inline in the header for template compatibility // This file exists for potential future non-template implementations -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/core/memory_manager.cpp b/src/bolt/core/memory_manager.cpp index 6eec38a1..b8d0e733 100644 --- a/src/bolt/core/memory_manager.cpp +++ b/src/bolt/core/memory_manager.cpp @@ -3,4 +3,4 @@ namespace bolt { // All implementation is in the header for simplicity -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/core/memory_pool.cpp b/src/bolt/core/memory_pool.cpp index 012d4232..2794ecd4 100644 --- a/src/bolt/core/memory_pool.cpp +++ b/src/bolt/core/memory_pool.cpp @@ -3,4 +3,4 @@ namespace bolt { // All implementation is in the header -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/core/message_handler.cpp b/src/bolt/core/message_handler.cpp index 1f93c162..1d4bd628 100644 --- a/src/bolt/core/message_handler.cpp +++ b/src/bolt/core/message_handler.cpp @@ -1,41 +1,43 @@ #include "bolt/core/message_handler.hpp" -#include "bolt/core/chat_store.hpp" -#include + #include +#include + +#include "bolt/core/chat_store.hpp" namespace bolt { class MessageHandlerImpl { -private: + private: std::queue messageQueue_; mutable std::mutex queueMutex_; size_t maxQueueSize_ = MessageHandler::DEFAULT_MAX_QUEUE_SIZE; - -public: + + public: void setMaxQueueSize(size_t maxSize) { std::lock_guard lock(queueMutex_); ErrorHandler::validateParameter(maxSize > 0, "Max queue size must be greater than 0"); maxQueueSize_ = maxSize; } - + void pushMessage(const Message& msg) { - // Only validate non-empty messages + // Only validate non-empty messages if (!msg.content.empty()) { - msg.validateMessage(); // Validate message before adding to queue + msg.validateMessage(); // Validate message before adding to queue } - + std::lock_guard lock(queueMutex_); - + if (messageQueue_.size() >= maxQueueSize_) { throw MessageException(ErrorCode::MESSAGE_QUEUE_FULL, - "Message queue is full. Size: " + std::to_string(messageQueue_.size()) + - ", Max: " + std::to_string(maxQueueSize_)); + "Message queue is full. Size: " + std::to_string(messageQueue_.size()) + + ", Max: " + std::to_string(maxQueueSize_)); } - + messageQueue_.push(msg); } - + bool popMessage(Message& msg) { std::lock_guard lock(queueMutex_); if (messageQueue_.empty()) { @@ -45,7 +47,7 @@ class MessageHandlerImpl { messageQueue_.pop(); return true; } - + size_t getQueueSize() const { std::lock_guard lock(queueMutex_); return messageQueue_.size(); @@ -54,8 +56,8 @@ class MessageHandlerImpl { void processMessages() { Message msg; size_t processedCount = 0; - const size_t maxProcessPerCall = 100; // Prevent infinite processing - + const size_t maxProcessPerCall = 100; // Prevent infinite processing + while (popMessage(msg) && processedCount < maxProcessPerCall) { try { switch (msg.type) { @@ -70,27 +72,26 @@ class MessageHandlerImpl { break; default: throw MessageException(ErrorCode::INVALID_MESSAGE_TYPE, - "Unknown message type: " + std::to_string(static_cast(msg.type))); + "Unknown message type: " + std::to_string(static_cast(msg.type))); } processedCount++; } catch (const BoltException& e) { // Log the error but continue processing other messages // In a real implementation, this would go to a proper logging system - processSystemMessage(Message(MessageType::System, - "Error processing message: " + std::string(e.what()))); + processSystemMessage( + Message(MessageType::System, "Error processing message: " + std::string(e.what()))); } } } -private: + private: void processChatMessage(const Message& msg) { // Allow empty messages for chat (can be valid in some cases) // But validate that we have meaningful content for non-whitespace if (!msg.content.empty() && msg.content.find_first_not_of(" \t\n\r") == std::string::npos) { - throw MessageException(ErrorCode::INVALID_PARAMETER, - "Chat message cannot be whitespace only"); + throw MessageException(ErrorCode::INVALID_PARAMETER, "Chat message cannot be whitespace only"); } - + // Handle chat messages - simplified for now // ChatStore::getInstance().addMessage(...); } @@ -98,14 +99,12 @@ class MessageHandlerImpl { void processCommandMessage(const Message& msg) { // Commands must be non-empty and start with '/' if (msg.content.empty()) { - throw MessageException(ErrorCode::INVALID_PARAMETER, - "Command messages cannot be empty"); + throw MessageException(ErrorCode::INVALID_PARAMETER, "Command messages cannot be empty"); } if (msg.content[0] != '/') { - throw MessageException(ErrorCode::INVALID_PARAMETER, - "Command messages must start with '/'"); + throw MessageException(ErrorCode::INVALID_PARAMETER, "Command messages must start with '/'"); } - + // Handle command messages // This will be expanded based on command processing needs } @@ -113,10 +112,9 @@ class MessageHandlerImpl { void processSystemMessage(const Message& msg) { // System messages can be empty (for internal use) if (msg.content.length() > Message::MAX_MESSAGE_LENGTH) { - throw MessageException(ErrorCode::INVALID_PARAMETER, - "System message too long"); + throw MessageException(ErrorCode::INVALID_PARAMETER, "System message too long"); } - + // Handle system messages // This will be expanded based on system message needs } @@ -159,4 +157,4 @@ void MessageHandler::setMaxQueueSize(size_t maxSize) { impl_->setMaxQueueSize(maxSize); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/core/performance_profiler.cpp b/src/bolt/core/performance_profiler.cpp index 2f83f42d..eb014517 100644 --- a/src/bolt/core/performance_profiler.cpp +++ b/src/bolt/core/performance_profiler.cpp @@ -1,10 +1,11 @@ #include "bolt/core/performance_profiler.hpp" -#include -#include + #include -#include #include #include +#include +#include +#include #include #ifndef _WIN32 @@ -26,9 +27,7 @@ std::mutex PerformanceProfiler::instanceMutex_; thread_local std::shared_ptr PerformanceProfiler::currentSession_; // ProfilerSession implementation -ProfilerSession::ProfilerSession(const std::string& name) - : sessionName_(name), isActive_(false) { -} +ProfilerSession::ProfilerSession(const std::string& name) : sessionName_(name), isActive_(false) {} ProfilerSession::~ProfilerSession() { if (isActive_) { @@ -74,8 +73,9 @@ size_t ProfilerSession::getMetricsCount() const { double ProfilerSession::getAverageDurationMs() const { auto metrics = getMetrics(); - if (metrics.empty()) return 0.0; - + if (metrics.empty()) + return 0.0; + double total = 0.0; for (const auto& metric : metrics) { total += metric->getDurationMs(); @@ -85,8 +85,9 @@ double ProfilerSession::getAverageDurationMs() const { double ProfilerSession::getMinDurationMs() const { auto metrics = getMetrics(); - if (metrics.empty()) return 0.0; - + if (metrics.empty()) + return 0.0; + double minDuration = metrics[0]->getDurationMs(); for (const auto& metric : metrics) { minDuration = std::min(minDuration, metric->getDurationMs()); @@ -96,8 +97,9 @@ double ProfilerSession::getMinDurationMs() const { double ProfilerSession::getMaxDurationMs() const { auto metrics = getMetrics(); - if (metrics.empty()) return 0.0; - + if (metrics.empty()) + return 0.0; + double maxDuration = metrics[0]->getDurationMs(); for (const auto& metric : metrics) { maxDuration = std::max(maxDuration, metric->getDurationMs()); @@ -106,9 +108,7 @@ double ProfilerSession::getMaxDurationMs() const { } // PerformanceProfiler implementation -PerformanceProfiler::PerformanceProfiler() - : isEnabled_(true), isSystemMonitoringEnabled_(false) { -} +PerformanceProfiler::PerformanceProfiler() : isEnabled_(true), isSystemMonitoringEnabled_(false) {} PerformanceProfiler& PerformanceProfiler::getInstance() { std::lock_guard lock(instanceMutex_); @@ -119,8 +119,9 @@ PerformanceProfiler& PerformanceProfiler::getInstance() { } std::shared_ptr PerformanceProfiler::createSession(const std::string& name) { - if (!isEnabled_) return nullptr; - + if (!isEnabled_) + return nullptr; + std::lock_guard lock(sessionsMutex_); auto session = std::make_shared(name); sessions_[name] = session; @@ -157,25 +158,28 @@ void PerformanceProfiler::endSession(const std::string& name) { } } -std::shared_ptr PerformanceProfiler::startMetric(const std::string& name, const std::string& category) { - if (!isEnabled_) return nullptr; - +std::shared_ptr PerformanceProfiler::startMetric(const std::string& name, + const std::string& category) { + if (!isEnabled_) + return nullptr; + auto metric = std::make_shared(name, category); - + // Add system monitoring if enabled if (isSystemMonitoringEnabled_) { metric->memoryUsage = getCurrentMemoryUsage(); metric->cpuUsage = getCurrentCPUUsage(); } - + return metric; } void PerformanceProfiler::endMetric(std::shared_ptr metric) { - if (!metric || !isEnabled_) return; - + if (!metric || !isEnabled_) + return; + metric->finish(); - + // Add to current session if available auto currentSession = getCurrentSession(); if (currentSession && currentSession->isActive()) { @@ -185,18 +189,19 @@ void PerformanceProfiler::endMetric(std::shared_ptr metric) { std::lock_guard lock(metricsMutex_); globalMetrics_.push_back(metric); } - + // Log the metric logMetric(*metric); } void PerformanceProfiler::recordInstantMetric(const std::string& name, double value, const std::string& category) { - if (!isEnabled_) return; - + if (!isEnabled_) + return; + auto metric = std::make_shared(name, category); metric->finish(); metric->duration = std::chrono::duration(value); - + // Add to current session or global metrics auto currentSession = getCurrentSession(); if (currentSession && currentSession->isActive()) { @@ -217,7 +222,7 @@ size_t PerformanceProfiler::getCurrentMemoryUsage() const { std::string key, unit; size_t value; iss >> key >> value >> unit; - return value * 1024; // Convert from KB to bytes + return value * 1024; // Convert from KB to bytes } } #endif @@ -230,18 +235,18 @@ double PerformanceProfiler::getCurrentCPUUsage() const { #ifdef __linux__ static auto lastTime = std::chrono::steady_clock::now(); static clock_t lastCpuTime = clock(); - + auto currentTime = std::chrono::steady_clock::now(); clock_t currentCpuTime = clock(); - + auto wallTime = std::chrono::duration_cast(currentTime - lastTime).count(); auto cpuTime = (currentCpuTime - lastCpuTime) * 1000000 / CLOCKS_PER_SEC; - + lastTime = currentTime; lastCpuTime = currentCpuTime; - + if (wallTime > 0) { - return (double)cpuTime / wallTime * 100.0; + return static_cast(cpuTime) / wallTime * 100.0; } #endif return 0.0; @@ -253,28 +258,30 @@ void PerformanceProfiler::exportToJson(const std::string& filename) const { LogManager::getInstance().error("Failed to open file for JSON export: " + filename); return; } - + file << "{\n"; file << " \"sessions\": [\n"; - + std::lock_guard sessionsLock(sessionsMutex_); bool firstSession = true; for (const auto& [name, session] : sessions_) { - if (!firstSession) file << ",\n"; + if (!firstSession) + file << ",\n"; firstSession = false; - + file << " {\n"; file << " \"name\": \"" << name << "\",\n"; file << " \"totalDuration\": " << session->getTotalDurationMs() << ",\n"; file << " \"metricsCount\": " << session->getMetricsCount() << ",\n"; file << " \"metrics\": [\n"; - + auto metrics = session->getMetrics(); bool firstMetric = true; for (const auto& metric : metrics) { - if (!firstMetric) file << ",\n"; + if (!firstMetric) + file << ",\n"; firstMetric = false; - + file << " {\n"; file << " \"name\": \"" << metric->name << "\",\n"; file << " \"category\": \"" << metric->category << "\",\n"; @@ -282,20 +289,21 @@ void PerformanceProfiler::exportToJson(const std::string& filename) const { file << " \"memoryUsage\": " << metric->memoryUsage << "\n"; file << " }"; } - + file << "\n ]\n"; file << " }"; } - + file << "\n ],\n"; file << " \"globalMetrics\": [\n"; - + std::lock_guard metricsLock(metricsMutex_); bool firstGlobalMetric = true; for (const auto& metric : globalMetrics_) { - if (!firstGlobalMetric) file << ",\n"; + if (!firstGlobalMetric) + file << ",\n"; firstGlobalMetric = false; - + file << " {\n"; file << " \"name\": \"" << metric->name << "\",\n"; file << " \"category\": \"" << metric->category << "\",\n"; @@ -303,10 +311,10 @@ void PerformanceProfiler::exportToJson(const std::string& filename) const { file << " \"memoryUsage\": " << metric->memoryUsage << "\n"; file << " }"; } - + file << "\n ]\n"; file << "}\n"; - + file.close(); } @@ -316,53 +324,46 @@ void PerformanceProfiler::exportToCsv(const std::string& filename) const { LogManager::getInstance().error("Failed to open file for CSV export: " + filename); return; } - + // CSV header file << "Session,Name,Category,Duration(ms),MemoryUsage(bytes)\n"; - + // Sessions std::lock_guard sessionsLock(sessionsMutex_); for (const auto& [sessionName, session] : sessions_) { auto metrics = session->getMetrics(); for (const auto& metric : metrics) { - file << sessionName << "," - << metric->name << "," - << metric->category << "," - << metric->getDurationMs() << "," - << metric->memoryUsage << "\n"; + file << sessionName << "," << metric->name << "," << metric->category << "," << metric->getDurationMs() + << "," << metric->memoryUsage << "\n"; } } - + // Global metrics std::lock_guard metricsLock(metricsMutex_); for (const auto& metric : globalMetrics_) { - file << "Global," - << metric->name << "," - << metric->category << "," - << metric->getDurationMs() << "," + file << "Global," << metric->name << "," << metric->category << "," << metric->getDurationMs() << "," << metric->memoryUsage << "\n"; } - + file.close(); } void PerformanceProfiler::printSummary() const { auto& logger = LogManager::getInstance(); - + logger.info("=== Performance Profiler Summary ==="); - + std::lock_guard sessionsLock(sessionsMutex_); logger.info("Sessions: " + std::to_string(sessions_.size())); - + for (const auto& [name, session] : sessions_) { - logger.info("Session '" + name + "': " + - std::to_string(session->getMetricsCount()) + " metrics, " + - std::to_string(session->getTotalDurationMs()) + " ms total"); + logger.info("Session '" + name + "': " + std::to_string(session->getMetricsCount()) + " metrics, " + + std::to_string(session->getTotalDurationMs()) + " ms total"); } - + std::lock_guard metricsLock(metricsMutex_); logger.info("Global metrics: " + std::to_string(globalMetrics_.size())); - + if (!globalMetrics_.empty()) { double totalDuration = 0.0; for (const auto& metric : globalMetrics_) { @@ -375,9 +376,9 @@ void PerformanceProfiler::printSummary() const { void PerformanceProfiler::printDetailedReport() const { auto& logger = LogManager::getInstance(); - + logger.info("=== Detailed Performance Report ==="); - + // Sessions std::lock_guard sessionsLock(sessionsMutex_); for (const auto& [name, session] : sessions_) { @@ -387,21 +388,21 @@ void PerformanceProfiler::printDetailedReport() const { logger.info(" Average Duration: " + std::to_string(session->getAverageDurationMs()) + " ms"); logger.info(" Min Duration: " + std::to_string(session->getMinDurationMs()) + " ms"); logger.info(" Max Duration: " + std::to_string(session->getMaxDurationMs()) + " ms"); - + auto metrics = session->getMetrics(); for (const auto& metric : metrics) { - logger.info(" " + metric->category + "::" + metric->name + " - " + - std::to_string(metric->getDurationMs()) + " ms"); + logger.info(" " + metric->category + "::" + metric->name + " - " + + std::to_string(metric->getDurationMs()) + " ms"); } } - + // Global metrics by category std::unordered_map>> categorizedMetrics; std::lock_guard metricsLock(metricsMutex_); for (const auto& metric : globalMetrics_) { categorizedMetrics[metric->category].push_back(metric); } - + logger.info("Global Metrics by Category:"); for (const auto& [category, metrics] : categorizedMetrics) { double totalDuration = 0.0; @@ -409,37 +410,37 @@ void PerformanceProfiler::printDetailedReport() const { totalDuration += metric->getDurationMs(); } double avgDuration = totalDuration / metrics.size(); - - logger.info(" " + category + ": " + std::to_string(metrics.size()) + " metrics, " + - "avg " + std::to_string(avgDuration) + " ms"); + + logger.info(" " + category + ": " + std::to_string(metrics.size()) + " metrics, " + "avg " + + std::to_string(avgDuration) + " ms"); } } void PerformanceProfiler::logMetric(const PerformanceMetric& metric, LogLevel level) const { auto& logger = LogManager::getInstance(); - std::string message = "PERF [" + metric.category + "] " + metric.name + - " completed in " + std::to_string(metric.getDurationMs()) + " ms"; - + std::string message = "PERF [" + metric.category + "] " + metric.name + " completed in " + + std::to_string(metric.getDurationMs()) + " ms"; + if (metric.memoryUsage > 0) { message += " (memory: " + std::to_string(metric.memoryUsage) + " bytes)"; } - + logger.log(level, LogCategory::CORE, message); } void PerformanceProfiler::logSessionSummary(const ProfilerSession& session, LogLevel level) const { auto& logger = LogManager::getInstance(); - std::string message = "Session '" + session.getName() + "' completed: " + - std::to_string(session.getMetricsCount()) + " metrics in " + - std::to_string(session.getTotalDurationMs()) + " ms"; - + std::string message = "Session '" + session.getName() + + "' completed: " + std::to_string(session.getMetricsCount()) + " metrics in " + + std::to_string(session.getTotalDurationMs()) + " ms"; + logger.log(level, LogCategory::CORE, message); } void PerformanceProfiler::reset() { std::lock_guard sessionsLock(sessionsMutex_); std::lock_guard metricsLock(metricsMutex_); - + sessions_.clear(); globalMetrics_.clear(); currentSession_ = nullptr; @@ -447,20 +448,19 @@ void PerformanceProfiler::reset() { void PerformanceProfiler::clearOldMetrics(std::chrono::minutes olderThan) { auto cutoffTime = std::chrono::steady_clock::now() - olderThan; - + std::lock_guard metricsLock(metricsMutex_); - globalMetrics_.erase( - std::remove_if(globalMetrics_.begin(), globalMetrics_.end(), - [cutoffTime](const std::shared_ptr& metric) { - return metric->startTime < cutoffTime; - }), - globalMetrics_.end()); + globalMetrics_.erase(std::remove_if(globalMetrics_.begin(), globalMetrics_.end(), + [cutoffTime](const std::shared_ptr& metric) { + return metric->startTime < cutoffTime; + }), + globalMetrics_.end()); } size_t PerformanceProfiler::getTotalMetricsCount() const { std::lock_guard sessionsLock(sessionsMutex_); std::lock_guard metricsLock(metricsMutex_); - + size_t total = globalMetrics_.size(); for (const auto& [name, session] : sessions_) { total += session->getMetricsCount(); @@ -471,15 +471,15 @@ size_t PerformanceProfiler::getTotalMetricsCount() const { double PerformanceProfiler::getAverageMetricDuration() const { std::lock_guard sessionsLock(sessionsMutex_); std::lock_guard metricsLock(metricsMutex_); - + double totalDuration = 0.0; size_t totalCount = 0; - + for (const auto& metric : globalMetrics_) { totalDuration += metric->getDurationMs(); totalCount++; } - + for (const auto& [name, session] : sessions_) { auto metrics = session->getMetrics(); for (const auto& metric : metrics) { @@ -487,42 +487,43 @@ double PerformanceProfiler::getAverageMetricDuration() const { totalCount++; } } - + return totalCount > 0 ? totalDuration / totalCount : 0.0; } std::vector PerformanceProfiler::getCategories() const { std::unordered_set categorySet; - + std::lock_guard sessionsLock(sessionsMutex_); std::lock_guard metricsLock(metricsMutex_); - + for (const auto& metric : globalMetrics_) { categorySet.insert(metric->category); } - + for (const auto& [name, session] : sessions_) { auto metrics = session->getMetrics(); for (const auto& metric : metrics) { categorySet.insert(metric->category); } } - + return std::vector(categorySet.begin(), categorySet.end()); } -std::vector> PerformanceProfiler::getMetricsByCategory(const std::string& category) const { +std::vector> PerformanceProfiler::getMetricsByCategory( + const std::string& category) const { std::vector> result; - + std::lock_guard sessionsLock(sessionsMutex_); std::lock_guard metricsLock(metricsMutex_); - + for (const auto& metric : globalMetrics_) { if (metric->category == category) { result.push_back(metric); } } - + for (const auto& [name, session] : sessions_) { auto metrics = session->getMetrics(); for (const auto& metric : metrics) { @@ -531,12 +532,12 @@ std::vector> PerformanceProfiler::getMetricsB } } } - + return result; } // ScopedProfiler implementation -ScopedProfiler::ScopedProfiler(const std::string& name, const std::string& category) +ScopedProfiler::ScopedProfiler(const std::string& name, const std::string& category) : wasEnabled_(PerformanceProfiler::getInstance().isEnabled()) { if (wasEnabled_) { metric_ = PerformanceProfiler::getInstance().startMetric(name, category); @@ -556,11 +557,12 @@ void ScopedProfiler::addMetadata(const std::string& key, const std::string& valu } double ScopedProfiler::getCurrentDurationMs() const { - if (!metric_) return 0.0; - + if (!metric_) + return 0.0; + auto now = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast>(now - metric_->startTime); return duration.count(); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/core/workbench_store.cpp b/src/bolt/core/workbench_store.cpp index b585fb8b..dfcfa349 100644 --- a/src/bolt/core/workbench_store.cpp +++ b/src/bolt/core/workbench_store.cpp @@ -3,4 +3,4 @@ namespace bolt { // All implementation is in the header -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/drawkern/dis_vm.cpp b/src/bolt/drawkern/dis_vm.cpp index 3225b152..e8783079 100644 --- a/src/bolt/drawkern/dis_vm.cpp +++ b/src/bolt/drawkern/dis_vm.cpp @@ -1,8 +1,9 @@ #include "bolt/drawkern/dis_vm.hpp" -#include -#include + #include +#include #include +#include #include namespace bolt { @@ -23,11 +24,13 @@ bool DISVM::load_program(const DISProgram& program) { pc_ = 0; running_ = false; halted_ = false; - + // Clear stacks - while (!stack_.empty()) stack_.pop(); - while (!call_stack_.empty()) call_stack_.pop(); - + while (!stack_.empty()) + stack_.pop(); + while (!call_stack_.empty()) + call_stack_.pop(); + std::cout << "Loaded DIS program with " << program_.instructions.size() << " instructions" << std::endl; return true; } @@ -35,7 +38,7 @@ bool DISVM::load_program(const DISProgram& program) { bool DISVM::load_limbo_source(const std::string& source) { LimboCompiler compiler; DISProgram program = compiler.compile(source); - + if (compiler.has_errors()) { std::cout << "Compilation errors:" << std::endl; for (const auto& error : compiler.get_errors()) { @@ -43,7 +46,7 @@ bool DISVM::load_limbo_source(const std::string& source) { } return false; } - + return load_program(program); } @@ -52,16 +55,16 @@ bool DISVM::run() { std::cout << "No program loaded" << std::endl; return false; } - + running_ = true; halted_ = false; - + std::cout << "Starting DIS VM execution..." << std::endl; - + while (running_ && !halted_ && pc_ < program_.instructions.size()) { step(); } - + if (halted_) { std::cout << "DIS VM halted normally" << std::endl; } else if (pc_ >= program_.instructions.size()) { @@ -69,7 +72,7 @@ bool DISVM::run() { } else { std::cout << "DIS VM stopped" << std::endl; } - + running_ = false; return true; } @@ -92,7 +95,7 @@ void DISVM::step() { if (breakpoint_callback_) { breakpoint_callback_(pc_); } - return; // Pause execution at breakpoint + return; // Pause execution at breakpoint } at_breakpoint_ = false; @@ -110,11 +113,8 @@ void DISVM::step() { } // Advance PC unless it was modified by a jump/call instruction - if (inst.opcode != DISOpcode::JMP && - inst.opcode != DISOpcode::JMPT && - inst.opcode != DISOpcode::JMPF && - inst.opcode != DISOpcode::CALL && - inst.opcode != DISOpcode::RET) { + if (inst.opcode != DISOpcode::JMP && inst.opcode != DISOpcode::JMPT && inst.opcode != DISOpcode::JMPF && + inst.opcode != DISOpcode::CALL && inst.opcode != DISOpcode::RET) { pc_++; } @@ -153,10 +153,12 @@ void DISVM::reset() { at_breakpoint_ = false; step_mode_ = false; step_depth_ = 0; - - while (!stack_.empty()) stack_.pop(); - while (!call_stack_.empty()) call_stack_.pop(); - + + while (!stack_.empty()) + stack_.pop(); + while (!call_stack_.empty()) + call_stack_.pop(); + globals_.clear(); program_ = DISProgram{}; // Note: breakpoints are preserved across resets @@ -171,7 +173,7 @@ DISValue DISVM::pop() { runtime_error("Stack underflow"); return DISValue(int64_t(0)); } - + DISValue value = stack_.top(); stack_.pop(); return value; @@ -252,7 +254,7 @@ void DISVM::execute_instruction(const DISInstruction& inst) { case DISOpcode::DUP: handle_load(inst); break; - + case DISOpcode::ADD: case DISOpcode::SUB: case DISOpcode::MUL: @@ -260,7 +262,7 @@ void DISVM::execute_instruction(const DISInstruction& inst) { case DISOpcode::MOD: handle_arithmetic(inst); break; - + case DISOpcode::EQ: case DISOpcode::NE: case DISOpcode::LT: @@ -269,7 +271,7 @@ void DISVM::execute_instruction(const DISInstruction& inst) { case DISOpcode::GE: handle_comparison(inst); break; - + case DISOpcode::JMP: case DISOpcode::JMPT: case DISOpcode::JMPF: @@ -277,34 +279,34 @@ void DISVM::execute_instruction(const DISInstruction& inst) { case DISOpcode::RET: handle_control_flow(inst); break; - + case DISOpcode::NEWSTR: case DISOpcode::CONCAT: case DISOpcode::STRLEN: handle_string_ops(inst); break; - + case DISOpcode::PRINT: case DISOpcode::READ: handle_io_ops(inst); break; - + case DISOpcode::AI_INIT: case DISOpcode::AI_COMPLETE: case DISOpcode::AI_CHAT: handle_ai_ops(inst); break; - + case DISOpcode::RENDER_GLYPH: case DISOpcode::SPAWN_VM: case DISOpcode::MOUNT_NS: handle_drawkern_ops(inst); break; - + case DISOpcode::HALT: halt(); break; - + default: runtime_error("Unknown opcode: " + std::to_string(static_cast(inst.opcode))); break; @@ -318,31 +320,32 @@ void DISVM::handle_load(const DISInstruction& inst) { push(inst.operands[0]); } break; - + case DISOpcode::POP: if (!stack_.empty()) { pop(); } break; - + case DISOpcode::DUP: if (!stack_.empty()) { push(peek()); } break; - + default: break; } } void DISVM::handle_arithmetic(const DISInstruction& inst) { - if (!check_stack_size(2)) return; - + if (!check_stack_size(2)) + return; + DISValue b = pop(); DISValue a = pop(); DISValue result(int64_t(0)); - + if (a.type == DISValue::INT && b.type == DISValue::INT) { switch (inst.opcode) { case DISOpcode::ADD: @@ -372,29 +375,43 @@ void DISVM::handle_arithmetic(const DISInstruction& inst) { break; } } - + push(result); } void DISVM::handle_comparison(const DISInstruction& inst) { - if (!check_stack_size(2)) return; - + if (!check_stack_size(2)) + return; + DISValue b = pop(); DISValue a = pop(); bool result = false; - + if (a.type == DISValue::INT && b.type == DISValue::INT) { switch (inst.opcode) { - case DISOpcode::EQ: result = a.int_val == b.int_val; break; - case DISOpcode::NE: result = a.int_val != b.int_val; break; - case DISOpcode::LT: result = a.int_val < b.int_val; break; - case DISOpcode::GT: result = a.int_val > b.int_val; break; - case DISOpcode::LE: result = a.int_val <= b.int_val; break; - case DISOpcode::GE: result = a.int_val >= b.int_val; break; - default: break; + case DISOpcode::EQ: + result = a.int_val == b.int_val; + break; + case DISOpcode::NE: + result = a.int_val != b.int_val; + break; + case DISOpcode::LT: + result = a.int_val < b.int_val; + break; + case DISOpcode::GT: + result = a.int_val > b.int_val; + break; + case DISOpcode::LE: + result = a.int_val <= b.int_val; + break; + case DISOpcode::GE: + result = a.int_val >= b.int_val; + break; + default: + break; } } - + push(DISValue(result ? int64_t(1) : int64_t(0))); } @@ -405,9 +422,10 @@ void DISVM::handle_control_flow(const DISInstruction& inst) { pc_ = inst.operands[0].int_val; } break; - + case DISOpcode::JMPT: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue condition = pop(); if (condition.int_val != 0 && !inst.operands.empty()) { @@ -417,9 +435,10 @@ void DISVM::handle_control_flow(const DISInstruction& inst) { } } break; - + case DISOpcode::JMPF: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue condition = pop(); if (condition.int_val == 0 && !inst.operands.empty()) { @@ -429,14 +448,14 @@ void DISVM::handle_control_flow(const DISInstruction& inst) { } } break; - + case DISOpcode::CALL: call_stack_.push(pc_ + 1); if (!inst.operands.empty()) { pc_ = inst.operands[0].int_val; } break; - + case DISOpcode::RET: if (!call_stack_.empty()) { pc_ = call_stack_.top(); @@ -445,7 +464,7 @@ void DISVM::handle_control_flow(const DISInstruction& inst) { halt(); } break; - + default: break; } @@ -458,9 +477,10 @@ void DISVM::handle_string_ops(const DISInstruction& inst) { push(DISValue(inst.operands[0].string_val)); } break; - + case DISOpcode::CONCAT: - if (!check_stack_size(2)) break; + if (!check_stack_size(2)) + break; { DISValue b = pop(); DISValue a = pop(); @@ -468,15 +488,16 @@ void DISVM::handle_string_ops(const DISInstruction& inst) { push(DISValue(result)); } break; - + case DISOpcode::STRLEN: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue str = pop(); push(DISValue(static_cast(str.string_val.length()))); } break; - + default: break; } @@ -485,7 +506,8 @@ void DISVM::handle_string_ops(const DISInstruction& inst) { void DISVM::handle_io_ops(const DISInstruction& inst) { switch (inst.opcode) { case DISOpcode::PRINT: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue value = pop(); std::string output; @@ -521,47 +543,50 @@ void DISVM::handle_io_ops(const DISInstruction& inst) { void DISVM::handle_ai_ops(const DISInstruction& inst) { switch (inst.opcode) { case DISOpcode::AI_INIT: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue model = pop(); std::cout << "๐Ÿค– Initializing AI model: " << model.string_val << std::endl; - push(DISValue(int64_t(1))); // Success + push(DISValue(int64_t(1))); // Success } break; - + case DISOpcode::AI_COMPLETE: - if (!check_stack_size(2)) break; + if (!check_stack_size(2)) + break; { DISValue context = pop(); DISValue prompt = pop(); - + std::string response; if (ai_handler_) { response = ai_handler_(prompt.string_val, context.string_val); } else { response = "๐Ÿค– AI: " + prompt.string_val + " (completed)"; } - + push(DISValue(response)); } break; - + case DISOpcode::AI_CHAT: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue message = pop(); std::string response; - + if (ai_handler_) { response = ai_handler_(message.string_val, "chat"); } else { response = "๐Ÿค– AI Chat: Hello! You said: " + message.string_val; } - + push(DISValue(response)); } break; - + default: break; } @@ -570,7 +595,8 @@ void DISVM::handle_ai_ops(const DISInstruction& inst) { void DISVM::handle_drawkern_ops(const DISInstruction& inst) { switch (inst.opcode) { case DISOpcode::RENDER_GLYPH: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue glyph = pop(); if (glyph_renderer_) { @@ -578,46 +604,48 @@ void DISVM::handle_drawkern_ops(const DISInstruction& inst) { } else { std::cout << "๐ŸŽจ Rendering glyph: " << glyph.string_val << std::endl; } - push(DISValue(int64_t(1))); // Success + push(DISValue(int64_t(1))); // Success } break; - + case DISOpcode::SPAWN_VM: - if (!check_stack_size(1)) break; + if (!check_stack_size(1)) + break; { DISValue spec = pop(); bool success = false; - + if (vm_spawner_) { success = vm_spawner_(spec.string_val); } else { std::cout << "๐Ÿš€ Spawning VM: " << spec.string_val << std::endl; success = true; } - + push(DISValue(success ? int64_t(1) : int64_t(0))); } break; - + case DISOpcode::MOUNT_NS: - if (!check_stack_size(2)) break; + if (!check_stack_size(2)) + break; { DISValue local_path = pop(); DISValue remote_addr = pop(); bool success = false; - + if (namespace_mounter_) { success = namespace_mounter_(remote_addr.string_val, local_path.string_val); } else { - std::cout << "๐Ÿ”— Mounting namespace: " << remote_addr.string_val - << " -> " << local_path.string_val << std::endl; + std::cout << "๐Ÿ”— Mounting namespace: " << remote_addr.string_val << " -> " << local_path.string_val + << std::endl; success = true; } - + push(DISValue(success ? int64_t(1) : int64_t(0))); } break; - + default: break; } @@ -625,8 +653,7 @@ void DISVM::handle_drawkern_ops(const DISInstruction& inst) { bool DISVM::check_stack_size(size_t required) const { if (stack_.size() < required) { - const_cast(this)->runtime_error("Stack underflow - need " + - std::to_string(required) + " items, have " + + const_cast(this)->runtime_error("Stack underflow - need " + std::to_string(required) + " items, have " + std::to_string(stack_.size())); return false; } @@ -660,52 +687,119 @@ std::string DISVM::get_instruction_info(size_t pc) const { if (pc >= program_.instructions.size()) { return "Invalid PC"; } - + const DISInstruction& inst = program_.instructions[pc]; std::stringstream ss; ss << "PC " << pc << ": "; - + // Convert opcode to string representation switch (inst.opcode) { - case DISOpcode::LOAD: ss << "LOAD"; break; - case DISOpcode::STORE: ss << "STORE"; break; - case DISOpcode::POP: ss << "POP"; break; - case DISOpcode::DUP: ss << "DUP"; break; - case DISOpcode::ADD: ss << "ADD"; break; - case DISOpcode::SUB: ss << "SUB"; break; - case DISOpcode::MUL: ss << "MUL"; break; - case DISOpcode::DIV: ss << "DIV"; break; - case DISOpcode::MOD: ss << "MOD"; break; - case DISOpcode::EQ: ss << "EQ"; break; - case DISOpcode::NE: ss << "NE"; break; - case DISOpcode::LT: ss << "LT"; break; - case DISOpcode::GT: ss << "GT"; break; - case DISOpcode::LE: ss << "LE"; break; - case DISOpcode::GE: ss << "GE"; break; - case DISOpcode::JMP: ss << "JMP"; break; - case DISOpcode::JMPT: ss << "JMPT"; break; - case DISOpcode::JMPF: ss << "JMPF"; break; - case DISOpcode::CALL: ss << "CALL"; break; - case DISOpcode::RET: ss << "RET"; break; - case DISOpcode::NEWSTR: ss << "NEWSTR"; break; - case DISOpcode::CONCAT: ss << "CONCAT"; break; - case DISOpcode::STRLEN: ss << "STRLEN"; break; - case DISOpcode::PRINT: ss << "PRINT"; break; - case DISOpcode::READ: ss << "READ"; break; - case DISOpcode::AI_INIT: ss << "AI_INIT"; break; - case DISOpcode::AI_COMPLETE: ss << "AI_COMPLETE"; break; - case DISOpcode::AI_CHAT: ss << "AI_CHAT"; break; - case DISOpcode::RENDER_GLYPH: ss << "RENDER_GLYPH"; break; - case DISOpcode::SPAWN_VM: ss << "SPAWN_VM"; break; - case DISOpcode::MOUNT_NS: ss << "MOUNT_NS"; break; - case DISOpcode::HALT: ss << "HALT"; break; - default: ss << "UNKNOWN(" << static_cast(inst.opcode) << ")"; break; + case DISOpcode::LOAD: + ss << "LOAD"; + break; + case DISOpcode::STORE: + ss << "STORE"; + break; + case DISOpcode::POP: + ss << "POP"; + break; + case DISOpcode::DUP: + ss << "DUP"; + break; + case DISOpcode::ADD: + ss << "ADD"; + break; + case DISOpcode::SUB: + ss << "SUB"; + break; + case DISOpcode::MUL: + ss << "MUL"; + break; + case DISOpcode::DIV: + ss << "DIV"; + break; + case DISOpcode::MOD: + ss << "MOD"; + break; + case DISOpcode::EQ: + ss << "EQ"; + break; + case DISOpcode::NE: + ss << "NE"; + break; + case DISOpcode::LT: + ss << "LT"; + break; + case DISOpcode::GT: + ss << "GT"; + break; + case DISOpcode::LE: + ss << "LE"; + break; + case DISOpcode::GE: + ss << "GE"; + break; + case DISOpcode::JMP: + ss << "JMP"; + break; + case DISOpcode::JMPT: + ss << "JMPT"; + break; + case DISOpcode::JMPF: + ss << "JMPF"; + break; + case DISOpcode::CALL: + ss << "CALL"; + break; + case DISOpcode::RET: + ss << "RET"; + break; + case DISOpcode::NEWSTR: + ss << "NEWSTR"; + break; + case DISOpcode::CONCAT: + ss << "CONCAT"; + break; + case DISOpcode::STRLEN: + ss << "STRLEN"; + break; + case DISOpcode::PRINT: + ss << "PRINT"; + break; + case DISOpcode::READ: + ss << "READ"; + break; + case DISOpcode::AI_INIT: + ss << "AI_INIT"; + break; + case DISOpcode::AI_COMPLETE: + ss << "AI_COMPLETE"; + break; + case DISOpcode::AI_CHAT: + ss << "AI_CHAT"; + break; + case DISOpcode::RENDER_GLYPH: + ss << "RENDER_GLYPH"; + break; + case DISOpcode::SPAWN_VM: + ss << "SPAWN_VM"; + break; + case DISOpcode::MOUNT_NS: + ss << "MOUNT_NS"; + break; + case DISOpcode::HALT: + ss << "HALT"; + break; + default: + ss << "UNKNOWN(" << static_cast(inst.opcode) << ")"; + break; } - + if (!inst.operands.empty()) { ss << " "; for (size_t i = 0; i < inst.operands.size(); ++i) { - if (i > 0) ss << ", "; + if (i > 0) + ss << ", "; const auto& operand = inst.operands[i]; if (operand.type == DISValue::INT) { ss << operand.int_val; @@ -714,7 +808,7 @@ std::string DISVM::get_instruction_info(size_t pc) const { } } } - + return ss.str(); } @@ -723,7 +817,7 @@ bool DISVM::set_breakpoint(size_t pc) { if (pc >= program_.instructions.size()) { return false; } - + breakpoints_.insert(pc); std::cout << "๐Ÿ”ด Breakpoint set at PC " << pc << std::endl; return true; @@ -757,14 +851,14 @@ void DISVM::step_over() { if (!running_ || halted_) { return; } - + step_mode_ = true; - step_depth_ = call_stack_.size(); // Don't step into calls + step_depth_ = call_stack_.size(); // Don't step into calls at_breakpoint_ = false; - + // Execute one instruction step(); - + std::cout << "๐Ÿ”ง Step over at PC " << pc_ << std::endl; } @@ -772,14 +866,14 @@ void DISVM::step_into() { if (!running_ || halted_) { return; } - + step_mode_ = true; - step_depth_ = 0; // Step into calls + step_depth_ = 0; // Step into calls at_breakpoint_ = false; - + // Execute one instruction step(); - + std::cout << "๐Ÿ”ง Step into at PC " << pc_ << std::endl; } @@ -787,18 +881,18 @@ void DISVM::step_out() { if (!running_ || halted_ || call_stack_.empty()) { return; } - + step_mode_ = true; - step_depth_ = call_stack_.size() - 1; // Step out of current function + step_depth_ = call_stack_.size() - 1; // Step out of current function at_breakpoint_ = false; - + std::cout << "๐Ÿ”ง Stepping out from call depth " << call_stack_.size() << std::endl; - + // Continue until we return from current function while (running_ && !halted_ && call_stack_.size() > step_depth_ && pc_ < program_.instructions.size()) { step(); } - + step_mode_ = false; step_depth_ = 0; } @@ -807,13 +901,13 @@ void DISVM::continue_execution() { if (!running_ || halted_) { return; } - + step_mode_ = false; step_depth_ = 0; at_breakpoint_ = false; - + std::cout << "โ–ถ๏ธ Continuing execution from PC " << pc_ << std::endl; - + // Continue until breakpoint or halt while (running_ && !halted_ && !at_breakpoint_ && pc_ < program_.instructions.size()) { step(); @@ -828,12 +922,12 @@ bool DISVM::is_at_breakpoint() const { std::vector DISVM::get_call_stack() const { std::vector result; std::stack temp = call_stack_; - + while (!temp.empty()) { result.push_back(temp.top()); temp.pop(); } - + // Reverse to show most recent call first std::reverse(result.begin(), result.end()); return result; @@ -844,15 +938,13 @@ size_t DISVM::get_call_stack_depth() const { } // LimboCompiler implementation (simplified) -LimboCompiler::LimboCompiler() { -} +LimboCompiler::LimboCompiler() {} -LimboCompiler::~LimboCompiler() { -} +LimboCompiler::~LimboCompiler() {} DISProgram LimboCompiler::compile(const std::string& source) { errors_.clear(); - + std::vector tokens = tokenize(source); return parse_tokens(tokens); } @@ -861,106 +953,106 @@ std::vector LimboCompiler::tokenize(const std::string& source) { std::vector tokens; std::istringstream stream(source); std::string token; - + while (stream >> token) { tokens.push_back(token); } - + return tokens; } DISProgram LimboCompiler::parse_tokens(const std::vector& tokens) { DISProgram program; program.source_limbo = ""; - + // Very simplified compiler - just handle basic cases for demo for (size_t i = 0; i < tokens.size(); i++) { const std::string& token = tokens[i]; - + if (token == "print") { if (i + 1 < tokens.size()) { program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue(tokens[i + 1]))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - i++; // Skip next token + i++; // Skip next token } } else if (token == "ai_chat") { if (i + 1 < tokens.size()) { program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue(tokens[i + 1]))); program.add_instruction(DISInstruction(DISOpcode::AI_CHAT)); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - i++; // Skip next token + i++; // Skip next token } } else if (token == "render_glyph") { if (i + 1 < tokens.size()) { program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue(tokens[i + 1]))); program.add_instruction(DISInstruction(DISOpcode::RENDER_GLYPH)); - i++; // Skip next token + i++; // Skip next token } } else if (token == "halt") { program.add_instruction(DISInstruction(DISOpcode::HALT)); } } - + return program; } // DISProgramFactory implementation DISProgram DISProgramFactory::create_ai_workbench(const std::string& model_name) { DISProgram program; - + // Initialize AI model program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue(model_name))); program.add_instruction(DISInstruction(DISOpcode::AI_INIT)); - + // Print welcome message program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("๐Ÿค– AI Workbench ready!\n"))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + // Simple chat loop (simplified for demo) program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("Hello from AI workbench"))); program.add_instruction(DISInstruction(DISOpcode::AI_CHAT)); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + program.add_instruction(DISInstruction(DISOpcode::HALT)); - + return program; } DISProgram DISProgramFactory::create_echo_server() { DISProgram program; - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("Echo server started\n"))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); program.add_instruction(DISInstruction(DISOpcode::HALT)); - + return program; } DISProgram DISProgramFactory::create_file_server(const std::string& root_path) { DISProgram program; - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("๐Ÿ—‚๏ธ File server starting...\n"))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("Root path: " + root_path + "\n"))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + program.add_instruction(DISInstruction(DISOpcode::HALT)); - + return program; } DISProgram DISProgramFactory::create_drawkern_renderer() { DISProgram program; - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("๐ŸŽจ DrawKern Renderer\n"))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("ai-workbench-glyph"))); program.add_instruction(DISInstruction(DISOpcode::RENDER_GLYPH)); - + program.add_instruction(DISInstruction(DISOpcode::HALT)); - + return program; } @@ -970,8 +1062,7 @@ DISProgram DISProgramFactory::from_limbo_source(const std::string& source) { } // DISVMManager implementation -DISVMManager::DISVMManager() : next_vm_id_(1) { -} +DISVMManager::DISVMManager() : next_vm_id_(1) {} DISVMManager::~DISVMManager() { // Clean up all VMs @@ -982,15 +1073,15 @@ DISVMManager::~DISVMManager() { std::string DISVMManager::create_vm(const DISProgram& program) { std::string vm_id = generate_vm_id(); - + auto vm = std::make_unique(); if (!vm->load_program(program)) { return ""; } - + vms_[vm_id] = std::move(vm); vm_message_queues_[vm_id] = {}; - + std::cout << "Created DIS VM: " << vm_id << std::endl; return vm_id; } @@ -1000,13 +1091,11 @@ bool DISVMManager::start_vm(const std::string& vm_id) { if (it == vms_.end()) { return false; } - + // Run VM in separate thread - std::thread vm_thread([&vm = it->second]() { - vm->run(); - }); + std::thread vm_thread([&vm = it->second]() { vm->run(); }); vm_thread.detach(); - + std::cout << "Started DIS VM: " << vm_id << std::endl; return true; } @@ -1016,7 +1105,7 @@ bool DISVMManager::stop_vm(const std::string& vm_id) { if (it == vms_.end()) { return false; } - + it->second->halt(); std::cout << "Stopped DIS VM: " << vm_id << std::endl; return true; @@ -1027,11 +1116,11 @@ bool DISVMManager::destroy_vm(const std::string& vm_id) { if (it == vms_.end()) { return false; } - + it->second->halt(); vms_.erase(it); vm_message_queues_.erase(vm_id); - + std::cout << "Destroyed DIS VM: " << vm_id << std::endl; return true; } @@ -1054,7 +1143,7 @@ std::string DISVMManager::get_vm_status(const std::string& vm_id) const { if (it == vms_.end()) { return "not found"; } - + return it->second->is_running() ? "running" : "stopped"; } @@ -1062,5 +1151,5 @@ std::string DISVMManager::generate_vm_id() { return "vm_" + std::to_string(next_vm_id_++); } -} // namespace drawkern -} // namespace bolt \ No newline at end of file +} // namespace drawkern +} // namespace bolt diff --git a/src/bolt/drawkern/drawkern.cpp b/src/bolt/drawkern/drawkern.cpp index edbb2857..330c6d00 100644 --- a/src/bolt/drawkern/drawkern.cpp +++ b/src/bolt/drawkern/drawkern.cpp @@ -1,16 +1,16 @@ #include "bolt/drawkern/drawkern.hpp" + +#include #include #include #include -#include namespace bolt { namespace drawkern { // Base class implementations -DrawKernClient::DrawKernClient(const std::string& server_address) - : server_address_(server_address), connected_(false) { -} +DrawKernClient::DrawKernClient(const std::string& server_address) + : server_address_(server_address), connected_(false) {} DrawKernClient::~DrawKernClient() { if (connected_) { @@ -47,12 +47,12 @@ AIWorkbenchGlyph create_bolt_ai_glyph() { glyph.workbench_id = "bolt-ai-ide-v1"; glyph.ai_model = "ggml-rwkv"; glyph.tools = {"code-completion", "chat-assistant", "error-analysis", "refactoring"}; - + // Define the VM to host this workbench - glyph.host_vm.vm_type = "dis"; // Inferno DIS VM + glyph.host_vm.vm_type = "dis"; // Inferno DIS VM glyph.host_vm.architecture = "any"; // DIS is portable! glyph.host_vm.capabilities = {"ai-inference", "code-parsing", "file-io"}; - + // Limbo code for the AI workbench (simplified example) glyph.host_vm.limbo_code = R"( implement BoltAI; @@ -77,29 +77,30 @@ AIWorkbenchGlyph create_bolt_ai_glyph() { } } )"; - + // Rendering properties - how this workbench looks when "drawn" glyph.host_vm.render.width = 1200; - glyph.host_vm.render.height = 800; + glyph.host_vm.render.height = 800; glyph.host_vm.render.background_color = 0x1e1e1e; // Dark theme glyph.host_vm.render.font_family = "Fira Code"; glyph.host_vm.render.interactive = true; glyph.host_vm.render.ai_enabled = true; - + // Network deployment glyph.styx_address = "tcp!*!9999"; // Serve on port 9999 - glyph.allowed_clients = {"*"}; // Allow any client - + glyph.allowed_clients = {"*"}; // Allow any client + return glyph; } // Terminal implementation - renders the workbench as ASCII art void TerminalDrawKernClient::render_ai_interface(const AIWorkbenchGlyph& workbench) { std::cout << "โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”\n"; - std::cout << "โ”‚ ๐Ÿš€ " << workbench.workbench_id << " (DrawKern) โ”‚\n"; + std::cout << "โ”‚ ๐Ÿš€ " << workbench.workbench_id << " (DrawKern) โ”‚\n"; std::cout << "โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค\n"; std::cout << "โ”‚ ๐Ÿค– AI Model: " << workbench.ai_model << " โ”‚\n"; - std::cout << "โ”‚ ๐Ÿ–ฅ๏ธ VM Type: " << workbench.host_vm.vm_type << " (" << workbench.host_vm.architecture << ") โ”‚\n"; + std::cout << "โ”‚ ๐Ÿ–ฅ๏ธ VM Type: " << workbench.host_vm.vm_type << " (" << workbench.host_vm.architecture + << ") โ”‚\n"; std::cout << "โ”‚ ๐ŸŒ Address: " << workbench.styx_address << " โ”‚\n"; std::cout << "โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค\n"; std::cout << "โ”‚ ๐Ÿ’ป Available Tools: โ”‚\n"; @@ -114,7 +115,7 @@ void TerminalDrawKernClient::render_ai_interface(const AIWorkbenchGlyph& workben std::cout << "โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜\n"; std::cout << "\n๐ŸŽฏ This workbench is now 'rendered' and can be deployed to:\n"; std::cout << " โ€ข IoT devices running Inferno\n"; - std::cout << " โ€ข Web browsers via WebAssembly\n"; + std::cout << " โ€ข Web browsers via WebAssembly\n"; std::cout << " โ€ข Mobile devices with DIS VM\n"; std::cout << " โ€ข Embedded systems with minimal resources\n"; std::cout << " โ€ข Any device with a Styx client!\n\n"; @@ -126,7 +127,8 @@ void TerminalDrawKernClient::render_text(int32_t x, int32_t y, const std::string } void TerminalDrawKernClient::render_rect(int32_t x, int32_t y, int32_t w, int32_t h, uint32_t color) { - std::cout << "[RECT] " << x << "," << y << " " << w << "x" << h << " color=0x" << std::hex << color << std::dec << std::endl; + std::cout << "[RECT] " << x << "," << y << " " << w << "x" << h << " color=0x" << std::hex << color << std::dec + << std::endl; } // Web implementation - generates HTML/JS for browser rendering @@ -202,8 +204,9 @@ void WebDrawKernClient::render_text(int32_t x, int32_t y, const std::string& tex } void WebDrawKernClient::render_rect(int32_t x, int32_t y, int32_t w, int32_t h, uint32_t color) { - std::cout << "[Web] Rect " << x << "," << y << " " << w << "x" << h << " #" << std::hex << color << std::dec << std::endl; + std::cout << "[Web] Rect " << x << "," << y << " " << w << "x" << h << " #" << std::hex << color << std::dec + << std::endl; } -} // namespace drawkern -} // namespace bolt +} // namespace drawkern +} // namespace bolt diff --git a/src/bolt/drawkern/styx_protocol.cpp b/src/bolt/drawkern/styx_protocol.cpp index d0215608..9fdeb64e 100644 --- a/src/bolt/drawkern/styx_protocol.cpp +++ b/src/bolt/drawkern/styx_protocol.cpp @@ -1,19 +1,20 @@ #include "bolt/drawkern/styx_protocol.hpp" -#include + #include +#include #ifdef _WIN32 - #include - #include - #include - #include - #define close closesocket - typedef SSIZE_T ssize_t; +#include +#include +#include +#include +#define close closesocket +typedef SSIZE_T ssize_t; #else - #include - #include - #include - #include +#include +#include +#include +#include #endif #include @@ -23,43 +24,43 @@ namespace drawkern { // Helper functions for Styx protocol serialization namespace { - void write_uint16(std::vector& buffer, uint16_t value) { - buffer.push_back(value & 0xFF); - buffer.push_back((value >> 8) & 0xFF); - } - - void write_uint32(std::vector& buffer, uint32_t value) { - buffer.push_back(value & 0xFF); - buffer.push_back((value >> 8) & 0xFF); - buffer.push_back((value >> 16) & 0xFF); - buffer.push_back((value >> 24) & 0xFF); - } - - void write_string(std::vector& buffer, const std::string& str) { - write_uint16(buffer, str.length()); - buffer.insert(buffer.end(), str.begin(), str.end()); - } - - uint16_t read_uint16(const std::vector& buffer, size_t& offset) { - uint16_t value = buffer[offset] | (buffer[offset + 1] << 8); - offset += 2; - return value; - } - - uint32_t read_uint32(const std::vector& buffer, size_t& offset) { - uint32_t value = buffer[offset] | (buffer[offset + 1] << 8) | - (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); - offset += 4; - return value; - } - - [[maybe_unused]] std::string read_string(const std::vector& buffer, size_t& offset) { - uint16_t length = read_uint16(buffer, offset); - std::string str(buffer.begin() + offset, buffer.begin() + offset + length); - offset += length; - return str; - } +void write_uint16(std::vector& buffer, uint16_t value) { + buffer.push_back(value & 0xFF); + buffer.push_back((value >> 8) & 0xFF); +} + +void write_uint32(std::vector& buffer, uint32_t value) { + buffer.push_back(value & 0xFF); + buffer.push_back((value >> 8) & 0xFF); + buffer.push_back((value >> 16) & 0xFF); + buffer.push_back((value >> 24) & 0xFF); +} + +void write_string(std::vector& buffer, const std::string& str) { + write_uint16(buffer, str.length()); + buffer.insert(buffer.end(), str.begin(), str.end()); +} + +uint16_t read_uint16(const std::vector& buffer, size_t& offset) { + uint16_t value = buffer[offset] | (buffer[offset + 1] << 8); + offset += 2; + return value; +} + +uint32_t read_uint32(const std::vector& buffer, size_t& offset) { + uint32_t value = + buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); + offset += 4; + return value; +} + +[[maybe_unused]] std::string read_string(const std::vector& buffer, size_t& offset) { + uint16_t length = read_uint16(buffer, offset); + std::string str(buffer.begin() + offset, buffer.begin() + offset + length); + offset += length; + return str; } +} // namespace void StyxMessage::serialize(std::vector& buffer) const { buffer.clear(); @@ -72,19 +73,18 @@ void StyxMessage::serialize(std::vector& buffer) const { StyxMessage StyxMessage::deserialize(const std::vector& buffer) { StyxMessage msg; size_t offset = 0; - + msg.size = read_uint32(buffer, offset); msg.type = static_cast(buffer[offset++]); msg.tag = read_uint16(buffer, offset); - + msg.data.assign(buffer.begin() + offset, buffer.end()); return msg; } // StyxConnection implementation -StyxConnection::StyxConnection(const std::string& address) - : address_(address), socket_fd_(-1), connected_(false), next_tag_(1), next_fid_(1) { -} +StyxConnection::StyxConnection(const std::string& address) + : address_(address), socket_fd_(-1), connected_(false), next_tag_(1), next_fid_(1) {} StyxConnection::~StyxConnection() { disconnect(); @@ -96,10 +96,10 @@ bool StyxConnection::connect() { if (colon_pos == std::string::npos) { return false; } - + std::string host = address_.substr(0, colon_pos); int port = std::stoi(address_.substr(colon_pos + 1)); - + #ifdef _WIN32 socket_fd_ = static_cast(socket(AF_INET, SOCK_STREAM, 0)); #else @@ -108,11 +108,11 @@ bool StyxConnection::connect() { if (socket_fd_ < 0) { return false; } - + sockaddr_in server_addr{}; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); - + if (host == "localhost" || host == "127.0.0.1") { server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); } else { @@ -120,13 +120,13 @@ bool StyxConnection::connect() { close(socket_fd_); return false; } - - if (::connect(socket_fd_, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) { + + if (::connect(socket_fd_, reinterpret_cast(&server_addr), sizeof(server_addr)) < 0) { close(socket_fd_); socket_fd_ = -1; return false; } - + connected_ = true; return true; } @@ -140,65 +140,69 @@ void StyxConnection::disconnect() { } bool StyxConnection::version(const std::string& version) { - if (!connected_) return false; - + if (!connected_) + return false; + StyxMessage msg; msg.type = StyxMessageType::Tversion; msg.tag = next_tag_++; - + // Tversion message data: msize[4] version[s] write_uint32(msg.data, 8192); // Max message size write_string(msg.data, version); msg.size = msg.data.size() + 7; // Header size - + StyxMessage response = send_message(msg); return response.type == StyxMessageType::Rversion; } bool StyxConnection::attach(const std::string& aname, const std::string& uname) { - if (!connected_) return false; - + if (!connected_) + return false; + StyxMessage msg; msg.type = StyxMessageType::Tattach; msg.tag = next_tag_++; - + // Tattach message data: fid[4] afid[4] uname[s] aname[s] write_uint32(msg.data, next_fid_++); // fid write_uint32(msg.data, ~0U); // afid (no auth) write_string(msg.data, uname); write_string(msg.data, aname); msg.size = msg.data.size() + 7; - + StyxMessage response = send_message(msg); return response.type == StyxMessageType::Rattach; } bool StyxConnection::send_glyph(const std::string& glyph_data) { - if (!connected_) return false; - + if (!connected_) + return false; + StyxMessage msg; msg.type = StyxMessageType::Tdrawkern; msg.tag = next_tag_++; - + // Custom DrawKern message format write_string(msg.data, "glyph"); write_string(msg.data, glyph_data); msg.size = msg.data.size() + 7; - + StyxMessage response = send_message(msg); return response.type == StyxMessageType::Rdrawkern; } bool StyxConnection::spawn_vm(const std::string& vm_spec) { - if (!connected_) return false; - + if (!connected_) + return false; + StyxMessage msg; msg.type = StyxMessageType::Tvmspawn; msg.tag = next_tag_++; - + write_string(msg.data, vm_spec); msg.size = msg.data.size() + 7; - + StyxMessage response = send_message(msg); return response.type == StyxMessageType::Rvmspawn; } @@ -206,65 +210,66 @@ bool StyxConnection::spawn_vm(const std::string& vm_spec) { StyxMessage StyxConnection::send_message(const StyxMessage& message) { std::vector buffer; message.serialize(buffer); - + if (!send_data(buffer)) { StyxMessage error; error.type = StyxMessageType::Terror; return error; } - + std::vector response_data = receive_data(); if (response_data.empty()) { StyxMessage error; error.type = StyxMessageType::Terror; return error; } - + return StyxMessage::deserialize(response_data); } bool StyxConnection::send_data(const std::vector& data) { - if (socket_fd_ < 0) return false; - + if (socket_fd_ < 0) + return false; + size_t sent = 0; while (sent < data.size()) { ssize_t result = send(socket_fd_, reinterpret_cast(data.data() + sent), data.size() - sent, 0); - if (result <= 0) return false; + if (result <= 0) + return false; sent += result; } return true; } std::vector StyxConnection::receive_data() { - if (socket_fd_ < 0) return {}; - + if (socket_fd_ < 0) + return {}; + // First read the size field uint8_t size_buffer[4]; if (recv(socket_fd_, reinterpret_cast(size_buffer), 4, MSG_WAITALL) != 4) { return {}; } - - uint32_t message_size = size_buffer[0] | (size_buffer[1] << 8) | - (size_buffer[2] << 16) | (size_buffer[3] << 24); - + + uint32_t message_size = size_buffer[0] | (size_buffer[1] << 8) | (size_buffer[2] << 16) | (size_buffer[3] << 24); + if (message_size > 8192 || message_size < 7) { return {}; } - + std::vector buffer(message_size); memcpy(buffer.data(), size_buffer, 4); - - if (recv(socket_fd_, reinterpret_cast(buffer.data() + 4), message_size - 4, MSG_WAITALL) != (message_size - 4)) { + + if (recv(socket_fd_, reinterpret_cast(buffer.data() + 4), message_size - 4, MSG_WAITALL) != + (message_size - 4)) { return {}; } - + return buffer; } // StyxServer implementation (minimal for demo) -StyxServer::StyxServer(const std::string& address) - : address_(address), listen_fd_(-1), running_(false) { -} +StyxServer::StyxServer(const std::string& address) : address_(address), listen_fd_(-1), running_(false) {} StyxServer::~StyxServer() { stop(); @@ -276,9 +281,9 @@ bool StyxServer::start() { if (colon_pos == std::string::npos) { return false; } - + int port = std::stoi(address_.substr(colon_pos + 1)); - + #ifdef _WIN32 listen_fd_ = static_cast(socket(AF_INET, SOCK_STREAM, 0)); #else @@ -287,25 +292,25 @@ bool StyxServer::start() { if (listen_fd_ < 0) { return false; } - + int opt = 1; setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&opt), sizeof(opt)); - + sockaddr_in server_addr{}; server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); - - if (bind(listen_fd_, (sockaddr*)&server_addr, sizeof(server_addr)) < 0) { + + if (bind(listen_fd_, reinterpret_cast(&server_addr), sizeof(server_addr)) < 0) { close(listen_fd_); return false; } - + if (listen(listen_fd_, 5) < 0) { close(listen_fd_); return false; } - + running_ = true; std::cout << "Styx server listening on " << address_ << std::endl; return true; @@ -323,11 +328,11 @@ void StyxServer::run() { while (running_) { sockaddr_in client_addr{}; socklen_t client_len = sizeof(client_addr); - + #ifdef _WIN32 - int client_fd = static_cast(accept(listen_fd_, (sockaddr*)&client_addr, &client_len)); + int client_fd = static_cast(accept(listen_fd_, reinterpret_cast(&client_addr), &client_len)); #else - int client_fd = accept(listen_fd_, (sockaddr*)&client_addr, &client_len); + int client_fd = accept(listen_fd_, reinterpret_cast(&client_addr), &client_len); #endif if (client_fd < 0) { if (running_) { @@ -335,13 +340,11 @@ void StyxServer::run() { } continue; } - + std::cout << "Styx client connected" << std::endl; - + // Handle client in separate thread - std::thread client_thread([this, client_fd]() { - handle_client(client_fd); - }); + std::thread client_thread([this, client_fd]() { handle_client(client_fd); }); client_thread.detach(); } } @@ -361,41 +364,40 @@ void StyxServer::register_vm_handler(std::function han void StyxServer::handle_client(int client_fd) { // Simplified client handling for demo std::cout << "Handling Styx client connection" << std::endl; - + // Echo back basic responses for now char buffer[1024]; while (running_) { ssize_t bytes = recv(client_fd, reinterpret_cast(buffer), sizeof(buffer), 0); - if (bytes <= 0) break; - + if (bytes <= 0) + break; + std::cout << "Received Styx message: " << bytes << " bytes" << std::endl; - + // Send a simple response const char* response = "Styx DrawKern server ready\n"; send(client_fd, reinterpret_cast(response), strlen(response), 0); } - + close(client_fd); std::cout << "Styx client disconnected" << std::endl; } // DrawKernNamespace implementation -DrawKernNamespace::DrawKernNamespace() { -} +DrawKernNamespace::DrawKernNamespace() {} -DrawKernNamespace::~DrawKernNamespace() { -} +DrawKernNamespace::~DrawKernNamespace() {} bool DrawKernNamespace::mount(const std::string& address, const std::string& local_path) { auto connection = std::make_unique(address); if (!connection->connect()) { return false; } - + if (!connection->version() || !connection->attach()) { return false; } - + mounted_services_[local_path] = std::move(connection); std::cout << "Mounted DrawKern namespace: " << address << " -> " << local_path << std::endl; return true; @@ -430,5 +432,5 @@ std::string DrawKernNamespace::get_vm_status(const std::string& vm_id) { return "VM " + vm_id + " running"; } -} // namespace drawkern -} // namespace bolt \ No newline at end of file +} // namespace drawkern +} // namespace bolt diff --git a/src/bolt/editor/code_completion.cpp b/src/bolt/editor/code_completion.cpp index 61fae698..db1e6030 100644 --- a/src/bolt/editor/code_completion.cpp +++ b/src/bolt/editor/code_completion.cpp @@ -1,5 +1,6 @@ #include "bolt/editor/code_completion.hpp" + #include #include #include @@ -8,7 +9,7 @@ namespace bolt { class CodeCompletionImpl { -public: + public: CodeCompletionImpl() : active_(false) {} void activate() { @@ -21,9 +22,7 @@ class CodeCompletionImpl { suggestions_.clear(); } - bool isActive() const { - return active_; - } + bool isActive() const { return active_; } void setSuggestions(const std::vector& suggestions) { suggestions_ = suggestions; @@ -31,7 +30,8 @@ class CodeCompletionImpl { } CompletionItem getSelectedSuggestion() const { - if (suggestions_.empty()) return CompletionItem(); + if (suggestions_.empty()) + return CompletionItem(); return suggestions_[currentIndex_]; } @@ -47,7 +47,7 @@ class CodeCompletionImpl { } } -private: + private: bool active_; std::vector suggestions_; size_t currentIndex_{0}; @@ -84,4 +84,4 @@ void CodeCompletion::selectPrevious() { impl_->selectPrevious(); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/code_folding.cpp b/src/bolt/editor/code_folding.cpp index daf449c9..523d766b 100644 --- a/src/bolt/editor/code_folding.cpp +++ b/src/bolt/editor/code_folding.cpp @@ -6,4 +6,4 @@ namespace bolt { // Implementation of any non-inline methods would go here // Currently all methods are inline in the header -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/code_folding_detector.cpp b/src/bolt/editor/code_folding_detector.cpp index e7eb35da..af3c469a 100644 --- a/src/bolt/editor/code_folding_detector.cpp +++ b/src/bolt/editor/code_folding_detector.cpp @@ -1,8 +1,9 @@ #include "bolt/editor/code_folding_detector.hpp" -#include -#include + #include +#include +#include namespace bolt { @@ -11,13 +12,13 @@ std::vector CodeFoldingDetector::detectFoldableRanges(const std::stri std::stack bracketStack; size_t lineNumber = 0; bool inComment = false; - + for (size_t i = 0; i < content.length(); ++i) { if (content[i] == '\n') { lineNumber++; continue; } - + // Handle multi-line comments if (i < content.length() - 1 && content[i] == '/' && content[i + 1] == '*') { bracketStack.push(lineNumber); @@ -25,7 +26,7 @@ std::vector CodeFoldingDetector::detectFoldableRanges(const std::stri i++; continue; } - + if (inComment && i < content.length() - 1 && content[i] == '*' && content[i + 1] == '/') { if (!bracketStack.empty()) { size_t startLine = bracketStack.top(); @@ -36,12 +37,11 @@ std::vector CodeFoldingDetector::detectFoldableRanges(const std::stri i++; continue; } - + // Handle code blocks if (content[i] == '{' && !inComment) { bracketStack.push(lineNumber); - } - else if (content[i] == '}' && !inComment && !bracketStack.empty()) { + } else if (content[i] == '}' && !inComment && !bracketStack.empty()) { size_t startLine = bracketStack.top(); bracketStack.pop(); if (lineNumber > startLine) { @@ -49,19 +49,19 @@ std::vector CodeFoldingDetector::detectFoldableRanges(const std::stri } } } - + return ranges; } bool CodeFoldingDetector::isFoldableRegion(const std::string& line) { // Common patterns for foldable regions static const std::vector patterns = { - std::regex(R"(\{[\s]*$)"), // Opening brace - std::regex(R"(^\s*function.*\{[\s]*$)"), // Function definition - std::regex(R"(^\s*class.*\{[\s]*$)"), // Class definition - std::regex(R"(^\s*if.*\{[\s]*$)"), // If statement - std::regex(R"(^\s*for.*\{[\s]*$)"), // For loop - std::regex(R"(^\s*while.*\{[\s]*$)") // While loop + std::regex(R"(\{[\s]*$)"), // Opening brace + std::regex(R"(^\s*function.*\{[\s]*$)"), // Function definition + std::regex(R"(^\s*class.*\{[\s]*$)"), // Class definition + std::regex(R"(^\s*if.*\{[\s]*$)"), // If statement + std::regex(R"(^\s*for.*\{[\s]*$)"), // For loop + std::regex(R"(^\s*while.*\{[\s]*$)") // While loop }; for (const auto& pattern : patterns) { @@ -75,15 +75,15 @@ bool CodeFoldingDetector::isFoldableRegion(const std::string& line) { int CodeFoldingDetector::findMatchingEnd(const std::vector& lines, int startLine) { int braceCount = 1; int currentLine = startLine + 1; - + while (currentLine < static_cast(lines.size()) && braceCount > 0) { const std::string& line = lines[currentLine]; braceCount += std::count(line.begin(), line.end(), '{'); braceCount -= std::count(line.begin(), line.end(), '}'); currentLine++; } - + return braceCount == 0 ? currentLine - 1 : -1; } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/code_folding_manager.cpp b/src/bolt/editor/code_folding_manager.cpp index 21caf844..9f6a6c6c 100644 --- a/src/bolt/editor/code_folding_manager.cpp +++ b/src/bolt/editor/code_folding_manager.cpp @@ -4,8 +4,9 @@ namespace bolt { void CodeFoldingManager::updateFoldingRanges(const std::string& filePath, const std::string& content) { bool enabled = foldingEnabled_.read([](const bool& value) { return value; }); - if (!enabled) return; - + if (!enabled) + return; + auto ranges = CodeFoldingDetector::detectFoldableRanges(content); foldingRanges_[filePath] = ranges; } @@ -45,7 +46,8 @@ bool CodeFoldingManager::isFoldingEnabled() const { void CodeFoldingManager::handleClick(const std::string& filePath, size_t lineNumber) { bool enabled = foldingEnabled_.read([](const bool& value) { return value; }); - if (!enabled) return; + if (!enabled) + return; toggleFold(filePath, lineNumber); } @@ -64,4 +66,4 @@ void CodeFoldingManager::refreshFoldingRanges() { } } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/code_folding_renderer.cpp b/src/bolt/editor/code_folding_renderer.cpp index 5c20461c..5844a7cf 100644 --- a/src/bolt/editor/code_folding_renderer.cpp +++ b/src/bolt/editor/code_folding_renderer.cpp @@ -1,25 +1,27 @@ -#include "bolt/editor/code_folding.hpp" #include #include #include +#include "bolt/editor/code_folding.hpp" + namespace bolt { class CodeFoldingRenderer { -private: + private: std::shared_ptr foldingManager_; std::shared_ptr foldingUI_; bool showFoldingMarkers_{true}; -public: + public: CodeFoldingRenderer() { foldingManager_ = std::make_shared(); foldingUI_ = std::make_shared(); } void render(const std::string& filePath, size_t viewportStartLine, size_t viewportEndLine) { - if (!showFoldingMarkers_) return; + if (!showFoldingMarkers_) + return; auto ranges = foldingManager_->getFoldingRanges(filePath); for (const auto& range : ranges) { @@ -41,13 +43,13 @@ class CodeFoldingRenderer { invalidateView(); } -private: + private: void renderFoldingMarker(const FoldRange& range) { auto gutter = foldingUI_->createGutter(); // Calculate marker position based on line number int xPos = 0; int yPos = range.startLine * lineHeight; - + // Render appropriate icon based on fold state const std::string& icon = range.isFolded ? gutter.iconCollapsed : gutter.iconExpanded; drawIcon(xPos, yPos, icon); @@ -61,7 +63,7 @@ class CodeFoldingRenderer { // Signal the editor to refresh the view } - static constexpr int lineHeight = 20; // Default line height in pixels + static constexpr int lineHeight = 20; // Default line height in pixels }; -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/code_folding_state.cpp b/src/bolt/editor/code_folding_state.cpp index 87979b2c..ef4f4e56 100644 --- a/src/bolt/editor/code_folding_state.cpp +++ b/src/bolt/editor/code_folding_state.cpp @@ -1,6 +1,9 @@ -#include "bolt/editor/code_folding.hpp" +#include #include +#include "bolt/editor/code_folding.hpp" +#include "json/json.hpp" + namespace bolt { void CodeFoldingState::setFoldState(size_t lineNumber, bool folded) { @@ -26,19 +29,16 @@ void CodeFoldingState::clear() { foldedLines_.clear(); } -} // namespace bolt - -#include -#include +} // namespace bolt namespace bolt { class CodeFoldingStateManager { -private: + private: std::map> storedStates_; const std::string stateFile_ = "code_folding_state.json"; -public: + public: void saveState(const std::string& filePath, const std::vector& ranges) { storedStates_[filePath] = ranges; persistToDisk(); @@ -54,17 +54,14 @@ class CodeFoldingStateManager { persistToDisk(); } -private: + private: void persistToDisk() { nlohmann::json j; for (const auto& [path, ranges] : storedStates_) { nlohmann::json rangeArray = nlohmann::json::array(); for (const auto& range : ranges) { - rangeArray.push_back({ - {"startLine", range.startLine}, - {"endLine", range.endLine}, - {"isFolded", range.isFolded} - }); + rangeArray.push_back( + {{"startLine", range.startLine}, {"endLine", range.endLine}, {"isFolded", range.isFolded}}); } j[path] = rangeArray; } @@ -83,11 +80,7 @@ class CodeFoldingStateManager { for (auto& [path, ranges] : j.items()) { std::vector foldRanges; for (auto& range : ranges) { - foldRanges.push_back({ - range["startLine"], - range["endLine"], - range["isFolded"] - }); + foldRanges.push_back({range["startLine"], range["endLine"], range["isFolded"]}); } storedStates_[path] = foldRanges; } @@ -99,4 +92,4 @@ class CodeFoldingStateManager { } }; -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/code_folding_ui.cpp b/src/bolt/editor/code_folding_ui.cpp index 67f44738..b607f437 100644 --- a/src/bolt/editor/code_folding_ui.cpp +++ b/src/bolt/editor/code_folding_ui.cpp @@ -17,7 +17,8 @@ bool CodeFoldingUI::isVisible() const { } void CodeFoldingUI::renderFoldingIndicator(size_t lineNumber, bool isFolded) { - if (!visible_) return; + if (!visible_) + return; // Render folding indicator icon based on fold state std::string indicator = isFolded ? "[+]" : "[-]"; @@ -25,7 +26,8 @@ void CodeFoldingUI::renderFoldingIndicator(size_t lineNumber, bool isFolded) { } void CodeFoldingUI::handleFoldingClick(size_t lineNumber) { - if (!visible_) return; + if (!visible_) + return; // In a real implementation, this would emit an event or signal // emit("fold-click", lineNumber); @@ -33,10 +35,10 @@ void CodeFoldingUI::handleFoldingClick(size_t lineNumber) { CodeFoldingUI::FoldingGutter CodeFoldingUI::createGutter() { return { - true, // isVisible - 14, // width in pixels - "โ–ถ", // iconCollapsed - "โ–ผ" // iconExpanded + true, // isVisible + 14, // width in pixels + "โ–ถ", // iconCollapsed + "โ–ผ" // iconExpanded }; } @@ -55,7 +57,8 @@ void CodeFoldingUI::renderFoldingMarkers(const std::string& filePath) { void CodeFoldingUI::renderMarker(size_t startLine, size_t endLine, bool isCollapsed) { auto gutter = createGutter(); - if (!gutter.isVisible) return; + if (!gutter.isVisible) + return; // Position calculation for the marker int xPos = 0; @@ -71,4 +74,4 @@ void CodeFoldingUI::drawIcon(int x, int y, const std::string& icon) { // This is a placeholder for the actual drawing implementation } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/code_folding_visibility.cpp b/src/bolt/editor/code_folding_visibility.cpp index 63c65231..f843f0bb 100644 --- a/src/bolt/editor/code_folding_visibility.cpp +++ b/src/bolt/editor/code_folding_visibility.cpp @@ -10,12 +10,12 @@ void CodeFoldingVisibilityManager::setLineVisibility(const std::string& filePath bool CodeFoldingVisibilityManager::isLineVisible(const std::string& filePath, size_t line) const { auto fileIt = visibilityMap_.find(filePath); if (fileIt == visibilityMap_.end()) { - return true; // Default visible if not managed + return true; // Default visible if not managed } auto lineIt = fileIt->second.find(line); if (lineIt == fileIt->second.end()) { - return true; // Default visible if not managed + return true; // Default visible if not managed } return lineIt->second; @@ -32,7 +32,8 @@ void CodeFoldingVisibilityManager::showAllLines(const std::string& filePath) { visibilityMap_.erase(filePath); } -void CodeFoldingVisibilityManager::updateFoldedSections(const std::string& filePath, const std::vector& foldRanges) { +void CodeFoldingVisibilityManager::updateFoldedSections(const std::string& filePath, + const std::vector& foldRanges) { for (const auto& range : foldRanges) { if (range.isFolded) { for (size_t line = range.startLine + 1; line <= range.endLine; ++line) { @@ -42,4 +43,4 @@ void CodeFoldingVisibilityManager::updateFoldedSections(const std::string& fileP } } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/cursor_manager.cpp b/src/bolt/editor/cursor_manager.cpp index 8ac88cb1..49a6d243 100644 --- a/src/bolt/editor/cursor_manager.cpp +++ b/src/bolt/editor/cursor_manager.cpp @@ -1,6 +1,8 @@ #include "bolt/editor/cursor_manager.hpp" + #include +#include #include #include @@ -32,21 +34,14 @@ void CursorManager::addCursorWithSelection(size_t line, size_t column, const Sel void CursorManager::removeCursor(size_t line, size_t column) { cursors_.write([&](auto& c) { - c.erase( - std::remove_if(c.begin(), c.end(), - [&](const Cursor& cursor) { - return cursor.line == line && cursor.column == column; - } - ), - c.end() - ); + c.erase(std::remove_if(c.begin(), c.end(), + [&](const Cursor& cursor) { return cursor.line == line && cursor.column == column; }), + c.end()); }); } void CursorManager::clearCursors() { - cursors_.write([](auto& c) { - c.clear(); - }); + cursors_.write([](auto& c) { c.clear(); }); } std::vector CursorManager::getCursors() const { @@ -54,15 +49,13 @@ std::vector CursorManager::getCursors() const { } void CursorManager::setPrimaryCursor(size_t index) { - primaryCursorIndex_.write([&](auto& idx) { - idx = index; - }); + primaryCursorIndex_.write([&](auto& idx) { idx = index; }); } Cursor CursorManager::getPrimaryCursor() const { return cursors_.read([&](const auto& c) { size_t idx = primaryCursorIndex_.read([](const auto& i) { return i; }); - return idx < c.size() ? c[idx] : Cursor{0, 0}; // Use 2-argument constructor + return idx < c.size() ? c[idx] : Cursor{0, 0}; // Use 2-argument constructor }); } @@ -70,8 +63,8 @@ void CursorManager::moveCursors(int deltaLine, int deltaColumn) { cursors_.write([&](auto& c) { for (auto& cursor : c) { if (cursor.isActive) { - cursor.line = std::max(0L, static_cast(cursor.line) + deltaLine); - cursor.column = std::max(0L, static_cast(cursor.column) + deltaColumn); + cursor.line = std::max(0, static_cast(cursor.line) + deltaLine); + cursor.column = std::max(0, static_cast(cursor.column) + deltaColumn); // Update selection to maintain cursor position cursor.selection.endLine = cursor.line; cursor.selection.endColumn = cursor.column; @@ -87,7 +80,7 @@ void CursorManager::insertTextAtCursors(const std::string& text) { std::sort(c.begin(), c.end(), [](const Cursor& a, const Cursor& b) { return a.line > b.line || (a.line == b.line && a.column > b.column); }); - + for (auto& cursor : c) { if (cursor.isActive) { // In a real implementation, this would interface with the document @@ -131,7 +124,7 @@ std::vector CursorManager::getSelectedText() const { for (const auto& cursor : c) { if (cursor.isActive && cursor.selection.hasSelection()) { // In a real implementation, this would extract text from document - selections.push_back(""); // Placeholder + selections.push_back(""); // Placeholder } } return selections; @@ -186,7 +179,7 @@ void CursorManager::selectLineAtCursors() { void CursorManager::findNextOccurrence(const std::string& text, const std::string& documentContent) { // Simplified implementation - in real editor would search document size_t newLine = 0, newColumn = 0; - + // Get the position for the new cursor without holding the lock cursors_.read([&](const auto& c) { if (!c.empty()) { @@ -195,7 +188,7 @@ void CursorManager::findNextOccurrence(const std::string& text, const std::strin newColumn = lastCursor.column; } }); - + // Add cursor without deadlock addCursor(newLine, newColumn); } @@ -207,7 +200,7 @@ void CursorManager::addCursorAtNextOccurrence(const std::string& text, const std void CursorManager::selectAllOccurrences(const std::string& text, const std::string& documentContent) { // Simplified implementation - would find all occurrences in real editor clearCursors(); - for (size_t i = 0; i < 3; ++i) { // Demo: add 3 cursors + for (size_t i = 0; i < 3; ++i) { // Demo: add 3 cursors addCursor(i * 5, 10); } } @@ -229,4 +222,4 @@ void CursorManager::sortCursorsByPosition() { }); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/debugger_ui.cpp b/src/bolt/editor/debugger_ui.cpp index 2591fcaa..3caf1afa 100644 --- a/src/bolt/editor/debugger_ui.cpp +++ b/src/bolt/editor/debugger_ui.cpp @@ -1,22 +1,22 @@ #include "bolt/editor/debugger_ui.hpp" + +#include +#include #include #include -#include -#include namespace bolt { DebuggerUI::DebuggerUI() - : debugger_(nullptr) - , visible_(false) - , initialized_(false) - , auto_refresh_enabled_(true) - , refresh_interval_ms_(100.0f) - , last_refresh_time_(0.0f) - , controls_panel_height_(60.0f) - , variables_panel_width_(300.0f) - , output_panel_height_(200.0f) { -} + : debugger_(nullptr), + visible_(false), + initialized_(false), + auto_refresh_enabled_(true), + refresh_interval_ms_(100.0f), + last_refresh_time_(0.0f), + controls_panel_height_(60.0f), + variables_panel_width_(300.0f), + output_panel_height_(200.0f) {} DebuggerUI::~DebuggerUI() { shutdown(); @@ -26,10 +26,10 @@ void DebuggerUI::initialize() { if (initialized_) { return; } - + initialized_ = true; status_message_ = "Debugger UI initialized"; - + std::cout << "๐Ÿ”ง Debugger UI initialized" << std::endl; } @@ -37,10 +37,10 @@ void DebuggerUI::shutdown() { if (!initialized_) { return; } - + initialized_ = false; visible_ = false; - + std::cout << "๐Ÿ”ง Debugger UI shutdown" << std::endl; } @@ -52,9 +52,9 @@ void DebuggerUI::set_visible(bool visible) { if (visible && !initialized_) { initialize(); } - + visible_ = visible; - + if (visible) { std::cout << "๐Ÿ”ง Debugger UI shown" << std::endl; } else { @@ -66,14 +66,15 @@ void DebuggerUI::render() { if (!visible_ || !initialized_) { return; } - + // Check if we should refresh the UI if (should_refresh()) { update_status_message(); - last_refresh_time_ = std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()).count(); + last_refresh_time_ = + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); } - + // Render all panels render_controls(); render_breakpoints(); @@ -85,54 +86,54 @@ void DebuggerUI::render() { void DebuggerUI::render_controls() { std::cout << "=== Debug Controls ===" << std::endl; - + if (!debugger_) { std::cout << "No debugger attached" << std::endl; return; } - + DebugState state = debugger_->get_debug_state(); std::cout << "State: " << format_debug_state(state) << std::endl; std::cout << "PC: " << format_pc_address(debugger_->get_current_pc()) << std::endl; - + // Show available controls based on state switch (state) { case DebugState::STOPPED: std::cout << "Controls: [Start Debug Session]" << std::endl; break; - + case DebugState::PAUSED: std::cout << "Controls: [Continue] [Step Over] [Step Into] [Step Out] [Stop]" << std::endl; break; - + case DebugState::RUNNING: std::cout << "Controls: [Pause] [Stop]" << std::endl; break; - + case DebugState::FINISHED: std::cout << "Controls: [Stop]" << std::endl; break; - + case DebugState::ERROR: std::cout << "Controls: [Stop] (Error occurred)" << std::endl; break; } - + if (!status_message_.empty()) { std::cout << "Status: " << status_message_ << std::endl; } - + std::cout << std::endl; } void DebuggerUI::render_breakpoints() { std::cout << "=== Breakpoints ===" << std::endl; - + if (!debugger_) { std::cout << "No debugger attached" << std::endl; return; } - + auto breakpoints = debugger_->get_all_breakpoints(); if (breakpoints.empty()) { std::cout << "No breakpoints set" << std::endl; @@ -141,18 +142,18 @@ void DebuggerUI::render_breakpoints() { render_breakpoint_item(bp); } } - + std::cout << std::endl; } void DebuggerUI::render_call_stack() { std::cout << "=== Call Stack ===" << std::endl; - + if (!debugger_) { std::cout << "No debugger attached" << std::endl; return; } - + auto call_stack = debugger_->get_call_stack(); if (call_stack.empty()) { std::cout << "No active calls" << std::endl; @@ -161,18 +162,18 @@ void DebuggerUI::render_call_stack() { render_call_stack_item(call_stack[i], i); } } - + std::cout << std::endl; } void DebuggerUI::render_variables() { std::cout << "=== Variables ===" << std::endl; - + if (!debugger_) { std::cout << "No debugger attached" << std::endl; return; } - + auto globals = debugger_->get_global_variables(); if (globals.empty()) { std::cout << "No global variables" << std::endl; @@ -181,7 +182,7 @@ void DebuggerUI::render_variables() { std::cout << " " << name << " = " << value << std::endl; } } - + auto stack_contents = debugger_->get_stack_contents(); if (!stack_contents.empty()) { std::cout << "Stack:" << std::endl; @@ -189,18 +190,18 @@ void DebuggerUI::render_variables() { std::cout << " " << item << std::endl; } } - + std::cout << std::endl; } void DebuggerUI::render_watch_expressions() { std::cout << "=== Watch Expressions ===" << std::endl; - + if (!debugger_) { std::cout << "No debugger attached" << std::endl; return; } - + auto watches = debugger_->get_watch_expressions(); if (watches.empty()) { std::cout << "No watch expressions" << std::endl; @@ -209,19 +210,19 @@ void DebuggerUI::render_watch_expressions() { render_watch_item(watch); } } - + std::cout << "Add new watch: [expression]" << std::endl; std::cout << std::endl; } void DebuggerUI::render_debug_output() { std::cout << "=== Debug Output ===" << std::endl; - + if (!debugger_) { std::cout << "No debugger attached" << std::endl; return; } - + auto log = debugger_->get_debug_log(); if (log.empty()) { std::cout << "No debug output" << std::endl; @@ -231,24 +232,23 @@ void DebuggerUI::render_debug_output() { for (size_t i = start; i < log.size(); ++i) { std::cout << " " << log[i] << std::endl; } - + if (log.size() > 5) { std::cout << " (" << (log.size() - 5) << " more entries...)" << std::endl; } } - + std::cout << std::endl; } void DebuggerUI::set_debugger(std::shared_ptr debugger) { debugger_ = debugger; - + if (debugger_) { // Set up event callback - debugger_->set_event_callback([this](DebugEvent event, const std::string& message) { - on_debug_event(event, message); - }); - + debugger_->set_event_callback( + [this](DebugEvent event, const std::string& message) { on_debug_event(event, message); }); + std::cout << "๐Ÿ”ง Debugger attached to UI" << std::endl; } else { std::cout << "๐Ÿ”ง Debugger detached from UI" << std::endl; @@ -260,28 +260,28 @@ void DebuggerUI::on_debug_event(DebugEvent event, const std::string& message) { case DebugEvent::SESSION_STARTED: status_message_ = "Debug session started"; break; - + case DebugEvent::SESSION_STOPPED: status_message_ = "Debug session stopped"; break; - + case DebugEvent::BREAKPOINT_HIT: status_message_ = "Breakpoint hit: " + message; break; - + case DebugEvent::STEP_COMPLETED: status_message_ = "Step completed"; break; - + case DebugEvent::EXECUTION_FINISHED: status_message_ = "Execution finished"; break; - + case DebugEvent::ERROR_OCCURRED: status_message_ = "Error: " + message; break; } - + std::cout << "๐Ÿ”ง Debug event: " << status_message_ << std::endl; } @@ -333,7 +333,7 @@ void DebuggerUI::handle_breakpoint_condition_edit(size_t pc, const std::string& std::cout << "โŒ No debugger attached" << std::endl; return; } - + // Set or update the breakpoint condition if (condition.empty()) { // Remove condition (make it unconditional) @@ -344,7 +344,7 @@ void DebuggerUI::handle_breakpoint_condition_edit(size_t pc, const std::string& debugger_->set_breakpoint_condition(pc, condition); std::cout << "โœ… Set breakpoint condition at PC " << pc << ": " << condition << std::endl; } - + status_message_ = "Breakpoint condition updated"; } @@ -390,40 +390,40 @@ void DebuggerUI::render_breakpoint_item(const BreakpointInfo& bp) { std::cout << " "; std::cout << (bp.enabled ? "๐Ÿ”ด" : "โšช") << " "; std::cout << "PC " << format_pc_address(bp.pc); - + if (!bp.file_path.empty()) { std::cout << " (" << bp.file_path << ":" << bp.line_number << ")"; } - + if (!bp.condition.empty()) { std::cout << " [" << bp.condition << "]"; } - + std::cout << std::endl; } void DebuggerUI::render_watch_item(const WatchExpression& watch) { std::cout << " " << watch.expression << " = "; - + if (watch.valid) { std::cout << watch.value << " (" << watch.type << ")"; } else { std::cout << ""; } - + std::cout << std::endl; } void DebuggerUI::render_call_stack_item(size_t pc, size_t index) { std::cout << " #" << index << " " << format_pc_address(pc); - + if (debugger_) { std::string instruction = debugger_->get_instruction_at(pc); if (!instruction.empty()) { std::cout << " - " << instruction; } } - + std::cout << std::endl; } @@ -432,7 +432,7 @@ void DebuggerUI::update_status_message() { status_message_ = "No debugger attached"; return; } - + DebugState state = debugger_->get_debug_state(); if (state == DebugState::RUNNING) { status_message_ = "Running..."; @@ -445,21 +445,28 @@ bool DebuggerUI::should_refresh() const { if (!auto_refresh_enabled_) { return false; } - - float current_time = std::chrono::duration_cast( - std::chrono::steady_clock::now().time_since_epoch()).count(); - + + float current_time = + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); + return (current_time - last_refresh_time_) >= refresh_interval_ms_; } std::string DebuggerUI::format_debug_state(DebugState state) const { switch (state) { - case DebugState::STOPPED: return "STOPPED"; - case DebugState::RUNNING: return "RUNNING"; - case DebugState::PAUSED: return "PAUSED"; - case DebugState::FINISHED: return "FINISHED"; - case DebugState::ERROR: return "ERROR"; - default: return "UNKNOWN"; + case DebugState::STOPPED: + return "STOPPED"; + case DebugState::RUNNING: + return "RUNNING"; + case DebugState::PAUSED: + return "PAUSED"; + case DebugState::FINISHED: + return "FINISHED"; + case DebugState::ERROR: + return "ERROR"; + default: + return "UNKNOWN"; } } @@ -469,4 +476,4 @@ std::string DebuggerUI::format_pc_address(size_t pc) const { return ss.str(); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/file_tree_manager.cpp b/src/bolt/editor/file_tree_manager.cpp index dc6ad4e6..61f7d94e 100644 --- a/src/bolt/editor/file_tree_manager.cpp +++ b/src/bolt/editor/file_tree_manager.cpp @@ -1,31 +1,25 @@ #include "bolt/editor/file_tree_manager.hpp" -#include + #include +#include #include namespace bolt { namespace fs = std::filesystem; void FileTreeManager::setRootDirectory(const std::string& path) { - currentRootPath_.write([&path](std::string& current) { - current = path; - }); - + currentRootPath_.write([&path](std::string& current) { current = path; }); + if (fs::exists(path) && fs::is_directory(path)) { - rootNode_ = std::make_shared( - fs::path(path).filename().string(), - path, - FileTreeNodeType::DIRECTORY - ); + rootNode_ = + std::make_shared(fs::path(path).filename().string(), path, FileTreeNodeType::DIRECTORY); rootNode_->isExpanded = true; refreshTree(); } } std::string FileTreeManager::getRootDirectory() const { - return currentRootPath_.read([](const std::string& current) { - return current; - }); + return currentRootPath_.read([](const std::string& current) { return current; }); } void FileTreeManager::refreshTree() { @@ -92,42 +86,43 @@ std::shared_ptr FileTreeManager::getSelectedNode() const { if (rootNode_) { collectVisibleNodes(rootNode_, allNodes); } - + auto it = std::find_if(allNodes.begin(), allNodes.end(), - [](const std::shared_ptr& node) { - return node->isSelected; - }); - + [](const std::shared_ptr& node) { return node->isSelected; }); + return (it != allNodes.end()) ? *it : nullptr; } std::shared_ptr FileTreeManager::findNode(const std::string& path) const { - if (!rootNode_) return nullptr; - + if (!rootNode_) + return nullptr; + // Convert to canonical path for comparison fs::path searchPath = fs::path(path).lexically_normal(); fs::path rootPath = fs::path(rootNode_->fullPath).lexically_normal(); - + if (searchPath == rootPath) { return rootNode_; } - + // Check if path is under root auto relativePath = fs::relative(searchPath, rootPath); if (relativePath.begin() != relativePath.end() && *relativePath.begin() == "..") { - return nullptr; // Path is not under root + return nullptr; // Path is not under root } - + // Traverse the tree following the relative path std::shared_ptr current = rootNode_; for (const auto& part : relativePath) { - if (part == ".") continue; - + if (part == ".") + continue; + auto child = current->findChild(part.string()); - if (!child) return nullptr; + if (!child) + return nullptr; current = child; } - + return current; } @@ -140,16 +135,12 @@ std::vector> FileTreeManager::getVisibleNodes() co } void FileTreeManager::setShowHiddenFiles(bool show) { - showHiddenFiles_.write([show](bool& current) { - current = show; - }); + showHiddenFiles_.write([show](bool& current) { current = show; }); refreshTree(); } bool FileTreeManager::getShowHiddenFiles() const { - return showHiddenFiles_.read([](const bool& current) { - return current; - }); + return showHiddenFiles_.read([](const bool& current) { return current; }); } void FileTreeManager::setOnFileSelected(std::function callback) { @@ -162,10 +153,11 @@ void FileTreeManager::setOnDirectoryExpanded(std::functionisDirectory()) return false; - + if (!parentNode || !parentNode->isDirectory()) + return false; + fs::path filePath = fs::path(parentPath) / fileName; - + try { std::ofstream file(filePath); if (file.is_open()) { @@ -176,16 +168,17 @@ bool FileTreeManager::createFile(const std::string& parentPath, const std::strin } catch (const std::exception&) { // File creation failed } - + return false; } bool FileTreeManager::createDirectory(const std::string& parentPath, const std::string& dirName) { auto parentNode = findNode(parentPath); - if (!parentNode || !parentNode->isDirectory()) return false; - + if (!parentNode || !parentNode->isDirectory()) + return false; + fs::path dirPath = fs::path(parentPath) / dirName; - + try { if (fs::create_directory(dirPath)) { refreshNode(parentNode); @@ -194,14 +187,15 @@ bool FileTreeManager::createDirectory(const std::string& parentPath, const std:: } catch (const std::exception&) { // Directory creation failed } - + return false; } bool FileTreeManager::deleteNode(const std::string& path) { auto node = findNode(path); - if (!node) return false; - + if (!node) + return false; + try { if (fs::remove_all(path) > 0) { auto parent = node->parent.lock(); @@ -213,17 +207,18 @@ bool FileTreeManager::deleteNode(const std::string& path) { } catch (const std::exception&) { // Deletion failed } - + return false; } bool FileTreeManager::renameNode(const std::string& path, const std::string& newName) { auto node = findNode(path); - if (!node) return false; - + if (!node) + return false; + fs::path oldPath(path); fs::path newPath = oldPath.parent_path() / newName; - + try { fs::rename(oldPath, newPath); auto parent = node->parent.lock(); @@ -234,24 +229,26 @@ bool FileTreeManager::renameNode(const std::string& path, const std::string& new } catch (const std::exception&) { // Rename failed } - + return false; } void FileTreeManager::scanDirectory(std::shared_ptr dirNode) { - if (!dirNode || !dirNode->isDirectory()) return; - + if (!dirNode || !dirNode->isDirectory()) + return; + dirNode->children.clear(); - + try { for (const auto& entry : fs::directory_iterator(dirNode->fullPath)) { - if (!shouldShowFile(entry)) continue; - + if (!shouldShowFile(entry)) + continue; + auto fileName = entry.path().filename().string(); auto fileType = entry.is_directory() ? FileTreeNodeType::DIRECTORY : FileTreeNodeType::FILE; - + auto child = std::make_shared(fileName, entry.path().string(), fileType); - + // Set file metadata try { if (entry.is_regular_file()) { @@ -261,7 +258,7 @@ void FileTreeManager::scanDirectory(std::shared_ptr dirNode) { } catch (const std::exception&) { // Metadata access failed, use defaults } - + dirNode->addChild(child); } } catch (const std::exception&) { @@ -271,14 +268,16 @@ void FileTreeManager::scanDirectory(std::shared_ptr dirNode) { bool FileTreeManager::shouldShowFile(const std::filesystem::directory_entry& entry) const { auto fileName = entry.path().filename().string(); - + // Always show if hidden files are enabled auto showHidden = getShowHiddenFiles(); - if (showHidden) return true; - + if (showHidden) + return true; + // Hide files starting with dot (Unix hidden files) - if (fileName.front() == '.') return false; - + if (fileName.front() == '.') + return false; + return true; } @@ -295,19 +294,22 @@ void FileTreeManager::notifyDirectoryExpanded(const std::string& path) { } void FileTreeManager::clearSelectionRecursive(std::shared_ptr node) { - if (!node) return; - + if (!node) + return; + node->isSelected = false; for (auto& child : node->children) { clearSelectionRecursive(child); } } -void FileTreeManager::collectVisibleNodes(std::shared_ptr node, std::vector>& result) const { - if (!node) return; - +void FileTreeManager::collectVisibleNodes(std::shared_ptr node, + std::vector>& result) const { + if (!node) + return; + result.push_back(node); - + if (node->isDirectory() && node->isExpanded) { for (const auto& child : node->children) { collectVisibleNodes(child, result); @@ -315,4 +317,4 @@ void FileTreeManager::collectVisibleNodes(std::shared_ptr node, st } } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/file_tree_node.cpp b/src/bolt/editor/file_tree_node.cpp index fc4dd4a8..29bf5590 100644 --- a/src/bolt/editor/file_tree_node.cpp +++ b/src/bolt/editor/file_tree_node.cpp @@ -1,13 +1,12 @@ #include "bolt/editor/file_tree_node.hpp" + #include namespace bolt { std::shared_ptr FileTreeNode::findChild(const std::string& name) const { - auto it = std::find_if(children.begin(), children.end(), - [&name](const std::shared_ptr& child) { - return child->name == name; - }); + auto it = std::find_if(children.begin(), children.end(), + [&name](const std::shared_ptr& child) { return child->name == name; }); return (it != children.end()) ? *it : nullptr; } @@ -20,24 +19,22 @@ void FileTreeNode::addChild(std::shared_ptr child) { } void FileTreeNode::removeChild(const std::string& name) { - children.erase( - std::remove_if(children.begin(), children.end(), - [&name](const std::shared_ptr& child) { - return child->name == name; - }), - children.end() - ); + children.erase(std::remove_if(children.begin(), children.end(), + [&name](const std::shared_ptr& child) { return child->name == name; }), + children.end()); } void FileTreeNode::sortChildren() { std::sort(children.begin(), children.end(), - [](const std::shared_ptr& a, const std::shared_ptr& b) { - // Directories first, then files - if (a->isDirectory() && b->isFile()) return true; - if (a->isFile() && b->isDirectory()) return false; - // Within same type, sort alphabetically - return a->name < b->name; - }); + [](const std::shared_ptr& a, const std::shared_ptr& b) { + // Directories first, then files + if (a->isDirectory() && b->isFile()) + return true; + if (a->isFile() && b->isDirectory()) + return false; + // Within same type, sort alphabetically + return a->name < b->name; + }); } size_t FileTreeNode::getDepth() const { @@ -52,17 +49,17 @@ size_t FileTreeNode::getDepth() const { std::vector> FileTreeNode::getAllFiles() const { std::vector> files; - + if (isFile()) { files.push_back(std::const_pointer_cast(shared_from_this())); } - + for (const auto& child : children) { auto childFiles = child->getAllFiles(); files.insert(files.end(), childFiles.begin(), childFiles.end()); } - + return files; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/file_tree_ui.cpp b/src/bolt/editor/file_tree_ui.cpp index 9751b47d..15e1eeec 100644 --- a/src/bolt/editor/file_tree_ui.cpp +++ b/src/bolt/editor/file_tree_ui.cpp @@ -1,13 +1,15 @@ #include "bolt/editor/file_tree_ui.hpp" + +#include #include #include -#include namespace bolt { void FileTreeUI::render() { - if (!isVisible()) return; - + if (!isVisible()) + return; + std::string output; renderToString(output); std::cout << output; @@ -15,33 +17,33 @@ void FileTreeUI::render() { void FileTreeUI::renderToString(std::string& output) { output.clear(); - + auto rootNode = manager_.getRootNode(); if (!rootNode) { output = "No directory loaded\n"; return; } - + output += "File Tree: " + rootNode->fullPath + "\n"; output += std::string(50, '-') + "\n"; - + renderNode(rootNode, output, 0); } std::vector FileTreeUI::renderToLines() const { std::vector lines; - + auto rootNode = manager_.getRootNode(); if (!rootNode) { lines.push_back("No directory loaded"); return lines; } - + lines.push_back("File Tree: " + rootNode->fullPath); lines.push_back(std::string(50, '-')); - + renderNodeToLine(rootNode, lines, 0); - + return lines; } @@ -50,24 +52,22 @@ void FileTreeUI::setRenderOptions(const FileTreeRenderOptions& options) { } void FileTreeUI::setVisible(bool visible) { - isVisible_.write([visible](bool& current) { - current = visible; - }); + isVisible_.write([visible](bool& current) { current = visible; }); } bool FileTreeUI::isVisible() const { - return isVisible_.read([](const bool& current) { - return current; - }); + return isVisible_.read([](const bool& current) { return current; }); } void FileTreeUI::handleClick(size_t lineNumber) { std::string path = getPathFromLineNumber(lineNumber); - if (path.empty()) return; - + if (path.empty()) + return; + auto node = manager_.findNode(path); - if (!node) return; - + if (!node) + return; + if (node->isDirectory()) { manager_.toggleDirectory(path); } else { @@ -77,11 +77,13 @@ void FileTreeUI::handleClick(size_t lineNumber) { void FileTreeUI::handleDoubleClick(size_t lineNumber) { std::string path = getPathFromLineNumber(lineNumber); - if (path.empty()) return; - + if (path.empty()) + return; + auto node = manager_.findNode(path); - if (!node) return; - + if (!node) + return; + if (node->isFile()) { manager_.selectFile(path); // File is now selected and callback should be triggered @@ -92,8 +94,9 @@ void FileTreeUI::handleDoubleClick(size_t lineNumber) { void FileTreeUI::handleKeyPress(const std::string& key) { auto selectedNode = manager_.getSelectedNode(); - if (!selectedNode) return; - + if (!selectedNode) + return; + if (key == "Enter" || key == "Return") { if (selectedNode->isDirectory()) { manager_.toggleDirectory(selectedNode->fullPath); @@ -116,20 +119,21 @@ void FileTreeUI::showContextMenu(const std::string& path) { } void FileTreeUI::renderNode(std::shared_ptr node, std::string& output, size_t depth) const { - if (!node) return; - + if (!node) + return; + std::string indent = getIndentation(depth); std::string prefix = getNodePrefix(node); std::string selection = node->isSelected ? "*" : " "; - + output += selection + indent + prefix + node->name; - + if (node->isFile() && options_.showIcons) { output += " (" + formatFileSize(node->size) + ")"; } - + output += "\n"; - + // Render children if directory is expanded if (node->isDirectory() && node->isExpanded) { for (const auto& child : node->children) { @@ -138,21 +142,23 @@ void FileTreeUI::renderNode(std::shared_ptr node, std::string& out } } -void FileTreeUI::renderNodeToLine(std::shared_ptr node, std::vector& lines, size_t depth) const { - if (!node) return; - +void FileTreeUI::renderNodeToLine(std::shared_ptr node, std::vector& lines, + size_t depth) const { + if (!node) + return; + std::string indent = getIndentation(depth); std::string prefix = getNodePrefix(node); std::string selection = node->isSelected ? "*" : " "; - + std::string line = selection + indent + prefix + node->name; - + if (node->isFile() && options_.showIcons) { line += " (" + formatFileSize(node->size) + ")"; } - + lines.push_back(line); - + // Render children if directory is expanded if (node->isDirectory() && node->isExpanded) { for (const auto& child : node->children) { @@ -166,8 +172,9 @@ std::string FileTreeUI::getIndentation(size_t depth) const { } std::string FileTreeUI::getNodePrefix(std::shared_ptr node) const { - if (!options_.showIcons) return ""; - + if (!options_.showIcons) + return ""; + if (node->isDirectory()) { if (node->isExpanded) { return std::string(1, options_.expandedIcon) + std::string(1, options_.directoryIcon) + " "; @@ -183,39 +190,39 @@ std::string FileTreeUI::formatFileSize(size_t size) const { const char* units[] = {"B", "KB", "MB", "GB"}; size_t unitIndex = 0; double displaySize = static_cast(size); - + while (displaySize >= 1024.0 && unitIndex < 3) { displaySize /= 1024.0; unitIndex++; } - + std::ostringstream oss; if (unitIndex == 0) { oss << static_cast(displaySize) << " " << units[unitIndex]; } else { oss << std::fixed << std::setprecision(1) << displaySize << " " << units[unitIndex]; } - + return oss.str(); } std::string FileTreeUI::getPathFromLineNumber(size_t lineNumber) const { auto lines = renderToLines(); - + // Account for header lines (title and separator) if (lineNumber < 2 || lineNumber >= lines.size()) { return ""; } - + // Get the visible nodes auto visibleNodes = manager_.getVisibleNodes(); - size_t nodeIndex = lineNumber - 2; // Subtract header lines - + size_t nodeIndex = lineNumber - 2; // Subtract header lines + if (nodeIndex < visibleNodes.size()) { return visibleNodes[nodeIndex]->fullPath; } - + return ""; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/find_replace.cpp b/src/bolt/editor/find_replace.cpp index 0150758a..55849526 100644 --- a/src/bolt/editor/find_replace.cpp +++ b/src/bolt/editor/find_replace.cpp @@ -1,5 +1,6 @@ #include "bolt/editor/find_replace.hpp" + #include #include @@ -9,26 +10,22 @@ FindReplace::FindReplace() : case_sensitive_(false), use_regex_(false) {} std::vector FindReplace::find(const std::string& text, const std::string& search_term) { std::vector results; - + if (search_term.empty() || text.empty()) { return results; } if (use_regex_) { try { - std::regex pattern(search_term, - case_sensitive_ ? std::regex::ECMAScript : - std::regex::ECMAScript | std::regex::icase); - + std::regex pattern(search_term, + case_sensitive_ ? std::regex::ECMAScript : std::regex::ECMAScript | std::regex::icase); + auto words_begin = std::sregex_iterator(text.begin(), text.end(), pattern); auto words_end = std::sregex_iterator(); for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; - results.push_back({ - static_cast(match.position()), - static_cast(match.length()) - }); + results.push_back({static_cast(match.position()), static_cast(match.length())}); } } catch (const std::regex_error&) { // Invalid regex pattern, return empty results @@ -38,7 +35,7 @@ std::vector FindReplace::find(const std::string& text, const std::str size_t pos = 0; std::string text_copy = text; std::string term_copy = search_term; - + if (!case_sensitive_) { std::transform(text_copy.begin(), text_copy.end(), text_copy.begin(), ::tolower); std::transform(term_copy.begin(), term_copy.end(), term_copy.begin(), ::tolower); @@ -53,20 +50,18 @@ std::vector FindReplace::find(const std::string& text, const std::str return results; } -std::string FindReplace::replace(const std::string& text, - const std::string& search_term, - const std::string& replace_term) { +std::string FindReplace::replace(const std::string& text, const std::string& search_term, + const std::string& replace_term) { if (search_term.empty() || text.empty()) { return text; } std::string result = text; - + if (use_regex_) { try { std::regex pattern(search_term, - case_sensitive_ ? std::regex::ECMAScript : - std::regex::ECMAScript | std::regex::icase); + case_sensitive_ ? std::regex::ECMAScript : std::regex::ECMAScript | std::regex::icase); result = std::regex_replace(text, pattern, replace_term); } catch (const std::regex_error&) { return text; @@ -98,4 +93,4 @@ bool FindReplace::isUsingRegex() const { return use_regex_; } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/integrated_editor.cpp b/src/bolt/editor/integrated_editor.cpp index afc6212b..d046224e 100644 --- a/src/bolt/editor/integrated_editor.cpp +++ b/src/bolt/editor/integrated_editor.cpp @@ -1,27 +1,28 @@ #include "bolt/editor/integrated_editor.hpp" + +#include + +#include "bolt/ai/ai_completion_provider.hpp" #include "bolt/editor/cursor_manager.hpp" #include "bolt/editor/keyboard_shortcuts.hpp" #include "bolt/editor/split_view_manager.hpp" -#include "bolt/ai/ai_completion_provider.hpp" -#include namespace bolt { -IntegratedEditor::IntegratedEditor() - : editorStore_(EditorStore::getInstance()) - , foldingManager_(CodeFoldingManager::getInstance()) - , foldingUI_(std::make_unique()) - , fileTreeManager_(FileTreeManager::getInstance()) - , fileTreeUI_(std::make_unique()) - , cursorManager_(CursorManager::getInstance()) - , keyboardShortcuts_(KeyboardShortcuts::getInstance()) - , splitViewManager_(SplitViewManager::getInstance()) - , tabBar_(TabBar::getInstance()) - , aiCompletionEngine_(AICodeCompletionEngine::getInstance()) - , codeCompletion_(std::make_unique()) - , debugger_(std::make_shared()) - , debuggerUI_(std::make_unique()) { - +IntegratedEditor::IntegratedEditor() + : editorStore_(EditorStore::getInstance()), + foldingManager_(CodeFoldingManager::getInstance()), + foldingUI_(std::make_unique()), + fileTreeManager_(FileTreeManager::getInstance()), + fileTreeUI_(std::make_unique()), + cursorManager_(CursorManager::getInstance()), + keyboardShortcuts_(KeyboardShortcuts::getInstance()), + splitViewManager_(SplitViewManager::getInstance()), + tabBar_(TabBar::getInstance()), + aiCompletionEngine_(AICodeCompletionEngine::getInstance()), + codeCompletion_(std::make_unique()), + debugger_(std::make_shared()), + debuggerUI_(std::make_unique()) { // Set up folding change callback to synchronize with editor store foldingManager_.setOnFoldingChanged([this]() { auto currentFile = editorStore_.getSelectedFile(); @@ -29,15 +30,13 @@ IntegratedEditor::IntegratedEditor() synchronizeFoldingState(currentFile); } }); - + // Set up file tree callbacks for editor integration - fileTreeManager_.setOnFileSelected([this](const std::string& path) { - openFileFromTree(path); - }); - + fileTreeManager_.setOnFileSelected([this](const std::string& path) { openFileFromTree(path); }); + // Initialize keyboard shortcuts with multi-cursor support initializeKeyboardShortcuts(); - + // Set up split view callbacks splitViewManager_.setOnPaneOperation([this](SplitViewManager::PaneOperation op, const std::string& paneId) { // Handle pane operations (focus changes, etc.) @@ -49,7 +48,7 @@ IntegratedEditor::IntegratedEditor() } } }); - + // Set up debugger integration debugger_->set_editor(this); debuggerUI_->set_debugger(debugger_); @@ -62,14 +61,14 @@ void IntegratedEditor::openDocument(const std::string& filePath, const std::stri doc.filePath = filePath; doc.scroll = {0, 0}; doc.cursor = {0, std::nullopt}; - + // Detect and set up folding ranges detectAndUpdateFolding(filePath, content); doc.foldingRanges = getFoldingRanges(filePath); - + editorStore_.setDocument(filePath, doc); editorStore_.setSelectedFile(filePath); - + // Open in active pane if split view is enabled if (splitViewManager_.isEnabled()) { EditorPane* activePane = splitViewManager_.getActivePane(); @@ -84,7 +83,7 @@ void IntegratedEditor::updateDocumentContent(const std::string& filePath, const if (doc && doc->filePath == filePath) { doc->value = content; } - + // Re-detect folding ranges when content changes detectAndUpdateFolding(filePath, content); synchronizeFoldingState(filePath); @@ -93,7 +92,7 @@ void IntegratedEditor::updateDocumentContent(const std::string& filePath, const void IntegratedEditor::closeDocument(const std::string& filePath) { // Clean up folding state foldingManager_.updateFoldingRanges(filePath, ""); - + // In a real implementation, we would remove the document from the store // For now, we'll just update the folding ranges } @@ -134,7 +133,7 @@ void IntegratedEditor::renderEditor(const std::string& filePath) { if (foldingUI_->isVisible()) { foldingUI_->renderFoldingMarkers(filePath); } - + if (fileTreeUI_->isVisible()) { renderFileTree(); } @@ -150,7 +149,7 @@ void IntegratedEditor::handleClick(const std::string& filePath, size_t line, siz return; } } - + // Handle regular editor click... } @@ -207,16 +206,14 @@ void IntegratedEditor::openFileFromTree(const std::string& filePath) { // Read file content std::ifstream file(filePath); if (!file.is_open()) { - return; // File couldn't be opened + return; // File couldn't be opened } - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); - + // Open the document in the editor openDocument(filePath, content); - } catch (const std::exception&) { // File reading failed, ignore silently for now } @@ -280,150 +277,182 @@ bool IntegratedEditor::handleKeyboardShortcut(const std::string& key, const std: void IntegratedEditor::initializeKeyboardShortcuts() { // Set editor as active context keyboardShortcuts_.setActiveContext(ShortcutContext::Editor); - + // Register multi-cursor specific shortcuts with proper context - keyboardShortcuts_.registerShortcut("Ctrl+D", "addCursorAtNextOccurrence", [this]() { - // Get selected text and add cursor at next occurrence - auto cursors = getAllCursors(); - if (!cursors.empty()) { - // Simplified: add cursor at next line - auto& lastCursor = cursors.back(); - addCursorAtPosition(lastCursor.line + 1, lastCursor.column); - } - }, ShortcutContext::Editor, "Add cursor at next occurrence of selected text"); - - keyboardShortcuts_.registerShortcut("Ctrl+Shift+L", "selectAllOccurrences", [this]() { - // Get selected text and select all occurrences - selectAllOccurrences(""); // Simplified implementation - }, ShortcutContext::Editor, "Select all occurrences of selected text"); - - keyboardShortcuts_.registerShortcut("Ctrl+Alt+Up", "addCursorAbove", [this]() { - auto cursors = getAllCursors(); - if (!cursors.empty()) { - auto& primary = cursors[0]; - if (primary.line > 0) { - addCursorAtPosition(primary.line - 1, primary.column); + keyboardShortcuts_.registerShortcut( + "Ctrl+D", "addCursorAtNextOccurrence", + [this]() { + // Get selected text and add cursor at next occurrence + auto cursors = getAllCursors(); + if (!cursors.empty()) { + // Simplified: add cursor at next line + auto& lastCursor = cursors.back(); + addCursorAtPosition(lastCursor.line + 1, lastCursor.column); } - } - }, ShortcutContext::Editor, "Add cursor above current line"); - - keyboardShortcuts_.registerShortcut("Ctrl+Alt+Down", "addCursorBelow", [this]() { - auto cursors = getAllCursors(); - if (!cursors.empty()) { - auto& primary = cursors[0]; - addCursorAtPosition(primary.line + 1, primary.column); - } - }, ShortcutContext::Editor, "Add cursor below current line"); - - keyboardShortcuts_.registerShortcut("Escape", "clearExtraCursors", [this]() { - clearExtraCursors(); - }, ShortcutContext::Editor, "Clear all extra cursors"); - + }, + ShortcutContext::Editor, "Add cursor at next occurrence of selected text"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+Shift+L", "selectAllOccurrences", + [this]() { + // Get selected text and select all occurrences + selectAllOccurrences(""); // Simplified implementation + }, + ShortcutContext::Editor, "Select all occurrences of selected text"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+Alt+Up", "addCursorAbove", + [this]() { + auto cursors = getAllCursors(); + if (!cursors.empty()) { + auto& primary = cursors[0]; + if (primary.line > 0) { + addCursorAtPosition(primary.line - 1, primary.column); + } + } + }, + ShortcutContext::Editor, "Add cursor above current line"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+Alt+Down", "addCursorBelow", + [this]() { + auto cursors = getAllCursors(); + if (!cursors.empty()) { + auto& primary = cursors[0]; + addCursorAtPosition(primary.line + 1, primary.column); + } + }, + ShortcutContext::Editor, "Add cursor below current line"); + + keyboardShortcuts_.registerShortcut( + "Escape", "clearExtraCursors", [this]() { clearExtraCursors(); }, ShortcutContext::Editor, + "Clear all extra cursors"); + // Initialize default shortcuts for all contexts keyboardShortcuts_.initDefaultShortcuts(); - + // Add split view shortcuts with global context - keyboardShortcuts_.registerShortcut("Ctrl+\\", "createHorizontalSplit", [this]() { - createHorizontalSplit(); - }, ShortcutContext::Global, "Create horizontal split"); - - keyboardShortcuts_.registerShortcut("Ctrl+Shift+\\", "createVerticalSplit", [this]() { - createVerticalSplit(); - }, ShortcutContext::Global, "Create vertical split"); - - keyboardShortcuts_.registerShortcut("Ctrl+W", "closePane", [this]() { - std::string activeId = splitViewManager_.getActivePaneId(); - closePane(activeId); - }, ShortcutContext::Global, "Close current pane"); - - keyboardShortcuts_.registerShortcut("Ctrl+Tab", "navigateToNextPane", [this]() { - navigateToNextPane(); - }, ShortcutContext::Global, "Navigate to next pane"); - - keyboardShortcuts_.registerShortcut("Ctrl+Shift+Tab", "navigateToPreviousPane", [this]() { - navigateToPreviousPane(); - }, ShortcutContext::Global, "Navigate to previous pane"); - + keyboardShortcuts_.registerShortcut( + "Ctrl+\\", "createHorizontalSplit", [this]() { createHorizontalSplit(); }, ShortcutContext::Global, + "Create horizontal split"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+Shift+\\", "createVerticalSplit", [this]() { createVerticalSplit(); }, ShortcutContext::Global, + "Create vertical split"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+W", "closePane", + [this]() { + std::string activeId = splitViewManager_.getActivePaneId(); + closePane(activeId); + }, + ShortcutContext::Global, "Close current pane"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+Tab", "navigateToNextPane", [this]() { navigateToNextPane(); }, ShortcutContext::Global, + "Navigate to next pane"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+Shift+Tab", "navigateToPreviousPane", [this]() { navigateToPreviousPane(); }, ShortcutContext::Global, + "Navigate to previous pane"); + // AI Code Completion shortcuts - keyboardShortcuts_.registerShortcut("Ctrl+Space", "triggerCodeCompletion", [this]() { - auto currentFile = editorStore_.getSelectedFile(); - if (!currentFile.empty()) { - auto* doc = editorStore_.getCurrentDocument(); - if (doc) { - // Convert cursor position to line/column (simplified implementation) - size_t line = 0, column = 0; - for (size_t i = 0; i < doc->cursor.position && i < doc->value.length(); ++i) { - if (doc->value[i] == '\n') { - line++; - column = 0; - } else { - column++; + keyboardShortcuts_.registerShortcut( + "Ctrl+Space", "triggerCodeCompletion", + [this]() { + auto currentFile = editorStore_.getSelectedFile(); + if (!currentFile.empty()) { + auto* doc = editorStore_.getCurrentDocument(); + if (doc) { + // Convert cursor position to line/column (simplified implementation) + size_t line = 0, column = 0; + for (size_t i = 0; i < doc->cursor.position && i < doc->value.length(); ++i) { + if (doc->value[i] == '\n') { + line++; + column = 0; + } else { + column++; + } } + triggerCodeCompletion(currentFile, line, column); } - triggerCodeCompletion(currentFile, line, column); } - } - }, ShortcutContext::Editor, "Trigger AI code completion"); - - keyboardShortcuts_.registerShortcut("Enter", "acceptCompletion", [this]() { - if (isCodeCompletionActive()) { - acceptCompletion(); - } - }, ShortcutContext::Editor, "Accept code completion"); - - keyboardShortcuts_.registerShortcut("Escape", "cancelCompletion", [this]() { - if (isCodeCompletionActive()) { - cancelCompletion(); - } - }, ShortcutContext::Editor, "Cancel code completion"); - - keyboardShortcuts_.registerShortcut("Down", "selectNextCompletion", [this]() { - if (isCodeCompletionActive()) { - selectNextCompletion(); - } - }, ShortcutContext::Editor, "Select next completion"); - - keyboardShortcuts_.registerShortcut("Up", "selectPreviousCompletion", [this]() { - if (isCodeCompletionActive()) { - selectPreviousCompletion(); - } - }, ShortcutContext::Editor, "Select previous completion"); - + }, + ShortcutContext::Editor, "Trigger AI code completion"); + + keyboardShortcuts_.registerShortcut( + "Enter", "acceptCompletion", + [this]() { + if (isCodeCompletionActive()) { + acceptCompletion(); + } + }, + ShortcutContext::Editor, "Accept code completion"); + + keyboardShortcuts_.registerShortcut( + "Escape", "cancelCompletion", + [this]() { + if (isCodeCompletionActive()) { + cancelCompletion(); + } + }, + ShortcutContext::Editor, "Cancel code completion"); + + keyboardShortcuts_.registerShortcut( + "Down", "selectNextCompletion", + [this]() { + if (isCodeCompletionActive()) { + selectNextCompletion(); + } + }, + ShortcutContext::Editor, "Select next completion"); + + keyboardShortcuts_.registerShortcut( + "Up", "selectPreviousCompletion", + [this]() { + if (isCodeCompletionActive()) { + selectPreviousCompletion(); + } + }, + ShortcutContext::Editor, "Select previous completion"); + // Tab navigation shortcuts - keyboardShortcuts_.registerShortcut("Ctrl+PageDown", "nextTab", [this]() { - switchToNextTab(); - }, ShortcutContext::Global, "Switch to next tab"); - - keyboardShortcuts_.registerShortcut("Ctrl+PageUp", "previousTab", [this]() { - switchToPreviousTab(); - }, ShortcutContext::Global, "Switch to previous tab"); - - keyboardShortcuts_.registerShortcut("Ctrl+W", "closeCurrentTab", [this]() { - auto activeTab = getActiveTab(); - if (activeTab.has_value()) { - closeTabById(activeTab->id); - } - }, ShortcutContext::Global, "Close current tab"); + keyboardShortcuts_.registerShortcut( + "Ctrl+PageDown", "nextTab", [this]() { switchToNextTab(); }, ShortcutContext::Global, "Switch to next tab"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+PageUp", "previousTab", [this]() { switchToPreviousTab(); }, ShortcutContext::Global, + "Switch to previous tab"); + + keyboardShortcuts_.registerShortcut( + "Ctrl+W", "closeCurrentTab", + [this]() { + auto activeTab = getActiveTab(); + if (activeTab.has_value()) { + closeTabById(activeTab->id); + } + }, + ShortcutContext::Global, "Close current tab"); } // Split view operations std::string IntegratedEditor::createHorizontalSplit(const std::string& filePath) { std::string newPaneId = splitViewManager_.createHorizontalSplit(); - + if (!newPaneId.empty() && !filePath.empty()) { openDocumentInPane(newPaneId, filePath); } - + return newPaneId; } std::string IntegratedEditor::createVerticalSplit(const std::string& filePath) { std::string newPaneId = splitViewManager_.createVerticalSplit(); - + if (!newPaneId.empty() && !filePath.empty()) { openDocumentInPane(newPaneId, filePath); } - + return newPaneId; } @@ -493,14 +522,14 @@ std::string IntegratedEditor::findPaneWithDocument(const std::string& filePath) void IntegratedEditor::triggerCodeCompletion(const std::string& filePath, size_t line, size_t column) { auto* doc = editorStore_.getCurrentDocument(); if (!doc || doc->filePath != filePath) { - return; // Document not found or not active + return; // Document not found or not active } - + // Calculate cursor position in the document size_t cursorPosition = 0; std::string content = doc->value; size_t currentLine = 0; - + for (size_t i = 0; i < content.length() && currentLine < line; ++i) { if (content[i] == '\n') { currentLine++; @@ -510,17 +539,18 @@ void IntegratedEditor::triggerCodeCompletion(const std::string& filePath, size_t } } } - + // Extract prefix (word before cursor) std::string prefix; if (cursorPosition > 0) { size_t start = cursorPosition; - while (start > 0 && (std::isalnum(content[start - 1]) || content[start - 1] == '_' || content[start - 1] == ':')) { + while (start > 0 && + (std::isalnum(content[start - 1]) || content[start - 1] == '_' || content[start - 1] == ':')) { start--; } prefix = content.substr(start, cursorPosition - start); } - + triggerCodeCompletion(filePath, prefix); } @@ -529,22 +559,23 @@ void IntegratedEditor::triggerCodeCompletion(const std::string& filePath, const if (!doc || doc->filePath != filePath) { return; } - + // Get AI completions auto completions = getAICompletions(filePath, prefix); - + if (!completions.empty()) { codeCompletion_->setSuggestions(completions); codeCompletion_->activate(); } } -std::vector IntegratedEditor::getAICompletions(const std::string& filePath, const std::string& prefix, size_t limit) { +std::vector IntegratedEditor::getAICompletions(const std::string& filePath, const std::string& prefix, + size_t limit) { auto* doc = editorStore_.getCurrentDocument(); if (!doc || doc->filePath != filePath) { return {}; } - + // Determine file language from extension std::string language = "text"; if (filePath.length() >= 4) { @@ -565,7 +596,7 @@ std::vector IntegratedEditor::getAICompletions(const std::string language = "javascript"; } } - + // Convert cursor position to line/column size_t line = 0, column = 0; for (size_t i = 0; i < doc->cursor.position && i < doc->value.length(); ++i) { @@ -576,7 +607,7 @@ std::vector IntegratedEditor::getAICompletions(const std::string column++; } } - + // Create context for AI completion CodeContext context; context.filePath = filePath; @@ -585,7 +616,7 @@ std::vector IntegratedEditor::getAICompletions(const std::string context.line = line; context.column = column; context.language = language; - + return aiCompletionEngine_.getCompletions(context, prefix, limit); } @@ -596,33 +627,32 @@ bool IntegratedEditor::isCodeCompletionActive() const { void IntegratedEditor::acceptCompletion() { if (codeCompletion_->isActive()) { auto selectedCompletion = codeCompletion_->getSelectedSuggestion(); - + // Get current document auto* doc = editorStore_.getCurrentDocument(); if (!doc || selectedCompletion.label.empty()) { codeCompletion_->deactivate(); return; } - + // Calculate the prefix to remove (word before cursor) size_t cursorPos = doc->cursor.position; std::string content = doc->value; - + // Bounds check for cursor position if (cursorPos > content.length()) { cursorPos = content.length(); } - + size_t prefixStart = cursorPos; - + // Find the start of the current word/prefix while (prefixStart > 0 && prefixStart <= content.length() && - (std::isalnum(content[prefixStart - 1]) || - content[prefixStart - 1] == '_' || + (std::isalnum(content[prefixStart - 1]) || content[prefixStart - 1] == '_' || content[prefixStart - 1] == ':')) { prefixStart--; } - + // Determine what text to insert based on completion kind std::string insertText; if (selectedCompletion.kind == "snippet") { @@ -632,22 +662,20 @@ void IntegratedEditor::acceptCompletion() { // For simple completions, use the label insertText = selectedCompletion.label; } - + // Remove the prefix and insert the completion - std::string newContent = content.substr(0, prefixStart) + - insertText + - content.substr(cursorPos); - + std::string newContent = content.substr(0, prefixStart) + insertText + content.substr(cursorPos); + // Update document content doc->value = newContent; - + // Move cursor to end of inserted text size_t newCursorPos = prefixStart + insertText.length(); doc->cursor.position = newCursorPos; - + // Update editor store editorStore_.setDocument(doc->filePath, *doc); - + // Deactivate completion codeCompletion_->deactivate(); } @@ -694,14 +722,12 @@ bool IntegratedEditor::startDebugSession(const std::string& filePath) { if (!file.is_open()) { return false; } - - std::string content((std::istreambuf_iterator(file)), - std::istreambuf_iterator()); + + std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); file.close(); - + // Start debug session from Limbo source return debugger_->start_debug_session_from_source(content); - } catch (const std::exception&) { return false; } @@ -807,10 +833,10 @@ std::map IntegratedEditor::getDebugGlobalVariables() c size_t IntegratedEditor::openDocumentInTab(const std::string& filePath, const std::string& content) { // Add tab first size_t tabId = tabBar_.addTab(filePath); - + // Open the document openDocument(filePath, content); - + return tabId; } @@ -820,10 +846,10 @@ bool IntegratedEditor::closeTabById(size_t tabId) { if (!tab.has_value()) { return false; } - + // Close the document closeDocument(tab->filePath); - + // Close the tab return tabBar_.closeTab(tabId); } @@ -831,7 +857,7 @@ bool IntegratedEditor::closeTabById(size_t tabId) { bool IntegratedEditor::closeTabByPath(const std::string& filePath) { // Close the document closeDocument(filePath); - + // Close the tab return tabBar_.closeTabByPath(filePath); } @@ -839,14 +865,14 @@ bool IntegratedEditor::closeTabByPath(const std::string& filePath) { void IntegratedEditor::closeAllTabs() { // Get all tabs first (to avoid modification during iteration) auto tabs = tabBar_.getAllTabs(); - + // Close all documents for (const auto& tab : tabs) { if (!tab.isPinned) { closeDocument(tab.filePath); } } - + // Close all tabs tabBar_.closeAllTabs(); } @@ -854,14 +880,14 @@ void IntegratedEditor::closeAllTabs() { void IntegratedEditor::closeOtherTabs(size_t exceptTabId) { // Get all tabs first auto tabs = tabBar_.getAllTabs(); - + // Close all documents except the one we're keeping for (const auto& tab : tabs) { if (tab.id != exceptTabId && !tab.isPinned) { closeDocument(tab.filePath); } } - + // Close other tabs tabBar_.closeOtherTabs(exceptTabId); } @@ -872,10 +898,10 @@ bool IntegratedEditor::switchToTab(size_t tabId) { if (!tab.has_value()) { return false; } - + // Set as selected file in editor store editorStore_.setSelectedFile(tab->filePath); - + // Activate the tab return tabBar_.activateTab(tabId); } @@ -883,14 +909,14 @@ bool IntegratedEditor::switchToTab(size_t tabId) { bool IntegratedEditor::switchToTabByPath(const std::string& filePath) { // Set as selected file in editor store editorStore_.setSelectedFile(filePath); - + // Activate the tab return tabBar_.activateTabByPath(filePath); } void IntegratedEditor::switchToNextTab() { tabBar_.activateNextTab(); - + // Update selected file in editor store auto activeTab = tabBar_.getActiveTab(); if (activeTab.has_value()) { @@ -900,7 +926,7 @@ void IntegratedEditor::switchToNextTab() { void IntegratedEditor::switchToPreviousTab() { tabBar_.activatePreviousTab(); - + // Update selected file in editor store auto activeTab = tabBar_.getActiveTab(); if (activeTab.has_value()) { @@ -968,7 +994,7 @@ void IntegratedEditor::clearAllHighlights(const std::string& filePath) { void IntegratedEditor::clearAllHighlightsOfType(HighlightType type) { for (auto& [filePath, lines] : lineHighlights_) { - for (auto lineIt = lines.begin(); lineIt != lines.end(); ) { + for (auto lineIt = lines.begin(); lineIt != lines.end();) { lineIt->second.erase(type); if (lineIt->second.empty()) { lineIt = lines.erase(lineIt); @@ -978,7 +1004,7 @@ void IntegratedEditor::clearAllHighlightsOfType(HighlightType type) { } } // Clean up empty file entries - for (auto it = lineHighlights_.begin(); it != lineHighlights_.end(); ) { + for (auto it = lineHighlights_.begin(); it != lineHighlights_.end();) { if (it->second.empty()) { it = lineHighlights_.erase(it); } else { @@ -998,7 +1024,8 @@ bool IntegratedEditor::hasHighlight(const std::string& filePath, size_t line, Hi return false; } -std::vector> IntegratedEditor::getHighlights(const std::string& filePath) const { +std::vector> IntegratedEditor::getHighlights( + const std::string& filePath) const { std::vector> result; auto fileIt = lineHighlights_.find(filePath); if (fileIt != lineHighlights_.end()) { @@ -1128,7 +1155,7 @@ void IntegratedEditor::clearSourceMappings(const std::string& filePath) { std::string prefix = filePath + ":"; // Find and remove line->PC mappings - for (auto it = lineToPc_.begin(); it != lineToPc_.end(); ) { + for (auto it = lineToPc_.begin(); it != lineToPc_.end();) { if (it->first.compare(0, prefix.length(), prefix) == 0) { // Also remove the corresponding PC->line mapping pcToLine_.erase(it->second); @@ -1156,4 +1183,4 @@ std::optional> IntegratedEditor::getLineForPC(siz return std::nullopt; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/keyboard_shortcuts.cpp b/src/bolt/editor/keyboard_shortcuts.cpp index 25479249..1d634030 100644 --- a/src/bolt/editor/keyboard_shortcuts.cpp +++ b/src/bolt/editor/keyboard_shortcuts.cpp @@ -1,31 +1,40 @@ #include "bolt/editor/keyboard_shortcuts.hpp" + #include -#include -#include #include +#include #include #include +#include namespace bolt { // KeyCombination implementation bool KeyCombination::operator<(const KeyCombination& other) const { - if (ctrl != other.ctrl) return ctrl < other.ctrl; - if (shift != other.shift) return shift < other.shift; - if (alt != other.alt) return alt < other.alt; - if (meta != other.meta) return meta < other.meta; + if (ctrl != other.ctrl) + return ctrl < other.ctrl; + if (shift != other.shift) + return shift < other.shift; + if (alt != other.alt) + return alt < other.alt; + if (meta != other.meta) + return meta < other.meta; return key < other.key; } std::string KeyCombination::toString() const { std::string result; - - if (ctrl) result += "Ctrl+"; - if (shift) result += "Shift+"; - if (alt) result += "Alt+"; - if (meta) result += "Meta+"; - + + if (ctrl) + result += "Ctrl+"; + if (shift) + result += "Shift+"; + if (alt) + result += "Alt+"; + if (meta) + result += "Meta+"; + result += key; return result; } @@ -33,7 +42,7 @@ std::string KeyCombination::toString() const { KeyCombination KeyCombination::fromString(const std::string& keyString) { KeyCombination combo; std::string remaining = keyString; - + // Parse modifiers while (true) { if (remaining.find("Ctrl+") == 0) { @@ -52,7 +61,7 @@ KeyCombination KeyCombination::fromString(const std::string& keyString) { break; } } - + combo.key = remaining; return combo; } @@ -68,37 +77,37 @@ KeyboardShortcuts& KeyboardShortcuts::getInstance() { } bool KeyboardShortcuts::registerShortcut(const std::string& keyString, const std::string& command, - ShortcutCallback callback, ShortcutContext context, - const std::string& description) { + ShortcutCallback callback, ShortcutContext context, + const std::string& description) { KeyCombination combo = KeyCombination::fromString(keyString); return registerShortcut(combo, command, callback, context, description); } bool KeyboardShortcuts::registerShortcut(const KeyCombination& keyCombination, const std::string& command, - ShortcutCallback callback, ShortcutContext context, - const std::string& description) { + ShortcutCallback callback, ShortcutContext context, + const std::string& description) { if (!keyCombination.isValid() || command.empty() || !callback) { return false; } - + // Check for conflicts if (isKeyConflict(keyCombination, context, command)) { return false; } - + ShortcutInfo info{keyCombination, command, description, context, callback}; shortcuts_[info] = callback; return true; } bool KeyboardShortcuts::unregisterShortcut(const std::string& keyString, const std::string& command, - ShortcutContext context) { + ShortcutContext context) { KeyCombination combo = KeyCombination::fromString(keyString); return unregisterShortcut(combo, command, context); } bool KeyboardShortcuts::unregisterShortcut(const KeyCombination& keyCombination, const std::string& command, - ShortcutContext context) { + ShortcutContext context) { ShortcutInfo info{keyCombination, command, "", context, nullptr}; auto it = shortcuts_.find(info); if (it != shortcuts_.end()) { @@ -117,25 +126,22 @@ bool KeyboardShortcuts::executeShortcut(const KeyCombination& keyCombination, Sh if (!enabled_) { return false; } - + // Try to find shortcut in current context first for (const auto& [info, callback] : shortcuts_) { - if (info.keyCombination.ctrl == keyCombination.ctrl && - info.keyCombination.shift == keyCombination.shift && - info.keyCombination.alt == keyCombination.alt && - info.keyCombination.meta == keyCombination.meta && - info.keyCombination.key == keyCombination.key && - info.context == context) { + if (info.keyCombination.ctrl == keyCombination.ctrl && info.keyCombination.shift == keyCombination.shift && + info.keyCombination.alt == keyCombination.alt && info.keyCombination.meta == keyCombination.meta && + info.keyCombination.key == keyCombination.key && info.context == context) { callback(); return true; } } - + // If not found in specific context, try global context if (context != ShortcutContext::Global) { return executeShortcut(keyCombination, ShortcutContext::Global); } - + return false; } @@ -191,10 +197,8 @@ std::vector KeyboardShortcuts::findShortcutsByKey(const std::strin KeyCombination combo = KeyCombination::fromString(keyString); std::vector result; for (const auto& [info, callback] : shortcuts_) { - if (info.keyCombination.ctrl == combo.ctrl && - info.keyCombination.shift == combo.shift && - info.keyCombination.alt == combo.alt && - info.keyCombination.meta == combo.meta && + if (info.keyCombination.ctrl == combo.ctrl && info.keyCombination.shift == combo.shift && + info.keyCombination.alt == combo.alt && info.keyCombination.meta == combo.meta && info.keyCombination.key == combo.key) { result.push_back(info); } @@ -204,12 +208,9 @@ std::vector KeyboardShortcuts::findShortcutsByKey(const std::strin bool KeyboardShortcuts::hasShortcut(const KeyCombination& keyCombination, ShortcutContext context) const { for (const auto& [info, callback] : shortcuts_) { - if (info.keyCombination.ctrl == keyCombination.ctrl && - info.keyCombination.shift == keyCombination.shift && - info.keyCombination.alt == keyCombination.alt && - info.keyCombination.meta == keyCombination.meta && - info.keyCombination.key == keyCombination.key && - info.context == context) { + if (info.keyCombination.ctrl == keyCombination.ctrl && info.keyCombination.shift == keyCombination.shift && + info.keyCombination.alt == keyCombination.alt && info.keyCombination.meta == keyCombination.meta && + info.keyCombination.key == keyCombination.key && info.context == context) { return true; } } @@ -220,18 +221,17 @@ std::string KeyboardShortcuts::getHelpText(ShortcutContext context) const { std::ostringstream oss; oss << "Keyboard Shortcuts - " << contextToString(context) << ":\n"; oss << std::string(50, '=') << "\n\n"; - + auto shortcuts = getShortcutsForContext(context); std::sort(shortcuts.begin(), shortcuts.end(), [](const ShortcutInfo& a, const ShortcutInfo& b) { return a.keyCombination.toString() < b.keyCombination.toString(); }); - + for (const auto& info : shortcuts) { - oss << std::left << std::setw(25) << info.keyCombination.toString() - << std::setw(30) << info.command + oss << std::left << std::setw(25) << info.keyCombination.toString() << std::setw(30) << info.command << info.description << "\n"; } - + return oss.str(); } @@ -262,115 +262,118 @@ void KeyboardShortcuts::initDefaultShortcuts() { void KeyboardShortcuts::initGlobalShortcuts() { // File operations - registerShortcut("Ctrl+S", "save", []() { /* Save current file */ }, - ShortcutContext::Global, "Save current file"); - registerShortcut("Ctrl+O", "open", []() { /* Open file dialog */ }, - ShortcutContext::Global, "Open file"); - registerShortcut("Ctrl+N", "new", []() { /* Create new file */ }, - ShortcutContext::Global, "Create new file"); - registerShortcut("Ctrl+Shift+S", "saveAs", []() { /* Save as dialog */ }, - ShortcutContext::Global, "Save file as"); - registerShortcut("Ctrl+W", "close", []() { /* Close current file */ }, - ShortcutContext::Global, "Close current file"); - registerShortcut("Ctrl+Shift+T", "reopenTab", []() { /* Reopen last closed tab */ }, - ShortcutContext::Global, "Reopen last closed tab"); + registerShortcut( + "Ctrl+S", "save", []() { /* Save current file */ }, ShortcutContext::Global, "Save current file"); + registerShortcut( + "Ctrl+O", "open", []() { /* Open file dialog */ }, ShortcutContext::Global, "Open file"); + registerShortcut( + "Ctrl+N", "new", []() { /* Create new file */ }, ShortcutContext::Global, "Create new file"); + registerShortcut( + "Ctrl+Shift+S", "saveAs", []() { /* Save as dialog */ }, ShortcutContext::Global, "Save file as"); + registerShortcut( + "Ctrl+W", "close", []() { /* Close current file */ }, ShortcutContext::Global, "Close current file"); + registerShortcut( + "Ctrl+Shift+T", "reopenTab", []() { /* Reopen last closed tab */ }, ShortcutContext::Global, + "Reopen last closed tab"); } void KeyboardShortcuts::initEditorShortcuts() { // Edit operations - registerShortcut("Ctrl+Z", "undo", []() { /* Undo last action */ }, - ShortcutContext::Editor, "Undo"); - registerShortcut("Ctrl+Y", "redo", []() { /* Redo last action */ }, - ShortcutContext::Editor, "Redo"); - registerShortcut("Ctrl+Shift+Z", "redo", []() { /* Alternative redo */ }, - ShortcutContext::Editor, "Redo (alternative)"); - registerShortcut("Ctrl+X", "cut", []() { /* Cut selection */ }, - ShortcutContext::Editor, "Cut"); - registerShortcut("Ctrl+C", "copy", []() { /* Copy selection */ }, - ShortcutContext::Editor, "Copy"); - registerShortcut("Ctrl+V", "paste", []() { /* Paste from clipboard */ }, - ShortcutContext::Editor, "Paste"); - registerShortcut("Ctrl+A", "selectAll", []() { /* Select all text */ }, - ShortcutContext::Editor, "Select all"); - + registerShortcut( + "Ctrl+Z", "undo", []() { /* Undo last action */ }, ShortcutContext::Editor, "Undo"); + registerShortcut( + "Ctrl+Y", "redo", []() { /* Redo last action */ }, ShortcutContext::Editor, "Redo"); + registerShortcut( + "Ctrl+Shift+Z", "redo", []() { /* Alternative redo */ }, ShortcutContext::Editor, "Redo (alternative)"); + registerShortcut( + "Ctrl+X", "cut", []() { /* Cut selection */ }, ShortcutContext::Editor, "Cut"); + registerShortcut( + "Ctrl+C", "copy", []() { /* Copy selection */ }, ShortcutContext::Editor, "Copy"); + registerShortcut( + "Ctrl+V", "paste", []() { /* Paste from clipboard */ }, ShortcutContext::Editor, "Paste"); + registerShortcut( + "Ctrl+A", "selectAll", []() { /* Select all text */ }, ShortcutContext::Editor, "Select all"); + // Multi-cursor operations - registerShortcut("Ctrl+D", "addCursorAtNextOccurrence", []() { /* Add cursor at next occurrence */ }, - ShortcutContext::Editor, "Add cursor at next occurrence"); - registerShortcut("Ctrl+Shift+L", "selectAllOccurrences", []() { /* Select all occurrences */ }, - ShortcutContext::Editor, "Select all occurrences"); - registerShortcut("Ctrl+Alt+Up", "addCursorAbove", []() { /* Add cursor above */ }, - ShortcutContext::Editor, "Add cursor above"); - registerShortcut("Ctrl+Alt+Down", "addCursorBelow", []() { /* Add cursor below */ }, - ShortcutContext::Editor, "Add cursor below"); - registerShortcut("Escape", "clearExtraCursors", []() { /* Clear extra cursors */ }, - ShortcutContext::Editor, "Clear extra cursors"); - + registerShortcut( + "Ctrl+D", "addCursorAtNextOccurrence", []() { /* Add cursor at next occurrence */ }, ShortcutContext::Editor, + "Add cursor at next occurrence"); + registerShortcut( + "Ctrl+Shift+L", "selectAllOccurrences", []() { /* Select all occurrences */ }, ShortcutContext::Editor, + "Select all occurrences"); + registerShortcut( + "Ctrl+Alt+Up", "addCursorAbove", []() { /* Add cursor above */ }, ShortcutContext::Editor, "Add cursor above"); + registerShortcut( + "Ctrl+Alt+Down", "addCursorBelow", []() { /* Add cursor below */ }, ShortcutContext::Editor, + "Add cursor below"); + registerShortcut( + "Escape", "clearExtraCursors", []() { /* Clear extra cursors */ }, ShortcutContext::Editor, + "Clear extra cursors"); + // Code folding - registerShortcut("Ctrl+Shift+[", "foldRegion", []() { /* Fold current region */ }, - ShortcutContext::Editor, "Fold region"); - registerShortcut("Ctrl+Shift+]", "unfoldRegion", []() { /* Unfold current region */ }, - ShortcutContext::Editor, "Unfold region"); - registerShortcut("Ctrl+K Ctrl+0", "foldAll", []() { /* Fold all regions */ }, - ShortcutContext::Editor, "Fold all"); - registerShortcut("Ctrl+K Ctrl+J", "unfoldAll", []() { /* Unfold all regions */ }, - ShortcutContext::Editor, "Unfold all"); + registerShortcut( + "Ctrl+Shift+[", "foldRegion", []() { /* Fold current region */ }, ShortcutContext::Editor, "Fold region"); + registerShortcut( + "Ctrl+Shift+]", "unfoldRegion", []() { /* Unfold current region */ }, ShortcutContext::Editor, "Unfold region"); + registerShortcut( + "Ctrl+K Ctrl+0", "foldAll", []() { /* Fold all regions */ }, ShortcutContext::Editor, "Fold all"); + registerShortcut( + "Ctrl+K Ctrl+J", "unfoldAll", []() { /* Unfold all regions */ }, ShortcutContext::Editor, "Unfold all"); } void KeyboardShortcuts::initFileTreeShortcuts() { - registerShortcut("Ctrl+Shift+E", "toggleFileTree", []() { /* Toggle file tree visibility */ }, - ShortcutContext::FileTree, "Toggle file tree"); - registerShortcut("F2", "rename", []() { /* Rename selected file */ }, - ShortcutContext::FileTree, "Rename file"); - registerShortcut("Delete", "delete", []() { /* Delete selected file */ }, - ShortcutContext::FileTree, "Delete file"); - registerShortcut("Ctrl+Shift+N", "newFile", []() { /* Create new file */ }, - ShortcutContext::FileTree, "New file"); - registerShortcut("Ctrl+Shift+Alt+N", "newFolder", []() { /* Create new folder */ }, - ShortcutContext::FileTree, "New folder"); + registerShortcut( + "Ctrl+Shift+E", "toggleFileTree", []() { /* Toggle file tree visibility */ }, ShortcutContext::FileTree, + "Toggle file tree"); + registerShortcut( + "F2", "rename", []() { /* Rename selected file */ }, ShortcutContext::FileTree, "Rename file"); + registerShortcut( + "Delete", "delete", []() { /* Delete selected file */ }, ShortcutContext::FileTree, "Delete file"); + registerShortcut( + "Ctrl+Shift+N", "newFile", []() { /* Create new file */ }, ShortcutContext::FileTree, "New file"); + registerShortcut( + "Ctrl+Shift+Alt+N", "newFolder", []() { /* Create new folder */ }, ShortcutContext::FileTree, "New folder"); } void KeyboardShortcuts::initSearchShortcuts() { - registerShortcut("Ctrl+F", "find", []() { /* Open find dialog */ }, - ShortcutContext::Search, "Find"); - registerShortcut("Ctrl+H", "replace", []() { /* Open find/replace dialog */ }, - ShortcutContext::Search, "Find and replace"); - registerShortcut("F3", "findNext", []() { /* Find next occurrence */ }, - ShortcutContext::Search, "Find next"); - registerShortcut("Shift+F3", "findPrevious", []() { /* Find previous occurrence */ }, - ShortcutContext::Search, "Find previous"); - registerShortcut("Ctrl+G", "goto", []() { /* Go to line */ }, - ShortcutContext::Search, "Go to line"); - registerShortcut("Ctrl+Shift+F", "findInFiles", []() { /* Find in files */ }, - ShortcutContext::Search, "Find in files"); + registerShortcut( + "Ctrl+F", "find", []() { /* Open find dialog */ }, ShortcutContext::Search, "Find"); + registerShortcut( + "Ctrl+H", "replace", []() { /* Open find/replace dialog */ }, ShortcutContext::Search, "Find and replace"); + registerShortcut( + "F3", "findNext", []() { /* Find next occurrence */ }, ShortcutContext::Search, "Find next"); + registerShortcut( + "Shift+F3", "findPrevious", []() { /* Find previous occurrence */ }, ShortcutContext::Search, "Find previous"); + registerShortcut( + "Ctrl+G", "goto", []() { /* Go to line */ }, ShortcutContext::Search, "Go to line"); + registerShortcut( + "Ctrl+Shift+F", "findInFiles", []() { /* Find in files */ }, ShortcutContext::Search, "Find in files"); } void KeyboardShortcuts::initDebuggingShortcuts() { - registerShortcut("F5", "startDebugging", []() { /* Start debugging */ }, - ShortcutContext::Debugging, "Start debugging"); - registerShortcut("Ctrl+F5", "runWithoutDebugging", []() { /* Run without debugging */ }, - ShortcutContext::Debugging, "Run without debugging"); - registerShortcut("Shift+F5", "stopDebugging", []() { /* Stop debugging */ }, - ShortcutContext::Debugging, "Stop debugging"); - registerShortcut("F9", "toggleBreakpoint", []() { /* Toggle breakpoint */ }, - ShortcutContext::Debugging, "Toggle breakpoint"); - registerShortcut("F10", "stepOver", []() { /* Step over */ }, - ShortcutContext::Debugging, "Step over"); - registerShortcut("F11", "stepInto", []() { /* Step into */ }, - ShortcutContext::Debugging, "Step into"); - registerShortcut("Shift+F11", "stepOut", []() { /* Step out */ }, - ShortcutContext::Debugging, "Step out"); + registerShortcut( + "F5", "startDebugging", []() { /* Start debugging */ }, ShortcutContext::Debugging, "Start debugging"); + registerShortcut( + "Ctrl+F5", "runWithoutDebugging", []() { /* Run without debugging */ }, ShortcutContext::Debugging, + "Run without debugging"); + registerShortcut( + "Shift+F5", "stopDebugging", []() { /* Stop debugging */ }, ShortcutContext::Debugging, "Stop debugging"); + registerShortcut( + "F9", "toggleBreakpoint", []() { /* Toggle breakpoint */ }, ShortcutContext::Debugging, "Toggle breakpoint"); + registerShortcut( + "F10", "stepOver", []() { /* Step over */ }, ShortcutContext::Debugging, "Step over"); + registerShortcut( + "F11", "stepInto", []() { /* Step into */ }, ShortcutContext::Debugging, "Step into"); + registerShortcut( + "Shift+F11", "stepOut", []() { /* Step out */ }, ShortcutContext::Debugging, "Step out"); } bool KeyboardShortcuts::isKeyConflict(const KeyCombination& keyCombination, ShortcutContext context, - const std::string& command) const { + const std::string& command) const { for (const auto& [info, callback] : shortcuts_) { - if (info.keyCombination.ctrl == keyCombination.ctrl && - info.keyCombination.shift == keyCombination.shift && - info.keyCombination.alt == keyCombination.alt && - info.keyCombination.meta == keyCombination.meta && - info.keyCombination.key == keyCombination.key && - info.context == context && - info.command != command) { + if (info.keyCombination.ctrl == keyCombination.ctrl && info.keyCombination.shift == keyCombination.shift && + info.keyCombination.alt == keyCombination.alt && info.keyCombination.meta == keyCombination.meta && + info.keyCombination.key == keyCombination.key && info.context == context && info.command != command) { return true; } } @@ -382,45 +385,48 @@ bool KeyboardShortcuts::loadShortcutsFromFile(const std::string& filePath) { if (!file.is_open()) { return false; } - + std::string line; int lineNumber = 0; - + while (std::getline(file, line)) { lineNumber++; - + // Skip empty lines and comments if (line.empty() || line[0] == '#') { continue; } - + // Parse line format: key_combination|command|context|description std::vector parts; std::stringstream ss(line); std::string part; - + while (std::getline(ss, part, '|')) { parts.push_back(part); } - + if (parts.size() < 3) { std::cerr << "Warning: Invalid line " << lineNumber << " in " << filePath << std::endl; continue; } - + std::string keyString = parts[0]; std::string command = parts[1]; std::string contextStr = parts[2]; std::string description = parts.size() > 3 ? parts[3] : ""; - + ShortcutContext context = stringToContext(contextStr); - + // Register shortcut with empty callback (will be overridden by actual implementation) - registerShortcut(keyString, command, []() { - // Placeholder callback - will be replaced by actual implementations - }, context, description); + registerShortcut( + keyString, command, + []() { + // Placeholder callback - will be replaced by actual implementations + }, + context, description); } - + return true; } @@ -429,28 +435,26 @@ bool KeyboardShortcuts::saveShortcutsToFile(const std::string& filePath) const { if (!file.is_open()) { return false; } - + file << "# Bolt C++ Keyboard Shortcuts Configuration\n"; file << "# Format: key_combination|command|context|description\n\n"; - + // Group shortcuts by context std::map> groupedShortcuts; for (const auto& [info, callback] : shortcuts_) { groupedShortcuts[info.context].push_back(info); } - + for (const auto& [context, shortcuts] : groupedShortcuts) { file << "# " << contextToString(context) << " shortcuts\n"; - + for (const auto& info : shortcuts) { - file << info.keyCombination.toString() << "|" - << info.command << "|" - << contextToString(info.context) << "|" + file << info.keyCombination.toString() << "|" << info.command << "|" << contextToString(info.context) << "|" << info.description << "\n"; } file << "\n"; } - + return true; } @@ -461,22 +465,33 @@ void KeyboardShortcuts::resetToDefaults() { std::string KeyboardShortcuts::contextToString(ShortcutContext context) const { switch (context) { - case ShortcutContext::Global: return "Global"; - case ShortcutContext::Editor: return "Editor"; - case ShortcutContext::FileTree: return "File Tree"; - case ShortcutContext::Search: return "Search"; - case ShortcutContext::Debugging: return "Debugging"; - default: return "Unknown"; + case ShortcutContext::Global: + return "Global"; + case ShortcutContext::Editor: + return "Editor"; + case ShortcutContext::FileTree: + return "File Tree"; + case ShortcutContext::Search: + return "Search"; + case ShortcutContext::Debugging: + return "Debugging"; + default: + return "Unknown"; } } ShortcutContext KeyboardShortcuts::stringToContext(const std::string& contextStr) const { - if (contextStr == "Global") return ShortcutContext::Global; - if (contextStr == "Editor") return ShortcutContext::Editor; - if (contextStr == "File Tree") return ShortcutContext::FileTree; - if (contextStr == "Search") return ShortcutContext::Search; - if (contextStr == "Debugging") return ShortcutContext::Debugging; + if (contextStr == "Global") + return ShortcutContext::Global; + if (contextStr == "Editor") + return ShortcutContext::Editor; + if (contextStr == "File Tree") + return ShortcutContext::FileTree; + if (contextStr == "Search") + return ShortcutContext::Search; + if (contextStr == "Debugging") + return ShortcutContext::Debugging; return ShortcutContext::Global; } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/editor/lsp_client.cpp b/src/bolt/editor/lsp_client.cpp index fa5a6bc5..e4f8a23a 100644 --- a/src/bolt/editor/lsp_client.cpp +++ b/src/bolt/editor/lsp_client.cpp @@ -1,25 +1,26 @@ #include "bolt/editor/lsp_client.hpp" + #include "bolt/editor/lsp_protocol.hpp" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN -#include #include #include +#include // Windows compatibility types typedef SSIZE_T ssize_t; #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #else -#include -#include -#include -#include #include +#include +#include +#include +#include #endif -#include #include +#include namespace bolt { namespace lsp { @@ -32,31 +33,31 @@ ProcessLspConnection::~ProcessLspConnection() { bool ProcessLspConnection::start(const std::string& command, const std::vector& args) { command_ = command; args_ = args; - + if (!createProcess()) { return false; } - + connected_ = true; shouldStop_ = false; - + // Start reader thread readerThread_ = std::thread(&ProcessLspConnection::readerThreadFunc, this); - + return true; } void ProcessLspConnection::stop() { shouldStop_ = true; connected_ = false; - + terminateProcess(); - + if (readerThread_.joinable()) { messageAvailable_.notify_all(); readerThread_.join(); } - + #ifdef _WIN32 if (stdinPipe_ != INVALID_HANDLE_VALUE) { CloseHandle(stdinPipe_); @@ -80,22 +81,23 @@ void ProcessLspConnection::stop() { } void ProcessLspConnection::sendMessage(const std::string& message) { - if (!connected_) return; - + if (!connected_) + return; + writeLspMessage(message); } std::string ProcessLspConnection::receiveMessage() { std::unique_lock lock(queueMutex_); - + if (messageQueue_.empty()) { messageAvailable_.wait(lock, [this] { return !messageQueue_.empty() || shouldStop_; }); } - + if (messageQueue_.empty()) { return ""; } - + std::string message = messageQueue_.front(); messageQueue_.pop(); return message; @@ -116,9 +118,10 @@ void ProcessLspConnection::readerThreadFunc() { } messageAvailable_.notify_one(); } - - if (!connected_) break; - + + if (!connected_) + break; + // Small delay to prevent busy waiting std::this_thread::sleep_for(std::chrono::milliseconds(10)); } @@ -178,17 +181,16 @@ bool ProcessLspConnection::createProcess() { ZeroMemory(&pi, sizeof(pi)); // Create the child process - if (!CreateProcessA( - NULL, // No module name (use command line) - const_cast(cmdLine.c_str()), // Command line - NULL, // Process handle not inheritable - NULL, // Thread handle not inheritable - TRUE, // Set handle inheritance to TRUE - CREATE_NO_WINDOW, // Creation flags - NULL, // Use parent's environment block - NULL, // Use parent's starting directory - &si, // Pointer to STARTUPINFO structure - &pi) // Pointer to PROCESS_INFORMATION structure + if (!CreateProcessA(NULL, // No module name (use command line) + const_cast(cmdLine.c_str()), // Command line + NULL, // Process handle not inheritable + NULL, // Thread handle not inheritable + TRUE, // Set handle inheritance to TRUE + CREATE_NO_WINDOW, // Creation flags + NULL, // Use parent's environment block + NULL, // Use parent's starting directory + &si, // Pointer to STARTUPINFO structure + &pi) // Pointer to PROCESS_INFORMATION structure ) { CloseHandle(hChildStdinRd); CloseHandle(hChildStdinWr); @@ -225,13 +227,14 @@ void ProcessLspConnection::terminateProcess() { } std::string ProcessLspConnection::readLspMessage() { - if (stdoutPipe_ == INVALID_HANDLE_VALUE) return ""; - + if (stdoutPipe_ == INVALID_HANDLE_VALUE) + return ""; + // Read LSP header std::string header; char ch; DWORD bytesRead; - + while (true) { // Check if data is available (non-blocking) DWORD bytesAvailable = 0; @@ -239,71 +242,72 @@ std::string ProcessLspConnection::readLspMessage() { connected_ = false; return ""; } - + if (bytesAvailable == 0) { // No data available return ""; } - + if (!ReadFile(stdoutPipe_, &ch, 1, &bytesRead, NULL) || bytesRead == 0) { connected_ = false; return ""; } - + header += ch; if (header.length() >= 4 && header.substr(header.length() - 4) == "\r\n\r\n") { break; } - + // Prevent infinite loop if (header.length() > 1000) { return ""; } } - + // Parse Content-Length size_t contentLength = 0; size_t pos = header.find("Content-Length: "); if (pos != std::string::npos) { - pos += 16; // Length of "Content-Length: " + pos += 16; // Length of "Content-Length: " size_t endPos = header.find("\r\n", pos); if (endPos != std::string::npos) { std::string lengthStr = header.substr(pos, endPos - pos); contentLength = std::stoul(lengthStr); } } - + if (contentLength == 0) { return ""; } - + // Read message content std::string content; content.reserve(contentLength); - + while (content.length() < contentLength) { char buffer[1024]; DWORD toRead = static_cast(std::min(sizeof(buffer), contentLength - content.length())); DWORD bytesReadNow; - + if (!ReadFile(stdoutPipe_, buffer, toRead, &bytesReadNow, NULL) || bytesReadNow == 0) { connected_ = false; return ""; } - + content.append(buffer, bytesReadNow); } - + return content; } void ProcessLspConnection::writeLspMessage(const std::string& message) { - if (stdinPipe_ == INVALID_HANDLE_VALUE) return; - + if (stdinPipe_ == INVALID_HANDLE_VALUE) + return; + // Create LSP header std::string header = "Content-Length: " + std::to_string(message.length()) + "\r\n\r\n"; std::string fullMessage = header + message; - + // Write message DWORD bytesWritten; if (!WriteFile(stdinPipe_, fullMessage.c_str(), static_cast(fullMessage.length()), &bytesWritten, NULL) || @@ -316,12 +320,12 @@ void ProcessLspConnection::writeLspMessage(const std::string& message) { // POSIX implementation (Linux/macOS) bool ProcessLspConnection::createProcess() { int stdinPipes[2], stdoutPipes[2]; - + // Create pipes if (pipe(stdinPipes) == -1 || pipe(stdoutPipes) == -1) { return false; } - + processId_ = fork(); if (processId_ == -1) { // Fork failed @@ -331,20 +335,20 @@ bool ProcessLspConnection::createProcess() { close(stdoutPipes[1]); return false; } - + if (processId_ == 0) { // Child process - + // Redirect stdin and stdout dup2(stdinPipes[0], STDIN_FILENO); dup2(stdoutPipes[1], STDOUT_FILENO); - + // Close unused pipe ends close(stdinPipes[1]); close(stdoutPipes[0]); close(stdinPipes[0]); close(stdoutPipes[1]); - + // Prepare arguments std::vector argv; argv.push_back(const_cast(command_.c_str())); @@ -352,33 +356,33 @@ bool ProcessLspConnection::createProcess() { argv.push_back(const_cast(arg.c_str())); } argv.push_back(nullptr); - + // Execute the language server execvp(command_.c_str(), argv.data()); - + // If we get here, exec failed _exit(1); } else { // Parent process - stdinPipe_ = stdinPipes[1]; // Write to child's stdin - stdoutPipe_ = stdoutPipes[0]; // Read from child's stdout - + stdinPipe_ = stdinPipes[1]; // Write to child's stdin + stdoutPipe_ = stdoutPipes[0]; // Read from child's stdout + // Close unused pipe ends close(stdinPipes[0]); close(stdoutPipes[1]); - + // Make stdout pipe non-blocking int flags = fcntl(stdoutPipe_, F_GETFL); fcntl(stdoutPipe_, F_SETFL, flags | O_NONBLOCK); } - + return true; } void ProcessLspConnection::terminateProcess() { if (processId_ > 0) { kill(processId_, SIGTERM); - + // Wait for process to terminate int status; if (waitpid(processId_, &status, WNOHANG) == 0) { @@ -387,14 +391,15 @@ void ProcessLspConnection::terminateProcess() { kill(processId_, SIGKILL); waitpid(processId_, &status, 0); } - + processId_ = -1; } } std::string ProcessLspConnection::readLspMessage() { - if (stdoutPipe_ < 0) return ""; - + if (stdoutPipe_ < 0) + return ""; + // Read LSP header std::string header; char ch; @@ -409,43 +414,43 @@ std::string ProcessLspConnection::readLspMessage() { connected_ = false; return ""; } - + header += ch; if (header.length() >= 4 && header.substr(header.length() - 4) == "\r\n\r\n") { break; } - + // Prevent infinite loop if (header.length() > 1000) { return ""; } } - + // Parse Content-Length size_t contentLength = 0; size_t pos = header.find("Content-Length: "); if (pos != std::string::npos) { - pos += 16; // Length of "Content-Length: " + pos += 16; // Length of "Content-Length: " size_t endPos = header.find("\r\n", pos); if (endPos != std::string::npos) { std::string lengthStr = header.substr(pos, endPos - pos); contentLength = std::stoul(lengthStr); } } - + if (contentLength == 0) { return ""; } - + // Read message content std::string content; content.reserve(contentLength); - + while (content.length() < contentLength) { char buffer[1024]; size_t toRead = std::min(sizeof(buffer), contentLength - content.length()); ssize_t bytesRead = read(stdoutPipe_, buffer, toRead); - + if (bytesRead <= 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // Wait a bit and try again @@ -456,20 +461,21 @@ std::string ProcessLspConnection::readLspMessage() { connected_ = false; return ""; } - + content.append(buffer, static_cast(bytesRead)); } - + return content; } void ProcessLspConnection::writeLspMessage(const std::string& message) { - if (stdinPipe_ < 0) return; - + if (stdinPipe_ < 0) + return; + // Create LSP header std::string header = "Content-Length: " + std::to_string(message.length()) + "\r\n\r\n"; std::string fullMessage = header + message; - + // Write message ssize_t bytesWritten = write(stdinPipe_, fullMessage.c_str(), fullMessage.length()); if (bytesWritten != static_cast(fullMessage.length())) { @@ -488,9 +494,7 @@ static int getPlatformPid() { } // LspClient implementation -LspClient::LspClient(std::unique_ptr connection) - : connection_(std::move(connection)) { -} +LspClient::LspClient(std::unique_ptr connection) : connection_(std::move(connection)) {} LspClient::~LspClient() { disconnect(); @@ -498,28 +502,28 @@ LspClient::~LspClient() { bool LspClient::connect(const LspClientConfig& config) { config_ = config; - + if (!connection_->start(config.serverCommand, config.serverArgs)) { return false; } - + running_ = true; messageProcessor_ = std::thread(&LspClient::messageProcessorFunc, this); - + return true; } void LspClient::disconnect() { running_ = false; - + if (connection_) { connection_->stop(); } - + if (messageProcessor_.joinable()) { messageProcessor_.join(); } - + initialized_ = false; } @@ -533,33 +537,33 @@ void LspClient::initialize(std::function callback) { params->setProperty("processId", std::make_shared(static_cast(getPlatformPid()))); params->setProperty("rootPath", std::make_shared(config_.rootPath)); params->setProperty("rootUri", std::make_shared("file://" + config_.rootPath)); - + // Add client capabilities auto capabilities = std::make_shared(); capabilities->setObject(); - + auto textDocumentCapabilities = std::make_shared(); textDocumentCapabilities->setObject(); - + auto completionCapabilities = std::make_shared(); completionCapabilities->setObject(); completionCapabilities->setProperty("dynamicRegistration", std::make_shared(false)); textDocumentCapabilities->setProperty("completion", completionCapabilities); - + auto hoverCapabilities = std::make_shared(); hoverCapabilities->setObject(); hoverCapabilities->setProperty("dynamicRegistration", std::make_shared(false)); textDocumentCapabilities->setProperty("hover", hoverCapabilities); - + capabilities->setProperty("textDocument", textDocumentCapabilities); params->setProperty("capabilities", capabilities); - + sendRequest("initialize", params, [this, callback](std::shared_ptr result) { initialized_ = (result != nullptr); if (callback) { callback(initialized_); } - + // Send initialized notification if (initialized_) { sendNotification("initialized", std::make_shared()); @@ -579,20 +583,20 @@ void LspClient::shutdown(std::function callback) { void LspClient::didOpenTextDocument(const TextDocumentItem& document) { auto params = textDocumentItemToJson(document); - + auto notification = std::make_shared(); notification->setObject(); notification->setProperty("textDocument", params); - + sendNotification("textDocument/didOpen", notification); } -void LspClient::didChangeTextDocument(const VersionedTextDocumentIdentifier& document, - const std::vector& changes) { +void LspClient::didChangeTextDocument(const VersionedTextDocumentIdentifier& document, + const std::vector& changes) { auto params = std::make_shared(); params->setObject(); params->setProperty("textDocument", versionedTextDocumentIdentifierToJson(document)); - + auto changesArray = std::make_shared(); changesArray->setArray(); for (const auto& change : changes) { @@ -602,7 +606,7 @@ void LspClient::didChangeTextDocument(const VersionedTextDocumentIdentifier& doc changesArray->addArrayElement(changeJson); } params->setProperty("contentChanges", changesArray); - + sendNotification("textDocument/didChange", params); } @@ -610,7 +614,7 @@ void LspClient::didCloseTextDocument(const TextDocumentIdentifier& document) { auto params = std::make_shared(); params->setObject(); params->setProperty("textDocument", textDocumentIdentifierToJson(document)); - + sendNotification("textDocument/didClose", params); } @@ -618,14 +622,14 @@ void LspClient::didSaveTextDocument(const TextDocumentIdentifier& document) { auto params = std::make_shared(); params->setObject(); params->setProperty("textDocument", textDocumentIdentifierToJson(document)); - + sendNotification("textDocument/didSave", params); } -void LspClient::completion(const TextDocumentPositionParams& params, - std::function callback) { +void LspClient::completion(const TextDocumentPositionParams& params, + std::function callback) { auto jsonParams = textDocumentPositionParamsToJson(params); - + sendRequest("textDocument/completion", jsonParams, [this, callback](std::shared_ptr result) { if (callback) { CompletionList completions = jsonToCompletionList(result); @@ -634,10 +638,10 @@ void LspClient::completion(const TextDocumentPositionParams& params, }); } -void LspClient::hover(const TextDocumentPositionParams& params, - std::function&)> callback) { +void LspClient::hover(const TextDocumentPositionParams& params, + std::function&)> callback) { auto jsonParams = textDocumentPositionParamsToJson(params); - + sendRequest("textDocument/hover", jsonParams, [this, callback](std::shared_ptr result) { if (callback) { if (result && result->getType() != JsonValue::Null) { @@ -651,9 +655,9 @@ void LspClient::hover(const TextDocumentPositionParams& params, } void LspClient::definition(const TextDocumentPositionParams& params, - std::function&)> callback) { + std::function&)> callback) { auto jsonParams = textDocumentPositionParamsToJson(params); - + sendRequest("textDocument/definition", jsonParams, [this, callback](std::shared_ptr result) { if (callback) { std::vector locations; @@ -677,21 +681,21 @@ void LspClient::definition(const TextDocumentPositionParams& params, } void LspClient::references(const TextDocumentPositionParams& params, - std::function&)> callback) { + std::function&)> callback) { // Create params with context (includeDeclaration) auto jsonParams = std::make_shared(JsonValue::Object); jsonParams->setProperty("textDocument", textDocumentIdentifierToJson(params.textDocument)); - + auto positionJson = std::make_shared(JsonValue::Object); positionJson->setProperty("line", std::make_shared(static_cast(params.position.line))); positionJson->setProperty("character", std::make_shared(static_cast(params.position.character))); jsonParams->setProperty("position", positionJson); - + // Add context with includeDeclaration auto contextJson = std::make_shared(JsonValue::Object); contextJson->setProperty("includeDeclaration", std::make_shared(true)); jsonParams->setProperty("context", contextJson); - + sendRequest("textDocument/references", jsonParams, [this, callback](std::shared_ptr result) { if (callback) { std::vector locations; @@ -709,10 +713,10 @@ void LspClient::references(const TextDocumentPositionParams& params, } void LspClient::documentSymbol(const TextDocumentIdentifier& document, - std::function&)> callback) { + std::function&)> callback) { auto jsonParams = std::make_shared(JsonValue::Object); jsonParams->setProperty("textDocument", textDocumentIdentifierToJson(document)); - + sendRequest("textDocument/documentSymbol", jsonParams, [this, callback](std::shared_ptr result) { if (callback) { std::vector symbols; @@ -730,11 +734,11 @@ void LspClient::documentSymbol(const TextDocumentIdentifier& document, } void LspClient::formatting(const TextDocumentIdentifier& document, const FormattingOptions& options, - std::function&)> callback) { + std::function&)> callback) { auto jsonParams = std::make_shared(JsonValue::Object); jsonParams->setProperty("textDocument", textDocumentIdentifierToJson(document)); jsonParams->setProperty("options", formattingOptionsToJson(options)); - + sendRequest("textDocument/formatting", jsonParams, [this, callback](std::shared_ptr result) { if (callback) { std::vector edits; @@ -757,17 +761,17 @@ CompletionList LspClient::completionSync(const TextDocumentPositionParams& param std::mutex mtx; std::condition_variable cv; bool done = false; - + completion(params, [&](const CompletionList& completions) { std::lock_guard lock(mtx); result = completions; done = true; cv.notify_one(); }); - + std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [&] { return done; }); - + return result; } @@ -776,17 +780,17 @@ std::optional LspClient::hoverSync(const TextDocumentPositionParams& para std::mutex mtx; std::condition_variable cv; bool done = false; - + hover(params, [&](const std::optional& hoverResult) { std::lock_guard lock(mtx); result = hoverResult; done = true; cv.notify_one(); }); - + std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [&] { return done; }); - + return result; } @@ -795,17 +799,17 @@ std::vector LspClient::definitionSync(const TextDocumentPositionParams std::mutex mtx; std::condition_variable cv; bool done = false; - + definition(params, [&](const std::vector& locations) { std::lock_guard lock(mtx); result = locations; done = true; cv.notify_one(); }); - + std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [&] { return done; }); - + return result; } @@ -814,17 +818,17 @@ std::vector LspClient::referencesSync(const TextDocumentPositionParams std::mutex mtx; std::condition_variable cv; bool done = false; - + references(params, [&](const std::vector& locations) { std::lock_guard lock(mtx); result = locations; done = true; cv.notify_one(); }); - + std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [&] { return done; }); - + return result; } @@ -833,36 +837,37 @@ std::vector LspClient::documentSymbolSync(const TextDocumentIden std::mutex mtx; std::condition_variable cv; bool done = false; - + documentSymbol(document, [&](const std::vector& symbols) { std::lock_guard lock(mtx); result = symbols; done = true; cv.notify_one(); }); - + std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [&] { return done; }); - + return result; } -std::vector LspClient::formattingSync(const TextDocumentIdentifier& document, const FormattingOptions& options, int timeoutMs) { +std::vector LspClient::formattingSync(const TextDocumentIdentifier& document, + const FormattingOptions& options, int timeoutMs) { std::vector result; std::mutex mtx; std::condition_variable cv; bool done = false; - + formatting(document, options, [&](const std::vector& edits) { std::lock_guard lock(mtx); result = edits; done = true; cv.notify_one(); }); - + std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(timeoutMs), [&] { return done; }); - + return result; } @@ -873,7 +878,7 @@ void LspClient::messageProcessorFunc() { if (!message.empty()) { // Debug: print received message // std::cerr << "[LSP] Received: " << message.substr(0, 200) << "...\n"; - + // Process response auto json = JsonValue::fromString(message); if (json && json->getType() == JsonValue::Object) { @@ -888,7 +893,6 @@ void LspClient::messageProcessorFunc() { } } if (!id.empty()) { - std::lock_guard lock(requestMutex_); auto it = pendingRequests_.find(id); if (it != pendingRequests_.end()) { @@ -900,7 +904,7 @@ void LspClient::messageProcessorFunc() { } } } - + std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } @@ -910,24 +914,26 @@ std::string LspClient::generateRequestId() { return std::to_string(++counter); } -void LspClient::sendRequest(const std::string& method, std::shared_ptr params, - std::function)> callback) { - if (!connection_) return; - +void LspClient::sendRequest(const std::string& method, std::shared_ptr params, + std::function)> callback) { + if (!connection_) + return; + std::string id = generateRequestId(); - + if (callback) { std::lock_guard lock(requestMutex_); pendingRequests_[id] = callback; } - + std::string message = rpcHandler_.createRequest(method, params, id); connection_->sendMessage(message); } void LspClient::sendNotification(const std::string& method, std::shared_ptr params) { - if (!connection_) return; - + if (!connection_) + return; + std::string message = rpcHandler_.createNotification(method, params); connection_->sendMessage(message); } @@ -950,7 +956,8 @@ std::shared_ptr LspClient::textDocumentIdentifierToJson(const TextDoc return json; } -std::shared_ptr LspClient::versionedTextDocumentIdentifierToJson(const VersionedTextDocumentIdentifier& identifier) { +std::shared_ptr LspClient::versionedTextDocumentIdentifierToJson( + const VersionedTextDocumentIdentifier& identifier) { auto json = std::make_shared(); json->setObject(); json->setProperty("uri", std::make_shared(identifier.uri)); @@ -962,13 +969,13 @@ std::shared_ptr LspClient::textDocumentPositionParamsToJson(const Tex auto json = std::make_shared(); json->setObject(); json->setProperty("textDocument", textDocumentIdentifierToJson(params.textDocument)); - + auto position = std::make_shared(); position->setObject(); position->setProperty("line", std::make_shared(static_cast(params.position.line))); position->setProperty("character", std::make_shared(static_cast(params.position.character))); json->setProperty("position", position); - + return json; } @@ -982,7 +989,7 @@ std::shared_ptr LspClient::formattingOptionsToJson(const FormattingOp CompletionList LspClient::jsonToCompletionList(std::shared_ptr json) { CompletionList result; - + if (json && json->getType() == JsonValue::Object) { auto items = json->getProperty("items"); if (items && items->getType() == JsonValue::Array) { @@ -998,20 +1005,20 @@ CompletionList LspClient::jsonToCompletionList(std::shared_ptr json) } } } - + return result; } Hover LspClient::jsonToHover(std::shared_ptr json) { Hover result; - + if (json && json->getType() == JsonValue::Object) { auto contents = json->getProperty("contents"); if (contents && contents->getType() == JsonValue::String) { result.contents = contents->asString(); } } - + return result; } @@ -1069,7 +1076,7 @@ DocumentSymbol LspClient::jsonToDocumentSymbol(std::shared_ptr json) auto range = json->getProperty("range"); auto selectionRange = json->getProperty("selectionRange"); auto children = json->getProperty("children"); - + if (name && name->getType() == JsonValue::String) { symbol.name = name->asString(); } @@ -1120,7 +1127,7 @@ LspClientManager::~LspClientManager() { void LspClientManager::registerLanguageServer(const std::string& languageId, const LspClientConfig& config) { std::lock_guard lock(clientsMutex_); languageConfigs_[languageId] = config; - + // Map file extensions to language IDs for (const auto& ext : config.fileExtensions) { fileExtensionToLanguage_[ext] = languageId; @@ -1129,13 +1136,13 @@ void LspClientManager::registerLanguageServer(const std::string& languageId, con void LspClientManager::unregisterLanguageServer(const std::string& languageId) { std::lock_guard lock(clientsMutex_); - + // Remove client clients_.erase(languageId); - + // Remove language config languageConfigs_.erase(languageId); - + // Remove file extension mappings for (auto it = fileExtensionToLanguage_.begin(); it != fileExtensionToLanguage_.end();) { if (it->second == languageId) { @@ -1153,19 +1160,19 @@ LspClient* LspClientManager::getClientForFile(const std::string& filePath) { LspClient* LspClientManager::getClientForLanguage(const std::string& languageId) { std::lock_guard lock(clientsMutex_); - + auto it = clients_.find(languageId); if (it != clients_.end()) { return it->second.get(); } - + // Try to create a new client return createClientForLanguage(languageId); } std::vector LspClientManager::getRegisteredLanguages() const { std::lock_guard lock(clientsMutex_); - + std::vector languages; for (const auto& config : languageConfigs_) { languages.push_back(config.first); @@ -1173,7 +1180,8 @@ std::vector LspClientManager::getRegisteredLanguages() const { return languages; } -void LspClientManager::didOpenTextDocument(const std::string& filePath, const std::string& content, const std::string& languageId) { +void LspClientManager::didOpenTextDocument(const std::string& filePath, const std::string& content, + const std::string& languageId) { LspClient* client = getClientForFile(filePath); if (client) { TextDocumentItem item; @@ -1181,7 +1189,7 @@ void LspClientManager::didOpenTextDocument(const std::string& filePath, const st item.languageId = languageId.empty() ? getLanguageIdFromFilePath(filePath) : languageId; item.version = 1; item.text = content; - + client->didOpenTextDocument(item); } } @@ -1192,10 +1200,10 @@ void LspClientManager::didChangeTextDocument(const std::string& filePath, const VersionedTextDocumentIdentifier identifier; identifier.uri = filePathToUri(filePath); identifier.version = version; - + TextDocumentContentChangeEvent change; change.text = content; - + client->didChangeTextDocument(identifier, {change}); } } @@ -1205,7 +1213,7 @@ void LspClientManager::didCloseTextDocument(const std::string& filePath) { if (client) { TextDocumentIdentifier identifier; identifier.uri = filePathToUri(filePath); - + client->didCloseTextDocument(identifier); } } @@ -1215,47 +1223,47 @@ void LspClientManager::didSaveTextDocument(const std::string& filePath) { if (client) { TextDocumentIdentifier identifier; identifier.uri = filePathToUri(filePath); - + client->didSaveTextDocument(identifier); } } -void LspClientManager::completion(const std::string& filePath, size_t line, size_t character, - std::function callback) { +void LspClientManager::completion(const std::string& filePath, size_t line, size_t character, + std::function callback) { LspClient* client = getClientForFile(filePath); if (client) { TextDocumentPositionParams params; params.textDocument.uri = filePathToUri(filePath); params.position = Position(line, character); - + client->completion(params, callback); } else if (callback) { callback(CompletionList()); } } -void LspClientManager::hover(const std::string& filePath, size_t line, size_t character, - std::function&)> callback) { +void LspClientManager::hover(const std::string& filePath, size_t line, size_t character, + std::function&)> callback) { LspClient* client = getClientForFile(filePath); if (client) { TextDocumentPositionParams params; params.textDocument.uri = filePathToUri(filePath); params.position = Position(line, character); - + client->hover(params, callback); } else if (callback) { callback(std::nullopt); } } -void LspClientManager::definition(const std::string& filePath, size_t line, size_t character, - std::function&)> callback) { +void LspClientManager::definition(const std::string& filePath, size_t line, size_t character, + std::function&)> callback) { LspClient* client = getClientForFile(filePath); if (client) { TextDocumentPositionParams params; params.textDocument.uri = filePathToUri(filePath); params.position = Position(line, character); - + client->definition(params, callback); } else if (callback) { callback({}); @@ -1264,11 +1272,11 @@ void LspClientManager::definition(const std::string& filePath, size_t line, size void LspClientManager::shutdown() { std::lock_guard lock(clientsMutex_); - + for (auto& client : clients_) { client.second->disconnect(); } - + clients_.clear(); languageConfigs_.clear(); fileExtensionToLanguage_.clear(); @@ -1279,13 +1287,13 @@ std::string LspClientManager::getLanguageIdFromFilePath(const std::string& fileP if (dotPos == std::string::npos) { return "text"; } - + std::string extension = filePath.substr(dotPos); auto it = fileExtensionToLanguage_.find(extension); if (it != fileExtensionToLanguage_.end()) { return it->second; } - + return "text"; } @@ -1298,22 +1306,22 @@ LspClient* LspClientManager::createClientForLanguage(const std::string& language if (configIt == languageConfigs_.end()) { return nullptr; } - + auto connection = std::make_unique(); auto client = std::make_unique(std::move(connection)); - + if (!client->connect(configIt->second)) { return nullptr; } - + // Initialize client client->initialize(); - + LspClient* clientPtr = client.get(); clients_[languageId] = std::move(client); - + return clientPtr; } -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/editor/lsp_json_rpc.cpp b/src/bolt/editor/lsp_json_rpc.cpp index 9a00a602..75902d70 100644 --- a/src/bolt/editor/lsp_json_rpc.cpp +++ b/src/bolt/editor/lsp_json_rpc.cpp @@ -1,7 +1,8 @@ #include "bolt/editor/lsp_json_rpc.hpp" -#include -#include + #include +#include +#include namespace bolt { namespace lsp { @@ -21,12 +22,24 @@ std::string JsonValue::toString() const { // Basic string escaping for (char c : stringValue_) { switch (c) { - case '"': oss << "\\\""; break; - case '\\': oss << "\\\\"; break; - case '\n': oss << "\\n"; break; - case '\r': oss << "\\r"; break; - case '\t': oss << "\\t"; break; - default: oss << c; break; + case '"': + oss << "\\\""; + break; + case '\\': + oss << "\\\\"; + break; + case '\n': + oss << "\\n"; + break; + case '\r': + oss << "\\r"; + break; + case '\t': + oss << "\\t"; + break; + default: + oss << c; + break; } } oss << "\""; @@ -36,7 +49,8 @@ std::string JsonValue::toString() const { std::ostringstream oss; oss << "["; for (size_t i = 0; i < arrayValue_.size(); ++i) { - if (i > 0) oss << ","; + if (i > 0) + oss << ","; oss << arrayValue_[i]->toString(); } oss << "]"; @@ -47,7 +61,8 @@ std::string JsonValue::toString() const { oss << "{"; bool first = true; for (const auto& pair : objectValue_) { - if (!first) oss << ","; + if (!first) + oss << ","; first = false; oss << "\"" << pair.first << "\":" << pair.second->toString(); } @@ -60,7 +75,7 @@ std::string JsonValue::toString() const { // Simple built-in JSON parser (no external dependencies) class SimpleJsonParser { -private: + private: const std::string& json_; size_t pos_ = 0; @@ -70,13 +85,9 @@ class SimpleJsonParser { } } - char peek() const { - return pos_ < json_.size() ? json_[pos_] : '\0'; - } + char peek() const { return pos_ < json_.size() ? json_[pos_] : '\0'; } - char consume() { - return pos_ < json_.size() ? json_[pos_++] : '\0'; - } + char consume() { return pos_ < json_.size() ? json_[pos_++] : '\0'; } bool match(char c) { if (peek() == c) { @@ -96,22 +107,40 @@ class SimpleJsonParser { std::string parseString() { std::string result; - if (!match('"')) return result; + if (!match('"')) + return result; while (pos_ < json_.size()) { char c = consume(); - if (c == '"') break; + if (c == '"') + break; if (c == '\\') { c = consume(); switch (c) { - case '"': result += '"'; break; - case '\\': result += '\\'; break; - case '/': result += '/'; break; - case 'b': result += '\b'; break; - case 'f': result += '\f'; break; - case 'n': result += '\n'; break; - case 'r': result += '\r'; break; - case 't': result += '\t'; break; + case '"': + result += '"'; + break; + case '\\': + result += '\\'; + break; + case '/': + result += '/'; + break; + case 'b': + result += '\b'; + break; + case 'f': + result += '\f'; + break; + case 'n': + result += '\n'; + break; + case 'r': + result += '\r'; + break; + case 't': + result += '\t'; + break; case 'u': { // Unicode escape - simplified handling std::string hex; @@ -122,7 +151,9 @@ class SimpleJsonParser { result += '?'; break; } - default: result += c; break; + default: + result += c; + break; } } else { result += c; @@ -133,8 +164,10 @@ class SimpleJsonParser { double parseNumber() { std::string numStr; - if (peek() == '-') numStr += consume(); - while (pos_ < json_.size() && (std::isdigit(peek()) || peek() == '.' || peek() == 'e' || peek() == 'E' || peek() == '+' || peek() == '-')) { + if (peek() == '-') + numStr += consume(); + while (pos_ < json_.size() && (std::isdigit(peek()) || peek() == '.' || peek() == 'e' || peek() == 'E' || + peek() == '+' || peek() == '-')) { char c = consume(); // Don't add sign if it's not at start or after e/E if ((c == '+' || c == '-') && !numStr.empty() && numStr.back() != 'e' && numStr.back() != 'E') { @@ -150,7 +183,7 @@ class SimpleJsonParser { } } -public: + public: explicit SimpleJsonParser(const std::string& json) : json_(json) {} std::shared_ptr parse() { @@ -210,7 +243,8 @@ class SimpleJsonParser { auto arr = std::make_shared(); arr->setArray(); - if (!match('[')) return arr; + if (!match('[')) + return arr; skipWhitespace(); if (peek() == ']') { @@ -228,7 +262,8 @@ class SimpleJsonParser { consume(); break; } - if (!match(',')) break; + if (!match(',')) + break; } return arr; @@ -238,7 +273,8 @@ class SimpleJsonParser { auto obj = std::make_shared(); obj->setObject(); - if (!match('{')) return obj; + if (!match('{')) + return obj; skipWhitespace(); if (peek() == '}') { @@ -248,12 +284,14 @@ class SimpleJsonParser { while (true) { skipWhitespace(); - if (peek() != '"') break; + if (peek() != '"') + break; std::string key = parseString(); skipWhitespace(); - if (!match(':')) break; + if (!match(':')) + break; skipWhitespace(); auto value = parseValue(); @@ -264,7 +302,8 @@ class SimpleJsonParser { consume(); break; } - if (!match(',')) break; + if (!match(',')) + break; } return obj; @@ -313,7 +352,7 @@ std::string JsonRpcHandler::processMessage(const std::string& message) { if (it != notificationHandlers_.end()) { it->second(method, paramsProperty); } - return ""; // No response for notifications + return ""; // No response for notifications } else { // Request std::string id = idProperty->asString(); @@ -330,7 +369,8 @@ std::string JsonRpcHandler::processMessage(const std::string& message) { } } -std::string JsonRpcHandler::createRequest(const std::string& method, std::shared_ptr params, const std::string& id) { +std::string JsonRpcHandler::createRequest(const std::string& method, std::shared_ptr params, + const std::string& id) { auto request = std::make_shared(); request->setObject(); request->setProperty("jsonrpc", std::make_shared("2.0")); @@ -345,7 +385,7 @@ std::string JsonRpcHandler::createRequest(const std::string& method, std::shared } std::string JsonRpcHandler::createNotification(const std::string& method, std::shared_ptr params) { - return createRequest(method, params, ""); // No id for notifications + return createRequest(method, params, ""); // No id for notifications } std::string JsonRpcHandler::createResponse(const std::string& id, std::shared_ptr result) { @@ -356,7 +396,7 @@ std::string JsonRpcHandler::createResponse(const std::string& id, std::shared_pt if (result) { response->setProperty("result", result); } else { - response->setProperty("result", std::make_shared()); // null + response->setProperty("result", std::make_shared()); // null } return response->toString(); } @@ -376,5 +416,5 @@ std::string JsonRpcHandler::createErrorResponse(const std::string& id, int code, return response->toString(); } -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/editor/lsp_plugin_adapter.cpp b/src/bolt/editor/lsp_plugin_adapter.cpp index 215aa227..3af6a2c4 100644 --- a/src/bolt/editor/lsp_plugin_adapter.cpp +++ b/src/bolt/editor/lsp_plugin_adapter.cpp @@ -1,95 +1,99 @@ #include "bolt/editor/lsp_plugin_adapter.hpp" -#include "bolt/core/editor_store.hpp" + #include #include +#include "bolt/core/editor_store.hpp" + namespace bolt { namespace lsp { // LanguagePluginLspAdapter implementation -LanguagePluginLspAdapter::LanguagePluginLspAdapter(std::shared_ptr plugin, const std::string& languageId) - : plugin_(plugin), languageId_(languageId) { -} +LanguagePluginLspAdapter::LanguagePluginLspAdapter(std::shared_ptr plugin, + const std::string& languageId) + : plugin_(plugin), languageId_(languageId) {} CompletionList LanguagePluginLspAdapter::getCompletion(const std::string& filePath, const Position& position) { CompletionList result; - + if (plugin_) { auto completions = plugin_->getCodeCompletions(filePath, position.line, position.character); - + for (const auto& completion : completions) { result.items.push_back(convertToLspCompletionItem(completion)); } } - + return result; } std::optional LanguagePluginLspAdapter::getHover(const std::string& filePath, const Position& position) { if (plugin_) { std::string hoverInfo = plugin_->getHoverInfo(filePath, position.line, position.character); - + if (!hoverInfo.empty()) { return Hover(hoverInfo); } } - + return std::nullopt; } std::vector LanguagePluginLspAdapter::getDefinition(const std::string& filePath, const Position& position) { std::vector result; - + if (plugin_) { auto references = plugin_->findReferences(filePath, position.line, position.character); - + for (const auto& ref : references) { result.push_back(createLocationFromReferences(filePath, ref)); } } - + return result; } std::vector LanguagePluginLspAdapter::getReferences(const std::string& filePath, const Position& position) { - return getDefinition(filePath, position); // For simplicity, use same implementation + return getDefinition(filePath, position); // For simplicity, use same implementation } -std::vector LanguagePluginLspAdapter::getDiagnostics(const std::string& filePath, const std::string& content) { +std::vector LanguagePluginLspAdapter::getDiagnostics(const std::string& filePath, + const std::string& content) { std::vector result; - + if (plugin_) { auto diagnosticStrings = plugin_->getDiagnostics(filePath, content); - + for (const auto& diagStr : diagnosticStrings) { result.push_back(createDiagnosticFromString(diagStr, filePath)); } } - + return result; } -std::vector LanguagePluginLspAdapter::formatDocument(const std::string& filePath, const std::string& content, const FormattingOptions& options) { +std::vector LanguagePluginLspAdapter::formatDocument(const std::string& filePath, const std::string& content, + const FormattingOptions& options) { std::vector result; - + if (plugin_) { std::string formatted = plugin_->formatCode(content); - + if (formatted != content) { TextEdit edit; - edit.range = Range(Position(0, 0), Position(SIZE_MAX, 0)); // Full document range + edit.range = Range(Position(0, 0), Position(SIZE_MAX, 0)); // Full document range edit.newText = formatted; result.push_back(edit); } } - + return result; } CompletionItem LanguagePluginLspAdapter::convertToLspCompletionItem(const std::string& item) { CompletionItem lspItem(item); lspItem.kind = CompletionItemKind::Text; - + // Try to determine kind based on content if (item.find("()") != std::string::npos) { lspItem.kind = CompletionItemKind::Function; @@ -98,22 +102,24 @@ CompletionItem LanguagePluginLspAdapter::convertToLspCompletionItem(const std::s } else if (item.find("#include") != std::string::npos) { lspItem.kind = CompletionItemKind::Module; } - + return lspItem; } -Location LanguagePluginLspAdapter::createLocationFromReferences(const std::string& filePath, const std::pair& ref) { +Location LanguagePluginLspAdapter::createLocationFromReferences(const std::string& filePath, + const std::pair& ref) { Location location; location.uri = "file://" + filePath; location.range = Range(Position(ref.first, 0), Position(ref.first, ref.second)); return location; } -Diagnostic LanguagePluginLspAdapter::createDiagnosticFromString(const std::string& diagnostic, const std::string& filePath) { +Diagnostic LanguagePluginLspAdapter::createDiagnosticFromString(const std::string& diagnostic, + const std::string& filePath) { Diagnostic diag; diag.message = diagnostic; diag.severity = DiagnosticSeverity::Error; - diag.range = Range(Position(0, 0), Position(0, 1)); // Default range + diag.range = Range(Position(0, 0), Position(0, 1)); // Default range diag.source = languageId_; return diag; } @@ -123,7 +129,7 @@ std::string LanguagePluginLspAdapter::getFileContent(const std::string& filePath if (!file.is_open()) { return ""; } - + std::ostringstream content; content << file.rdbuf(); return content.str(); @@ -152,11 +158,11 @@ void LspIntegrationPlugin::cleanup() { if (lspServer_) { lspServer_->shutdown(); } - + if (clientManager_) { clientManager_->shutdown(); } - + pluginAdapters_.clear(); languageIdMapping_.clear(); } @@ -181,8 +187,9 @@ bool LspIntegrationPlugin::configure(const std::unordered_mapdidOpenTextDocument(filePath, content, languageId); @@ -190,16 +197,18 @@ void LspIntegrationPlugin::onDocumentOpened(const std::string& filePath, const s } void LspIntegrationPlugin::onDocumentClosed(const std::string& filePath) { - if (!enabled_) return; - + if (!enabled_) + return; + if (clientManager_) { clientManager_->didCloseTextDocument(filePath); } } void LspIntegrationPlugin::onDocumentModified(const std::string& filePath, const std::string& content) { - if (!enabled_) return; - + if (!enabled_) + return; + if (clientManager_) { clientManager_->didChangeTextDocument(filePath, content); } @@ -209,17 +218,19 @@ void LspIntegrationPlugin::onCursorChanged(const std::string& filePath, size_t l // LSP doesn't typically need cursor change notifications, but we could use this for hover requests } -std::vector LspIntegrationPlugin::getCodeCompletions(const std::string& filePath, size_t line, size_t column) { - if (!enabled_) return {}; - +std::vector LspIntegrationPlugin::getCodeCompletions(const std::string& filePath, size_t line, + size_t column) { + if (!enabled_) + return {}; + std::vector result; - + // Try LSP client first if (clientManager_) { // This would be async in real implementation // For now, return empty to keep it simple } - + // Fallback to direct language plugins std::string languageId = getLanguageIdFromFilePath(filePath); auto it = pluginAdapters_.find(languageId); @@ -227,15 +238,16 @@ std::vector LspIntegrationPlugin::getCodeCompletions(const std::str auto completions = it->second->getCompletion(filePath, Position(line, column)); result = convertLspCompletions(completions); } - + return result; } std::vector LspIntegrationPlugin::getDiagnostics(const std::string& filePath, const std::string& content) { - if (!enabled_) return {}; - + if (!enabled_) + return {}; + std::vector result; - + // Use direct language plugins for diagnostics std::string languageId = getLanguageIdFromFilePath(filePath); auto it = pluginAdapters_.find(languageId); @@ -243,46 +255,50 @@ std::vector LspIntegrationPlugin::getDiagnostics(const std::string& auto diagnostics = it->second->getDiagnostics(filePath, content); result = convertLspDiagnostics(diagnostics); } - + return result; } std::string LspIntegrationPlugin::formatCode(const std::string& code) { - if (!enabled_) return code; - + if (!enabled_) + return code; + // Basic formatting - in real implementation, would determine language and format accordingly return code; } -std::vector> LspIntegrationPlugin::findReferences(const std::string& filePath, size_t line, size_t column) { - if (!enabled_) return {}; - +std::vector> LspIntegrationPlugin::findReferences(const std::string& filePath, size_t line, + size_t column) { + if (!enabled_) + return {}; + std::string languageId = getLanguageIdFromFilePath(filePath); auto it = pluginAdapters_.find(languageId); if (it != pluginAdapters_.end()) { auto locations = it->second->getReferences(filePath, Position(line, column)); return convertLspReferences(locations); } - + return {}; } std::string LspIntegrationPlugin::getHoverInfo(const std::string& filePath, size_t line, size_t column) { - if (!enabled_) return ""; - + if (!enabled_) + return ""; + std::string languageId = getLanguageIdFromFilePath(filePath); auto it = pluginAdapters_.find(languageId); if (it != pluginAdapters_.end()) { auto hover = it->second->getHover(filePath, Position(line, column)); return convertLspHover(hover); } - + return ""; } std::vector LspIntegrationPlugin::getSupportedExtensions() const { std::vector extensions; - + // Collect extensions from all registered plugins for (const auto& adapter : pluginAdapters_) { auto plugin = adapter.second->getPlugin(); @@ -291,24 +307,26 @@ std::vector LspIntegrationPlugin::getSupportedExtensions() const { extensions.insert(extensions.end(), pluginExtensions.begin(), pluginExtensions.end()); } } - + // Add common LSP extensions extensions.insert(extensions.end(), {".cpp", ".hpp", ".h", ".c", ".py", ".js", ".ts"}); - + return extensions; } -void LspIntegrationPlugin::registerLanguagePlugin(const std::string& languageId, std::shared_ptr plugin) { +void LspIntegrationPlugin::registerLanguagePlugin(const std::string& languageId, + std::shared_ptr plugin) { auto adapter = std::make_unique(plugin, languageId); pluginAdapters_[languageId] = std::move(adapter); - + // Register with LSP server if (lspServer_) { lspServer_->registerLanguagePlugin(languageId, plugin); } } -void LspIntegrationPlugin::registerExternalLanguageServer(const std::string& languageId, const LspClientConfig& config) { +void LspIntegrationPlugin::registerExternalLanguageServer(const std::string& languageId, + const LspClientConfig& config) { if (clientManager_) { clientManager_->registerLanguageServer(languageId, config); } @@ -316,7 +334,7 @@ void LspIntegrationPlugin::registerExternalLanguageServer(const std::string& lan void LspIntegrationPlugin::unregisterLanguagePlugin(const std::string& languageId) { pluginAdapters_.erase(languageId); - + if (lspServer_) { lspServer_->unregisterLanguagePlugin(languageId); } @@ -337,7 +355,7 @@ std::string LspIntegrationPlugin::processLspMessage(const std::string& message) std::string LspIntegrationPlugin::getLanguageIdFromFilePath(const std::string& filePath) { std::string extension = getFileExtension(filePath); - + if (extension == ".cpp" || extension == ".hpp" || extension == ".h" || extension == ".c") { return "cpp"; } else if (extension == ".py") { @@ -349,7 +367,7 @@ std::string LspIntegrationPlugin::getLanguageIdFromFilePath(const std::string& f } else if (extension == ".rs") { return "rust"; } - + return "text"; } @@ -363,7 +381,7 @@ std::string LspIntegrationPlugin::getFileExtension(const std::string& filePath) void LspIntegrationPlugin::initializeLspServer() { lspServer_ = std::make_unique(); - + // Set up basic capabilities ServerCapabilities capabilities; capabilities.textDocumentSync = true; @@ -372,7 +390,7 @@ void LspIntegrationPlugin::initializeLspServer() { capabilities.definitionProvider = true; capabilities.referencesProvider = true; capabilities.documentFormattingProvider = true; - + lspServer_->setCapabilities(capabilities); } @@ -396,7 +414,8 @@ std::vector LspIntegrationPlugin::convertLspDiagnostics(const std:: return result; } -std::vector> LspIntegrationPlugin::convertLspReferences(const std::vector& references) { +std::vector> LspIntegrationPlugin::convertLspReferences( + const std::vector& references) { std::vector> result; for (const auto& location : references) { result.emplace_back(location.range.start.line, location.range.start.character); @@ -416,5 +435,5 @@ std::shared_ptr createLspIntegrationPlugin() { return std::make_shared(); } -} // namespace lsp -} // namespace bolt \ No newline at end of file +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/editor/lsp_server.cpp b/src/bolt/editor/lsp_server.cpp index 27db0c1f..b9fbefec 100644 --- a/src/bolt/editor/lsp_server.cpp +++ b/src/bolt/editor/lsp_server.cpp @@ -1,8 +1,10 @@ #include "bolt/editor/lsp_server.hpp" -#include "bolt/editor/lsp_protocol.hpp" + #include #include +#include "bolt/editor/lsp_protocol.hpp" + namespace bolt { namespace lsp { @@ -24,7 +26,7 @@ void LanguageServer::shutdown() { void LanguageServer::didOpenTextDocument(const TextDocumentItem& document) { documents_[document.uri] = document; - + // Notify language plugin auto plugin = getLanguagePlugin(document.uri); if (plugin) { @@ -33,8 +35,8 @@ void LanguageServer::didOpenTextDocument(const TextDocumentItem& document) { } } -void LanguageServer::didChangeTextDocument(const VersionedTextDocumentIdentifier& document, - const std::vector& changes) { +void LanguageServer::didChangeTextDocument(const VersionedTextDocumentIdentifier& document, + const std::vector& changes) { auto it = documents_.find(document.uri); if (it != documents_.end()) { // Apply changes to document @@ -49,7 +51,7 @@ void LanguageServer::didChangeTextDocument(const VersionedTextDocumentIdentifier } } it->second.version = document.version; - + // Notify language plugin auto plugin = getLanguagePlugin(document.uri); if (plugin) { @@ -68,7 +70,7 @@ void LanguageServer::didCloseTextDocument(const TextDocumentIdentifier& document std::string filePath = uriToFilePath(document.uri); plugin->onDocumentClosed(filePath); } - + documents_.erase(it); } } @@ -79,19 +81,19 @@ void LanguageServer::didSaveTextDocument(const TextDocumentIdentifier& document) CompletionList LanguageServer::completion(const TextDocumentPositionParams& params) { CompletionList result; - + auto plugin = getLanguagePlugin(params.textDocument.uri); if (plugin) { std::string filePath = uriToFilePath(params.textDocument.uri); auto completions = plugin->getCodeCompletions(filePath, params.position.line, params.position.character); - + for (const auto& completion : completions) { CompletionItem item(completion); item.kind = CompletionItemKind::Text; result.items.push_back(item); } } - + return result; } @@ -100,12 +102,12 @@ std::optional LanguageServer::hover(const TextDocumentPositionParams& par if (plugin) { std::string filePath = uriToFilePath(params.textDocument.uri); std::string hoverInfo = plugin->getHoverInfo(filePath, params.position.line, params.position.character); - + if (!hoverInfo.empty()) { return Hover(hoverInfo); } } - + return std::nullopt; } @@ -116,12 +118,12 @@ std::vector LanguageServer::definition(const TextDocumentPositionParam std::vector LanguageServer::references(const TextDocumentPositionParams& params) { std::vector result; - + auto plugin = getLanguagePlugin(params.textDocument.uri); if (plugin) { std::string filePath = uriToFilePath(params.textDocument.uri); auto refs = plugin->findReferences(filePath, params.position.line, params.position.character); - + for (const auto& ref : refs) { Location location; location.uri = params.textDocument.uri; @@ -129,7 +131,7 @@ std::vector LanguageServer::references(const TextDocumentPositionParam result.push_back(location); } } - + return result; } @@ -138,9 +140,10 @@ std::vector LanguageServer::documentSymbol(const TextDocumentIde return {}; } -std::vector LanguageServer::formatting(const TextDocumentIdentifier& document, const FormattingOptions& options) { +std::vector LanguageServer::formatting(const TextDocumentIdentifier& document, + const FormattingOptions& options) { std::vector result; - + auto it = documents_.find(document.uri); if (it != documents_.end()) { auto plugin = getLanguagePlugin(document.uri); @@ -148,36 +151,36 @@ std::vector LanguageServer::formatting(const TextDocumentIdentifier& d std::string formatted = plugin->formatCode(it->second.text); if (formatted != it->second.text) { TextEdit edit; - edit.range = Range(Position(0, 0), Position(SIZE_MAX, 0)); // Full document + edit.range = Range(Position(0, 0), Position(SIZE_MAX, 0)); // Full document edit.newText = formatted; result.push_back(edit); } } } - + return result; } std::vector LanguageServer::diagnostics(const TextDocumentIdentifier& document) { std::vector result; - + auto it = documents_.find(document.uri); if (it != documents_.end()) { auto plugin = getLanguagePlugin(document.uri); if (plugin) { std::string filePath = uriToFilePath(document.uri); auto diagnosticStrings = plugin->getDiagnostics(filePath, it->second.text); - + for (const auto& diagStr : diagnosticStrings) { Diagnostic diag; diag.message = diagStr; diag.severity = DiagnosticSeverity::Error; - diag.range = Range(Position(0, 0), Position(0, 1)); // Default range + diag.range = Range(Position(0, 0), Position(0, 1)); // Default range result.push_back(diag); } } } - + return result; } @@ -201,76 +204,72 @@ std::string LanguageServer::processMessage(const std::string& message) { void LanguageServer::setupMessageHandlers() { // Request handlers - rpcHandler_.registerRequestHandler("initialize", - [this](const std::string& method, std::shared_ptr params) { - return handleInitialize(method, params); - }); - - rpcHandler_.registerRequestHandler("textDocument/completion", - [this](const std::string& method, std::shared_ptr params) { - return handleTextDocumentCompletion(method, params); - }); - - rpcHandler_.registerRequestHandler("textDocument/hover", - [this](const std::string& method, std::shared_ptr params) { - return handleTextDocumentHover(method, params); - }); - - rpcHandler_.registerRequestHandler("textDocument/definition", - [this](const std::string& method, std::shared_ptr params) { - return handleTextDocumentDefinition(method, params); - }); - - rpcHandler_.registerRequestHandler("textDocument/references", - [this](const std::string& method, std::shared_ptr params) { - return handleTextDocumentReferences(method, params); - }); - - rpcHandler_.registerRequestHandler("textDocument/documentSymbol", - [this](const std::string& method, std::shared_ptr params) { - return handleTextDocumentDocumentSymbol(method, params); - }); - - rpcHandler_.registerRequestHandler("textDocument/formatting", - [this](const std::string& method, std::shared_ptr params) { - return handleTextDocumentFormatting(method, params); - }); - + rpcHandler_.registerRequestHandler("initialize", + [this](const std::string& method, std::shared_ptr params) { + return handleInitialize(method, params); + }); + + rpcHandler_.registerRequestHandler("textDocument/completion", + [this](const std::string& method, std::shared_ptr params) { + return handleTextDocumentCompletion(method, params); + }); + + rpcHandler_.registerRequestHandler("textDocument/hover", + [this](const std::string& method, std::shared_ptr params) { + return handleTextDocumentHover(method, params); + }); + + rpcHandler_.registerRequestHandler("textDocument/definition", + [this](const std::string& method, std::shared_ptr params) { + return handleTextDocumentDefinition(method, params); + }); + + rpcHandler_.registerRequestHandler("textDocument/references", + [this](const std::string& method, std::shared_ptr params) { + return handleTextDocumentReferences(method, params); + }); + + rpcHandler_.registerRequestHandler("textDocument/documentSymbol", + [this](const std::string& method, std::shared_ptr params) { + return handleTextDocumentDocumentSymbol(method, params); + }); + + rpcHandler_.registerRequestHandler("textDocument/formatting", + [this](const std::string& method, std::shared_ptr params) { + return handleTextDocumentFormatting(method, params); + }); + // Notification handlers - rpcHandler_.registerNotificationHandler("textDocument/didOpen", - [this](const std::string& method, std::shared_ptr params) { - handleTextDocumentDidOpen(method, params); - }); - - rpcHandler_.registerNotificationHandler("textDocument/didChange", - [this](const std::string& method, std::shared_ptr params) { - handleTextDocumentDidChange(method, params); - }); - - rpcHandler_.registerNotificationHandler("textDocument/didClose", - [this](const std::string& method, std::shared_ptr params) { - handleTextDocumentDidClose(method, params); - }); - - rpcHandler_.registerNotificationHandler("textDocument/didSave", - [this](const std::string& method, std::shared_ptr params) { - handleTextDocumentDidSave(method, params); - }); - - rpcHandler_.registerNotificationHandler("initialized", - [this](const std::string& method, std::shared_ptr params) { - handleInitialized(method, params); - }); - - rpcHandler_.registerNotificationHandler("shutdown", - [this](const std::string& method, std::shared_ptr params) { - handleShutdown(method, params); - }); - - rpcHandler_.registerNotificationHandler("exit", - [this](const std::string& method, std::shared_ptr params) { - handleExit(method, params); - }); + rpcHandler_.registerNotificationHandler("textDocument/didOpen", + [this](const std::string& method, std::shared_ptr params) { + handleTextDocumentDidOpen(method, params); + }); + + rpcHandler_.registerNotificationHandler("textDocument/didChange", + [this](const std::string& method, std::shared_ptr params) { + handleTextDocumentDidChange(method, params); + }); + + rpcHandler_.registerNotificationHandler("textDocument/didClose", + [this](const std::string& method, std::shared_ptr params) { + handleTextDocumentDidClose(method, params); + }); + + rpcHandler_.registerNotificationHandler("textDocument/didSave", + [this](const std::string& method, std::shared_ptr params) { + handleTextDocumentDidSave(method, params); + }); + + rpcHandler_.registerNotificationHandler( + "initialized", + [this](const std::string& method, std::shared_ptr params) { handleInitialized(method, params); }); + + rpcHandler_.registerNotificationHandler( + "shutdown", + [this](const std::string& method, std::shared_ptr params) { handleShutdown(method, params); }); + + rpcHandler_.registerNotificationHandler( + "exit", [this](const std::string& method, std::shared_ptr params) { handleExit(method, params); }); } std::string LanguageServer::getLanguageIdFromUri(const std::string& uri) { @@ -302,62 +301,71 @@ std::string LanguageServer::filePathToUri(const std::string& filePath) { } // JSON-RPC handler implementations (simplified) -std::shared_ptr LanguageServer::handleInitialize(const std::string& method, std::shared_ptr params) { +std::shared_ptr LanguageServer::handleInitialize(const std::string& method, + std::shared_ptr params) { auto result = std::make_shared(); result->setObject(); - + auto capabilities = std::make_shared(); capabilities->setObject(); - capabilities->setProperty("textDocumentSync", std::make_shared(1.0)); // Full sync + capabilities->setProperty("textDocumentSync", std::make_shared(1.0)); // Full sync capabilities->setProperty("hoverProvider", std::make_shared(true)); capabilities->setProperty("completionProvider", std::make_shared(true)); capabilities->setProperty("definitionProvider", std::make_shared(true)); capabilities->setProperty("referencesProvider", std::make_shared(true)); capabilities->setProperty("documentFormattingProvider", std::make_shared(true)); - + result->setProperty("capabilities", capabilities); - + initialized_ = true; return result; } -std::shared_ptr LanguageServer::handleTextDocumentCompletion(const std::string& method, std::shared_ptr params) { - if (!params) return std::make_shared(); - +std::shared_ptr LanguageServer::handleTextDocumentCompletion(const std::string& method, + std::shared_ptr params) { + if (!params) + return std::make_shared(); + auto textDocParams = jsonToTextDocumentPositionParams(params); auto completionList = completion(textDocParams); return completionListToJson(completionList); } -std::shared_ptr LanguageServer::handleTextDocumentHover(const std::string& method, std::shared_ptr params) { - if (!params) return std::make_shared(); - +std::shared_ptr LanguageServer::handleTextDocumentHover(const std::string& method, + std::shared_ptr params) { + if (!params) + return std::make_shared(); + auto textDocParams = jsonToTextDocumentPositionParams(params); auto hoverResult = hover(textDocParams); - + if (hoverResult.has_value()) { return hoverToJson(hoverResult.value()); } - - return std::make_shared(); // null + + return std::make_shared(); // null } -std::shared_ptr LanguageServer::handleTextDocumentDefinition(const std::string& method, std::shared_ptr params) { +std::shared_ptr LanguageServer::handleTextDocumentDefinition(const std::string& method, + std::shared_ptr params) { // Implementation would go here return std::make_shared(); } -std::shared_ptr LanguageServer::handleTextDocumentReferences(const std::string& method, std::shared_ptr params) { +std::shared_ptr LanguageServer::handleTextDocumentReferences(const std::string& method, + std::shared_ptr params) { // Implementation would go here return std::make_shared(); } -std::shared_ptr LanguageServer::handleTextDocumentDocumentSymbol(const std::string& method, std::shared_ptr params) { +std::shared_ptr LanguageServer::handleTextDocumentDocumentSymbol(const std::string& method, + std::shared_ptr params) { // Implementation would go here return std::make_shared(); } -std::shared_ptr LanguageServer::handleTextDocumentFormatting(const std::string& method, std::shared_ptr params) { +std::shared_ptr LanguageServer::handleTextDocumentFormatting(const std::string& method, + std::shared_ptr params) { // Implementation would go here return std::make_shared(); } @@ -393,27 +401,25 @@ void LanguageServer::handleExit(const std::string& method, std::shared_ptr json) { - if (!json || json->getType() != JsonValue::Object) return Position(); - + if (!json || json->getType() != JsonValue::Object) + return Position(); + auto line = json->getProperty("line"); auto character = json->getProperty("character"); - + return Position( line && line->getType() == JsonValue::Number ? static_cast(line->asNumber()) : 0, - character && character->getType() == JsonValue::Number ? static_cast(character->asNumber()) : 0 - ); + character && character->getType() == JsonValue::Number ? static_cast(character->asNumber()) : 0); } Range LanguageServer::jsonToRange(std::shared_ptr json) { - if (!json || json->getType() != JsonValue::Object) return Range(); - + if (!json || json->getType() != JsonValue::Object) + return Range(); + auto start = json->getProperty("start"); auto end = json->getProperty("end"); - - return Range( - jsonToPosition(start), - jsonToPosition(end) - ); + + return Range(jsonToPosition(start), jsonToPosition(end)); } TextDocumentIdentifier LanguageServer::jsonToTextDocumentIdentifier(std::shared_ptr json) { @@ -432,7 +438,7 @@ TextDocumentPositionParams LanguageServer::jsonToTextDocumentPositionParams(std: if (json && json->getType() == JsonValue::Object) { auto textDocument = json->getProperty("textDocument"); auto position = json->getProperty("position"); - + params.textDocument = jsonToTextDocumentIdentifier(textDocument); params.position = jsonToPosition(position); } @@ -459,19 +465,20 @@ std::shared_ptr LanguageServer::completionItemToJson(const Completion auto json = std::make_shared(); json->setObject(); json->setProperty("label", std::make_shared(item.label)); - + if (item.kind.has_value()) { - json->setProperty("kind", std::make_shared(static_cast(static_cast(item.kind.value())))); + json->setProperty("kind", + std::make_shared(static_cast(static_cast(item.kind.value())))); } - + if (item.detail.has_value()) { json->setProperty("detail", std::make_shared(item.detail.value())); } - + if (item.documentation.has_value()) { json->setProperty("documentation", std::make_shared(item.documentation.value())); } - + return json; } @@ -479,14 +486,14 @@ std::shared_ptr LanguageServer::completionListToJson(const Completion auto json = std::make_shared(); json->setObject(); json->setProperty("isIncomplete", std::make_shared(list.isIncomplete)); - + auto items = std::make_shared(); items->setArray(); for (const auto& item : list.items) { items->addArrayElement(completionItemToJson(item)); } json->setProperty("items", items); - + return json; } @@ -494,11 +501,11 @@ std::shared_ptr LanguageServer::hoverToJson(const Hover& hover) { auto json = std::make_shared(); json->setObject(); json->setProperty("contents", std::make_shared(hover.contents)); - + if (hover.range.has_value()) { json->setProperty("range", rangeToJson(hover.range.value())); } - + return json; } @@ -515,11 +522,12 @@ std::shared_ptr LanguageServer::diagnosticToJson(const Diagnostic& di json->setObject(); json->setProperty("range", rangeToJson(diagnostic.range)); json->setProperty("message", std::make_shared(diagnostic.message)); - + if (diagnostic.severity.has_value()) { - json->setProperty("severity", std::make_shared(static_cast(static_cast(diagnostic.severity.value())))); + json->setProperty("severity", std::make_shared( + static_cast(static_cast(diagnostic.severity.value())))); } - + return json; } @@ -531,5 +539,5 @@ std::shared_ptr LanguageServer::textEditToJson(const TextEdit& edit) return json; } -} // namespace lsp -} // namespace bolt \ No newline at end of file +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/editor/lsp_server_configs.cpp b/src/bolt/editor/lsp_server_configs.cpp index 6bd58bf2..92493eb0 100644 --- a/src/bolt/editor/lsp_server_configs.cpp +++ b/src/bolt/editor/lsp_server_configs.cpp @@ -1,10 +1,11 @@ #include "bolt/editor/lsp_server_configs.hpp" + +#include #include #include #include -#include -#include #include +#include namespace bolt { namespace lsp { @@ -18,7 +19,8 @@ std::string LspServerConfigs::findExecutable(const std::string& name) { // Search in PATH const char* pathEnv = std::getenv("PATH"); - if (!pathEnv) return ""; + if (!pathEnv) + return ""; std::string path(pathEnv); std::istringstream pathStream(path); @@ -36,67 +38,47 @@ std::string LspServerConfigs::findExecutable(const std::string& name) { const std::map& LspServerConfigs::getExtensionMap() { static const std::map extensionMap = { - {".cpp", "cpp"}, - {".cxx", "cpp"}, - {".cc", "cpp"}, - {".c", "c"}, - {".hpp", "cpp"}, - {".hxx", "cpp"}, + {".cpp", "cpp"}, {".cxx", "cpp"}, + {".cc", "cpp"}, {".c", "c"}, + {".hpp", "cpp"}, {".hxx", "cpp"}, {".h", "c"}, // Could be C or C++, default to C - {".py", "python"}, - {".pyi", "python"}, - {".pyw", "python"}, - {".rs", "rust"}, - {".ts", "typescript"}, - {".tsx", "typescriptreact"}, - {".js", "javascript"}, - {".jsx", "javascriptreact"}, - {".json", "json"}, - {".go", "go"}, - {".java", "java"}, - {".kt", "kotlin"}, - {".kts", "kotlin"}, - {".lua", "lua"}, - {".rb", "ruby"}, - {".php", "php"}, - {".cs", "csharp"}, - {".swift", "swift"}, + {".py", "python"}, {".pyi", "python"}, + {".pyw", "python"}, {".rs", "rust"}, + {".ts", "typescript"}, {".tsx", "typescriptreact"}, + {".js", "javascript"}, {".jsx", "javascriptreact"}, + {".json", "json"}, {".go", "go"}, + {".java", "java"}, {".kt", "kotlin"}, + {".kts", "kotlin"}, {".lua", "lua"}, + {".rb", "ruby"}, {".php", "php"}, + {".cs", "csharp"}, {".swift", "swift"}, {".zig", "zig"}, }; return extensionMap; } -LspClientConfig LspServerConfigs::clangd(const std::string& rootPath, - const std::vector& extraArgs) { +LspClientConfig LspServerConfigs::clangd(const std::string& rootPath, const std::vector& extraArgs) { LspClientConfig config; config.serverCommand = findExecutable("clangd"); if (config.serverCommand.empty()) { config.serverCommand = "clangd"; // Fall back to name, let system find it } - + // Default clangd arguments for better performance - config.serverArgs = { - "--background-index", - "--clang-tidy", - "--completion-style=detailed", - "--header-insertion=iwyu", - "--pch-storage=memory", - "-j=4" - }; - + config.serverArgs = {"--background-index", "--clang-tidy", "--completion-style=detailed", + "--header-insertion=iwyu", "--pch-storage=memory", "-j=4"}; + // Add extra arguments config.serverArgs.insert(config.serverArgs.end(), extraArgs.begin(), extraArgs.end()); - + config.languageId = "cpp"; config.fileExtensions = {".cpp", ".cxx", ".cc", ".c", ".hpp", ".hxx", ".h"}; config.rootPath = rootPath; config.timeoutMs = 10000; // 10 second timeout for clangd - + return config; } -LspClientConfig LspServerConfigs::pyright(const std::string& rootPath, - const std::vector& extraArgs) { +LspClientConfig LspServerConfigs::pyright(const std::string& rootPath, const std::vector& extraArgs) { LspClientConfig config; config.serverCommand = findExecutable("pyright-langserver"); if (config.serverCommand.empty()) { @@ -105,33 +87,32 @@ LspClientConfig LspServerConfigs::pyright(const std::string& rootPath, if (config.serverCommand.empty()) { config.serverCommand = "pyright-langserver"; } - + // Pyright requires --stdio flag config.serverArgs = {"--stdio"}; config.serverArgs.insert(config.serverArgs.end(), extraArgs.begin(), extraArgs.end()); - + config.languageId = "python"; config.fileExtensions = {".py", ".pyi", ".pyw"}; config.rootPath = rootPath; config.timeoutMs = 5000; - + return config; } -LspClientConfig LspServerConfigs::rustAnalyzer(const std::string& rootPath, - const std::vector& extraArgs) { +LspClientConfig LspServerConfigs::rustAnalyzer(const std::string& rootPath, const std::vector& extraArgs) { LspClientConfig config; config.serverCommand = findExecutable("rust-analyzer"); if (config.serverCommand.empty()) { config.serverCommand = "rust-analyzer"; } - + config.serverArgs = extraArgs; config.languageId = "rust"; config.fileExtensions = {".rs"}; config.rootPath = rootPath; config.timeoutMs = 10000; - + return config; } @@ -142,15 +123,15 @@ LspClientConfig LspServerConfigs::typescriptLanguageServer(const std::string& ro if (config.serverCommand.empty()) { config.serverCommand = "typescript-language-server"; } - + config.serverArgs = {"--stdio"}; config.serverArgs.insert(config.serverArgs.end(), extraArgs.begin(), extraArgs.end()); - + config.languageId = "typescript"; config.fileExtensions = {".ts", ".tsx", ".js", ".jsx"}; config.rootPath = rootPath; config.timeoutMs = 5000; - + return config; } @@ -158,8 +139,7 @@ std::vector LspServerConfigs::getAvailableConfigs() { return {"cpp", "python", "rust", "typescript"}; } -LspClientConfig LspServerConfigs::getConfigForLanguage(const std::string& languageId, - const std::string& rootPath) { +LspClientConfig LspServerConfigs::getConfigForLanguage(const std::string& languageId, const std::string& rootPath) { if (languageId == "cpp" || languageId == "c") { return clangd(rootPath); } else if (languageId == "python") { @@ -169,13 +149,13 @@ LspClientConfig LspServerConfigs::getConfigForLanguage(const std::string& langua } else if (languageId == "typescript" || languageId == "javascript") { return typescriptLanguageServer(rootPath); } - + return LspClientConfig{}; // Empty config for unknown languages } bool LspServerConfigs::isServerAvailable(const std::string& languageId) { std::string executable; - + if (languageId == "cpp" || languageId == "c") { executable = "clangd"; } else if (languageId == "python") { @@ -190,7 +170,7 @@ bool LspServerConfigs::isServerAvailable(const std::string& languageId) { } else { return false; } - + return !findExecutable(executable).empty(); } @@ -206,23 +186,23 @@ std::vector LspServerConfigs::getFileExtensions(const std::string& } else if (languageId == "javascript") { return {".js", ".jsx"}; } - + return {}; } std::string LspServerConfigs::getLanguageIdForFile(const std::string& filePath) { std::filesystem::path path(filePath); std::string ext = path.extension().string(); - + // Convert to lowercase std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); - + const auto& extMap = getExtensionMap(); auto it = extMap.find(ext); if (it != extMap.end()) { return it->second; } - + return ""; } @@ -230,7 +210,7 @@ std::string LspServerConfigs::getLanguageIdForFile(const std::string& filePath) int LspAutoConfigurator::autoConfigureAll(LspClientManager& manager, const std::string& rootPath) { int configured = 0; - + for (const auto& langId : LspServerConfigs::getAvailableConfigs()) { if (LspServerConfigs::isServerAvailable(langId)) { auto config = LspServerConfigs::getConfigForLanguage(langId, rootPath); @@ -240,13 +220,13 @@ int LspAutoConfigurator::autoConfigureAll(LspClientManager& manager, const std:: } } } - + return configured; } int LspAutoConfigurator::configureForProject(LspClientManager& manager, const std::string& projectPath) { std::set detectedLanguages; - + // Scan project directory for source files try { for (const auto& entry : std::filesystem::recursive_directory_iterator(projectPath)) { @@ -260,7 +240,7 @@ int LspAutoConfigurator::configureForProject(LspClientManager& manager, const st } catch (const std::exception&) { // Ignore filesystem errors } - + int configured = 0; for (const auto& langId : detectedLanguages) { if (LspServerConfigs::isServerAvailable(langId)) { @@ -271,7 +251,7 @@ int LspAutoConfigurator::configureForProject(LspClientManager& manager, const st } } } - + return configured; } @@ -279,20 +259,19 @@ std::string LspAutoConfigurator::getAvailabilityReport() { std::ostringstream report; report << "Language Server Availability Report\n"; report << "====================================\n\n"; - + struct ServerInfo { std::string name; std::string langId; std::string executable; }; - + std::vector servers = { {"clangd (C/C++)", "cpp", "clangd"}, {"pyright (Python)", "python", "pyright"}, {"rust-analyzer (Rust)", "rust", "rust-analyzer"}, - {"typescript-language-server (TS/JS)", "typescript", "typescript-language-server"} - }; - + {"typescript-language-server (TS/JS)", "typescript", "typescript-language-server"}}; + for (const auto& server : servers) { bool available = LspServerConfigs::isServerAvailable(server.langId); report << (available ? "โœ…" : "โŒ") << " " << server.name << "\n"; @@ -304,9 +283,9 @@ std::string LspAutoConfigurator::getAvailabilityReport() { } report << "\n"; } - + return report.str(); } -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/editor/minimap.cpp b/src/bolt/editor/minimap.cpp index f1a5929c..a29b59cb 100644 --- a/src/bolt/editor/minimap.cpp +++ b/src/bolt/editor/minimap.cpp @@ -1,15 +1,15 @@ #include "bolt/editor/minimap.hpp" -#include "bolt/editor/minimap_renderer.hpp" + #include #include +#include "bolt/editor/minimap_renderer.hpp" + namespace bolt { -Minimap::Minimap() : Minimap(MinimapConfig{}) { -} +Minimap::Minimap() : Minimap(MinimapConfig{}) {} -Minimap::Minimap(const MinimapConfig& config) - : config_(config) { +Minimap::Minimap(const MinimapConfig& config) : config_(config) { initializeRenderer(); } @@ -18,7 +18,7 @@ Minimap::~Minimap() = default; void Minimap::setDocument(const std::string& filePath, const std::vector& lines) { documentPath_ = filePath; documentLines_ = lines; - + // Update viewport to show full document initially viewport_.totalLines = lines.size(); viewport_.startLine = 0; @@ -29,7 +29,7 @@ void Minimap::setDocument(const std::string& filePath, const std::vector& lines) { documentLines_ = lines; viewport_.totalLines = lines.size(); - + // Adjust viewport if document changed if (viewport_.endLine > lines.size()) { viewport_.endLine = lines.size(); @@ -44,7 +44,7 @@ void Minimap::clearDocument() { void Minimap::updateViewport(const ViewportInfo& viewport) { viewport_ = viewport; - + // Ensure viewport is within document bounds if (!documentLines_.empty()) { viewport_.totalLines = documentLines_.size(); @@ -58,11 +58,11 @@ size_t Minimap::getLineFromPosition(size_t x, size_t y) const { if (documentLines_.empty()) { return 0; } - + // Calculate which document line corresponds to this minimap position size_t linesPerMinimapLine = calculateLinesPerMinimapLine(); size_t startLine = calculateStartLine(); - + size_t documentLine = startLine + (y * linesPerMinimapLine); return std::min(documentLine, documentLines_.size() - 1); } @@ -71,17 +71,17 @@ std::pair Minimap::getPositionFromLine(size_t line) const { if (documentLines_.empty()) { return {0, 0}; } - + size_t linesPerMinimapLine = calculateLinesPerMinimapLine(); size_t startLine = calculateStartLine(); - + if (line < startLine) { return {0, 0}; } - + size_t minimapY = (line - startLine) / linesPerMinimapLine; minimapY = std::min(minimapY, config_.height - 1); - + return {0, minimapY}; } @@ -89,17 +89,17 @@ void Minimap::scrollToLine(size_t line) { if (documentLines_.empty()) { return; } - + // Update viewport to center on the requested line size_t visibleLines = getVisibleLines(); size_t halfVisible = visibleLines / 2; - + if (line >= halfVisible) { viewport_.startLine = line - halfVisible; } else { viewport_.startLine = 0; } - + viewport_.endLine = std::min(viewport_.startLine + visibleLines, documentLines_.size()); viewport_.currentLine = line; } @@ -113,37 +113,26 @@ std::vector Minimap::render() const { if (!enabled_ || documentLines_.empty()) { return std::vector(config_.height, std::string(config_.width, ' ')); } - - return renderer_->render({ - documentLines_, - calculateStartLine(), - calculateEndLine(), - viewport_.currentLine, - viewport_.startLine, - viewport_.endLine - }); + + return renderer_->render({documentLines_, calculateStartLine(), calculateEndLine(), viewport_.currentLine, + viewport_.startLine, viewport_.endLine}); } std::string Minimap::renderLine(size_t minimapLine) const { if (!enabled_ || documentLines_.empty() || minimapLine >= config_.height) { return std::string(config_.width, ' '); } - - return renderer_->renderLine({ - documentLines_, - calculateStartLine(), - calculateEndLine(), - viewport_.currentLine, - viewport_.startLine, - viewport_.endLine - }, minimapLine); + + return renderer_->renderLine({documentLines_, calculateStartLine(), calculateEndLine(), viewport_.currentLine, + viewport_.startLine, viewport_.endLine}, + minimapLine); } size_t Minimap::getVisibleLines() const { if (documentLines_.empty()) { return 0; } - + return std::min(config_.height * calculateLinesPerMinimapLine(), documentLines_.size()); } @@ -151,16 +140,15 @@ double Minimap::getScrollPercentage() const { if (documentLines_.empty() || documentLines_.size() <= getVisibleLines()) { return 0.0; } - - return static_cast(viewport_.startLine) / - static_cast(documentLines_.size() - getVisibleLines()); + + return static_cast(viewport_.startLine) / static_cast(documentLines_.size() - getVisibleLines()); } void Minimap::initializeRenderer() { MinimapRenderer::RenderConfig renderConfig; renderConfig.width = config_.width; renderConfig.height = config_.height; - + renderer_ = std::make_unique(renderConfig); } @@ -168,26 +156,26 @@ size_t Minimap::calculateStartLine() const { if (documentLines_.empty()) { return 0; } - + // Show content around the current viewport size_t totalMinimapLines = config_.height; size_t linesPerMinimapLine = calculateLinesPerMinimapLine(); size_t totalDocumentLines = documentLines_.size(); - + // If document fits in minimap, start from beginning if (totalDocumentLines <= totalMinimapLines * linesPerMinimapLine) { return 0; } - + // Center minimap around current viewport size_t viewportCenter = (viewport_.startLine + viewport_.endLine) / 2; size_t minimapCoverage = totalMinimapLines * linesPerMinimapLine; - + if (viewportCenter >= minimapCoverage / 2) { size_t start = viewportCenter - minimapCoverage / 2; return std::min(start, totalDocumentLines - minimapCoverage); } - + return 0; } @@ -195,7 +183,7 @@ size_t Minimap::calculateEndLine() const { size_t startLine = calculateStartLine(); size_t linesPerMinimapLine = calculateLinesPerMinimapLine(); size_t endLine = startLine + (config_.height * linesPerMinimapLine); - + return std::min(endLine, documentLines_.size()); } @@ -203,10 +191,10 @@ size_t Minimap::calculateLinesPerMinimapLine() const { if (documentLines_.empty()) { return 1; } - + // Calculate how many document lines should be represented by each minimap line size_t ratio = std::max(size_t{1}, documentLines_.size() / config_.height); return ratio; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/minimap_renderer.cpp b/src/bolt/editor/minimap_renderer.cpp index 88d496f1..6ee9931f 100644 --- a/src/bolt/editor/minimap_renderer.cpp +++ b/src/bolt/editor/minimap_renderer.cpp @@ -1,24 +1,22 @@ #include "bolt/editor/minimap_renderer.hpp" + #include #include namespace bolt { -MinimapRenderer::MinimapRenderer() : MinimapRenderer(RenderConfig{}) { -} +MinimapRenderer::MinimapRenderer() : MinimapRenderer(RenderConfig{}) {} -MinimapRenderer::MinimapRenderer(const RenderConfig& config) - : config_(config) { -} +MinimapRenderer::MinimapRenderer(const RenderConfig& config) : config_(config) {} std::vector MinimapRenderer::render(const RenderContext& context) const { std::vector result; result.reserve(config_.height); - + for (size_t minimapLine = 0; minimapLine < config_.height; ++minimapLine) { result.push_back(renderLine(context, minimapLine)); } - + return result; } @@ -26,28 +24,28 @@ std::string MinimapRenderer::renderLine(const RenderContext& context, size_t min if (context.documentLines.empty()) { return std::string(config_.width, config_.emptyChar); } - + std::string line(config_.width, config_.emptyChar); - + // Calculate which document lines this minimap line represents size_t totalDocumentLines = context.endLine - context.startLine; if (totalDocumentLines == 0) { return line; } - + size_t linesPerMinimapLine = std::max(size_t{1}, totalDocumentLines / config_.height); size_t docLineStart = context.startLine + (minimapLine * linesPerMinimapLine); size_t docLineEnd = std::min(docLineStart + linesPerMinimapLine, context.endLine); - + // Analyze the content of these document lines char representation = analyzeLinesRange(context.documentLines, docLineStart, docLineEnd); - + // Fill the minimap line with the representation character std::fill(line.begin(), line.end(), representation); - + // Add viewport overlay line = addViewportOverlay(line, minimapLine, context); - + return line; } @@ -55,7 +53,7 @@ char MinimapRenderer::analyzeDocumentLine(const std::string& line) const { if (line.empty()) { return config_.emptyChar; } - + size_t density = calculateContentDensity(line); return selectRepresentationChar(density); } @@ -64,27 +62,27 @@ char MinimapRenderer::analyzeLinesRange(const std::vector& lines, s if (start >= lines.size() || start >= end) { return config_.emptyChar; } - + size_t totalDensity = 0; size_t lineCount = 0; - + for (size_t i = start; i < std::min(end, lines.size()); ++i) { totalDensity += calculateContentDensity(lines[i]); lineCount++; } - + if (lineCount == 0) { return config_.emptyChar; } - + size_t averageDensity = totalDensity / lineCount; return selectRepresentationChar(averageDensity); } -std::string MinimapRenderer::addViewportOverlay(const std::string& line, size_t minimapLine, +std::string MinimapRenderer::addViewportOverlay(const std::string& line, size_t minimapLine, const RenderContext& context) const { std::string result = line; - + // Check if this minimap line intersects with the current viewport if (isViewportLine(minimapLine, context)) { // Replace some characters with viewport indicator @@ -92,7 +90,7 @@ std::string MinimapRenderer::addViewportOverlay(const std::string& line, size_t result[i] = config_.viewportChar; } } - + // Highlight current line if (isCurrentLine(minimapLine, context)) { if (!result.empty()) { @@ -102,18 +100,16 @@ std::string MinimapRenderer::addViewportOverlay(const std::string& line, size_t } } } - + return result; } bool MinimapRenderer::isViewportLine(size_t minimapLine, const RenderContext& context) const { - size_t documentLine = mapDocumentLineToMinimap(context.viewportStart, - context.endLine - context.startLine, - config_.height); - size_t endDocumentLine = mapDocumentLineToMinimap(context.viewportEnd, - context.endLine - context.startLine, - config_.height); - + size_t documentLine = + mapDocumentLineToMinimap(context.viewportStart, context.endLine - context.startLine, config_.height); + size_t endDocumentLine = + mapDocumentLineToMinimap(context.viewportEnd, context.endLine - context.startLine, config_.height); + return minimapLine >= documentLine && minimapLine <= endDocumentLine; } @@ -121,12 +117,10 @@ bool MinimapRenderer::isCurrentLine(size_t minimapLine, const RenderContext& con if (context.currentLine < context.startLine || context.currentLine >= context.endLine) { return false; } - + size_t relativeLine = context.currentLine - context.startLine; - size_t mappedLine = mapDocumentLineToMinimap(relativeLine, - context.endLine - context.startLine, - config_.height); - + size_t mappedLine = mapDocumentLineToMinimap(relativeLine, context.endLine - context.startLine, config_.height); + return minimapLine == mappedLine; } @@ -134,11 +128,11 @@ size_t MinimapRenderer::mapDocumentLineToMinimap(size_t documentLine, size_t tot if (totalLines == 0 || minimapHeight == 0) { return 0; } - + // Map document line to minimap line proportionally double ratio = static_cast(documentLine) / static_cast(totalLines); size_t minimapLine = static_cast(ratio * minimapHeight); - + return std::min(minimapLine, minimapHeight - 1); } @@ -146,14 +140,14 @@ size_t MinimapRenderer::calculateContentDensity(const std::string& line) const { if (line.empty()) { return 0; } - + size_t nonSpaceChars = 0; for (char c : line) { if (c != ' ' && c != '\t') { nonSpaceChars++; } } - + // Return density as percentage (0-100) return (nonSpaceChars * 100) / line.length(); } @@ -170,4 +164,4 @@ char MinimapRenderer::selectRepresentationChar(size_t density) const { } } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/minimap_ui.cpp b/src/bolt/editor/minimap_ui.cpp index a868ca2b..4b4dba75 100644 --- a/src/bolt/editor/minimap_ui.cpp +++ b/src/bolt/editor/minimap_ui.cpp @@ -1,33 +1,30 @@ #include "bolt/editor/minimap_ui.hpp" + #include #include namespace bolt { -MinimapUI::MinimapUI(Minimap& minimap) - : MinimapUI(minimap, UIConfig{}) { -} +MinimapUI::MinimapUI(Minimap& minimap) : MinimapUI(minimap, UIConfig{}) {} -MinimapUI::MinimapUI(Minimap& minimap, const UIConfig& config) - : minimap_(minimap), config_(config) { -} +MinimapUI::MinimapUI(Minimap& minimap, const UIConfig& config) : minimap_(minimap), config_(config) {} std::vector MinimapUI::render() const { if (!visible_) { return {}; } - + std::vector result; - + // Add title if enabled if (config_.showTitle) { result.push_back(renderTitle()); } - + // Get minimap content auto content = renderContent(); result.insert(result.end(), content.begin(), content.end()); - + // Add scroll indicator if enabled if (config_.showScrollIndicator) { std::string indicator = renderScrollIndicator(); @@ -35,7 +32,7 @@ std::vector MinimapUI::render() const { result.push_back(indicator); } } - + return result; } @@ -43,43 +40,43 @@ std::string MinimapUI::renderFrame() const { if (!config_.showBorder) { return ""; } - + std::string frame; size_t width = minimap_.getConfig().width; - + // Top border frame += config_.cornerChar; frame += std::string(width, config_.horizontalChar); frame += config_.cornerChar; frame += '\n'; - + // Bottom border (will be added by caller if needed) return frame; } std::vector MinimapUI::renderContent() const { auto minimapLines = minimap_.render(); - + if (!config_.showBorder) { return minimapLines; } - + // Add borders to each line std::vector borderedLines; for (const auto& line : minimapLines) { std::string bordered = config_.borderChar + line + config_.borderChar; borderedLines.push_back(bordered); } - + // Add top border size_t width = minimap_.getConfig().width; std::string topBorder = config_.cornerChar + std::string(width, config_.horizontalChar) + config_.cornerChar; borderedLines.insert(borderedLines.begin(), topBorder); - + // Add bottom border std::string bottomBorder = config_.cornerChar + std::string(width, config_.horizontalChar) + config_.cornerChar; borderedLines.push_back(bottomBorder); - + return borderedLines; } @@ -87,28 +84,28 @@ std::string MinimapUI::renderTitle() const { if (!config_.showTitle) { return ""; } - + size_t width = minimap_.getConfig().width; std::string title = config_.title; - + // Truncate title if too long if (title.length() > width) { title = title.substr(0, width - 3) + "..."; } - + // Center the title size_t padding = (width - title.length()) / 2; std::string centeredTitle = std::string(padding, ' ') + title; - + // Pad to full width if (centeredTitle.length() < width) { centeredTitle += std::string(width - centeredTitle.length(), ' '); } - + if (config_.showBorder) { return config_.borderChar + centeredTitle + config_.borderChar; } - + return centeredTitle; } @@ -116,37 +113,37 @@ std::string MinimapUI::renderScrollIndicator() const { if (!config_.showScrollIndicator || !minimap_.hasDocument()) { return ""; } - + auto viewport = minimap_.getViewport(); size_t totalLines = minimap_.getTotalLines(); - + if (totalLines == 0) { return ""; } - + std::ostringstream oss; oss << "Line " << (viewport.currentLine + 1) << "/" << totalLines; - + double scrollPercent = minimap_.getScrollPercentage(); oss << " (" << static_cast(scrollPercent * 100) << "%)"; - + std::string indicator = oss.str(); size_t width = minimap_.getConfig().width; - + // Truncate if too long if (indicator.length() > width) { indicator = indicator.substr(0, width); } - + // Pad to width if (indicator.length() < width) { indicator += std::string(width - indicator.length(), ' '); } - + if (config_.showBorder) { return config_.borderChar + indicator + config_.borderChar; } - + return indicator; } @@ -154,10 +151,10 @@ bool MinimapUI::handleClick(size_t x, size_t y) { if (!visible_ || !isInsideMinimap(x, y)) { return false; } - + auto [localX, localY] = translateCoordinates(x, y); size_t targetLine = minimap_.getLineFromPosition(localX, localY); - + navigateToLine(targetLine); return true; } @@ -166,10 +163,10 @@ bool MinimapUI::handleScroll(int direction, size_t steps) { if (!visible_ || !minimap_.hasDocument()) { return false; } - + auto viewport = minimap_.getViewport(); size_t currentLine = viewport.currentLine; - + if (direction > 0) { // Scroll down size_t newLine = std::min(currentLine + steps, minimap_.getTotalLines() - 1); @@ -179,7 +176,7 @@ bool MinimapUI::handleScroll(int direction, size_t steps) { size_t newLine = (currentLine >= steps) ? currentLine - steps : 0; navigateToLine(newLine); } - + return true; } @@ -187,11 +184,11 @@ bool MinimapUI::handleKeyPress(const std::string& key) { if (!visible_) { return false; } - + auto viewport = minimap_.getViewport(); size_t currentLine = viewport.currentLine; size_t totalLines = minimap_.getTotalLines(); - + if (key == "up" || key == "k") { if (currentLine > 0) { navigateToLine(currentLine - 1); @@ -217,35 +214,35 @@ bool MinimapUI::handleKeyPress(const std::string& key) { navigateToLine(currentLine + jump); return true; } - + return false; } size_t MinimapUI::getRequiredWidth() const { size_t width = minimap_.getConfig().width; - + if (config_.showBorder) { - width += 2; // Left and right borders + width += 2; // Left and right borders } - + return width; } size_t MinimapUI::getRequiredHeight() const { size_t height = minimap_.getConfig().height; - + if (config_.showTitle) { height += 1; } - + if (config_.showBorder) { - height += 2; // Top and bottom borders + height += 2; // Top and bottom borders } - + if (config_.showScrollIndicator) { height += 1; } - + return height; } @@ -257,32 +254,32 @@ void MinimapUI::navigateToLine(size_t line) { if (navigationCallback_) { navigationCallback_(line); } - + minimap_.scrollToLine(line); } bool MinimapUI::isInsideMinimap(size_t x, size_t y) const { - return x >= position_.x && x < position_.x + position_.width && - y >= position_.y && y < position_.y + position_.height; + return x >= position_.x && x < position_.x + position_.width && y >= position_.y && + y < position_.y + position_.height; } std::pair MinimapUI::translateCoordinates(size_t x, size_t y) const { size_t localX = (x >= position_.x) ? x - position_.x : 0; size_t localY = (y >= position_.y) ? y - position_.y : 0; - + // Adjust for borders and title if (config_.showBorder && localX > 0) { localX -= 1; } - + if (config_.showTitle && localY > 0) { localY -= 1; } - + if (config_.showBorder && localY > 0) { localY -= 1; } - + return {localX, localY}; } @@ -290,8 +287,8 @@ std::string MinimapUI::addBorder(const std::string& content) const { if (!config_.showBorder) { return content; } - + return config_.borderChar + content + config_.borderChar; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/editor/theme_system.cpp b/src/bolt/editor/theme_system.cpp index 5cbb5239..84de9134 100644 --- a/src/bolt/editor/theme_system.cpp +++ b/src/bolt/editor/theme_system.cpp @@ -1,9 +1,10 @@ #include "bolt/editor/theme_system.hpp" + +#include #include #include #include -#include namespace bolt { @@ -24,7 +25,7 @@ void ThemeSystem::initializeDefaults() { defaultColorScheme_.number = "#B5CEA8"; defaultColorScheme_.type = "#4EC9B0"; defaultColorScheme_.function = "#DCDCAA"; - + // Initialize default font settings defaultFontSettings_.family = "Consolas, 'Courier New', monospace"; defaultFontSettings_.size = 14; @@ -71,7 +72,7 @@ void ThemeSystem::loadDefaultThemes() { darkTheme.fontSettings.family = "Consolas, 'Courier New', monospace"; darkTheme.fontSettings.size = 14; darkTheme.fontSettings.lineHeight = 1.5; - + // Light theme Theme lightTheme; lightTheme.colors.background = "#FFFFFF"; @@ -90,7 +91,7 @@ void ThemeSystem::loadDefaultThemes() { addTheme("dark", darkTheme); addTheme("light", lightTheme); - setTheme("dark"); // Set default theme + setTheme("dark"); // Set default theme } std::vector ThemeSystem::getAvailableThemes() const { @@ -110,4 +111,4 @@ bool ThemeSystem::hasTheme(const std::string& themeName) const { return themes_.find(themeName) != themes_.end(); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/git/git_integration.cpp b/src/bolt/git/git_integration.cpp index 15a74e4e..2e2fce71 100644 --- a/src/bolt/git/git_integration.cpp +++ b/src/bolt/git/git_integration.cpp @@ -1,4 +1,5 @@ #include "bolt/git/git_integration.hpp" + #include #include #include @@ -15,14 +16,14 @@ bool GitIntegration::initialize(const std::string& projectPath) { if (isActive_) { shutdown(); } - + projectPath_ = projectPath; repository_ = std::make_shared(projectPath); - + if (!repository_->isGitRepository()) { return false; } - + // Set up repository callback repository_->setStatusCallback([this](bool success, const std::string& message) { if (operationCallback_) { @@ -32,28 +33,28 @@ bool GitIntegration::initialize(const std::string& projectPath) { refreshStatus(); } }); - + isActive_ = true; - + // Initial status refresh refreshStatus(); - + return true; } void GitIntegration::shutdown() { isActive_ = false; - + // Stop auto refresh setAutoRefresh(false); - + // Clear caches { std::lock_guard lock(statusMutex_); fileStatusCache_.clear(); allFileStatus_.clear(); } - + repository_.reset(); projectPath_.clear(); } @@ -70,7 +71,7 @@ void GitIntegration::refreshStatus() { if (!isActive_ || !repository_) { return; } - + updateStatusCache(); updateBranchStatusCache(); notifyStatusUpdate(); @@ -80,13 +81,13 @@ std::optional GitIntegration::getFileStatus(const std::string& fi if (!isActive_) { return std::nullopt; } - + std::lock_guard lock(statusMutex_); auto it = fileStatusCache_.find(filePath); if (it != fileStatusCache_.end()) { return it->second; } - + return std::nullopt; } @@ -94,7 +95,7 @@ std::vector GitIntegration::getAllFileStatus() const { if (!isActive_) { return {}; } - + std::lock_guard lock(statusMutex_); return allFileStatus_; } @@ -111,10 +112,10 @@ void GitIntegration::setAutoRefresh(bool enabled, int intervalSeconds) { if (autoRefreshEnabled_ == enabled) { return; } - + autoRefreshEnabled_ = enabled; refreshIntervalSeconds_ = intervalSeconds; - + if (enabled && isActive_) { shouldStopRefresh_ = false; refreshThread_ = std::make_unique(&GitIntegration::refreshLoop, this); @@ -131,7 +132,7 @@ void GitIntegration::notifyFileChanged(const std::string& filePath) { if (!isActive_) { return; } - + // For now, just trigger a refresh // In the future, we could optimize by only checking specific files refreshStatus(); @@ -141,7 +142,7 @@ bool GitIntegration::stageFile(const std::string& filePath) { if (!isActive_ || !repository_) { return false; } - + return repository_->addFile(filePath); } @@ -149,7 +150,7 @@ bool GitIntegration::stageAllFiles() { if (!isActive_ || !repository_) { return false; } - + return repository_->addAll(); } @@ -157,7 +158,7 @@ bool GitIntegration::commitChanges(const std::string& message) { if (!isActive_ || !repository_) { return false; } - + return repository_->commit(message); } @@ -165,7 +166,7 @@ bool GitIntegration::pushChanges() { if (!isActive_ || !repository_) { return false; } - + return repository_->push(); } @@ -173,7 +174,7 @@ bool GitIntegration::pullChanges() { if (!isActive_ || !repository_) { return false; } - + return repository_->pull(); } @@ -181,7 +182,7 @@ GitIntegration::BranchStatus GitIntegration::getBranchStatus() const { if (!isActive_) { return {}; } - + std::lock_guard lock(statusMutex_); return cachedBranchStatus_; } @@ -190,19 +191,19 @@ GitIntegration::RepositoryInfo GitIntegration::getRepositoryInfo() const { if (!isActive_ || !repository_) { return {}; } - + RepositoryInfo info; info.rootPath = repository_->getRepositoryRoot(); - + auto branch = repository_->getCurrentBranch(); info.currentBranch = branch.value_or("(detached)"); - + std::lock_guard lock(statusMutex_); - + info.uncommittedFiles = 0; info.stagedFiles = 0; info.untrackedFiles = 0; - + for (const auto& file : allFileStatus_) { switch (file.status) { case GitFileStatus::MODIFIED: @@ -219,22 +220,21 @@ GitIntegration::RepositoryInfo GitIntegration::getRepositoryInfo() const { break; } } - + info.isClean = (info.uncommittedFiles == 0 && info.stagedFiles == 0 && info.untrackedFiles == 0); - + return info; } void GitIntegration::refreshLoop() { while (!shouldStopRefresh_ && autoRefreshEnabled_) { refreshStatus(); - + // Sleep for the specified interval auto sleepDuration = std::chrono::seconds(refreshIntervalSeconds_); auto start = std::chrono::steady_clock::now(); - - while (!shouldStopRefresh_ && - std::chrono::steady_clock::now() - start < sleepDuration) { + + while (!shouldStopRefresh_ && std::chrono::steady_clock::now() - start < sleepDuration) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } @@ -244,19 +244,19 @@ void GitIntegration::updateStatusCache() { if (!repository_) { return; } - + auto allFiles = repository_->getFileStatus(); - + std::lock_guard lock(statusMutex_); - + // Clear old cache fileStatusCache_.clear(); - + // Update cache with new status for (const auto& fileInfo : allFiles) { fileStatusCache_[fileInfo.filePath] = fileInfo.status; } - + allFileStatus_ = std::move(allFiles); } @@ -264,19 +264,19 @@ void GitIntegration::updateBranchStatusCache() { if (!repository_) { return; } - + BranchStatus status; - + auto branch = repository_->getCurrentBranch(); status.currentBranch = branch.value_or("(detached)"); - + status.hasUncommittedChanges = repository_->hasUncommittedChanges(); - + auto remoteStatus = repository_->getRemoteStatus(); status.commitsAhead = remoteStatus.ahead; status.commitsBehind = remoteStatus.behind; status.hasRemote = remoteStatus.hasRemote; - + std::lock_guard lock(statusMutex_); cachedBranchStatus_ = status; } @@ -288,5 +288,5 @@ void GitIntegration::notifyStatusUpdate() { } } -} // namespace git -} // namespace bolt \ No newline at end of file +} // namespace git +} // namespace bolt diff --git a/src/bolt/gui/dark_theme.cpp b/src/bolt/gui/dark_theme.cpp index c7357d64..d3f2c201 100644 --- a/src/bolt/gui/dark_theme.cpp +++ b/src/bolt/gui/dark_theme.cpp @@ -11,123 +11,123 @@ void ApplyBoltDarkTheme() { #ifdef BOLT_HAVE_IMGUI ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // Bolt.diy inspired dark theme colors // Background colors (dark slate/charcoal) - colors[ImGuiCol_WindowBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); // #1a1a1f - colors[ImGuiCol_ChildBg] = ImVec4(0.12f, 0.12f, 0.14f, 1.00f); // #1e1e23 - colors[ImGuiCol_PopupBg] = ImVec4(0.10f, 0.10f, 0.12f, 0.98f); - colors[ImGuiCol_Border] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); // #33333d - colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_FrameBg] = ImVec4(0.15f, 0.15f, 0.18f, 1.00f); // #26262e - colors[ImGuiCol_FrameBgHovered] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); - colors[ImGuiCol_FrameBgActive] = ImVec4(0.25f, 0.25f, 0.30f, 1.00f); - + colors[ImGuiCol_WindowBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); // #1a1a1f + colors[ImGuiCol_ChildBg] = ImVec4(0.12f, 0.12f, 0.14f, 1.00f); // #1e1e23 + colors[ImGuiCol_PopupBg] = ImVec4(0.10f, 0.10f, 0.12f, 0.98f); + colors[ImGuiCol_Border] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); // #33333d + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.15f, 0.15f, 0.18f, 1.00f); // #26262e + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.25f, 0.25f, 0.30f, 1.00f); + // Title bar (darker) - colors[ImGuiCol_TitleBg] = ImVec4(0.08f, 0.08f, 0.10f, 1.00f); // #141418 - colors[ImGuiCol_TitleBgActive] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.08f, 0.08f, 0.10f, 0.75f); - + colors[ImGuiCol_TitleBg] = ImVec4(0.08f, 0.08f, 0.10f, 1.00f); // #141418 + colors[ImGuiCol_TitleBgActive] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.08f, 0.08f, 0.10f, 0.75f); + // Menu bar - colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - + colors[ImGuiCol_MenuBarBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); + // Scrollbar - colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.30f, 0.30f, 0.35f, 1.00f); - colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.45f, 1.00f); - colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.50f, 0.50f, 0.55f, 1.00f); - + colors[ImGuiCol_ScrollbarBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.30f, 0.30f, 0.35f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.45f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.50f, 0.50f, 0.55f, 1.00f); + // Checkboxes and radio buttons - colors[ImGuiCol_CheckMark] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); // Blue accent - + colors[ImGuiCol_CheckMark] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); // Blue accent + // Sliders - colors[ImGuiCol_SliderGrab] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); - colors[ImGuiCol_SliderGrabActive] = ImVec4(0.50f, 0.80f, 1.00f, 1.00f); - + colors[ImGuiCol_SliderGrab] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); + colors[ImGuiCol_SliderGrabActive] = ImVec4(0.50f, 0.80f, 1.00f, 1.00f); + // Buttons (primary action color - blue) - colors[ImGuiCol_Button] = ImVec4(0.25f, 0.50f, 0.90f, 1.00f); // #4080e6 - colors[ImGuiCol_ButtonHovered] = ImVec4(0.35f, 0.60f, 1.00f, 1.00f); // #5999ff - colors[ImGuiCol_ButtonActive] = ImVec4(0.20f, 0.45f, 0.85f, 1.00f); // #3373d9 - + colors[ImGuiCol_Button] = ImVec4(0.25f, 0.50f, 0.90f, 1.00f); // #4080e6 + colors[ImGuiCol_ButtonHovered] = ImVec4(0.35f, 0.60f, 1.00f, 1.00f); // #5999ff + colors[ImGuiCol_ButtonActive] = ImVec4(0.20f, 0.45f, 0.85f, 1.00f); // #3373d9 + // Headers (for tree nodes, collapsing headers, etc.) - colors[ImGuiCol_Header] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); - colors[ImGuiCol_HeaderHovered] = ImVec4(0.25f, 0.25f, 0.30f, 1.00f); - colors[ImGuiCol_HeaderActive] = ImVec4(0.30f, 0.30f, 0.36f, 1.00f); - + colors[ImGuiCol_Header] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.25f, 0.25f, 0.30f, 1.00f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.30f, 0.30f, 0.36f, 1.00f); + // Separator - colors[ImGuiCol_Separator] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); - colors[ImGuiCol_SeparatorHovered] = ImVec4(0.30f, 0.30f, 0.36f, 1.00f); - colors[ImGuiCol_SeparatorActive] = ImVec4(0.40f, 0.40f, 0.48f, 1.00f); - + colors[ImGuiCol_Separator] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); + colors[ImGuiCol_SeparatorHovered] = ImVec4(0.30f, 0.30f, 0.36f, 1.00f); + colors[ImGuiCol_SeparatorActive] = ImVec4(0.40f, 0.40f, 0.48f, 1.00f); + // Resize grip - colors[ImGuiCol_ResizeGrip] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); - colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.30f, 0.30f, 0.36f, 1.00f); - colors[ImGuiCol_ResizeGripActive] = ImVec4(0.40f, 0.40f, 0.48f, 1.00f); - + colors[ImGuiCol_ResizeGrip] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.30f, 0.30f, 0.36f, 1.00f); + colors[ImGuiCol_ResizeGripActive] = ImVec4(0.40f, 0.40f, 0.48f, 1.00f); + // Tabs - colors[ImGuiCol_Tab] = ImVec4(0.15f, 0.15f, 0.18f, 1.00f); - colors[ImGuiCol_TabHovered] = ImVec4(0.25f, 0.50f, 0.90f, 0.80f); - colors[ImGuiCol_TabActive] = ImVec4(0.20f, 0.40f, 0.80f, 1.00f); - colors[ImGuiCol_TabUnfocused] = ImVec4(0.12f, 0.12f, 0.14f, 1.00f); - colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.15f, 0.30f, 0.60f, 1.00f); - - // Docking (only if docking is enabled) - #ifdef IMGUI_HAS_DOCK - colors[ImGuiCol_DockingPreview] = ImVec4(0.25f, 0.50f, 0.90f, 0.70f); - colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - #endif - + colors[ImGuiCol_Tab] = ImVec4(0.15f, 0.15f, 0.18f, 1.00f); + colors[ImGuiCol_TabHovered] = ImVec4(0.25f, 0.50f, 0.90f, 0.80f); + colors[ImGuiCol_TabActive] = ImVec4(0.20f, 0.40f, 0.80f, 1.00f); + colors[ImGuiCol_TabUnfocused] = ImVec4(0.12f, 0.12f, 0.14f, 1.00f); + colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.15f, 0.30f, 0.60f, 1.00f); + +// Docking (only if docking is enabled) +#ifdef IMGUI_HAS_DOCK + colors[ImGuiCol_DockingPreview] = ImVec4(0.25f, 0.50f, 0.90f, 0.70f); + colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); +#endif + // Plot colors - colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); - colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.50f, 0.80f, 1.00f, 1.00f); - colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); - colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.50f, 0.80f, 1.00f, 1.00f); - + colors[ImGuiCol_PlotLines] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); + colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.50f, 0.80f, 1.00f, 1.00f); + colors[ImGuiCol_PlotHistogram] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); + colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.50f, 0.80f, 1.00f, 1.00f); + // Table colors - colors[ImGuiCol_TableHeaderBg] = ImVec4(0.15f, 0.15f, 0.18f, 1.00f); - colors[ImGuiCol_TableBorderStrong] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); - colors[ImGuiCol_TableBorderLight] = ImVec4(0.18f, 0.18f, 0.22f, 1.00f); - colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.03f); - + colors[ImGuiCol_TableHeaderBg] = ImVec4(0.15f, 0.15f, 0.18f, 1.00f); + colors[ImGuiCol_TableBorderStrong] = ImVec4(0.20f, 0.20f, 0.24f, 1.00f); + colors[ImGuiCol_TableBorderLight] = ImVec4(0.18f, 0.18f, 0.22f, 1.00f); + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.03f); + // Text colors - colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.92f, 1.00f); // Light gray - colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.52f, 1.00f); - colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 0.50f, 0.90f, 0.35f); - + colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.92f, 1.00f); // Light gray + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.52f, 1.00f); + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.25f, 0.50f, 0.90f, 0.35f); + // Drag and drop - colors[ImGuiCol_DragDropTarget] = ImVec4(0.40f, 0.70f, 1.00f, 0.90f); - + colors[ImGuiCol_DragDropTarget] = ImVec4(0.40f, 0.70f, 1.00f, 0.90f); + // Navigation - colors[ImGuiCol_NavHighlight] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); - colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); - colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); - + colors[ImGuiCol_NavHighlight] = ImVec4(0.40f, 0.70f, 1.00f, 1.00f); + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + // Modal window dimming - colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); - + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); + // Style adjustments for modern look - style.WindowRounding = 8.0f; - style.ChildRounding = 6.0f; - style.FrameRounding = 6.0f; - style.PopupRounding = 6.0f; + style.WindowRounding = 8.0f; + style.ChildRounding = 6.0f; + style.FrameRounding = 6.0f; + style.PopupRounding = 6.0f; style.ScrollbarRounding = 8.0f; - style.GrabRounding = 6.0f; - style.TabRounding = 6.0f; - - style.WindowBorderSize = 1.0f; - style.ChildBorderSize = 1.0f; - style.PopupBorderSize = 1.0f; - style.FrameBorderSize = 0.0f; - style.TabBorderSize = 0.0f; - - style.WindowPadding = ImVec2(12.0f, 12.0f); - style.FramePadding = ImVec2(8.0f, 6.0f); - style.ItemSpacing = ImVec2(8.0f, 6.0f); - style.ItemInnerSpacing = ImVec2(6.0f, 4.0f); - style.IndentSpacing = 20.0f; - style.ScrollbarSize = 14.0f; - style.GrabMinSize = 10.0f; + style.GrabRounding = 6.0f; + style.TabRounding = 6.0f; + + style.WindowBorderSize = 1.0f; + style.ChildBorderSize = 1.0f; + style.PopupBorderSize = 1.0f; + style.FrameBorderSize = 0.0f; + style.TabBorderSize = 0.0f; + + style.WindowPadding = ImVec2(12.0f, 12.0f); + style.FramePadding = ImVec2(8.0f, 6.0f); + style.ItemSpacing = ImVec2(8.0f, 6.0f); + style.ItemInnerSpacing = ImVec2(6.0f, 4.0f); + style.IndentSpacing = 20.0f; + style.ScrollbarSize = 14.0f; + style.GrabMinSize = 10.0f; #endif } @@ -135,40 +135,40 @@ void ApplyBoltLightTheme() { #ifdef BOLT_HAVE_IMGUI ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // Light theme colors (for optional light mode) - colors[ImGuiCol_WindowBg] = ImVec4(0.95f, 0.95f, 0.97f, 1.00f); - colors[ImGuiCol_ChildBg] = ImVec4(0.98f, 0.98f, 0.99f, 1.00f); - colors[ImGuiCol_PopupBg] = ImVec4(0.95f, 0.95f, 0.97f, 0.98f); - colors[ImGuiCol_Border] = ImVec4(0.80f, 0.80f, 0.82f, 1.00f); - colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_FrameBg] = ImVec4(0.90f, 0.90f, 0.92f, 1.00f); - colors[ImGuiCol_FrameBgHovered] = ImVec4(0.85f, 0.85f, 0.87f, 1.00f); - colors[ImGuiCol_FrameBgActive] = ImVec4(0.80f, 0.80f, 0.82f, 1.00f); - - colors[ImGuiCol_TitleBg] = ImVec4(0.92f, 0.92f, 0.94f, 1.00f); - colors[ImGuiCol_TitleBgActive] = ImVec4(0.88f, 0.88f, 0.90f, 1.00f); - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.92f, 0.92f, 0.94f, 0.75f); - - colors[ImGuiCol_MenuBarBg] = ImVec4(0.92f, 0.92f, 0.94f, 1.00f); - - colors[ImGuiCol_Button] = ImVec4(0.25f, 0.50f, 0.90f, 1.00f); - colors[ImGuiCol_ButtonHovered] = ImVec4(0.35f, 0.60f, 1.00f, 1.00f); - colors[ImGuiCol_ButtonActive] = ImVec4(0.20f, 0.45f, 0.85f, 1.00f); - - colors[ImGuiCol_Text] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); - colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.52f, 1.00f); - + colors[ImGuiCol_WindowBg] = ImVec4(0.95f, 0.95f, 0.97f, 1.00f); + colors[ImGuiCol_ChildBg] = ImVec4(0.98f, 0.98f, 0.99f, 1.00f); + colors[ImGuiCol_PopupBg] = ImVec4(0.95f, 0.95f, 0.97f, 0.98f); + colors[ImGuiCol_Border] = ImVec4(0.80f, 0.80f, 0.82f, 1.00f); + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_FrameBg] = ImVec4(0.90f, 0.90f, 0.92f, 1.00f); + colors[ImGuiCol_FrameBgHovered] = ImVec4(0.85f, 0.85f, 0.87f, 1.00f); + colors[ImGuiCol_FrameBgActive] = ImVec4(0.80f, 0.80f, 0.82f, 1.00f); + + colors[ImGuiCol_TitleBg] = ImVec4(0.92f, 0.92f, 0.94f, 1.00f); + colors[ImGuiCol_TitleBgActive] = ImVec4(0.88f, 0.88f, 0.90f, 1.00f); + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.92f, 0.92f, 0.94f, 0.75f); + + colors[ImGuiCol_MenuBarBg] = ImVec4(0.92f, 0.92f, 0.94f, 1.00f); + + colors[ImGuiCol_Button] = ImVec4(0.25f, 0.50f, 0.90f, 1.00f); + colors[ImGuiCol_ButtonHovered] = ImVec4(0.35f, 0.60f, 1.00f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.20f, 0.45f, 0.85f, 1.00f); + + colors[ImGuiCol_Text] = ImVec4(0.10f, 0.10f, 0.12f, 1.00f); + colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.52f, 1.00f); + // Apply same style settings as dark theme - style.WindowRounding = 8.0f; - style.ChildRounding = 6.0f; - style.FrameRounding = 6.0f; - style.PopupRounding = 6.0f; + style.WindowRounding = 8.0f; + style.ChildRounding = 6.0f; + style.FrameRounding = 6.0f; + style.PopupRounding = 6.0f; style.ScrollbarRounding = 8.0f; - style.GrabRounding = 6.0f; - style.TabRounding = 6.0f; + style.GrabRounding = 6.0f; + style.TabRounding = 6.0f; #endif } -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt diff --git a/src/bolt/gui/enhanced_dark_theme.cpp b/src/bolt/gui/enhanced_dark_theme.cpp index 2adf98e1..577a910e 100644 --- a/src/bolt/gui/enhanced_dark_theme.cpp +++ b/src/bolt/gui/enhanced_dark_theme.cpp @@ -12,182 +12,182 @@ void ApplyEnhancedBoltDarkTheme() { #ifdef BOLT_HAVE_IMGUI ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // ============================================================================ // COLOR PALETTE - Bolt.diy/Bolt.new Inspired // ============================================================================ - + // Primary dark backgrounds (deep blue-gray charcoal) - const ImVec4 bg_primary = ImVec4(0.10f, 0.11f, 0.14f, 1.00f); // #1a1c23 - const ImVec4 bg_secondary = ImVec4(0.12f, 0.13f, 0.16f, 1.00f); // #1e2129 - const ImVec4 bg_tertiary = ImVec4(0.14f, 0.15f, 0.18f, 1.00f); // #24262e - const ImVec4 bg_elevated = ImVec4(0.16f, 0.17f, 0.20f, 1.00f); // #292b33 - + const ImVec4 bg_primary = ImVec4(0.10f, 0.11f, 0.14f, 1.00f); // #1a1c23 + const ImVec4 bg_secondary = ImVec4(0.12f, 0.13f, 0.16f, 1.00f); // #1e2129 + const ImVec4 bg_tertiary = ImVec4(0.14f, 0.15f, 0.18f, 1.00f); // #24262e + const ImVec4 bg_elevated = ImVec4(0.16f, 0.17f, 0.20f, 1.00f); // #292b33 + // Accent colors (bright blue - bolt.new signature color) - const ImVec4 accent_blue = ImVec4(0.29f, 0.62f, 1.00f, 1.00f); // #4a9eff - const ImVec4 accent_blue_hover= ImVec4(0.35f, 0.68f, 1.00f, 1.00f); // #59adff - const ImVec4 accent_blue_active=ImVec4(0.24f, 0.56f, 0.95f, 1.00f); // #3d8ff2 - const ImVec4 accent_blue_dim = ImVec4(0.29f, 0.62f, 1.00f, 0.30f); // Semi-transparent - + const ImVec4 accent_blue = ImVec4(0.29f, 0.62f, 1.00f, 1.00f); // #4a9eff + const ImVec4 accent_blue_hover = ImVec4(0.35f, 0.68f, 1.00f, 1.00f); // #59adff + const ImVec4 accent_blue_active = ImVec4(0.24f, 0.56f, 0.95f, 1.00f); // #3d8ff2 + const ImVec4 accent_blue_dim = ImVec4(0.29f, 0.62f, 1.00f, 0.30f); // Semi-transparent + // Text colors - const ImVec4 text_primary = ImVec4(0.92f, 0.93f, 0.95f, 1.00f); // #ebecf2 - const ImVec4 text_secondary = ImVec4(0.70f, 0.72f, 0.76f, 1.00f); // #b3b8c2 - const ImVec4 text_disabled = ImVec4(0.50f, 0.52f, 0.56f, 1.00f); // #80858f - + const ImVec4 text_primary = ImVec4(0.92f, 0.93f, 0.95f, 1.00f); // #ebecf2 + const ImVec4 text_secondary = ImVec4(0.70f, 0.72f, 0.76f, 1.00f); // #b3b8c2 + const ImVec4 text_disabled = ImVec4(0.50f, 0.52f, 0.56f, 1.00f); // #80858f + // Border and separator colors - const ImVec4 border_default = ImVec4(0.22f, 0.24f, 0.28f, 1.00f); // #383d47 - const ImVec4 border_subtle = ImVec4(0.18f, 0.20f, 0.24f, 1.00f); // #2e333d - + const ImVec4 border_default = ImVec4(0.22f, 0.24f, 0.28f, 1.00f); // #383d47 + const ImVec4 border_subtle = ImVec4(0.18f, 0.20f, 0.24f, 1.00f); // #2e333d + // Success, warning, error colors - const ImVec4 success_green = ImVec4(0.26f, 0.78f, 0.50f, 1.00f); // #43c780 - const ImVec4 warning_yellow = ImVec4(0.95f, 0.77f, 0.26f, 1.00f); // #f2c443 - const ImVec4 error_red = ImVec4(0.95f, 0.38f, 0.38f, 1.00f); // #f26161 - + const ImVec4 success_green = ImVec4(0.26f, 0.78f, 0.50f, 1.00f); // #43c780 + const ImVec4 warning_yellow = ImVec4(0.95f, 0.77f, 0.26f, 1.00f); // #f2c443 + const ImVec4 error_red = ImVec4(0.95f, 0.38f, 0.38f, 1.00f); // #f26161 + // ============================================================================ // APPLY COLORS TO IMGUI ELEMENTS // ============================================================================ - + // Window backgrounds - colors[ImGuiCol_WindowBg] = bg_primary; - colors[ImGuiCol_ChildBg] = bg_secondary; - colors[ImGuiCol_PopupBg] = bg_elevated; - + colors[ImGuiCol_WindowBg] = bg_primary; + colors[ImGuiCol_ChildBg] = bg_secondary; + colors[ImGuiCol_PopupBg] = bg_elevated; + // Borders - colors[ImGuiCol_Border] = border_default; - colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - + colors[ImGuiCol_Border] = border_default; + colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + // Frame backgrounds (input fields, etc.) - colors[ImGuiCol_FrameBg] = bg_tertiary; - colors[ImGuiCol_FrameBgHovered] = bg_elevated; - colors[ImGuiCol_FrameBgActive] = ImVec4(0.18f, 0.19f, 0.22f, 1.00f); - + colors[ImGuiCol_FrameBg] = bg_tertiary; + colors[ImGuiCol_FrameBgHovered] = bg_elevated; + colors[ImGuiCol_FrameBgActive] = ImVec4(0.18f, 0.19f, 0.22f, 1.00f); + // Title bar - colors[ImGuiCol_TitleBg] = bg_primary; - colors[ImGuiCol_TitleBgActive] = bg_secondary; - colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.08f, 0.09f, 0.12f, 0.75f); - + colors[ImGuiCol_TitleBg] = bg_primary; + colors[ImGuiCol_TitleBgActive] = bg_secondary; + colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.08f, 0.09f, 0.12f, 0.75f); + // Menu bar - colors[ImGuiCol_MenuBarBg] = bg_primary; - + colors[ImGuiCol_MenuBarBg] = bg_primary; + // Scrollbar - colors[ImGuiCol_ScrollbarBg] = bg_primary; - colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.30f, 0.32f, 0.36f, 1.00f); - colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.38f, 0.40f, 0.44f, 1.00f); - colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.46f, 0.48f, 0.52f, 1.00f); - + colors[ImGuiCol_ScrollbarBg] = bg_primary; + colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.30f, 0.32f, 0.36f, 1.00f); + colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.38f, 0.40f, 0.44f, 1.00f); + colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.46f, 0.48f, 0.52f, 1.00f); + // Checkboxes and radio buttons - colors[ImGuiCol_CheckMark] = accent_blue; - + colors[ImGuiCol_CheckMark] = accent_blue; + // Sliders - colors[ImGuiCol_SliderGrab] = accent_blue; - colors[ImGuiCol_SliderGrabActive] = accent_blue_hover; - + colors[ImGuiCol_SliderGrab] = accent_blue; + colors[ImGuiCol_SliderGrabActive] = accent_blue_hover; + // Buttons - PRIMARY ACTION (bolt.new style) - colors[ImGuiCol_Button] = accent_blue; - colors[ImGuiCol_ButtonHovered] = accent_blue_hover; - colors[ImGuiCol_ButtonActive] = accent_blue_active; - + colors[ImGuiCol_Button] = accent_blue; + colors[ImGuiCol_ButtonHovered] = accent_blue_hover; + colors[ImGuiCol_ButtonActive] = accent_blue_active; + // Headers (for tree nodes, collapsing headers, etc.) - colors[ImGuiCol_Header] = accent_blue_dim; - colors[ImGuiCol_HeaderHovered] = ImVec4(0.29f, 0.62f, 1.00f, 0.50f); - colors[ImGuiCol_HeaderActive] = ImVec4(0.29f, 0.62f, 1.00f, 0.70f); - + colors[ImGuiCol_Header] = accent_blue_dim; + colors[ImGuiCol_HeaderHovered] = ImVec4(0.29f, 0.62f, 1.00f, 0.50f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.29f, 0.62f, 1.00f, 0.70f); + // Separator - colors[ImGuiCol_Separator] = border_subtle; - colors[ImGuiCol_SeparatorHovered] = accent_blue_dim; - colors[ImGuiCol_SeparatorActive] = accent_blue; - + colors[ImGuiCol_Separator] = border_subtle; + colors[ImGuiCol_SeparatorHovered] = accent_blue_dim; + colors[ImGuiCol_SeparatorActive] = accent_blue; + // Resize grip - colors[ImGuiCol_ResizeGrip] = accent_blue_dim; - colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.29f, 0.62f, 1.00f, 0.50f); - colors[ImGuiCol_ResizeGripActive] = accent_blue; - + colors[ImGuiCol_ResizeGrip] = accent_blue_dim; + colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.29f, 0.62f, 1.00f, 0.50f); + colors[ImGuiCol_ResizeGripActive] = accent_blue; + // Tabs - colors[ImGuiCol_Tab] = bg_secondary; - colors[ImGuiCol_TabHovered] = accent_blue_dim; - colors[ImGuiCol_TabActive] = accent_blue; - colors[ImGuiCol_TabUnfocused] = bg_primary; - colors[ImGuiCol_TabUnfocusedActive] = bg_tertiary; - - // Docking - #ifdef IMGUI_HAS_DOCK - colors[ImGuiCol_DockingPreview] = ImVec4(0.29f, 0.62f, 1.00f, 0.60f); - colors[ImGuiCol_DockingEmptyBg] = bg_primary; - #endif - + colors[ImGuiCol_Tab] = bg_secondary; + colors[ImGuiCol_TabHovered] = accent_blue_dim; + colors[ImGuiCol_TabActive] = accent_blue; + colors[ImGuiCol_TabUnfocused] = bg_primary; + colors[ImGuiCol_TabUnfocusedActive] = bg_tertiary; + +// Docking +#ifdef IMGUI_HAS_DOCK + colors[ImGuiCol_DockingPreview] = ImVec4(0.29f, 0.62f, 1.00f, 0.60f); + colors[ImGuiCol_DockingEmptyBg] = bg_primary; +#endif + // Plot colors - colors[ImGuiCol_PlotLines] = accent_blue; - colors[ImGuiCol_PlotLinesHovered] = accent_blue_hover; - colors[ImGuiCol_PlotHistogram] = accent_blue; - colors[ImGuiCol_PlotHistogramHovered] = accent_blue_hover; - + colors[ImGuiCol_PlotLines] = accent_blue; + colors[ImGuiCol_PlotLinesHovered] = accent_blue_hover; + colors[ImGuiCol_PlotHistogram] = accent_blue; + colors[ImGuiCol_PlotHistogramHovered] = accent_blue_hover; + // Table colors - colors[ImGuiCol_TableHeaderBg] = bg_tertiary; - colors[ImGuiCol_TableBorderStrong] = border_default; - colors[ImGuiCol_TableBorderLight] = border_subtle; - colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.03f); - + colors[ImGuiCol_TableHeaderBg] = bg_tertiary; + colors[ImGuiCol_TableBorderStrong] = border_default; + colors[ImGuiCol_TableBorderLight] = border_subtle; + colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); + colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.03f); + // Text colors - colors[ImGuiCol_Text] = text_primary; - colors[ImGuiCol_TextDisabled] = text_disabled; - colors[ImGuiCol_TextSelectedBg] = ImVec4(0.29f, 0.62f, 1.00f, 0.35f); - + colors[ImGuiCol_Text] = text_primary; + colors[ImGuiCol_TextDisabled] = text_disabled; + colors[ImGuiCol_TextSelectedBg] = ImVec4(0.29f, 0.62f, 1.00f, 0.35f); + // Drag and drop - colors[ImGuiCol_DragDropTarget] = accent_blue; - + colors[ImGuiCol_DragDropTarget] = accent_blue; + // Navigation - colors[ImGuiCol_NavHighlight] = accent_blue; - colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); - colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); - + colors[ImGuiCol_NavHighlight] = accent_blue; + colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); + colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); + // Modal window dimming - colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.65f); - + colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.65f); + // ============================================================================ // STYLE SETTINGS - Modern, Professional Look // ============================================================================ - + // Rounding (generous, modern look like bolt.new) - style.WindowRounding = 12.0f; - style.ChildRounding = 10.0f; - style.FrameRounding = 8.0f; - style.PopupRounding = 10.0f; + style.WindowRounding = 12.0f; + style.ChildRounding = 10.0f; + style.FrameRounding = 8.0f; + style.PopupRounding = 10.0f; style.ScrollbarRounding = 12.0f; - style.GrabRounding = 8.0f; - style.TabRounding = 8.0f; - + style.GrabRounding = 8.0f; + style.TabRounding = 8.0f; + // Border sizes - style.WindowBorderSize = 1.0f; - style.ChildBorderSize = 1.0f; - style.PopupBorderSize = 1.0f; - style.FrameBorderSize = 0.0f; - style.TabBorderSize = 0.0f; - + style.WindowBorderSize = 1.0f; + style.ChildBorderSize = 1.0f; + style.PopupBorderSize = 1.0f; + style.FrameBorderSize = 0.0f; + style.TabBorderSize = 0.0f; + // Padding and spacing (generous, comfortable) - style.WindowPadding = ImVec2(16.0f, 16.0f); - style.FramePadding = ImVec2(12.0f, 8.0f); - style.ItemSpacing = ImVec2(12.0f, 8.0f); - style.ItemInnerSpacing = ImVec2(8.0f, 6.0f); - style.IndentSpacing = 24.0f; - style.ScrollbarSize = 16.0f; - style.GrabMinSize = 12.0f; - + style.WindowPadding = ImVec2(16.0f, 16.0f); + style.FramePadding = ImVec2(12.0f, 8.0f); + style.ItemSpacing = ImVec2(12.0f, 8.0f); + style.ItemInnerSpacing = ImVec2(8.0f, 6.0f); + style.IndentSpacing = 24.0f; + style.ScrollbarSize = 16.0f; + style.GrabMinSize = 12.0f; + // Window title alignment - style.WindowTitleAlign = ImVec2(0.5f, 0.5f); // Center title - + style.WindowTitleAlign = ImVec2(0.5f, 0.5f); // Center title + // Button text alignment - style.ButtonTextAlign = ImVec2(0.5f, 0.5f); // Center button text - + style.ButtonTextAlign = ImVec2(0.5f, 0.5f); // Center button text + // Additional modern touches style.WindowMenuButtonPosition = ImGuiDir_None; // No collapse button style.ColorButtonPosition = ImGuiDir_Right; - + // Anti-aliasing style.AntiAliasedLines = true; style.AntiAliasedLinesUseTex = true; style.AntiAliasedFill = true; - + #endif } @@ -197,17 +197,17 @@ void ApplyBoltCodeEditorTheme() { #ifdef BOLT_HAVE_IMGUI // Start with enhanced dark theme ApplyEnhancedBoltDarkTheme(); - + ImGuiStyle& style = ImGui::GetStyle(); - + // Adjust for code editor - tighter spacing, monospace-friendly - style.ItemSpacing = ImVec2(8.0f, 4.0f); - style.FramePadding = ImVec2(8.0f, 4.0f); - style.WindowPadding = ImVec2(8.0f, 8.0f); - + style.ItemSpacing = ImVec2(8.0f, 4.0f); + style.FramePadding = ImVec2(8.0f, 4.0f); + style.WindowPadding = ImVec2(8.0f, 8.0f); + // Less rounding for code editor (more traditional IDE feel) - style.FrameRounding = 4.0f; - style.WindowRounding = 6.0f; + style.FrameRounding = 4.0f; + style.WindowRounding = 6.0f; #endif } @@ -215,32 +215,32 @@ void ApplyBoltHighContrastTheme() { #ifdef BOLT_HAVE_IMGUI ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // High contrast theme for accessibility - const ImVec4 bg_black = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); - const ImVec4 bg_dark_gray = ImVec4(0.10f, 0.10f, 0.10f, 1.00f); - const ImVec4 text_white = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); - const ImVec4 accent_cyan = ImVec4(0.00f, 1.00f, 1.00f, 1.00f); - const ImVec4 border_white = ImVec4(0.80f, 0.80f, 0.80f, 1.00f); - - colors[ImGuiCol_WindowBg] = bg_black; - colors[ImGuiCol_ChildBg] = bg_dark_gray; - colors[ImGuiCol_PopupBg] = bg_black; - colors[ImGuiCol_Border] = border_white; - colors[ImGuiCol_FrameBg] = bg_dark_gray; - colors[ImGuiCol_Button] = accent_cyan; - colors[ImGuiCol_ButtonHovered] = ImVec4(0.20f, 1.00f, 1.00f, 1.00f); - colors[ImGuiCol_ButtonActive] = ImVec4(0.00f, 0.80f, 0.80f, 1.00f); - colors[ImGuiCol_Text] = text_white; - colors[ImGuiCol_Header] = ImVec4(0.00f, 1.00f, 1.00f, 0.40f); - colors[ImGuiCol_HeaderHovered] = ImVec4(0.00f, 1.00f, 1.00f, 0.60f); - colors[ImGuiCol_HeaderActive] = ImVec4(0.00f, 1.00f, 1.00f, 0.80f); - + const ImVec4 bg_black = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + const ImVec4 bg_dark_gray = ImVec4(0.10f, 0.10f, 0.10f, 1.00f); + const ImVec4 text_white = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); + const ImVec4 accent_cyan = ImVec4(0.00f, 1.00f, 1.00f, 1.00f); + const ImVec4 border_white = ImVec4(0.80f, 0.80f, 0.80f, 1.00f); + + colors[ImGuiCol_WindowBg] = bg_black; + colors[ImGuiCol_ChildBg] = bg_dark_gray; + colors[ImGuiCol_PopupBg] = bg_black; + colors[ImGuiCol_Border] = border_white; + colors[ImGuiCol_FrameBg] = bg_dark_gray; + colors[ImGuiCol_Button] = accent_cyan; + colors[ImGuiCol_ButtonHovered] = ImVec4(0.20f, 1.00f, 1.00f, 1.00f); + colors[ImGuiCol_ButtonActive] = ImVec4(0.00f, 0.80f, 0.80f, 1.00f); + colors[ImGuiCol_Text] = text_white; + colors[ImGuiCol_Header] = ImVec4(0.00f, 1.00f, 1.00f, 0.40f); + colors[ImGuiCol_HeaderHovered] = ImVec4(0.00f, 1.00f, 1.00f, 0.60f); + colors[ImGuiCol_HeaderActive] = ImVec4(0.00f, 1.00f, 1.00f, 0.80f); + // Apply same style settings as enhanced theme - style.WindowRounding = 12.0f; - style.FrameRounding = 8.0f; - style.WindowBorderSize = 2.0f; // Thicker borders for high contrast - style.FrameBorderSize = 1.0f; + style.WindowRounding = 12.0f; + style.FrameRounding = 8.0f; + style.WindowBorderSize = 2.0f; // Thicker borders for high contrast + style.FrameBorderSize = 1.0f; #endif } @@ -248,22 +248,22 @@ void ApplyBoltHighContrastTheme() { void ApplyBoltCodeEditorEnhancements() { #ifdef BOLT_HAVE_IMGUI ImGuiStyle& style = ImGui::GetStyle(); - + // Tighter spacing for code editor style.ItemSpacing = ImVec2(4.0f, 4.0f); style.ItemInnerSpacing = ImVec2(4.0f, 4.0f); style.FramePadding = ImVec2(8.0f, 4.0f); - + // Monospace-friendly settings style.IndentSpacing = 20.0f; // Matches typical code indentation - + // Reduce rounding for code editor (more rectangular, professional) style.FrameRounding = 4.0f; style.ChildRounding = 6.0f; - + // Syntax highlighting colors (can be used with ImGui::PushStyleColor) // These match popular dark themes like VS Code Dark+ - + // Note: These would be applied contextually in the editor code: // - Keywords: ImVec4(0.86f, 0.56f, 0.77f, 1.00f) // #db8fc4 (purple) // - Strings: ImVec4(0.81f, 0.65f, 0.49f, 1.00f) // #cea67d (orange) @@ -278,24 +278,24 @@ void ApplyBoltCodeEditorEnhancements() { void ApplyBoltTerminalTheme() { #ifdef BOLT_HAVE_IMGUI ApplyEnhancedBoltDarkTheme(); - + ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // Even darker background for terminal const ImVec4 terminal_bg = ImVec4(0.06f, 0.07f, 0.09f, 1.00f); // #0f1117 colors[ImGuiCol_WindowBg] = terminal_bg; colors[ImGuiCol_ChildBg] = terminal_bg; - + // Terminal green accent const ImVec4 terminal_green = ImVec4(0.26f, 0.78f, 0.50f, 1.00f); colors[ImGuiCol_Text] = terminal_green; - + // Minimal padding for terminal style.WindowPadding = ImVec2(8.0f, 8.0f); style.FramePadding = ImVec2(8.0f, 4.0f); style.ItemSpacing = ImVec2(4.0f, 2.0f); - + // No rounding for terminal (classic look) style.WindowRounding = 0.0f; style.ChildRounding = 0.0f; @@ -308,23 +308,23 @@ void ApplyBoltTerminalTheme() { void ApplyBoltDebuggerTheme() { #ifdef BOLT_HAVE_IMGUI ApplyEnhancedBoltDarkTheme(); - + ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // Debugger-specific accent colors const ImVec4 debug_orange = ImVec4(0.95f, 0.61f, 0.26f, 1.00f); // #f29c43 (breakpoint) const ImVec4 debug_red = ImVec4(0.95f, 0.38f, 0.38f, 1.00f); // #f26161 (error) const ImVec4 debug_yellow = ImVec4(0.95f, 0.77f, 0.26f, 1.00f); // #f2c443 (current line) - + // Use orange for active elements in debugger colors[ImGuiCol_Button] = debug_orange; colors[ImGuiCol_ButtonHovered] = ImVec4(1.00f, 0.67f, 0.32f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.90f, 0.55f, 0.20f, 1.00f); - + // Highlight breakpoints in red colors[ImGuiCol_CheckMark] = debug_red; - + // Current line in yellow colors[ImGuiCol_HeaderActive] = ImVec4(0.95f, 0.77f, 0.26f, 0.70f); #endif @@ -334,21 +334,21 @@ void ApplyBoltDebuggerTheme() { void ApplyBoltFileTreeTheme() { #ifdef BOLT_HAVE_IMGUI ApplyEnhancedBoltDarkTheme(); - + ImGuiStyle& style = ImGui::GetStyle(); ImVec4* colors = style.Colors; - + // Compact spacing for file tree style.ItemSpacing = ImVec2(4.0f, 2.0f); style.ItemInnerSpacing = ImVec2(4.0f, 2.0f); style.FramePadding = ImVec2(4.0f, 2.0f); style.IndentSpacing = 16.0f; - + // Subtle selection highlight colors[ImGuiCol_Header] = ImVec4(0.29f, 0.62f, 1.00f, 0.20f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.29f, 0.62f, 1.00f, 0.35f); colors[ImGuiCol_HeaderActive] = ImVec4(0.29f, 0.62f, 1.00f, 0.50f); - + // Minimal rounding for tree nodes style.FrameRounding = 4.0f; #endif @@ -358,19 +358,19 @@ void ApplyBoltFileTreeTheme() { void ApplyBoltSettingsTheme() { #ifdef BOLT_HAVE_IMGUI ApplyEnhancedBoltDarkTheme(); - + ImGuiStyle& style = ImGui::GetStyle(); - + // Extra padding for settings (more comfortable) style.WindowPadding = ImVec2(20.0f, 20.0f); style.FramePadding = ImVec2(16.0f, 10.0f); style.ItemSpacing = ImVec2(16.0f, 12.0f); - + // Larger controls for settings style.GrabMinSize = 16.0f; style.ScrollbarSize = 18.0f; #endif } -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt diff --git a/src/bolt/gui/lsp_ui_components.cpp b/src/bolt/gui/lsp_ui_components.cpp index e1237f75..ef19393f 100644 --- a/src/bolt/gui/lsp_ui_components.cpp +++ b/src/bolt/gui/lsp_ui_components.cpp @@ -7,6 +7,7 @@ #ifdef BOLT_HAVE_IMGUI #include + #include #include @@ -20,89 +21,86 @@ namespace gui { LspCompletionPopup::LspCompletionPopup() = default; LspCompletionPopup::~LspCompletionPopup() = default; -void LspCompletionPopup::render(lsp::CompletionPopupState& state, float editorPosX, - float editorPosY, float lineHeight) { - if (!state.isVisible || state.items.empty()) return; - +void LspCompletionPopup::render(lsp::CompletionPopupState& state, float editorPosX, float editorPosY, + float lineHeight) { + if (!state.isVisible || state.items.empty()) + return; + // Position popup below the cursor ImGui::SetNextWindowPos(ImVec2(editorPosX, editorPosY + lineHeight), ImGuiCond_Always); ImGui::SetNextWindowSize(ImVec2(popupWidth_, 0), ImGuiCond_Always); - - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings | - ImGuiWindowFlags_AlwaysAutoResize; - + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(4, 4)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.15f, 0.15f, 0.18f, 0.98f)); ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0.3f, 0.3f, 0.35f, 1.0f)); - + if (ImGui::Begin("##CompletionPopup", nullptr, flags)) { // Filter items based on filter text std::vector filteredItems; for (const auto& item : state.items) { - if (state.filterText.empty() || - item.label.find(state.filterText) != std::string::npos) { + if (state.filterText.empty() || item.label.find(state.filterText) != std::string::npos) { filteredItems.push_back(&item); } } - + // Limit visible items size_t visibleCount = std::min(filteredItems.size(), static_cast(maxVisibleItems_)); - + // Calculate scroll position to keep selected item visible int scrollStart = 0; if (state.selectedIndex >= maxVisibleItems_) { scrollStart = state.selectedIndex - maxVisibleItems_ + 1; } - + for (size_t i = scrollStart; i < scrollStart + visibleCount && i < filteredItems.size(); ++i) { const auto* item = filteredItems[i]; bool isSelected = (static_cast(i) == state.selectedIndex); - + // Get kind icon and color const char* icon = getKindIcon(item->kind); float r, g, b; getKindColor(item->kind, r, g, b); - + // Highlight selected item if (isSelected) { ImGui::PushStyleColor(ImGuiCol_Header, ImVec4(0.26f, 0.59f, 0.98f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_HeaderHovered, ImVec4(0.26f, 0.59f, 0.98f, 0.8f)); } - + // Render item ImGui::PushID(static_cast(i)); - + if (ImGui::Selectable("##item", isSelected, 0, ImVec2(0, itemHeight_))) { state.selectedIndex = static_cast(i); if (acceptCallback_) { acceptCallback_(item->insertText); } } - + // Draw icon and label on same line ImGui::SameLine(8); ImGui::TextColored(ImVec4(r, g, b, 1.0f), "%s", icon); ImGui::SameLine(30); ImGui::Text("%s", item->label.c_str()); - + // Show detail on the right if available if (!item->detail.empty()) { float detailX = popupWidth_ - ImGui::CalcTextSize(item->detail.c_str()).x - 20; ImGui::SameLine(detailX); ImGui::TextDisabled("%s", item->detail.c_str()); } - + ImGui::PopID(); - + if (isSelected) { ImGui::PopStyleColor(2); } } - + // Show scroll indicator if there are more items if (filteredItems.size() > static_cast(maxVisibleItems_)) { ImGui::Separator(); @@ -110,27 +108,28 @@ void LspCompletionPopup::render(lsp::CompletionPopupState& state, float editorPo } } ImGui::End(); - + ImGui::PopStyleColor(2); ImGui::PopStyleVar(2); } bool LspCompletionPopup::handleInput(lsp::CompletionPopupState& state) { - if (!state.isVisible) return false; - + if (!state.isVisible) + return false; + ImGuiIO& io = ImGui::GetIO(); - + // Arrow keys for navigation if (ImGui::IsKeyPressed(ImGuiKey_DownArrow)) { state.selectedIndex = (state.selectedIndex + 1) % static_cast(state.items.size()); return true; } if (ImGui::IsKeyPressed(ImGuiKey_UpArrow)) { - state.selectedIndex = (state.selectedIndex - 1 + static_cast(state.items.size())) - % static_cast(state.items.size()); + state.selectedIndex = + (state.selectedIndex - 1 + static_cast(state.items.size())) % static_cast(state.items.size()); return true; } - + // Enter/Tab to accept if (ImGui::IsKeyPressed(ImGuiKey_Enter) || ImGui::IsKeyPressed(ImGuiKey_Tab)) { if (acceptCallback_ && !state.items.empty()) { @@ -139,52 +138,83 @@ bool LspCompletionPopup::handleInput(lsp::CompletionPopupState& state) { state.isVisible = false; return true; } - + // Escape to dismiss if (ImGui::IsKeyPressed(ImGuiKey_Escape)) { state.isVisible = false; return true; } - + return false; } const char* LspCompletionPopup::getKindIcon(const std::string& kind) { - if (kind == "function" || kind == "method") return "ฦ’"; - if (kind == "variable" || kind == "field") return "๐‘ฅ"; - if (kind == "class" || kind == "struct") return "โ—†"; - if (kind == "interface") return "โ—‡"; - if (kind == "module") return "โ–ก"; - if (kind == "property") return "โ—"; - if (kind == "enum") return "โˆˆ"; - if (kind == "enum_member") return "โˆ‹"; - if (kind == "constant") return "ฯ€"; - if (kind == "keyword") return "โŒ˜"; - if (kind == "snippet") return "โœ‚"; - if (kind == "text") return "T"; - if (kind == "file") return "๐Ÿ“„"; - if (kind == "folder") return "๐Ÿ“"; - if (kind == "type_parameter") return "ฯ„"; + if (kind == "function" || kind == "method") + return "ฦ’"; + if (kind == "variable" || kind == "field") + return "๐‘ฅ"; + if (kind == "class" || kind == "struct") + return "โ—†"; + if (kind == "interface") + return "โ—‡"; + if (kind == "module") + return "โ–ก"; + if (kind == "property") + return "โ—"; + if (kind == "enum") + return "โˆˆ"; + if (kind == "enum_member") + return "โˆ‹"; + if (kind == "constant") + return "ฯ€"; + if (kind == "keyword") + return "โŒ˜"; + if (kind == "snippet") + return "โœ‚"; + if (kind == "text") + return "T"; + if (kind == "file") + return "๐Ÿ“„"; + if (kind == "folder") + return "๐Ÿ“"; + if (kind == "type_parameter") + return "ฯ„"; return "โ€ข"; } void LspCompletionPopup::getKindColor(const std::string& kind, float& r, float& g, float& b) { if (kind == "function" || kind == "method") { - r = 0.6f; g = 0.4f; b = 0.8f; // Purple + r = 0.6f; + g = 0.4f; + b = 0.8f; // Purple } else if (kind == "variable" || kind == "field") { - r = 0.4f; g = 0.7f; b = 0.9f; // Light blue + r = 0.4f; + g = 0.7f; + b = 0.9f; // Light blue } else if (kind == "class" || kind == "struct") { - r = 0.9f; g = 0.7f; b = 0.3f; // Orange + r = 0.9f; + g = 0.7f; + b = 0.3f; // Orange } else if (kind == "interface") { - r = 0.3f; g = 0.8f; b = 0.6f; // Teal + r = 0.3f; + g = 0.8f; + b = 0.6f; // Teal } else if (kind == "keyword") { - r = 0.9f; g = 0.4f; b = 0.5f; // Pink + r = 0.9f; + g = 0.4f; + b = 0.5f; // Pink } else if (kind == "constant" || kind == "enum_member") { - r = 0.4f; g = 0.6f; b = 0.9f; // Blue + r = 0.4f; + g = 0.6f; + b = 0.9f; // Blue } else if (kind == "snippet") { - r = 0.7f; g = 0.7f; b = 0.7f; // Gray + r = 0.7f; + g = 0.7f; + b = 0.7f; // Gray } else { - r = 0.8f; g = 0.8f; b = 0.8f; // Default light gray + r = 0.8f; + g = 0.8f; + b = 0.8f; // Default light gray } } @@ -196,31 +226,29 @@ LspHoverTooltip::LspHoverTooltip() = default; LspHoverTooltip::~LspHoverTooltip() = default; void LspHoverTooltip::render(const lsp::HoverTooltipState& state, float mouseX, float mouseY) { - if (!state.isVisible || state.info.content.empty()) return; - + if (!state.isVisible || state.info.content.empty()) + return; + // Position tooltip near the mouse ImGui::SetNextWindowPos(ImVec2(mouseX + 10, mouseY + 10), ImGuiCond_Always); ImGui::SetNextWindowSizeConstraints(ImVec2(100, 0), ImVec2(maxWidth_, 400)); - - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings | - ImGuiWindowFlags_AlwaysAutoResize | + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing; - + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(padding_, padding_)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.12f, 0.12f, 0.15f, 0.98f)); ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0.3f, 0.3f, 0.35f, 1.0f)); - + if (ImGui::Begin("##HoverTooltip", nullptr, flags)) { // Render content with word wrapping ImGui::PushTextWrapPos(maxWidth_ - padding_ * 2); - + // Parse and render markdown-like content const std::string& content = state.info.content; - + // Simple markdown rendering - handle code blocks size_t pos = 0; while (pos < content.length()) { @@ -232,7 +260,7 @@ void LspHoverTooltip::render(const lsp::HoverTooltipState& state, float mouseX, size_t codeStart = content.find('\n', pos + 3); if (codeStart != std::string::npos && codeStart < endPos) { std::string code = content.substr(codeStart + 1, endPos - codeStart - 1); - + // Render code with monospace styling ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.7f, 0.9f, 0.7f, 1.0f)); ImGui::TextUnformatted(code.c_str()); @@ -242,24 +270,25 @@ void LspHoverTooltip::render(const lsp::HoverTooltipState& state, float mouseX, continue; } } - + // Find next special marker or end size_t nextMarker = content.find("```", pos); - if (nextMarker == std::string::npos) nextMarker = content.length(); - + if (nextMarker == std::string::npos) + nextMarker = content.length(); + // Render regular text std::string text = content.substr(pos, nextMarker - pos); if (!text.empty()) { ImGui::TextUnformatted(text.c_str()); } - + pos = nextMarker; } - + ImGui::PopTextWrapPos(); } ImGui::End(); - + ImGui::PopStyleColor(2); ImGui::PopStyleVar(2); } @@ -271,44 +300,39 @@ void LspHoverTooltip::render(const lsp::HoverTooltipState& state, float mouseX, LspDiagnosticsGutter::LspDiagnosticsGutter() = default; LspDiagnosticsGutter::~LspDiagnosticsGutter() = default; -void LspDiagnosticsGutter::render(const std::vector& diagnostics, - float gutterX, size_t firstVisibleLine, size_t lastVisibleLine, - float lineHeight, float scrollY) { - if (diagnostics.empty()) return; - +void LspDiagnosticsGutter::render(const std::vector& diagnostics, float gutterX, + size_t firstVisibleLine, size_t lastVisibleLine, float lineHeight, float scrollY) { + if (diagnostics.empty()) + return; + ImDrawList* drawList = ImGui::GetWindowDrawList(); - + for (const auto& diag : diagnostics) { // Check if diagnostic is in visible range if (diag.startLine < firstVisibleLine || diag.startLine > lastVisibleLine) { continue; } - + // Calculate Y position float y = (diag.startLine - firstVisibleLine) * lineHeight - scrollY; - + // Get color based on severity float r, g, b; getSeverityColor(diag.severity, r, g, b); - ImU32 color = IM_COL32(static_cast(r * 255), static_cast(g * 255), - static_cast(b * 255), 255); - + ImU32 color = IM_COL32(static_cast(r * 255), static_cast(g * 255), static_cast(b * 255), 255); + // Draw marker float centerX = gutterX + gutterWidth_ / 2; float centerY = y + lineHeight / 2; float radius = 4.0f; - + if (diag.severity == lsp::DiagnosticSeverity::Error) { // Filled circle for errors drawList->AddCircleFilled(ImVec2(centerX, centerY), radius, color); } else if (diag.severity == lsp::DiagnosticSeverity::Warning) { // Triangle for warnings - drawList->AddTriangleFilled( - ImVec2(centerX, centerY - radius), - ImVec2(centerX - radius, centerY + radius), - ImVec2(centerX + radius, centerY + radius), - color - ); + drawList->AddTriangleFilled(ImVec2(centerX, centerY - radius), ImVec2(centerX - radius, centerY + radius), + ImVec2(centerX + radius, centerY + radius), color); } else { // Circle outline for info/hints drawList->AddCircle(ImVec2(centerX, centerY), radius, color, 12, 1.5f); @@ -316,87 +340,107 @@ void LspDiagnosticsGutter::render(const std::vector& diag } } -void LspDiagnosticsGutter::renderDiagnosticTooltip(const lsp::EditorDiagnostic& diagnostic, - float mouseX, float mouseY) { +void LspDiagnosticsGutter::renderDiagnosticTooltip(const lsp::EditorDiagnostic& diagnostic, float mouseX, + float mouseY) { ImGui::SetNextWindowPos(ImVec2(mouseX + 10, mouseY + 10), ImGuiCond_Always); - - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | - ImGuiWindowFlags_NoResize | - ImGuiWindowFlags_NoMove | - ImGuiWindowFlags_NoSavedSettings | - ImGuiWindowFlags_AlwaysAutoResize; - + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | + ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize; + // Color based on severity float r, g, b; getSeverityColor(diagnostic.severity, r, g, b); - + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(8, 8)); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 4.0f); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.12f, 0.12f, 0.15f, 0.98f)); ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(r, g, b, 0.8f)); - + if (ImGui::Begin("##DiagnosticTooltip", nullptr, flags)) { // Severity icon and label const char* icon = getSeverityIcon(diagnostic.severity); ImGui::TextColored(ImVec4(r, g, b, 1.0f), "%s", icon); ImGui::SameLine(); - + const char* severityLabel = "Info"; switch (diagnostic.severity) { - case lsp::DiagnosticSeverity::Error: severityLabel = "Error"; break; - case lsp::DiagnosticSeverity::Warning: severityLabel = "Warning"; break; - case lsp::DiagnosticSeverity::Information: severityLabel = "Info"; break; - case lsp::DiagnosticSeverity::Hint: severityLabel = "Hint"; break; + case lsp::DiagnosticSeverity::Error: + severityLabel = "Error"; + break; + case lsp::DiagnosticSeverity::Warning: + severityLabel = "Warning"; + break; + case lsp::DiagnosticSeverity::Information: + severityLabel = "Info"; + break; + case lsp::DiagnosticSeverity::Hint: + severityLabel = "Hint"; + break; } ImGui::TextColored(ImVec4(r, g, b, 1.0f), "%s", severityLabel); - + if (!diagnostic.source.empty()) { ImGui::SameLine(); ImGui::TextDisabled("(%s)", diagnostic.source.c_str()); } - + ImGui::Separator(); - + // Message ImGui::PushTextWrapPos(400); ImGui::TextUnformatted(diagnostic.message.c_str()); ImGui::PopTextWrapPos(); - + // Location ImGui::TextDisabled("Line %zu, Column %zu", diagnostic.startLine + 1, diagnostic.startColumn + 1); } ImGui::End(); - + ImGui::PopStyleColor(2); ImGui::PopStyleVar(2); } const char* LspDiagnosticsGutter::getSeverityIcon(lsp::DiagnosticSeverity severity) { switch (severity) { - case lsp::DiagnosticSeverity::Error: return "โŒ"; - case lsp::DiagnosticSeverity::Warning: return "โš ๏ธ"; - case lsp::DiagnosticSeverity::Information: return "โ„น๏ธ"; - case lsp::DiagnosticSeverity::Hint: return "๐Ÿ’ก"; - default: return "โ€ข"; + case lsp::DiagnosticSeverity::Error: + return "โŒ"; + case lsp::DiagnosticSeverity::Warning: + return "โš ๏ธ"; + case lsp::DiagnosticSeverity::Information: + return "โ„น๏ธ"; + case lsp::DiagnosticSeverity::Hint: + return "๐Ÿ’ก"; + default: + return "โ€ข"; } } void LspDiagnosticsGutter::getSeverityColor(lsp::DiagnosticSeverity severity, float& r, float& g, float& b) { switch (severity) { case lsp::DiagnosticSeverity::Error: - r = 0.9f; g = 0.3f; b = 0.3f; // Red + r = 0.9f; + g = 0.3f; + b = 0.3f; // Red break; case lsp::DiagnosticSeverity::Warning: - r = 0.9f; g = 0.7f; b = 0.2f; // Yellow/Orange + r = 0.9f; + g = 0.7f; + b = 0.2f; // Yellow/Orange break; case lsp::DiagnosticSeverity::Information: - r = 0.3f; g = 0.6f; b = 0.9f; // Blue + r = 0.3f; + g = 0.6f; + b = 0.9f; // Blue break; case lsp::DiagnosticSeverity::Hint: - r = 0.5f; g = 0.8f; b = 0.5f; // Green + r = 0.5f; + g = 0.8f; + b = 0.5f; // Green break; default: - r = 0.7f; g = 0.7f; b = 0.7f; // Gray + r = 0.7f; + g = 0.7f; + b = 0.7f; // Gray break; } } @@ -408,52 +452,53 @@ void LspDiagnosticsGutter::getSeverityColor(lsp::DiagnosticSeverity severity, fl LspInlineDiagnostics::LspInlineDiagnostics() = default; LspInlineDiagnostics::~LspInlineDiagnostics() = default; -void LspInlineDiagnostics::render(const std::vector& diagnostics, - float editorX, float editorY, size_t firstVisibleLine, - float lineHeight, float charWidth, float scrollY) { - if (diagnostics.empty()) return; - +void LspInlineDiagnostics::render(const std::vector& diagnostics, float editorX, float editorY, + size_t firstVisibleLine, float lineHeight, float charWidth, float scrollY) { + if (diagnostics.empty()) + return; + ImDrawList* drawList = ImGui::GetWindowDrawList(); - + for (const auto& diag : diagnostics) { // Check if diagnostic is in visible range - if (diag.startLine < firstVisibleLine) continue; - + if (diag.startLine < firstVisibleLine) + continue; + // Calculate position float y = editorY + (diag.startLine - firstVisibleLine) * lineHeight - scrollY + lineHeight - 2; float x1 = editorX + diag.startColumn * charWidth; float x2 = editorX + diag.endColumn * charWidth; - + // Ensure minimum width if (x2 - x1 < charWidth) { x2 = x1 + charWidth; } - + // Get color based on severity float r, g, b; LspDiagnosticsGutter::getSeverityColor(diag.severity, r, g, b); - + // Draw squiggly underline drawSquigglyLine(x1, y, x2, 2.0f, r, g, b, 0.8f); } } -void LspInlineDiagnostics::drawSquigglyLine(float x1, float y, float x2, float amplitude, - float r, float g, float b, float a) { +void LspInlineDiagnostics::drawSquigglyLine(float x1, float y, float x2, float amplitude, float r, float g, float b, + float a) { ImDrawList* drawList = ImGui::GetWindowDrawList(); - ImU32 color = IM_COL32(static_cast(r * 255), static_cast(g * 255), - static_cast(b * 255), static_cast(a * 255)); - + ImU32 color = IM_COL32(static_cast(r * 255), static_cast(g * 255), static_cast(b * 255), + static_cast(a * 255)); + float wavelength = 4.0f; float x = x1; - + while (x < x2) { float nextX = std::min(x + wavelength / 2, x2); float midY = y + (static_cast((x - x1) / (wavelength / 2)) % 2 == 0 ? amplitude : -amplitude); - + drawList->AddLine(ImVec2(x, y), ImVec2((x + nextX) / 2, midY), color, 1.0f); drawList->AddLine(ImVec2((x + nextX) / 2, midY), ImVec2(nextX, y), color, 1.0f); - + x = nextX; } } @@ -466,11 +511,12 @@ LspStatusBar::LspStatusBar() = default; LspStatusBar::~LspStatusBar() = default; void LspStatusBar::render(const lsp::LspEditorBridge& bridge, const std::string& currentFile) { - if (currentFile.empty()) return; - + if (currentFile.empty()) + return; + size_t errorCount = bridge.getErrorCount(currentFile); size_t warningCount = bridge.getWarningCount(currentFile); - + // Error count if (errorCount > 0) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.9f, 0.3f, 0.3f, 1.0f)); @@ -478,7 +524,7 @@ void LspStatusBar::render(const lsp::LspEditorBridge& bridge, const std::string& ImGui::PopStyleColor(); ImGui::SameLine(); } - + // Warning count if (warningCount > 0) { ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.9f, 0.7f, 0.2f, 1.0f)); @@ -486,7 +532,7 @@ void LspStatusBar::render(const lsp::LspEditorBridge& bridge, const std::string& ImGui::PopStyleColor(); ImGui::SameLine(); } - + // Language server status std::string langId = lsp::LspEditorBridge::detectLanguageId(currentFile); if (bridge.isLanguageSupported(langId)) { @@ -498,10 +544,10 @@ void LspStatusBar::render(const lsp::LspEditorBridge& bridge, const std::string& } } -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt -#else // BOLT_HAVE_IMGUI +#else // BOLT_HAVE_IMGUI // Stub implementations when ImGui is not available namespace bolt { @@ -510,9 +556,15 @@ namespace gui { LspCompletionPopup::LspCompletionPopup() = default; LspCompletionPopup::~LspCompletionPopup() = default; void LspCompletionPopup::render(lsp::CompletionPopupState&, float, float, float) {} -bool LspCompletionPopup::handleInput(lsp::CompletionPopupState&) { return false; } -const char* LspCompletionPopup::getKindIcon(const std::string&) { return ""; } -void LspCompletionPopup::getKindColor(const std::string&, float& r, float& g, float& b) { r = g = b = 0.8f; } +bool LspCompletionPopup::handleInput(lsp::CompletionPopupState&) { + return false; +} +const char* LspCompletionPopup::getKindIcon(const std::string&) { + return ""; +} +void LspCompletionPopup::getKindColor(const std::string&, float& r, float& g, float& b) { + r = g = b = 0.8f; +} LspHoverTooltip::LspHoverTooltip() = default; LspHoverTooltip::~LspHoverTooltip() = default; @@ -522,18 +574,23 @@ LspDiagnosticsGutter::LspDiagnosticsGutter() = default; LspDiagnosticsGutter::~LspDiagnosticsGutter() = default; void LspDiagnosticsGutter::render(const std::vector&, float, size_t, size_t, float, float) {} void LspDiagnosticsGutter::renderDiagnosticTooltip(const lsp::EditorDiagnostic&, float, float) {} -const char* LspDiagnosticsGutter::getSeverityIcon(lsp::DiagnosticSeverity) { return ""; } -void LspDiagnosticsGutter::getSeverityColor(lsp::DiagnosticSeverity, float& r, float& g, float& b) { r = g = b = 0.7f; } +const char* LspDiagnosticsGutter::getSeverityIcon(lsp::DiagnosticSeverity) { + return ""; +} +void LspDiagnosticsGutter::getSeverityColor(lsp::DiagnosticSeverity, float& r, float& g, float& b) { + r = g = b = 0.7f; +} LspInlineDiagnostics::LspInlineDiagnostics() = default; LspInlineDiagnostics::~LspInlineDiagnostics() = default; -void LspInlineDiagnostics::render(const std::vector&, float, float, size_t, float, float, float) {} +void LspInlineDiagnostics::render(const std::vector&, float, float, size_t, float, float, + float) {} LspStatusBar::LspStatusBar() = default; LspStatusBar::~LspStatusBar() = default; void LspStatusBar::render(const lsp::LspEditorBridge&, const std::string&) {} -} // namespace gui -} // namespace bolt +} // namespace gui +} // namespace bolt -#endif // BOLT_HAVE_IMGUI +#endif // BOLT_HAVE_IMGUI diff --git a/src/bolt/gui/widget_framework.cpp b/src/bolt/gui/widget_framework.cpp index 9549a11b..2aad5bc5 100644 --- a/src/bolt/gui/widget_framework.cpp +++ b/src/bolt/gui/widget_framework.cpp @@ -5,26 +5,38 @@ #endif #include -#include #include +#include namespace bolt { namespace gui { // WidgetStyle implementation void WidgetStyle::merge(const WidgetStyle& other) { - if (other.backgroundColor) backgroundColor = other.backgroundColor; - if (other.borderColor) borderColor = other.borderColor; - if (other.textColor) textColor = other.textColor; - if (other.hoverColor) hoverColor = other.hoverColor; - if (other.activeColor) activeColor = other.activeColor; - if (other.borderWidth) borderWidth = other.borderWidth; - if (other.cornerRadius) cornerRadius = other.cornerRadius; - if (other.padding) padding = other.padding; - if (other.margin) margin = other.margin; - if (other.fontSize) fontSize = other.fontSize; - if (other.fontFamily) fontFamily = other.fontFamily; - if (other.animationDuration) animationDuration = other.animationDuration; + if (other.backgroundColor) + backgroundColor = other.backgroundColor; + if (other.borderColor) + borderColor = other.borderColor; + if (other.textColor) + textColor = other.textColor; + if (other.hoverColor) + hoverColor = other.hoverColor; + if (other.activeColor) + activeColor = other.activeColor; + if (other.borderWidth) + borderWidth = other.borderWidth; + if (other.cornerRadius) + cornerRadius = other.cornerRadius; + if (other.padding) + padding = other.padding; + if (other.margin) + margin = other.margin; + if (other.fontSize) + fontSize = other.fontSize; + if (other.fontFamily) + fontFamily = other.fontFamily; + if (other.animationDuration) + animationDuration = other.animationDuration; } void WidgetStyle::applyToImGui() const { @@ -60,51 +72,61 @@ void WidgetStyle::restoreImGui() const { #ifdef BOLT_HAVE_IMGUI int colorCount = 0; int styleCount = 0; - - if (backgroundColor) colorCount++; - if (borderColor) colorCount++; - if (textColor) colorCount++; - if (hoverColor) colorCount++; - if (activeColor) colorCount++; - - if (borderWidth) styleCount++; - if (cornerRadius) styleCount++; - if (padding) styleCount++; - - if (colorCount > 0) ImGui::PopStyleColor(colorCount); - if (styleCount > 0) ImGui::PopStyleVar(styleCount); + + if (backgroundColor) + colorCount++; + if (borderColor) + colorCount++; + if (textColor) + colorCount++; + if (hoverColor) + colorCount++; + if (activeColor) + colorCount++; + + if (borderWidth) + styleCount++; + if (cornerRadius) + styleCount++; + if (padding) + styleCount++; + + if (colorCount > 0) + ImGui::PopStyleColor(colorCount); + if (styleCount > 0) + ImGui::PopStyleVar(styleCount); #endif } // Widget implementation Widget::Widget(const std::string& id) - : id_(id.empty() ? "widget_" + std::to_string(reinterpret_cast(this)) : id) - , parent_(nullptr) - , visible_(true) - , enabled_(true) - , focused_(false) - , minimumSize_(0.0f, 0.0f) - , maximumSize_(FLT_MAX, FLT_MAX) - , imguiStylePushCount_(0) -{ -} + : id_(id.empty() ? "widget_" + std::to_string(reinterpret_cast(this)) : id), + parent_(nullptr), + visible_(true), + enabled_(true), + focused_(false), + minimumSize_(0.0f, 0.0f), + maximumSize_(FLT_MAX, FLT_MAX), + imguiStylePushCount_(0) {} void Widget::addChild(std::shared_ptr child) { - if (!child) return; - + if (!child) + return; + // Remove from previous parent if (child->parent_) { child->parent_->removeChild(child); } - + // Add to this widget children_.push_back(child); child->parent_ = this; } void Widget::removeChild(std::shared_ptr child) { - if (!child) return; - + if (!child) + return; + auto it = std::find(children_.begin(), children_.end(), child); if (it != children_.end()) { (*it)->parent_ = nullptr; @@ -114,10 +136,8 @@ void Widget::removeChild(std::shared_ptr child) { void Widget::removeChild(const std::string& childId) { auto it = std::find_if(children_.begin(), children_.end(), - [&childId](const std::shared_ptr& child) { - return child->getId() == childId; - }); - + [&childId](const std::shared_ptr& child) { return child->getId() == childId; }); + if (it != children_.end()) { (*it)->parent_ = nullptr; children_.erase(it); @@ -149,40 +169,42 @@ bool Widget::fireEvent(const WidgetEvent& event) { } } } - + // Call virtual onEvent handler const_cast(this)->onEvent(event); - + // Bubble event to parent if not handled if (!event.handled && parent_) { return parent_->fireEvent(event); } - + return event.handled; } void Widget::render() { - if (!visible_) return; - + if (!visible_) + return; + pushImGuiStyle(); - + onRender(); - + // Render children for (auto& child : children_) { if (child && child->isVisible()) { child->render(); } } - + popImGuiStyle(); } void Widget::update(float deltaTime) { - if (!visible_) return; - + if (!visible_) + return; + onUpdate(deltaTime); - + // Update children for (auto& child : children_) { if (child && child->isVisible()) { @@ -194,17 +216,15 @@ void Widget::update(float deltaTime) { Size Widget::calculatePreferredSize() const { // Default implementation: return minimum size or current size if (bounds_.size.isValid()) { - return Size( - std::max(bounds_.size.width, minimumSize_.width), - std::max(bounds_.size.height, minimumSize_.height) - ); + return Size(std::max(bounds_.size.width, minimumSize_.width), + std::max(bounds_.size.height, minimumSize_.height)); } return minimumSize_; } void Widget::layout() { onLayout(); - + // Layout children for (auto& child : children_) { if (child && child->isVisible()) { @@ -232,9 +252,7 @@ std::string Widget::getImGuiId() const { } // WidgetContainer implementation -WidgetContainer::WidgetContainer(const std::string& id, LayoutType layoutType) - : Widget(id) -{ +WidgetContainer::WidgetContainer(const std::string& id, LayoutType layoutType) : Widget(id) { LayoutParameters params; params.type = layoutType; params.spacing = 5.0f; @@ -256,19 +274,17 @@ void WidgetContainer::setSpacing(float spacing) { void WidgetContainer::onRender() { #ifdef BOLT_HAVE_IMGUI // Container-specific rendering - ImGui::BeginChild(getImGuiId().c_str(), - ImVec2(getBounds().size.width, getBounds().size.height), - true); - + ImGui::BeginChild(getImGuiId().c_str(), ImVec2(getBounds().size.width, getBounds().size.height), true); + // The actual layout and child rendering is handled by the base Widget::render() - + ImGui::EndChild(); #endif } void WidgetContainer::onLayout() { const auto& params = getLayoutParams(); - + switch (params.type) { case LayoutType::Vertical: layoutVertical(); @@ -295,114 +311,114 @@ void WidgetContainer::onLayout() { Size WidgetContainer::calculatePreferredSize() const { const auto& params = getLayoutParams(); const auto& children = getChildren(); - + if (children.empty()) { return Widget::calculatePreferredSize(); } - + Size totalSize(0.0f, 0.0f); - + switch (params.type) { case LayoutType::Vertical: { float maxWidth = 0.0f; float totalHeight = 0.0f; - + for (const auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + Size childSize = child->calculatePreferredSize(); maxWidth = std::max(maxWidth, childSize.width); totalHeight += childSize.height; - + if (totalHeight > 0.0f) { totalHeight += params.spacing; } } - + totalSize = Size(maxWidth, totalHeight); break; } - + case LayoutType::Horizontal: { float totalWidth = 0.0f; float maxHeight = 0.0f; - + for (const auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + Size childSize = child->calculatePreferredSize(); totalWidth += childSize.width; maxHeight = std::max(maxHeight, childSize.height); - + if (totalWidth > 0.0f) { totalWidth += params.spacing; } } - + totalSize = Size(totalWidth, maxHeight); break; } - + case LayoutType::Grid: { int visibleChildren = 0; for (const auto& child : children) { - if (child && child->isVisible()) visibleChildren++; + if (child && child->isVisible()) + visibleChildren++; } - + if (visibleChildren > 0) { int cols = std::max(1, params.columns); int rows = (visibleChildren + cols - 1) / cols; - + float cellWidth = 0.0f; float cellHeight = 0.0f; - + for (const auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + Size childSize = child->calculatePreferredSize(); cellWidth = std::max(cellWidth, childSize.width); cellHeight = std::max(cellHeight, childSize.height); } - - totalSize = Size( - cols * cellWidth + (cols - 1) * params.spacing, - rows * cellHeight + (rows - 1) * params.spacing - ); + + totalSize = Size(cols * cellWidth + (cols - 1) * params.spacing, + rows * cellHeight + (rows - 1) * params.spacing); } break; } - + default: totalSize = Widget::calculatePreferredSize(); break; } - + // Ensure we meet minimum size requirements - return Size( - std::max(totalSize.width, getMinimumSize().width), - std::max(totalSize.height, getMinimumSize().height) - ); + return Size(std::max(totalSize.width, getMinimumSize().width), std::max(totalSize.height, getMinimumSize().height)); } void WidgetContainer::layoutVertical() { const auto& params = getLayoutParams(); const auto& children = getChildren(); const Rect& bounds = getBounds(); - + float currentY = bounds.position.y; - + for (auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + Size childSize = child->calculatePreferredSize(); - + // Respect child's preferred width or use container width float childWidth = params.fillAvailableSpace ? bounds.size.width : childSize.width; childWidth = std::min(childWidth, bounds.size.width); - + child->setPosition(Position(bounds.position.x, currentY)); child->setSize(Size(childWidth, childSize.height)); - + currentY += childSize.height + params.spacing; } } @@ -411,21 +427,22 @@ void WidgetContainer::layoutHorizontal() { const auto& params = getLayoutParams(); const auto& children = getChildren(); const Rect& bounds = getBounds(); - + float currentX = bounds.position.x; - + for (auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + Size childSize = child->calculatePreferredSize(); - + // Respect child's preferred height or use container height float childHeight = params.fillAvailableSpace ? bounds.size.height : childSize.height; childHeight = std::min(childHeight, bounds.size.height); - + child->setPosition(Position(currentX, bounds.position.y)); child->setSize(Size(childSize.width, childHeight)); - + currentX += childSize.width + params.spacing; } } @@ -434,32 +451,35 @@ void WidgetContainer::layoutGrid() { const auto& params = getLayoutParams(); const auto& children = getChildren(); const Rect& bounds = getBounds(); - + int cols = std::max(1, params.columns); int visibleChildren = 0; for (const auto& child : children) { - if (child && child->isVisible()) visibleChildren++; + if (child && child->isVisible()) + visibleChildren++; } - - if (visibleChildren == 0) return; - + + if (visibleChildren == 0) + return; + int rows = (visibleChildren + cols - 1) / cols; float cellWidth = (bounds.size.width - (cols - 1) * params.spacing) / cols; float cellHeight = (bounds.size.height - (rows - 1) * params.spacing) / rows; - + int index = 0; for (auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + int row = index / cols; int col = index % cols; - + float x = bounds.position.x + col * (cellWidth + params.spacing); float y = bounds.position.y + row * (cellHeight + params.spacing); - + child->setPosition(Position(x, y)); child->setSize(Size(cellWidth, cellHeight)); - + index++; } } @@ -469,14 +489,15 @@ void WidgetContainer::layoutFlex() { const auto& params = getLayoutParams(); const auto& children = getChildren(); const Rect& bounds = getBounds(); - + // For now, implement as horizontal layout with flex grow float totalFlexGrow = 0.0f; float totalFixedWidth = 0.0f; - + for (const auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + float flexGrow = child->getProperty("flexGrow", 0.0f); if (flexGrow > 0.0f) { totalFlexGrow += flexGrow; @@ -484,26 +505,27 @@ void WidgetContainer::layoutFlex() { totalFixedWidth += child->calculatePreferredSize().width; } } - + float availableSpace = bounds.size.width - totalFixedWidth - (children.size() - 1) * params.spacing; float currentX = bounds.position.x; - + for (auto& child : children) { - if (!child || !child->isVisible()) continue; - + if (!child || !child->isVisible()) + continue; + float flexGrow = child->getProperty("flexGrow", 0.0f); Size childSize = child->calculatePreferredSize(); - + float childWidth; if (flexGrow > 0.0f && totalFlexGrow > 0.0f) { childWidth = (availableSpace * flexGrow) / totalFlexGrow; } else { childWidth = childSize.width; } - + child->setPosition(Position(currentX, bounds.position.y)); child->setSize(Size(childWidth, bounds.size.height)); - + currentX += childWidth + params.spacing; } } @@ -519,7 +541,7 @@ std::shared_ptr WidgetFactory::createWidget(const std::string& typeName, if (it != creators_.end()) { return it->second(id); } - + std::cerr << "Warning: Unknown widget type '" << typeName << "'" << std::endl; return nullptr; } @@ -527,11 +549,11 @@ std::shared_ptr WidgetFactory::createWidget(const std::string& typeName, std::vector WidgetFactory::getRegisteredTypes() const { std::vector types; types.reserve(creators_.size()); - + for (const auto& pair : creators_) { types.push_back(pair.first); } - + return types; } @@ -560,7 +582,7 @@ void WidgetTheme::setWidgetStyle(const std::string& widgetType, const std::strin WidgetStyle WidgetTheme::getWidgetStyle(const std::string& widgetType, const std::string& state) const { WidgetStyle baseStyle = getWidgetStyle(widgetType); - + auto typeIt = stateStyles_.find(widgetType); if (typeIt != stateStyles_.end()) { auto stateIt = typeIt->second.find(state); @@ -568,13 +590,14 @@ WidgetStyle WidgetTheme::getWidgetStyle(const std::string& widgetType, const std baseStyle.merge(stateIt->second); } } - + return baseStyle; } void WidgetTheme::applyToWidget(Widget* widget, const std::string& widgetType, const std::string& state) const { - if (!widget) return; - + if (!widget) + return; + WidgetStyle style = getWidgetStyle(widgetType, state); widget->setStyle(style); } @@ -588,7 +611,7 @@ ThemeManager& ThemeManager::getInstance() { void ThemeManager::addTheme(std::shared_ptr theme) { if (theme) { themes_[theme->getName()] = theme; - + // Set as current theme if it's the first one if (!currentTheme_) { currentTheme_ = theme; @@ -630,11 +653,11 @@ void ThemeManager::setCurrentTheme(std::shared_ptr theme) { std::vector ThemeManager::getThemeNames() const { std::vector names; names.reserve(themes_.size()); - + for (const auto& pair : themes_) { names.push_back(pair.first); } - + return names; } @@ -644,5 +667,5 @@ void ThemeManager::applyCurrentTheme(Widget* widget, const std::string& widgetTy } } -} // namespace gui -} // namespace bolt \ No newline at end of file +} // namespace gui +} // namespace bolt diff --git a/src/bolt/gui/widgets.cpp b/src/bolt/gui/widgets.cpp index 8a179b93..66465acd 100644 --- a/src/bolt/gui/widgets.cpp +++ b/src/bolt/gui/widgets.cpp @@ -1,7 +1,8 @@ #include "bolt/gui/widgets.hpp" + #include -#include #include +#include #ifdef BOLT_HAVE_IMGUI #include @@ -15,23 +16,21 @@ std::unordered_map> RadioButton::radioGro // Button implementation Button::Button(const std::string& id, const std::string& text) - : Widget(id), text_(text), pressed_(false), hovered_(false) -{ -} + : Widget(id), text_(text), pressed_(false), hovered_(false) {} void Button::onRender() { #ifdef BOLT_HAVE_IMGUI std::string displayText = icon_.empty() ? text_ : icon_ + " " + text_; - + if (ImGui::Button(displayText.c_str(), ImVec2(getBounds().size.width, getBounds().size.height))) { if (onClickCallback_) { onClickCallback_(); } - + WidgetEvent event(WidgetEventType::Click, this); fireEvent(event); } - + hovered_ = ImGui::IsItemHovered(); pressed_ = ImGui::IsItemActive(); #endif @@ -47,7 +46,7 @@ Size Button::calculatePreferredSize() const { #ifdef BOLT_HAVE_IMGUI std::string displayText = icon_.empty() ? text_ : icon_ + " " + text_; ImVec2 textSize = ImGui::CalcTextSize(displayText.c_str()); - + // Add padding return Size(textSize.x + 20.0f, textSize.y + 10.0f); #else @@ -57,14 +56,12 @@ Size Button::calculatePreferredSize() const { // Label implementation Label::Label(const std::string& id, const std::string& text) - : Widget(id), text_(text), alignment_(Alignment::Left), wordWrap_(false) -{ -} + : Widget(id), text_(text), alignment_(Alignment::Left), wordWrap_(false) {} void Label::onRender() { #ifdef BOLT_HAVE_IMGUI ImVec2 availableSize(getBounds().size.width, getBounds().size.height); - + if (wordWrap_) { ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + availableSize.x); ImGui::TextWrapped("%s", text_.c_str()); @@ -74,18 +71,18 @@ void Label::onRender() { if (alignment_ != Alignment::Left) { ImVec2 textSize = ImGui::CalcTextSize(text_.c_str()); float offsetX = 0.0f; - + if (alignment_ == Alignment::Center) { offsetX = (availableSize.x - textSize.x) * 0.5f; } else if (alignment_ == Alignment::Right) { offsetX = availableSize.x - textSize.x; } - + if (offsetX > 0.0f) { ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offsetX); } } - + ImGui::Text("%s", text_.c_str()); } #endif @@ -95,7 +92,7 @@ Size Label::calculatePreferredSize() const { #ifdef BOLT_HAVE_IMGUI if (wordWrap_) { // For word wrap, height depends on available width - return Size(200.0f, 20.0f); // Default size, will be adjusted by layout + return Size(200.0f, 20.0f); // Default size, will be adjusted by layout } else { ImVec2 textSize = ImGui::CalcTextSize(text_.c_str()); return Size(textSize.x, textSize.y); @@ -107,8 +104,7 @@ Size Label::calculatePreferredSize() const { // TextInput implementation TextInput::TextInput(const std::string& id, const std::string& placeholder) - : Widget(id), placeholder_(placeholder), readOnly_(false), password_(false) -{ + : Widget(id), placeholder_(placeholder), readOnly_(false), password_(false) { textBuffer_[0] = '\0'; } @@ -119,37 +115,39 @@ void TextInput::onRender() { strncpy(textBuffer_, text_.c_str(), sizeof(textBuffer_) - 1); textBuffer_[sizeof(textBuffer_) - 1] = '\0'; } - + ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; - if (readOnly_) flags |= ImGuiInputTextFlags_ReadOnly; - if (password_) flags |= ImGuiInputTextFlags_Password; - + if (readOnly_) + flags |= ImGuiInputTextFlags_ReadOnly; + if (password_) + flags |= ImGuiInputTextFlags_Password; + bool textChanged = false; if (password_) { textChanged = ImGui::InputText(getImGuiId().c_str(), textBuffer_, sizeof(textBuffer_), flags); } else { - textChanged = ImGui::InputTextWithHint(getImGuiId().c_str(), placeholder_.c_str(), - textBuffer_, sizeof(textBuffer_), flags); + textChanged = ImGui::InputTextWithHint(getImGuiId().c_str(), placeholder_.c_str(), textBuffer_, + sizeof(textBuffer_), flags); } - + if (textChanged) { text_ = textBuffer_; - + if (onTextChangedCallback_) { onTextChangedCallback_(text_); } - + WidgetEvent event(WidgetEventType::TextChanged, this); event.setData("text", text_); fireEvent(event); } - + // Check for Enter key if (ImGui::IsItemFocused() && ImGui::IsKeyPressed(ImGuiKey_Enter)) { if (onEnterPressedCallback_) { onEnterPressedCallback_(); } - + WidgetEvent event(WidgetEventType::KeyPress, this); event.setData("key", "Enter"); fireEvent(event); @@ -163,8 +161,7 @@ Size TextInput::calculatePreferredSize() const { // TextArea implementation TextArea::TextArea(const std::string& id, const std::string& placeholder) - : Widget(id), placeholder_(placeholder), readOnly_(false) -{ + : Widget(id), placeholder_(placeholder), readOnly_(false) { ensureBufferSize(1024); } @@ -178,20 +175,21 @@ void TextArea::setText(const std::string& text) { void TextArea::onRender() { #ifdef BOLT_HAVE_IMGUI ImGuiInputTextFlags flags = ImGuiInputTextFlags_None; - if (readOnly_) flags |= ImGuiInputTextFlags_ReadOnly; - + if (readOnly_) + flags |= ImGuiInputTextFlags_ReadOnly; + ImVec2 size(getBounds().size.width, getBounds().size.height); - - bool textChanged = ImGui::InputTextMultiline(getImGuiId().c_str(), textBuffer_.data(), - textBuffer_.size(), size, flags); - + + bool textChanged = + ImGui::InputTextMultiline(getImGuiId().c_str(), textBuffer_.data(), textBuffer_.size(), size, flags); + if (textChanged) { text_ = textBuffer_.data(); - + if (onTextChangedCallback_) { onTextChangedCallback_(text_); } - + WidgetEvent event(WidgetEventType::TextChanged, this); event.setData("text", text_); fireEvent(event); @@ -207,7 +205,7 @@ void TextArea::ensureBufferSize(size_t minSize) { if (textBuffer_.size() < minSize) { size_t oldSize = textBuffer_.size(); textBuffer_.resize(minSize); - + // Initialize new memory to zero std::fill(textBuffer_.begin() + oldSize, textBuffer_.end(), '\0'); } @@ -215,20 +213,18 @@ void TextArea::ensureBufferSize(size_t minSize) { // Checkbox implementation Checkbox::Checkbox(const std::string& id, const std::string& label, bool checked) - : Widget(id), checked_(checked), label_(label) -{ -} + : Widget(id), checked_(checked), label_(label) {} void Checkbox::onRender() { #ifdef BOLT_HAVE_IMGUI bool oldChecked = checked_; ImGui::Checkbox(label_.c_str(), &checked_); - + if (checked_ != oldChecked) { if (onStateChangedCallback_) { onStateChangedCallback_(checked_); } - + WidgetEvent event(WidgetEventType::ValueChanged, this); event.setData("checked", checked_); fireEvent(event); @@ -239,17 +235,15 @@ void Checkbox::onRender() { Size Checkbox::calculatePreferredSize() const { #ifdef BOLT_HAVE_IMGUI ImVec2 textSize = ImGui::CalcTextSize(label_.c_str()); - return Size(textSize.x + 30.0f, std::max(textSize.y, 20.0f)); // Add space for checkbox + return Size(textSize.x + 30.0f, std::max(textSize.y, 20.0f)); // Add space for checkbox #else return Size(100.0f, 20.0f); #endif } // RadioButton implementation -RadioButton::RadioButton(const std::string& id, const std::string& label, - const std::string& group, bool selected) - : Widget(id), selected_(selected), label_(label), group_(group) -{ +RadioButton::RadioButton(const std::string& id, const std::string& label, const std::string& group, bool selected) + : Widget(id), selected_(selected), label_(label), group_(group) { if (!group_.empty()) { radioGroups_[group_].push_back(this); } @@ -258,11 +252,11 @@ RadioButton::RadioButton(const std::string& id, const std::string& label, void RadioButton::setSelected(bool selected) { if (selected_ != selected) { selected_ = selected; - + if (selected_) { deselectOthersInGroup(); } - + if (onStateChangedCallback_) { onStateChangedCallback_(selected_); } @@ -273,14 +267,14 @@ void RadioButton::onRender() { #ifdef BOLT_HAVE_IMGUI bool oldSelected = selected_; ImGui::RadioButton(label_.c_str(), &selected_); - + if (selected_ != oldSelected && selected_) { deselectOthersInGroup(); - + if (onStateChangedCallback_) { onStateChangedCallback_(selected_); } - + WidgetEvent event(WidgetEventType::ValueChanged, this); event.setData("selected", selected_); fireEvent(event); @@ -298,8 +292,9 @@ Size RadioButton::calculatePreferredSize() const { } void RadioButton::deselectOthersInGroup() { - if (group_.empty()) return; - + if (group_.empty()) + return; + auto it = radioGroups_.find(group_); if (it != radioGroups_.end()) { for (RadioButton* radio : it->second) { @@ -314,15 +309,12 @@ void RadioButton::deselectOthersInGroup() { } // ComboBox implementation -ComboBox::ComboBox(const std::string& id) - : Widget(id), selectedIndex_(-1) -{ -} +ComboBox::ComboBox(const std::string& id) : Widget(id), selectedIndex_(-1) {} void ComboBox::addItem(const std::string& item, const std::any& userData) { items_.push_back(item); itemData_.push_back(userData); - + if (selectedIndex_ == -1) { selectedIndex_ = 0; } @@ -334,7 +326,7 @@ void ComboBox::removeItem(const std::string& item) { int index = static_cast(it - items_.begin()); items_.erase(it); itemData_.erase(itemData_.begin() + index); - + if (selectedIndex_ == index) { selectedIndex_ = items_.empty() ? -1 : std::min(selectedIndex_, static_cast(items_.size()) - 1); } else if (selectedIndex_ > index) { @@ -352,7 +344,7 @@ void ComboBox::clearItems() { void ComboBox::setSelectedIndex(int index) { if (index >= -1 && index < static_cast(items_.size()) && index != selectedIndex_) { selectedIndex_ = index; - + if (onSelectionChangedCallback_) { onSelectionChangedCallback_(selectedIndex_, getSelectedItem()); } @@ -368,27 +360,26 @@ void ComboBox::setSelectedItem(const std::string& item) { const std::string& ComboBox::getSelectedItem() const { static const std::string empty; - return (selectedIndex_ >= 0 && selectedIndex_ < static_cast(items_.size())) - ? items_[selectedIndex_] : empty; + return (selectedIndex_ >= 0 && selectedIndex_ < static_cast(items_.size())) ? items_[selectedIndex_] : empty; } void ComboBox::onRender() { #ifdef BOLT_HAVE_IMGUI - const char* currentItem = (selectedIndex_ >= 0 && selectedIndex_ < static_cast(items_.size())) - ? items_[selectedIndex_].c_str() : ""; - + const char* currentItem = + (selectedIndex_ >= 0 && selectedIndex_ < static_cast(items_.size())) ? items_[selectedIndex_].c_str() : ""; + if (ImGui::BeginCombo(getImGuiId().c_str(), currentItem)) { for (int i = 0; i < static_cast(items_.size()); i++) { bool isSelected = (selectedIndex_ == i); if (ImGui::Selectable(items_[i].c_str(), isSelected)) { setSelectedIndex(i); - + WidgetEvent event(WidgetEventType::ValueChanged, this); event.setData("selectedIndex", selectedIndex_); event.setData("selectedItem", getSelectedItem()); fireEvent(event); } - + if (isSelected) { ImGui::SetItemDefaultFocus(); } @@ -404,8 +395,7 @@ Size ComboBox::calculatePreferredSize() const { // Slider implementation Slider::Slider(const std::string& id, float minValue, float maxValue, float value) - : Widget(id), value_(value), minValue_(minValue), maxValue_(maxValue) -{ + : Widget(id), value_(value), minValue_(minValue), maxValue_(maxValue) { value_ = std::clamp(value_, minValue_, maxValue_); } @@ -413,7 +403,7 @@ void Slider::setValue(float value) { float newValue = std::clamp(value, minValue_, maxValue_); if (newValue != value_) { value_ = newValue; - + if (onValueChangedCallback_) { onValueChangedCallback_(value_); } @@ -424,12 +414,12 @@ void Slider::onRender() { #ifdef BOLT_HAVE_IMGUI float oldValue = value_; ImGui::SliderFloat(getImGuiId().c_str(), &value_, minValue_, maxValue_); - + if (value_ != oldValue) { if (onValueChangedCallback_) { onValueChangedCallback_(value_); } - + WidgetEvent event(WidgetEventType::ValueChanged, this); event.setData("value", value_); fireEvent(event); @@ -443,9 +433,7 @@ Size Slider::calculatePreferredSize() const { // ProgressBar implementation ProgressBar::ProgressBar(const std::string& id, float progress) - : Widget(id), progress_(std::clamp(progress, 0.0f, 1.0f)), indeterminate_(false), animationTime_(0.0f) -{ -} + : Widget(id), progress_(std::clamp(progress, 0.0f, 1.0f)), indeterminate_(false), animationTime_(0.0f) {} void ProgressBar::setProgress(float progress) { progress_ = std::clamp(progress, 0.0f, 1.0f); @@ -454,7 +442,7 @@ void ProgressBar::setProgress(float progress) { void ProgressBar::onRender() { #ifdef BOLT_HAVE_IMGUI ImVec2 size(getBounds().size.width, getBounds().size.height); - + if (indeterminate_) { // Animated indeterminate progress float animatedProgress = (sin(animationTime_ * 3.0f) + 1.0f) * 0.5f; @@ -477,9 +465,7 @@ Size ProgressBar::calculatePreferredSize() const { // Panel implementation Panel::Panel(const std::string& id, const std::string& title) - : WidgetContainer(id), title_(title), collapsible_(false), collapsed_(false), scrollbars_(false) -{ -} + : WidgetContainer(id), title_(title), collapsible_(false), collapsed_(false), scrollbars_(false) {} void Panel::onRender() { #ifdef BOLT_HAVE_IMGUI @@ -489,9 +475,9 @@ void Panel::onRender() { } else { flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; } - + bool open = !collapsible_ || !collapsed_; - + if (collapsible_) { if (ImGui::CollapsingHeader(title_.c_str(), &open)) { // Content will be rendered by child widgets @@ -502,13 +488,11 @@ void Panel::onRender() { ImGui::Text("%s", title_.c_str()); ImGui::Separator(); } - - ImGui::BeginChild(getImGuiId().c_str(), - ImVec2(getBounds().size.width, getBounds().size.height), - true, flags); - + + ImGui::BeginChild(getImGuiId().c_str(), ImVec2(getBounds().size.width, getBounds().size.height), true, flags); + // Child widgets will render themselves - + ImGui::EndChild(); } #endif @@ -516,29 +500,26 @@ void Panel::onRender() { Size Panel::calculatePreferredSize() const { Size contentSize = WidgetContainer::calculatePreferredSize(); - + // Add padding and title space float titleHeight = title_.empty() ? 0.0f : 25.0f; return Size(contentSize.width + 20.0f, contentSize.height + titleHeight + 20.0f); } // TabContainer implementation -TabContainer::TabContainer(const std::string& id) - : WidgetContainer(id), activeTab_(-1) -{ -} +TabContainer::TabContainer(const std::string& id) : WidgetContainer(id), activeTab_(-1) {} -void TabContainer::addTab(const std::string& title, std::shared_ptr content, - const std::string& icon, bool closable) { +void TabContainer::addTab(const std::string& title, std::shared_ptr content, const std::string& icon, + bool closable) { TabInfo tab(title, icon, closable); tab.content = content; tabs_.push_back(tab); - + if (content) { addChild(content); - content->setVisible(false); // Initially hide all tabs + content->setVisible(false); // Initially hide all tabs } - + if (activeTab_ == -1) { setActiveTab(0); } @@ -549,15 +530,15 @@ void TabContainer::removeTab(int index) { if (tabs_[index].content) { removeChild(tabs_[index].content); } - + tabs_.erase(tabs_.begin() + index); - + if (activeTab_ == index) { activeTab_ = tabs_.empty() ? -1 : std::min(activeTab_, static_cast(tabs_.size()) - 1); } else if (activeTab_ > index) { activeTab_--; } - + // Update visibility for (int i = 0; i < static_cast(tabs_.size()); ++i) { if (tabs_[i].content) { @@ -582,14 +563,14 @@ void TabContainer::setActiveTab(int index) { if (activeTab_ >= 0 && activeTab_ < static_cast(tabs_.size()) && tabs_[activeTab_].content) { tabs_[activeTab_].content->setVisible(false); } - + activeTab_ = index; - + // Show new tab if (tabs_[activeTab_].content) { tabs_[activeTab_].content->setVisible(true); } - + if (onTabChangedCallback_) { onTabChangedCallback_(activeTab_); } @@ -598,52 +579,51 @@ void TabContainer::setActiveTab(int index) { void TabContainer::onRender() { #ifdef BOLT_HAVE_IMGUI - if (tabs_.empty()) return; - + if (tabs_.empty()) + return; + // Render tab bar if (ImGui::BeginTabBar(getImGuiId().c_str())) { for (int i = 0; i < static_cast(tabs_.size()); ++i) { const auto& tab = tabs_[i]; - + ImGuiTabItemFlags flags = ImGuiTabItemFlags_None; bool open = true; - + std::string tabLabel = tab.icon.empty() ? tab.title : tab.icon + " " + tab.title; - + if (ImGui::BeginTabItem(tabLabel.c_str(), tab.closable ? &open : nullptr, flags)) { if (activeTab_ != i) { setActiveTab(i); } ImGui::EndTabItem(); } - + if (tab.closable && !open) { if (onTabClosedCallback_) { onTabClosedCallback_(i); } removeTab(i); - break; // Avoid iterator invalidation + break; // Avoid iterator invalidation } } ImGui::EndTabBar(); } - + // The active tab content will be rendered by the base Widget::render() #endif } Size TabContainer::calculatePreferredSize() const { Size contentSize = WidgetContainer::calculatePreferredSize(); - + // Add space for tab bar return Size(contentSize.width, contentSize.height + 30.0f); } // Splitter implementation Splitter::Splitter(const std::string& id, Orientation orientation) - : WidgetContainer(id), orientation_(orientation), splitRatio_(0.5f), splitterThickness_(4.0f) -{ -} + : WidgetContainer(id), orientation_(orientation), splitRatio_(0.5f), splitterThickness_(4.0f) {} void Splitter::setSplitRatio(float ratio) { splitRatio_ = std::clamp(ratio, 0.1f, 0.9f); @@ -672,29 +652,29 @@ void Splitter::setSecondWidget(std::shared_ptr widget) { void Splitter::onRender() { #ifdef BOLT_HAVE_IMGUI const Rect& bounds = getBounds(); - + if (orientation_ == Orientation::Horizontal) { float firstWidth = bounds.size.width * splitRatio_; float secondWidth = bounds.size.width - firstWidth - splitterThickness_; - + // First widget if (firstWidget_) { ImGui::BeginChild((getId() + "_first").c_str(), ImVec2(firstWidth, bounds.size.height), true); // Widget will render itself ImGui::EndChild(); } - + ImGui::SameLine(); - + // Splitter ImGui::Button("##splitter", ImVec2(splitterThickness_, bounds.size.height)); if (ImGui::IsItemActive()) { float mouseX = ImGui::GetMousePos().x - bounds.position.x; setSplitRatio(mouseX / bounds.size.width); } - + ImGui::SameLine(); - + // Second widget if (secondWidget_) { ImGui::BeginChild((getId() + "_second").c_str(), ImVec2(secondWidth, bounds.size.height), true); @@ -704,21 +684,21 @@ void Splitter::onRender() { } else { float firstHeight = bounds.size.height * splitRatio_; float secondHeight = bounds.size.height - firstHeight - splitterThickness_; - + // First widget if (firstWidget_) { ImGui::BeginChild((getId() + "_first").c_str(), ImVec2(bounds.size.width, firstHeight), true); // Widget will render itself ImGui::EndChild(); } - + // Splitter ImGui::Button("##splitter", ImVec2(bounds.size.width, splitterThickness_)); if (ImGui::IsItemActive()) { float mouseY = ImGui::GetMousePos().y - bounds.position.y; setSplitRatio(mouseY / bounds.size.height); } - + // Second widget if (secondWidget_) { ImGui::BeginChild((getId() + "_second").c_str(), ImVec2(bounds.size.width, secondHeight), true); @@ -731,15 +711,15 @@ void Splitter::onRender() { void Splitter::onLayout() { const Rect& bounds = getBounds(); - + if (orientation_ == Orientation::Horizontal) { float firstWidth = bounds.size.width * splitRatio_; float secondWidth = bounds.size.width - firstWidth - splitterThickness_; - + if (firstWidget_) { firstWidget_->setBounds(Rect(bounds.position.x, bounds.position.y, firstWidth, bounds.size.height)); } - + if (secondWidget_) { float secondX = bounds.position.x + firstWidth + splitterThickness_; secondWidget_->setBounds(Rect(secondX, bounds.position.y, secondWidth, bounds.size.height)); @@ -747,11 +727,11 @@ void Splitter::onLayout() { } else { float firstHeight = bounds.size.height * splitRatio_; float secondHeight = bounds.size.height - firstHeight - splitterThickness_; - + if (firstWidget_) { firstWidget_->setBounds(Rect(bounds.position.x, bounds.position.y, bounds.size.width, firstHeight)); } - + if (secondWidget_) { float secondY = bounds.position.y + firstHeight + splitterThickness_; secondWidget_->setBounds(Rect(bounds.position.x, secondY, bounds.size.width, secondHeight)); @@ -762,27 +742,23 @@ void Splitter::onLayout() { Size Splitter::calculatePreferredSize() const { Size firstSize(0.0f, 0.0f); Size secondSize(0.0f, 0.0f); - + if (firstWidget_) { firstSize = firstWidget_->calculatePreferredSize(); } - + if (secondWidget_) { secondSize = secondWidget_->calculatePreferredSize(); } - + if (orientation_ == Orientation::Horizontal) { - return Size( - firstSize.width + secondSize.width + splitterThickness_, - std::max(firstSize.height, secondSize.height) - ); + return Size(firstSize.width + secondSize.width + splitterThickness_, + std::max(firstSize.height, secondSize.height)); } else { - return Size( - std::max(firstSize.width, secondSize.width), - firstSize.height + secondSize.height + splitterThickness_ - ); + return Size(std::max(firstSize.width, secondSize.width), + firstSize.height + secondSize.height + splitterThickness_); } } -} // namespace gui -} // namespace bolt \ No newline at end of file +} // namespace gui +} // namespace bolt diff --git a/src/bolt/gui_main.cpp b/src/bolt/gui_main.cpp index 7341efeb..7e5b5d92 100644 --- a/src/bolt/gui_main.cpp +++ b/src/bolt/gui_main.cpp @@ -1,31 +1,31 @@ // gui_main.cpp - Main entry point for Bolt GUI application with AI chat #include + #include "../../include/bolt/gui/bolt_gui_app.hpp" -using namespace bolt::gui; +using namespace bolt::gui; // NOLINT(build/namespaces) int main() { std::cout << "๐Ÿš€ Starting Bolt C++ IDE with AI Chat..." << std::endl; - + try { BoltGuiApp app; - + if (!app.Initialize()) { std::cerr << "โŒ Failed to initialize Bolt GUI application" << std::endl; return 1; } - + std::cout << "โœ… Bolt GUI initialized successfully!" << std::endl; std::cout << "๐Ÿ’ฌ AI Chat ready - type messages and press Enter!" << std::endl; std::cout << "โš™๏ธ Use F1 or menu for AI Settings panel" << std::endl; - + app.Run(); - } catch (const std::exception& e) { std::cerr << "โŒ Error: " << e.what() << std::endl; return 1; } - + std::cout << "๐Ÿ‘‹ Bolt GUI application closed" << std::endl; return 0; } diff --git a/src/bolt/lsp/lsp_manager.cpp b/src/bolt/lsp/lsp_manager.cpp index b4f3df0e..92b2cd66 100644 --- a/src/bolt/lsp/lsp_manager.cpp +++ b/src/bolt/lsp/lsp_manager.cpp @@ -1,6 +1,7 @@ -#include "bolt/lsp/lsp_client.hpp" #include +#include "bolt/lsp/lsp_client.hpp" + namespace bolt { namespace lsp { @@ -12,30 +13,30 @@ void LSPManager::registerServer(const std::string& language_id, const std::strin LSPClient* LSPManager::getClient(const std::string& language_id) { std::lock_guard lock(mutex_); - + auto it = clients_.find(language_id); if (it != clients_.end()) { return it->second.get(); } - + // Try to create client if server is registered auto cmd_it = server_commands_.find(language_id); if (cmd_it == server_commands_.end()) { std::cerr << "No LSP server registered for language: " << language_id << std::endl; return nullptr; } - + // Create new client auto client = std::make_unique(cmd_it->second); auto* client_ptr = client.get(); clients_[language_id] = std::move(client); - + return client_ptr; } void LSPManager::initializeAll(const std::string& root_uri) { std::lock_guard lock(mutex_); - + for (const auto& [language_id, server_command] : server_commands_) { if (clients_.find(language_id) == clients_.end()) { auto client = std::make_unique(server_command); @@ -51,14 +52,14 @@ void LSPManager::initializeAll(const std::string& root_uri) { void LSPManager::shutdownAll() { std::lock_guard lock(mutex_); - + for (auto& [language_id, client] : clients_) { client->shutdown(); std::cout << "Shutdown LSP client for " << language_id << std::endl; } - + clients_.clear(); } -} // namespace lsp -} // namespace bolt +} // namespace lsp +} // namespace bolt diff --git a/src/bolt/network/connection_pool.cpp b/src/bolt/network/connection_pool.cpp index 9fe7cba1..ac32e10f 100644 --- a/src/bolt/network/connection_pool.cpp +++ b/src/bolt/network/connection_pool.cpp @@ -4,17 +4,18 @@ #include #define close closesocket #else -#include -#include #include +#include +#include #include #endif #ifndef _WIN32 #include #endif #include -#include + #include +#include namespace bolt { @@ -31,13 +32,13 @@ ConnectionPool::~ConnectionPool() { std::shared_ptr ConnectionPool::getConnection(const std::string& host, int port) { std::string key = getConnectionKey(host, port); - + { std::lock_guard lock(poolMutex_); auto it = pool_.find(key); if (it != pool_.end()) { auto& connections = it->second; - + // Find an available connection for (auto& conn : connections) { if (!conn->inUse && isConnectionValid(conn)) { @@ -50,61 +51,57 @@ std::shared_ptr ConnectionPool::getConnection(const std::strin } } } - + // Create new connection if none available auto newConn = createConnection(host, port); if (newConn) { std::lock_guard lock(poolMutex_); auto& connections = pool_[key]; - + // Remove expired connections to make room connections.erase( std::remove_if(connections.begin(), connections.end(), - [this](const std::shared_ptr& conn) { - return !isConnectionValid(conn); - }), - connections.end() - ); - + [this](const std::shared_ptr& conn) { return !isConnectionValid(conn); }), + connections.end()); + // Only add if we haven't exceeded the limit if (connections.size() < maxConnectionsPerHost_) { connections.push_back(newConn); } - + stats_.connectionsCreated++; } - + return newConn; } void ConnectionPool::releaseConnection(std::shared_ptr conn) { - if (!conn) return; - + if (!conn) + return; + std::lock_guard lock(poolMutex_); conn->inUse = false; conn->lastUsed = std::chrono::steady_clock::now(); } void ConnectionPool::closeConnection(std::shared_ptr conn) { - if (!conn) return; - + if (!conn) + return; + if (conn->socket >= 0) { close(conn->socket); conn->socket = -1; stats_.connectionsClosed++; } - + std::string key = getConnectionKey(conn->host, conn->port); std::lock_guard lock(poolMutex_); - + auto it = pool_.find(key); if (it != pool_.end()) { auto& connections = it->second; - connections.erase( - std::remove(connections.begin(), connections.end(), conn), - connections.end() - ); - + connections.erase(std::remove(connections.begin(), connections.end(), conn), connections.end()); + if (connections.empty()) { pool_.erase(it); } @@ -121,7 +118,7 @@ std::shared_ptr ConnectionPool::createConnection(const std::st stats_.errors++; return nullptr; } - + // Set socket to non-blocking for timeout handling #ifdef _WIN32 u_long mode = 1; @@ -130,42 +127,42 @@ std::shared_ptr ConnectionPool::createConnection(const std::st int flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); #endif - + struct sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(port); inet_pton(AF_INET, host.c_str(), &serverAddr.sin_addr); - + int result = connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)); - + if (result < 0 && errno != EINPROGRESS) { close(sockfd); stats_.errors++; return nullptr; } - + // Handle connection timeout if (errno == EINPROGRESS) { fd_set writeSet; FD_ZERO(&writeSet); FD_SET(sockfd, &writeSet); - + struct timeval timeout; timeout.tv_sec = connectionTimeout_.count(); timeout.tv_usec = 0; - + result = select(sockfd + 1, nullptr, &writeSet, nullptr, &timeout); if (result <= 0) { close(sockfd); stats_.timeouts++; return nullptr; } - + // Check if connection was successful int error; socklen_t len = sizeof(error); #ifdef _WIN32 - getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (char*)&error, &len); + getsockopt(sockfd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&error), &len); #else getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len); #endif @@ -175,7 +172,7 @@ std::shared_ptr ConnectionPool::createConnection(const std::st return nullptr; } } - + // Set socket back to blocking mode #ifdef _WIN32 u_long blockingMode = 0; @@ -183,15 +180,15 @@ std::shared_ptr ConnectionPool::createConnection(const std::st #else fcntl(sockfd, F_SETFL, flags); #endif - + // Enable keep-alive int keepAlive = 1; #ifdef _WIN32 - setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (char*)&keepAlive, sizeof(keepAlive)); + setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast(&keepAlive), sizeof(keepAlive)); #else setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(keepAlive)); #endif - + auto conn = std::make_shared(sockfd, host, port); conn->inUse = true; return conn; @@ -201,14 +198,14 @@ bool ConnectionPool::isConnectionValid(const std::shared_ptr& if (!conn || conn->socket < 0) { return false; } - + auto now = std::chrono::steady_clock::now(); auto idleTime = std::chrono::duration_cast(now - conn->lastUsed); - + if (idleTime > maxIdleTime_) { return false; } - + // Test socket validity with non-blocking send char testByte = 0; #ifdef _WIN32 @@ -226,25 +223,23 @@ std::string ConnectionPool::getConnectionKey(const std::string& host, int port) void ConnectionPool::cleanupExpiredConnections() { std::lock_guard lock(poolMutex_); - + for (auto it = pool_.begin(); it != pool_.end();) { auto& connections = it->second; - - connections.erase( - std::remove_if(connections.begin(), connections.end(), - [this](const std::shared_ptr& conn) { - if (!isConnectionValid(conn)) { - if (conn->socket >= 0) { - close(conn->socket); - stats_.connectionsClosed++; - } - return true; - } - return false; - }), - connections.end() - ); - + + connections.erase(std::remove_if(connections.begin(), connections.end(), + [this](const std::shared_ptr& conn) { + if (!isConnectionValid(conn)) { + if (conn->socket >= 0) { + close(conn->socket); + stats_.connectionsClosed++; + } + return true; + } + return false; + }), + connections.end()); + if (connections.empty()) { it = pool_.erase(it); } else { @@ -283,4 +278,4 @@ void ConnectionPool::resetStats() { stats_.errors = 0; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/network/message_compression.cpp b/src/bolt/network/message_compression.cpp index 32e391e5..8f82002b 100644 --- a/src/bolt/network/message_compression.cpp +++ b/src/bolt/network/message_compression.cpp @@ -1,7 +1,8 @@ #include "bolt/network/message_compression.hpp" -#include -#include + #include +#include +#include namespace bolt { @@ -19,24 +20,24 @@ void MessageCompressor::initializeZlib() { if (type_ == CompressionType::NONE) { return; } - + memset(&compressStream_, 0, sizeof(compressStream_)); memset(&decompressStream_, 0, sizeof(decompressStream_)); - + // Initialize compression stream int windowBits = (type_ == CompressionType::GZIP) ? 15 + 16 : 15; if (deflateInit2(&compressStream_, compressionLevel_, Z_DEFLATED, windowBits, 8, Z_DEFAULT_STRATEGY) != Z_OK) { std::cerr << "Failed to initialize compression stream" << std::endl; return; } - + // Initialize decompression stream if (inflateInit2(&decompressStream_, windowBits) != Z_OK) { std::cerr << "Failed to initialize decompression stream" << std::endl; deflateEnd(&compressStream_); return; } - + zlibInitialized_ = true; #else std::cerr << "Warning: zlib support not available, compression disabled" << std::endl; @@ -61,12 +62,12 @@ std::vector MessageCompressor::compress(const std::vector& dat if (type_ == CompressionType::NONE || !shouldCompress(data)) { return data; } - + stats_.totalBytesIn += data.size(); stats_.compressionCalls++; - + std::vector result; - + switch (type_) { case CompressionType::GZIP: result = compressGzip(data.data(), data.size()); @@ -78,7 +79,7 @@ std::vector MessageCompressor::compress(const std::vector& dat result = data; break; } - + stats_.totalBytesOut += result.size(); return result; } @@ -88,33 +89,32 @@ std::vector MessageCompressor::compressGzip(const uint8_t* data, size_t if (!zlibInitialized_) { return std::vector(data, data + size); } - + // Reset compression stream deflateReset(&compressStream_); - + std::vector compressed; - compressed.reserve(size); // Initial guess - + compressed.reserve(size); // Initial guess + compressStream_.next_in = const_cast(data); compressStream_.avail_in = size; - + int flush = Z_FINISH; do { uint8_t buffer[8192]; compressStream_.next_out = buffer; compressStream_.avail_out = sizeof(buffer); - + int result = deflate(&compressStream_, flush); if (result != Z_OK && result != Z_STREAM_END) { // Compression failed, return original data return std::vector(data, data + size); } - + size_t bytesCompressed = sizeof(buffer) - compressStream_.avail_out; compressed.insert(compressed.end(), buffer, buffer + bytesCompressed); - } while (compressStream_.avail_out == 0); - + return compressed; #else // Return original data when zlib is not available @@ -136,9 +136,9 @@ std::vector MessageCompressor::decompressToBytes(const std::vector MessageCompressor::decompressGzip(const uint8_t* data, size if (!zlibInitialized_) { return std::vector(data, data + size); } - + // Reset decompression stream inflateReset(&decompressStream_); - + std::vector decompressed; - decompressed.reserve(size * 4); // Guess expansion ratio - + decompressed.reserve(size * 4); // Guess expansion ratio + decompressStream_.next_in = const_cast(data); decompressStream_.avail_in = size; - + do { uint8_t buffer[8192]; decompressStream_.next_out = buffer; decompressStream_.avail_out = sizeof(buffer); - + int result = inflate(&decompressStream_, Z_NO_FLUSH); if (result != Z_OK && result != Z_STREAM_END) { // Decompression failed, return original data return std::vector(data, data + size); } - + size_t bytesDecompressed = sizeof(buffer) - decompressStream_.avail_out; decompressed.insert(decompressed.end(), buffer, buffer + bytesDecompressed); - } while (decompressStream_.avail_out == 0); - + return decompressed; #else // Return original data when zlib is not available @@ -218,20 +217,21 @@ bool MessageCompressor::shouldCompress(const std::vector& data) const { } bool MessageCompressor::isCompressed(const std::vector& data) { - if (data.size() < 2) return false; - + if (data.size() < 2) + return false; + // Check for GZIP magic number if (data[0] == 0x1f && data[1] == 0x8b) { return true; } - + // Check for DEFLATE (basic heuristic) uint8_t cmf = data[0]; uint8_t flg = data[1]; if ((cmf & 0x0f) == 8 && (cmf >> 4) <= 7 && ((cmf * 256 + flg) % 31) == 0) { return true; } - + return false; } @@ -248,24 +248,23 @@ WebSocketCompression::WebSocketCompression() serverMaxNoContextTakeover_(false), clientMaxNoContextTakeover_(false), minCompressionSize_(256), - minCompressionRatio_(0.8) { -} + minCompressionRatio_(0.8) {} std::vector WebSocketCompression::compressMessage(const std::string& message, bool& compressed) { compressed = false; - + if (message.size() < minCompressionSize_) { return std::vector(message.begin(), message.end()); } - + auto compressedData = compressor_.compress(message); double ratio = static_cast(compressedData.size()) / message.size(); - + if (ratio < minCompressionRatio_) { compressed = true; return compressedData; } - + return std::vector(message.begin(), message.end()); } @@ -273,29 +272,29 @@ std::string WebSocketCompression::decompressMessage(const std::vector& if (!isCompressed) { return std::string(data.begin(), data.end()); } - + return compressor_.decompress(data); } std::string WebSocketCompression::getExtensionOffer() const { std::string offer = "permessage-deflate"; - + if (serverMaxWindowBits_ != 15) { offer += "; server_max_window_bits=" + std::to_string(serverMaxWindowBits_); } - + if (clientMaxWindowBits_ != 15) { offer += "; client_max_window_bits=" + std::to_string(clientMaxWindowBits_); } - + if (serverMaxNoContextTakeover_) { offer += "; server_no_context_takeover"; } - + if (clientMaxNoContextTakeover_) { offer += "; client_no_context_takeover"; } - + return offer; } @@ -304,17 +303,17 @@ bool WebSocketCompression::parseExtensionResponse(const std::string& response) { if (response.find("permessage-deflate") == std::string::npos) { return false; } - + // Parse parameters (simplified implementation) if (response.find("server_no_context_takeover") != std::string::npos) { serverMaxNoContextTakeover_ = true; } - + if (response.find("client_no_context_takeover") != std::string::npos) { clientMaxNoContextTakeover_ = true; } - + return true; } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/network/websocket_server.cpp b/src/bolt/network/websocket_server.cpp index 592330ed..4ce58494 100644 --- a/src/bolt/network/websocket_server.cpp +++ b/src/bolt/network/websocket_server.cpp @@ -5,19 +5,19 @@ #include #define close closesocket #else -#include #include +#include #include #endif -#include #include +#include // Only include OpenSSL if available #ifdef BOLT_HAVE_OPENSSL -#include #include -#include #include +#include +#include #endif #include @@ -29,22 +29,22 @@ std::string WebSocketConnection::generateAcceptKey(const std::string& clientKey) #ifdef BOLT_HAVE_OPENSSL std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string combined = clientKey + magic; - + unsigned char hash[SHA_DIGEST_LENGTH]; SHA1(reinterpret_cast(combined.c_str()), combined.length(), hash); - + BIO* b64 = BIO_new(BIO_f_base64()); BIO* bmem = BIO_new(BIO_s_mem()); b64 = BIO_push(b64, bmem); BIO_write(b64, hash, SHA_DIGEST_LENGTH); BIO_flush(b64); - + BUF_MEM* bptr; BIO_get_mem_ptr(b64, &bptr); - + std::string encoded(bptr->data, bptr->length); encoded.erase(std::remove(encoded.begin(), encoded.end(), '\n'), encoded.end()); - + BIO_free_all(b64); return encoded; #else @@ -52,7 +52,7 @@ std::string WebSocketConnection::generateAcceptKey(const std::string& clientKey) // This is not secure and should only be used for testing std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; std::string combined = clientKey + magic; - + // Simple base64-like encoding as fallback (not secure) std::string encoded; for (char c : combined) { @@ -65,23 +65,24 @@ std::string WebSocketConnection::generateAcceptKey(const std::string& clientKey) bool WebSocketConnection::performHandshake() { char buffer[1024]; int bytes = recv(socket_, buffer, sizeof(buffer) - 1, 0); - if (bytes <= 0) return false; - + if (bytes <= 0) + return false; + buffer[bytes] = '\0'; std::string request(buffer); - + size_t keyStart = request.find("Sec-WebSocket-Key: ") + 19; size_t keyEnd = request.find("\r\n", keyStart); std::string clientKey = request.substr(keyStart, keyEnd - keyStart); - + std::string acceptKey = generateAcceptKey(clientKey); - + std::stringstream response; response << "HTTP/1.1 101 Switching Protocols\r\n" << "Upgrade: websocket\r\n" << "Connection: Upgrade\r\n" << "Sec-WebSocket-Accept: " << acceptKey << "\r\n\r\n"; - + std::string responseStr = response.str(); return ::send(socket_, responseStr.c_str(), responseStr.length(), 0) > 0; } @@ -90,7 +91,7 @@ std::vector WebSocketConnection::createFrame(const std::string& payload std::vector frame; uint8_t firstByte = binary ? 0x82 : 0x81; frame.push_back(firstByte); - + if (payload.length() <= 125) { frame.push_back(payload.length()); } else if (payload.length() <= 65535) { @@ -103,7 +104,7 @@ std::vector WebSocketConnection::createFrame(const std::string& payload frame.push_back((payload.length() >> (i * 8)) & 0xFF); } } - + frame.insert(frame.end(), payload.begin(), payload.end()); return frame; } @@ -180,19 +181,20 @@ void WebSocketServer::start(int port) { } std::vector WebSocketServer::parseFrame(const std::vector& buffer, bool& isBinary) { - if (buffer.size() < 2) return {}; - + if (buffer.size() < 2) + return {}; + uint8_t firstByte = buffer[0]; uint8_t secondByte = buffer[1]; - + bool fin = (firstByte & 0x80) != 0; - (void)fin; // Suppress unused variable warning + (void)fin; // Suppress unused variable warning uint8_t opcode = firstByte & 0x0F; bool masked = (secondByte & 0x80) != 0; uint64_t payloadLen = secondByte & 0x7F; - + isBinary = (opcode == 0x02); - + size_t headerLen = 2; if (payloadLen == 126) { headerLen += 2; @@ -204,12 +206,12 @@ std::vector WebSocketServer::parseFrame(const std::vector& buf payloadLen = (payloadLen << 8) | buffer[2 + i]; } } - + if (masked) { uint8_t mask[4]; std::copy(buffer.begin() + headerLen, buffer.begin() + headerLen + 4, mask); headerLen += 4; - + std::vector payload(payloadLen); for (size_t i = 0; i < payloadLen; ++i) { payload[i] = buffer[headerLen + i] ^ mask[i % 4]; @@ -223,7 +225,7 @@ std::vector WebSocketServer::parseFrame(const std::vector& buf void WebSocketServer::handleClient(int clientSocket) { std::vector buffer(1024); WebSocketConnection* conn = nullptr; - + { std::lock_guard lock(connectionsMutex_); for (auto c : connections_) { @@ -237,11 +239,12 @@ void WebSocketServer::handleClient(int clientSocket) { while (running_ && conn) { // Cast to char* for cross-platform compatibility (recv expects char*) int bytesRead = recv(clientSocket, reinterpret_cast(buffer.data()), static_cast(buffer.size()), 0); - if (bytesRead <= 0) break; - + if (bytesRead <= 0) + break; + bool isBinary; auto payload = parseFrame(std::vector(buffer.begin(), buffer.begin() + bytesRead), isBinary); - + if (!payload.empty() && messageCallback_) { std::string message(payload.begin(), payload.end()); messageCallback_(message, conn, isBinary); @@ -272,7 +275,7 @@ void WebSocketServer::stop() { close(serverSocket_); serverSocket_ = -1; } - + if (serverThread_.joinable()) { serverThread_.join(); } @@ -285,4 +288,4 @@ void WebSocketServer::stop() { connections_.clear(); } -} // namespace bolt +} // namespace bolt diff --git a/src/bolt/utils/string_utils.cpp b/src/bolt/utils/string_utils.cpp index becb12de..5e3f6364 100644 --- a/src/bolt/utils/string_utils.cpp +++ b/src/bolt/utils/string_utils.cpp @@ -3,4 +3,4 @@ namespace bolt { // All implementation is in the header -} // namespace bolt +} // namespace bolt diff --git a/terminal_chat_direct.cpp b/terminal_chat_direct.cpp index e407ff4b..76327691 100644 --- a/terminal_chat_direct.cpp +++ b/terminal_chat_direct.cpp @@ -1,6 +1,6 @@ +#include #include #include -#include // Include KoboldCpp headers extern "C" { @@ -10,11 +10,12 @@ extern "C" { int main() { std::cout << "๐Ÿš€ Bolt Terminal Chat with KoboldCpp Integration\n"; std::cout << "===============================================\n\n"; - - std::string model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + + std::string model_path = + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; + std::cout << "๐Ÿ“ฅ Preparing to load model: " << model_path << std::endl; - + // Initialize KoboldCpp inputs load_model_inputs inputs = {}; inputs.model_filename = model_path.c_str(); @@ -23,33 +24,34 @@ int main() { inputs.blasthreads = 4; inputs.blasbatchsize = 512; inputs.quiet = false; - + // Detect file format FileFormatExtraMeta meta = {}; FileFormat format = check_file_format(model_path, &meta); - + std::cout << "๐Ÿ“Š Detected format: " << static_cast(format) << std::endl; - + // Load model ModelLoadResult result = gpttype_load_model(inputs, format, meta); - + if (result == ModelLoadResult::SUCCESS) { std::cout << "โœ… Model loaded successfully!" << std::endl; - + // Interactive chat loop std::string input; while (true) { std::cout << "\n> "; std::getline(std::cin, input); - - if (input.empty()) continue; + + if (input.empty()) + continue; if (input == "quit" || input == "exit" || input == "/quit") { break; } - + // Format chat prompt std::string prompt = "You are a helpful AI assistant.\n\nHuman: " + input + "\nAssistant: "; - + // Generate response generation_inputs gen_inputs = {}; gen_inputs.prompt = prompt.c_str(); @@ -59,21 +61,21 @@ int main() { gen_inputs.top_p = 0.9f; gen_inputs.penalty_repeat = 1.1f; gen_inputs.quiet = false; - + generation_outputs outputs = gpttype_generate(gen_inputs); - + if (outputs.status == 1) { std::cout << "๐Ÿค– " << outputs.text << std::endl; } else { std::cout << "โŒ Generation failed" << std::endl; } } - + std::cout << "๐Ÿ‘‹ Goodbye!" << std::endl; } else { std::cout << "โŒ Failed to load model. Result: " << static_cast(result) << std::endl; return 1; } - + return 0; } diff --git a/terminal_chat_kobold.cpp b/terminal_chat_kobold.cpp index 4f31555d..065b9f66 100644 --- a/terminal_chat_kobold.cpp +++ b/terminal_chat_kobold.cpp @@ -1,12 +1,13 @@ +#include // For dynamic loading + +#include #include #include #include -#include // For dynamic loading -#include // KoboldCpp function signatures (from model_adapter.h) struct load_model_inputs { - const char * model_filename = nullptr; + const char* model_filename = nullptr; bool use_mmap = true; bool use_mlock = false; bool use_smartcontext = false; @@ -17,37 +18,37 @@ struct load_model_inputs { int n_batch = 8; int n_keep = 0; bool ignore_eos = false; - const char * memory_f16 = nullptr; + const char* memory_f16 = nullptr; int n_gpu_layers = 0; int n_vocab = 32000; float rope_freq_base = 10000.0f; float rope_freq_scale = 1.0f; bool low_vram = false; bool mul_mat_q = true; - const char * executable_path = nullptr; - const char * debugmode = nullptr; - const char * model_param = nullptr; - const char * lora_filename = nullptr; - const char * lora_base = nullptr; + const char* executable_path = nullptr; + const char* debugmode = nullptr; + const char* model_param = nullptr; + const char* lora_filename = nullptr; + const char* lora_base = nullptr; bool use_mmq = false; int blasbatchsize = 512; int blasthreads = 0; bool use_rowsplit = false; - const char * tensor_split = nullptr; - const char * gpulayers = nullptr; + const char* tensor_split = nullptr; + const char* gpulayers = nullptr; bool noblas = false; bool nommap = false; bool perplexity = false; bool winogrande = false; bool multiple_choice = false; - const char * multiple_choice_tasks = nullptr; + const char* multiple_choice_tasks = nullptr; bool kquants = false; - const char * model_type = nullptr; - const char * multimodal_model = nullptr; + const char* model_type = nullptr; + const char* multimodal_model = nullptr; bool benchmark = false; - const char * forceversion = nullptr; - const char * gpusplit = nullptr; - const char * contextsize = nullptr; + const char* forceversion = nullptr; + const char* gpusplit = nullptr; + const char* contextsize = nullptr; bool ropeconfig = false; float rope_freq_scale_value = 1.0f; float rope_freq_base_value = 10000.0f; @@ -82,29 +83,29 @@ struct generation_inputs { bool penalize_nl = true; int n_batch = 8; int n_threads = -1; - const char *grammar = nullptr; + const char* grammar = nullptr; float guidance_scale = 1.0f; - const char *banned_tokens = nullptr; + const char* banned_tokens = nullptr; bool ignore_eos = false; - const char *prompt = nullptr; + const char* prompt = nullptr; bool quiet = false; - const char *stop_sequence = nullptr; + const char* stop_sequence = nullptr; bool use_default_badwordsids = false; - const char *sampler_order = nullptr; + const char* sampler_order = nullptr; int sampler_len = 6; float dynatemp_range = 0.0f; float dynatemp_exponent = 1.0f; float smoothing_factor = 0.0f; int max_tokens = -1; - const char *images = nullptr; + const char* images = nullptr; bool stream_sse = false; - const char *api_type = nullptr; - const char *genkey = nullptr; + const char* api_type = nullptr; + const char* genkey = nullptr; }; struct generation_outputs { int status = 0; - char text[65536] = {0}; // Large buffer for generated text + char text[65536] = {0}; // Large buffer for generated text }; // Function pointer types @@ -112,49 +113,50 @@ typedef bool (*load_model_func)(load_model_inputs); typedef generation_outputs (*generate_func)(generation_inputs); class KoboldTerminalChat { -private: + private: void* kobold_lib; load_model_func load_model; generate_func generate; std::vector conversation_history; -public: + public: KoboldTerminalChat() : kobold_lib(nullptr), load_model(nullptr), generate(nullptr) {} - + ~KoboldTerminalChat() { if (kobold_lib) { dlclose(kobold_lib); } } - + bool initialize(const std::string& kobold_so_path, const std::string& model_path) { std::cout << "๐Ÿ”„ Loading KoboldCpp library: " << kobold_so_path << std::endl; - + // Load the shared library kobold_lib = dlopen(kobold_so_path.c_str(), RTLD_LAZY); if (!kobold_lib) { std::cerr << "โŒ Cannot load KoboldCpp library: " << dlerror() << std::endl; return false; } - + // Get function pointers (using mangled C++ names from nm output) - load_model = (load_model_func)dlsym(kobold_lib, "_Z18gpttype_load_model17load_model_inputs10FileFormat19FileFormatExtraMeta"); + load_model = (load_model_func)dlsym( + kobold_lib, "_Z18gpttype_load_model17load_model_inputs10FileFormat19FileFormatExtraMeta"); if (!load_model) { std::cerr << "โŒ Cannot find load_model function: " << dlerror() << std::endl; return false; } - + generate = (generate_func)dlsym(kobold_lib, "_Z16gpttype_generate17generation_inputs"); if (!generate) { std::cerr << "โŒ Cannot find gpttype_generate function: " << dlerror() << std::endl; return false; } - + std::cout << "โœ… KoboldCpp library loaded successfully" << std::endl; - + // Load model std::cout << "๐Ÿ“ฅ Loading model: " << model_path << std::endl; - + load_model_inputs inputs = {}; inputs.model_filename = model_path.c_str(); inputs.n_ctx = 4096; @@ -166,21 +168,21 @@ class KoboldTerminalChat { inputs.use_mmap = true; inputs.use_contextshift = true; inputs.usefastforward = true; - + bool success = load_model(inputs); if (!success) { std::cerr << "โŒ Failed to load model" << std::endl; return false; } - + std::cout << "โœ… Model loaded successfully!" << std::endl; return true; } - + std::string chat(const std::string& message) { // Format chat prompt std::string prompt = format_chat_prompt(message); - + generation_inputs inputs = {}; inputs.prompt = prompt.c_str(); inputs.n_predict = 150; @@ -190,31 +192,31 @@ class KoboldTerminalChat { inputs.penalty_repeat = 1.1f; inputs.n_threads = 4; inputs.quiet = false; - + generation_outputs outputs = generate(inputs); - + if (outputs.status == 1) { std::string response(outputs.text); - + // Add to conversation history conversation_history.push_back(message); conversation_history.push_back(response); - + // Keep history manageable if (conversation_history.size() > 10) { conversation_history.erase(conversation_history.begin(), conversation_history.begin() + 2); } - + return response; } - + return "โŒ Generation failed"; } - -private: + + private: std::string format_chat_prompt(const std::string& message) { std::string prompt = "You are a helpful AI assistant specialized in programming and technical topics.\n\n"; - + // Add recent conversation history for (size_t i = 0; i < conversation_history.size(); i += 2) { if (i + 1 < conversation_history.size()) { @@ -222,10 +224,10 @@ class KoboldTerminalChat { prompt += "Assistant: " + conversation_history[i + 1] + "\n\n"; } } - + prompt += "Human: " + message + "\n"; prompt += "Assistant: "; - + return prompt; } }; @@ -233,11 +235,12 @@ class KoboldTerminalChat { int main(int argc, char* argv[]) { std::cout << "๐Ÿš€ Bolt Terminal Chat with Direct GGUF Access\n"; std::cout << "============================================\n\n"; - + // Default paths std::string kobold_so = "/workspaces/bolt-cppml/ggml/kobold.cpp/koboldcpp_default.so"; - std::string model_path = "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; - + std::string model_path = + "/workspaces/bolt-cppml/models/TinyLlama-1.1B-Chat-v1.0-GGUF/tinyllama-1.1b-chat-v1.0.Q3_K_M.gguf"; + // Allow overriding paths if (argc > 1) { model_path = argv[1]; @@ -245,31 +248,32 @@ int main(int argc, char* argv[]) { if (argc > 2) { kobold_so = argv[2]; } - + KoboldTerminalChat chat; - + if (!chat.initialize(kobold_so, model_path)) { std::cerr << "โŒ Failed to initialize chat system" << std::endl; return 1; } - + std::cout << "\n๐Ÿ’ฌ Chat initialized! Type 'quit', 'exit', or '/quit' to end.\n"; std::cout << "Type your message and press Enter:\n\n"; - + std::string input; while (true) { std::cout << "> "; std::getline(std::cin, input); - - if (input.empty()) continue; - + + if (input.empty()) + continue; + if (input == "quit" || input == "exit" || input == "/quit" || input == "/exit") { std::cout << "๐Ÿ‘‹ Goodbye!\n"; break; } - + std::cout << "๐Ÿค– " << chat.chat(input) << "\n\n"; } - + return 0; } diff --git a/test/basic_test.cpp b/test/basic_test.cpp index a7187698..4e0878db 100644 --- a/test/basic_test.cpp +++ b/test/basic_test.cpp @@ -1,18 +1,19 @@ #include + #include "bolt/bolt.hpp" int main() { std::cout << "Running basic Bolt C++ tests..." << std::endl; - + try { // Basic test that the classes can be instantiated bolt::Chat chat; std::cout << "โœ“ Chat class instantiated successfully" << std::endl; - + // Test adding a message bolt::ChatMessage msg(bolt::ChatMessage::Role::User, "Test message"); chat.addMessage(msg); - + auto history = chat.getHistory(); if (history.size() == 1) { std::cout << "โœ“ Chat message added successfully" << std::endl; @@ -20,12 +21,11 @@ int main() { std::cout << "โœ— Chat message not added correctly" << std::endl; return 1; } - + std::cout << "All basic tests passed!" << std::endl; return 0; - } catch (const std::exception& e) { std::cout << "โœ— Test failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test/test_ai_features.cpp b/test/test_ai_features.cpp index ec751106..4e56e53c 100644 --- a/test/test_ai_features.cpp +++ b/test/test_ai_features.cpp @@ -3,24 +3,24 @@ * @brief Comprehensive unit tests for AI features */ -#include -#include -#include -#include -#include -#include +#include "bolt/ai/ai_code_generator.hpp" +#include "bolt/ai/ai_completion_provider.hpp" +#include "bolt/ai/ai_config_manager.hpp" +#include "bolt/ai/ai_refactoring_engine.hpp" +#include "bolt/ai/enhanced_ai_manager.hpp" +#include "bolt/test_framework.hpp" #ifdef BOLT_HAVE_GGML -#include -#include -#include -#include -#include +#include "bolt/ai/bpe_tokenizer.hpp" +#include "bolt/ai/direct_gguf_inference.hpp" +#include "bolt/ai/ggml_loader.hpp" +#include "bolt/ai/gguf_loader.hpp" +#include "bolt/ai/gpu_acceleration.hpp" #endif +#include #include #include -#include using namespace bolt::test; @@ -32,7 +32,7 @@ BOLT_TEST(AIConfig, DefaultConfiguration) { bolt::ai::AIConfigManager config; // Check default values - BOLT_ASSERT(!config.getApiKey().empty() || config.getApiKey().empty()); // May or may not be set + BOLT_ASSERT(!config.getApiKey().empty() || config.getApiKey().empty()); // May or may not be set BOLT_ASSERT(config.getMaxTokens() > 0); BOLT_ASSERT(config.getTemperature() >= 0.0 && config.getTemperature() <= 2.0); } @@ -95,7 +95,7 @@ BOLT_TEST(AIConfig, ConfigSerialization) { BOLT_TEST(AICompletion, ProviderInitialization) { bolt::ai::AICompletionProvider provider; - BOLT_ASSERT(!provider.isInitialized()); // Not initialized until configured + BOLT_ASSERT(!provider.isInitialized()); // Not initialized until configured } BOLT_TEST(AICompletion, CompletionContext) { @@ -125,12 +125,10 @@ BOLT_TEST(AICompletion, CompletionRequest) { BOLT_TEST(AICompletion, CompletionFiltering) { bolt::ai::AICompletionProvider provider; - std::vector items = { - {"printf", "Function", 1.0}, - {"print", "Function", 0.8}, - {"println", "Function", 0.6}, - {"sprintf", "Function", 0.4} - }; + std::vector items = {{"printf", "Function", 1.0}, + {"print", "Function", 0.8}, + {"println", "Function", 0.6}, + {"sprintf", "Function", 0.4}}; auto filtered = provider.filterCompletions(items, "pri", 3); @@ -182,8 +180,7 @@ BOLT_TEST(AICodeGenerator, PromptGeneration) { auto prompt = generator.generatePrompt(request); BOLT_ASSERT(!prompt.empty()); - BOLT_ASSERT(prompt.find("function") != std::string::npos || - prompt.find("add") != std::string::npos); + BOLT_ASSERT(prompt.find("function") != std::string::npos || prompt.find("add") != std::string::npos); } BOLT_TEST(AICodeGenerator, TemplateGeneration) { @@ -455,7 +452,7 @@ BOLT_TEST(GPUAcceleration, BackendSelection) { BOLT_ASSERT(!backends.empty()); } -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML // ============================================ // AI Prompt Engineering Tests @@ -466,8 +463,7 @@ BOLT_TEST(AIPrompt, SystemPromptGeneration) { auto systemPrompt = provider.getSystemPrompt("cpp"); BOLT_ASSERT(!systemPrompt.empty()); - BOLT_ASSERT(systemPrompt.find("C++") != std::string::npos || - systemPrompt.find("code") != std::string::npos); + BOLT_ASSERT(systemPrompt.find("C++") != std::string::npos || systemPrompt.find("code") != std::string::npos); } BOLT_TEST(AIPrompt, ContextFormatting) { diff --git a/test/test_ai_ggml.cpp b/test/test_ai_ggml.cpp index 11ada947..5a52082b 100644 --- a/test/test_ai_ggml.cpp +++ b/test/test_ai_ggml.cpp @@ -1,7 +1,7 @@ -#include "bolt/test_framework.hpp" #include "bolt/ai/ggml.hpp" #include "bolt/ai/ggml_wrapper.hpp" #include "bolt/ai/rwkv_wrapper.hpp" +#include "bolt/test_framework.hpp" using namespace bolt::test; @@ -10,12 +10,12 @@ using namespace bolt::test; #ifdef BOLT_HAVE_GGML BOLT_TEST(GGMLTest, GGMLContextCreation) { - const size_t mem_size = 1024 * 1024; // 1MB - + const size_t mem_size = 1024 * 1024; // 1MB + // Test context creation bolt::GGMLContext context(mem_size); BOLT_ASSERT_TRUE(context.get() != nullptr); - + // Test basic tensor operations auto* tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 100); BOLT_ASSERT_TRUE(tensor != nullptr); @@ -26,18 +26,18 @@ BOLT_TEST(GGMLTest, GGMLContextCreation) { BOLT_TEST(GGMLTest, TensorOperations) { const size_t mem_size = 1024 * 1024; bolt::GGMLContext context(mem_size); - + // Create tensors auto* a = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 10); auto* b = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 10); - + BOLT_ASSERT_TRUE(a != nullptr); BOLT_ASSERT_TRUE(b != nullptr); - + // Test basic operations auto* c = ggml_add(context.get(), a, b); BOLT_ASSERT_TRUE(c != nullptr); - + auto* d = ggml_mul(context.get(), a, b); BOLT_ASSERT_TRUE(d != nullptr); } @@ -45,15 +45,15 @@ BOLT_TEST(GGMLTest, TensorOperations) { BOLT_TEST(GGMLTest, GraphOperations) { const size_t mem_size = 1024 * 1024; bolt::GGMLContext context(mem_size); - + // Create computation graph auto* gf = ggml_new_graph_custom(context.get(), GGML_DEFAULT_GRAPH_SIZE, true); BOLT_ASSERT_TRUE(gf != nullptr); - + // Create simple computation auto* x = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 5); auto* y = ggml_dup(context.get(), x); - + // Build graph ggml_build_forward_expand(gf, y); BOLT_ASSERT_TRUE(gf != nullptr); @@ -64,32 +64,28 @@ BOLT_TEST(GGMLTest, GGMLWrapperBasics) { (void)wrapper; } -#else // !BOLT_HAVE_GGML +#else // !BOLT_HAVE_GGML BOLT_TEST(GGMLTest, GGMLNotAvailable) { // When GGML is not available, GGMLContext should throw - BOLT_ASSERT_THROWS(std::runtime_error, { - bolt::GGMLContext context(1024); - }); + BOLT_ASSERT_THROWS(std::runtime_error, { bolt::GGMLContext context(1024); }); } BOLT_TEST(GGMLTest, GGMLWrapperStub) { auto& wrapper = bolt::GGMLWrapper::getInstance(); // Wrapper should exist but throw on initialize - BOLT_ASSERT_THROWS(bolt::GGMLException, { - wrapper.initialize("nonexistent.gguf"); - }); + BOLT_ASSERT_THROWS(bolt::GGMLException, { wrapper.initialize("nonexistent.gguf"); }); } -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML // RWKV wrapper tests work regardless of GGML availability BOLT_TEST(GGMLTest, RWKVWrapperBasics) { auto& wrapper = bolt::RWKVWrapper::getInstance(); - + // Test that wrapper starts uninitialized BOLT_ASSERT_FALSE(wrapper.isInitialized()); - + // Test basic API accessibility BOLT_ASSERT_EQ(wrapper.getNumLayers(), 2); BOLT_ASSERT_EQ(wrapper.getEmbedDim(), 64); diff --git a/test/test_ai_models.cpp b/test/test_ai_models.cpp index c7d0928e..98e03f04 100644 --- a/test/test_ai_models.cpp +++ b/test/test_ai_models.cpp @@ -1,17 +1,19 @@ -#include "bolt/test_framework.hpp" -#include "bolt/ai/ggml.hpp" -#include "bolt/ai/ggml_wrapper.hpp" -#include "bolt/ai/rwkv_wrapper.hpp" #include + +#include #include #include -#include + +#include "bolt/ai/ggml.hpp" +#include "bolt/ai/ggml_wrapper.hpp" +#include "bolt/ai/rwkv_wrapper.hpp" +#include "bolt/test_framework.hpp" using namespace bolt::test; // Path to test models (relative to test directory) -static const std::string TEST_MODEL_PATH = "test/models/tiny-rwkv-5v1-730K-Q5_0.bin"; -static const std::string EXPECTED_LOGITS_PATH = "test/models/expected-logits-5v1-730K.bin"; +static const char TEST_MODEL_PATH[] = "test/models/tiny-rwkv-5v1-730K-Q5_0.bin"; +static const char EXPECTED_LOGITS_PATH[] = "test/models/expected-logits-5v1-730K.bin"; // ===== Utility Functions ===== @@ -20,11 +22,11 @@ std::vector load_expected_logits(const std::string& path) { if (!file.is_open()) { throw std::runtime_error("Failed to open expected logits file"); } - + file.seekg(0, std::ios::end); size_t size = file.tellg(); file.seekg(0, std::ios::beg); - + std::vector logits(size / sizeof(float)); file.read(reinterpret_cast(logits.data()), size); return logits; @@ -34,7 +36,7 @@ float calculate_logit_difference(const std::vector& expected, const std:: if (expected.size() != actual.size()) { return std::numeric_limits::max(); } - + float sum_diff = 0.0f; for (size_t i = 0; i < expected.size(); ++i) { sum_diff += std::abs(expected[i] - actual[i]); @@ -45,18 +47,18 @@ float calculate_logit_difference(const std::vector& expected, const std:: // ===== GGML Integration Tests ===== BOLT_TEST(AIModels, GGMLBasicTensorOperations) { - const size_t mem_size = 10 * 1024 * 1024; // 10MB + const size_t mem_size = 10 * 1024 * 1024; // 10MB bolt::GGMLContext context(mem_size); - + // Test tensor creation auto* tensor_a = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 1024); auto* tensor_b = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 1024); - + BOLT_ASSERT_NOT_NULL(tensor_a); BOLT_ASSERT_NOT_NULL(tensor_b); BOLT_ASSERT_EQ(ggml_nelements(tensor_a), 1024); BOLT_ASSERT_EQ(tensor_a->type, GGML_TYPE_F32); - + // Test tensor operations auto* result = ggml_add(context.get(), tensor_a, tensor_b); BOLT_ASSERT_NOT_NULL(result); @@ -64,44 +66,44 @@ BOLT_TEST(AIModels, GGMLBasicTensorOperations) { } BOLT_TEST(AIModels, GGMLMatrixOperations) { - const size_t mem_size = 10 * 1024 * 1024; // 10MB + const size_t mem_size = 10 * 1024 * 1024; // 10MB bolt::GGMLContext context(mem_size); - + // Create 2D tensors for matrix operations auto* matrix_a = ggml_new_tensor_2d(context.get(), GGML_TYPE_F32, 64, 32); auto* matrix_b = ggml_new_tensor_2d(context.get(), GGML_TYPE_F32, 32, 16); - + BOLT_ASSERT_NOT_NULL(matrix_a); BOLT_ASSERT_NOT_NULL(matrix_b); - + // Test matrix multiplication auto* result = ggml_mul_mat(context.get(), matrix_a, matrix_b); BOLT_ASSERT_NOT_NULL(result); - + // Result should be 64x16 BOLT_ASSERT_EQ(result->ne[0], 64); BOLT_ASSERT_EQ(result->ne[1], 16); } BOLT_TEST(AIModels, GGMLComputeGraph) { - const size_t mem_size = 10 * 1024 * 1024; // 10MB + const size_t mem_size = 10 * 1024 * 1024; // 10MB bolt::GGMLContext context(mem_size); - + // Create computation graph auto* gf = ggml_new_graph_custom(context.get(), GGML_DEFAULT_GRAPH_SIZE, true); BOLT_ASSERT_NOT_NULL(gf); - + // Create a simple computation: (a + b) * c auto* a = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 100); auto* b = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 100); auto* c = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 100); - + auto* sum = ggml_add(context.get(), a, b); auto* result = ggml_mul(context.get(), sum, c); - + // Build the forward computation graph ggml_build_forward_expand(gf, result); - + // Just check that the graph is not null and we can perform basic operations BOLT_ASSERT_NOT_NULL(gf); BOLT_ASSERT_NOT_NULL(result); @@ -113,7 +115,7 @@ BOLT_TEST(AIModels, RWKVModelInfo) { // First check if we can get system info (tests library linkage) const char* system_info = rwkv_get_system_info_string(); BOLT_ASSERT_NOT_NULL(system_info); - + // System info should contain some basic information std::string info_str(system_info); BOLT_ASSERT_TRUE(!info_str.empty()); @@ -122,26 +124,26 @@ BOLT_TEST(AIModels, RWKVModelInfo) { BOLT_TEST(AIModels, RWKVModelLoading) { // Silence verbose output during testing rwkv_set_print_errors(nullptr, false); - + // Try to load the tiny RWKV model with correct API (3 parameters: path, threads, gpu_layers) - struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH.c_str(), 1, 0); - + struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH, 1, 0); + if (ctx != nullptr) { // Model loaded successfully - test basic properties size_t state_size = rwkv_get_state_len(ctx); size_t logits_size = rwkv_get_logits_len(ctx); - + BOLT_ASSERT_TRUE(state_size > 0); BOLT_ASSERT_TRUE(logits_size > 0); - + // Test model inference capability std::vector state(state_size); std::vector logits(logits_size); - + // Eval a simple token (token 0) bool success = rwkv_eval(ctx, 0, state.data(), state.data(), logits.data()); BOLT_ASSERT_TRUE(success); - + // Logits should have reasonable values (not all zeros or inf/nan) bool has_valid_logits = false; for (float logit : logits) { @@ -151,7 +153,7 @@ BOLT_TEST(AIModels, RWKVModelLoading) { } } BOLT_ASSERT_TRUE(has_valid_logits); - + rwkv_free(ctx); } else { // Model loading failed - this might be expected if model file doesn't exist @@ -163,39 +165,38 @@ BOLT_TEST(AIModels, RWKVModelLoading) { BOLT_TEST(AIModels, RWKVLogitValidation) { // This test validates that our model produces expected logits // (Only runs if both model and expected logits files exist) - - struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH.c_str(), 1, 0); - + + struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH, 1, 0); + if (ctx != nullptr) { try { auto expected_logits = load_expected_logits(EXPECTED_LOGITS_PATH); - + size_t state_size = rwkv_get_state_len(ctx); size_t logits_size = rwkv_get_logits_len(ctx); - + std::vector state(state_size); std::vector actual_logits(logits_size); - + // Initialize state to zeros std::fill(state.begin(), state.end(), 0.0f); - + // Eval token 0 rwkv_eval(ctx, 0, state.data(), state.data(), actual_logits.data()); - + // Compare with expected logits (allowing for small numerical differences) if (expected_logits.size() == actual_logits.size()) { float difference = calculate_logit_difference(expected_logits, actual_logits); - + // Allow for reasonable numerical differences due to quantization - BOLT_ASSERT_TRUE(difference < 10.0f); // Generous threshold for Q5_0 quantization - + BOLT_ASSERT_TRUE(difference < 10.0f); // Generous threshold for Q5_0 quantization + std::cout << "Logit difference: " << difference << std::endl; } - } catch (const std::exception& e) { std::cerr << "Warning: Could not validate logits: " << e.what() << std::endl; } - + rwkv_free(ctx); } } @@ -204,24 +205,23 @@ BOLT_TEST(AIModels, RWKVLogitValidation) { BOLT_TEST(AIModels, RWKVWrapperIntegration) { auto& wrapper = bolt::RWKVWrapper::getInstance(); - + // Test initial state BOLT_ASSERT_FALSE(wrapper.isInitialized()); - + // Try to initialize with test model try { wrapper.initialize(TEST_MODEL_PATH); - + if (wrapper.isInitialized()) { // Test basic wrapper functionality BOLT_ASSERT_TRUE(wrapper.getNumLayers() >= 1); BOLT_ASSERT_TRUE(wrapper.getEmbedDim() >= 32); - + std::cout << "RWKV model initialized successfully:" << std::endl; std::cout << " Layers: " << wrapper.getNumLayers() << std::endl; std::cout << " Embed dim: " << wrapper.getEmbedDim() << std::endl; } - } catch (const std::exception& e) { std::cerr << "Warning: RWKV wrapper initialization failed: " << e.what() << std::endl; } @@ -230,25 +230,25 @@ BOLT_TEST(AIModels, RWKVWrapperIntegration) { BOLT_TEST(AIModels, ModelMemoryManagement) { // Test that we can create and destroy multiple model contexts without leaks for (int i = 0; i < 3; ++i) { - struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH.c_str(), 1, 0); - + struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH, 1, 0); + if (ctx != nullptr) { // Do minimal work size_t state_size = rwkv_get_state_len(ctx); BOLT_ASSERT_TRUE(state_size > 0); - + rwkv_free(ctx); } } - + // Test GGML context management for (int i = 0; i < 5; ++i) { - const size_t mem_size = 1024 * 1024; // 1MB + const size_t mem_size = 1024 * 1024; // 1MB bolt::GGMLContext context(mem_size); - + auto* tensor = ggml_new_tensor_1d(context.get(), GGML_TYPE_F32, 1000); BOLT_ASSERT_NOT_NULL(tensor); - + // Context destructor should handle cleanup } } @@ -256,33 +256,32 @@ BOLT_TEST(AIModels, ModelMemoryManagement) { // ===== Performance Tests ===== BOLT_TEST(AIModels, ModelInferencePerformance) { - struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH.c_str(), 1, 0); - + struct rwkv_context* ctx = rwkv_init_from_file(TEST_MODEL_PATH, 1, 0); + if (ctx != nullptr) { size_t state_size = rwkv_get_state_len(ctx); size_t logits_size = rwkv_get_logits_len(ctx); - + std::vector state(state_size); std::vector logits(logits_size); - + // Time a series of evaluations auto start = std::chrono::high_resolution_clock::now(); - + const int num_evals = 10; for (int i = 0; i < num_evals; ++i) { rwkv_eval(ctx, i % 256, state.data(), state.data(), logits.data()); } - + auto end = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(end - start); - - std::cout << "Performance: " << num_evals << " evaluations in " - << duration.count() << "ms (" - << (duration.count() / float(num_evals)) << "ms per eval)" << std::endl; - + + std::cout << "Performance: " << num_evals << " evaluations in " << duration.count() << "ms (" + << (duration.count() / static_cast(num_evals)) << "ms per eval)" << std::endl; + // Sanity check - shouldn't take more than 1 second per eval on any reasonable hardware BOLT_ASSERT_TRUE(duration.count() < num_evals * 1000); - + rwkv_free(ctx); } } diff --git a/test/test_bolt_core.cpp b/test/test_bolt_core.cpp index 25821259..a015f7a0 100644 --- a/test/test_bolt_core.cpp +++ b/test/test_bolt_core.cpp @@ -1,15 +1,15 @@ -#include "bolt/test_framework.hpp" #include "bolt/bolt.hpp" -#include "bolt/core/memory_manager.hpp" #include "bolt/core/chat_store.hpp" #include "bolt/core/editor_store.hpp" -#include "bolt/core/workbench_store.hpp" +#include "bolt/core/memory_manager.hpp" #include "bolt/core/message_handler.hpp" -#include "bolt/utils/string_utils.hpp" +#include "bolt/core/workbench_store.hpp" #include "bolt/editor/code_folding.hpp" #include "bolt/editor/code_folding_detector.hpp" #include "bolt/editor/code_folding_manager.hpp" #include "bolt/editor/integrated_editor.hpp" +#include "bolt/test_framework.hpp" +#include "bolt/utils/string_utils.hpp" using namespace bolt::test; @@ -23,9 +23,9 @@ BOLT_TEST(Chat, BasicInstantiation) { BOLT_TEST(Chat, AddSingleMessage) { bolt::Chat chat; bolt::ChatMessage msg(bolt::ChatMessage::Role::User, "Hello"); - + chat.addMessage(msg); - + auto history = chat.getHistory(); BOLT_ASSERT_EQ(1, history.size()); BOLT_ASSERT_EQ("Hello", history[0].getContent()); @@ -34,11 +34,11 @@ BOLT_TEST(Chat, AddSingleMessage) { BOLT_TEST(Chat, AddMultipleMessages) { bolt::Chat chat; - + chat.addMessage(bolt::ChatMessage(bolt::ChatMessage::Role::User, "Hello")); chat.addMessage(bolt::ChatMessage(bolt::ChatMessage::Role::Assistant, "Hi there!")); chat.addMessage(bolt::ChatMessage(bolt::ChatMessage::Role::User, "How are you?")); - + auto history = chat.getHistory(); BOLT_ASSERT_EQ(3, history.size()); BOLT_ASSERT_EQ("Hello", history[0].getContent()); @@ -48,14 +48,14 @@ BOLT_TEST(Chat, AddMultipleMessages) { BOLT_TEST(Chat, ClearHistory) { bolt::Chat chat; - + chat.addMessage(bolt::ChatMessage(bolt::ChatMessage::Role::User, "Hello")); chat.addMessage(bolt::ChatMessage(bolt::ChatMessage::Role::Assistant, "Hi!")); - + BOLT_ASSERT_EQ(2, chat.getHistory().size()); - + chat.clear(); - + BOLT_ASSERT_EQ(0, chat.getHistory().size()); } @@ -63,21 +63,21 @@ BOLT_TEST(Chat, ClearHistory) { BOLT_TEST(ChatMessage, UserMessageCreation) { bolt::ChatMessage msg(bolt::ChatMessage::Role::User, "Test message"); - + BOLT_ASSERT(bolt::ChatMessage::Role::User == msg.getRole()); BOLT_ASSERT_EQ("Test message", msg.getContent()); } BOLT_TEST(ChatMessage, AssistantMessageCreation) { bolt::ChatMessage msg(bolt::ChatMessage::Role::Assistant, "Assistant response"); - + BOLT_ASSERT(bolt::ChatMessage::Role::Assistant == msg.getRole()); BOLT_ASSERT_EQ("Assistant response", msg.getContent()); } BOLT_TEST(ChatMessage, EmptyMessage) { bolt::ChatMessage msg(bolt::ChatMessage::Role::User, ""); - + BOLT_ASSERT(bolt::ChatMessage::Role::User == msg.getRole()); BOLT_ASSERT_EQ("", msg.getContent()); } @@ -87,47 +87,47 @@ BOLT_TEST(ChatMessage, EmptyMessage) { BOLT_TEST(MemoryManager, SingletonInstance) { auto& manager1 = bolt::MemoryManager::getInstance(); auto& manager2 = bolt::MemoryManager::getInstance(); - + BOLT_ASSERT_EQ(&manager1, &manager2); } BOLT_TEST(MemoryManager, AllocateAndDeallocate) { auto& manager = bolt::MemoryManager::getInstance(); - + void* ptr = manager.allocate(1024); BOLT_ASSERT_NOT_NULL(ptr); - + size_t usage_before = manager.getCurrentUsage(); manager.deallocate(ptr); size_t usage_after = manager.getCurrentUsage(); - + BOLT_ASSERT_EQ(usage_before - 1024, usage_after); } BOLT_TEST(MemoryManager, TracksPeakUsage) { auto& manager = bolt::MemoryManager::getInstance(); - manager.reset(); // Start fresh - + manager.reset(); // Start fresh + void* ptr1 = manager.allocate(512); void* ptr2 = manager.allocate(256); - + size_t peak_usage = manager.getPeakUsage(); BOLT_ASSERT_EQ(768, peak_usage); - + manager.deallocate(ptr1); - + // Peak should still be 768 even after deallocation BOLT_ASSERT_EQ(768, manager.getPeakUsage()); - + manager.deallocate(ptr2); } BOLT_TEST(MemoryManager, NullPointerDeallocate) { auto& manager = bolt::MemoryManager::getInstance(); - + // Should not crash manager.deallocate(nullptr); - BOLT_ASSERT_TRUE(true); // If we get here, test passed + BOLT_ASSERT_TRUE(true); // If we get here, test passed } // ===== ChatStore Tests ===== @@ -135,13 +135,13 @@ BOLT_TEST(MemoryManager, NullPointerDeallocate) { BOLT_TEST(ChatStore, SingletonInstance) { auto& store1 = bolt::ChatStore::getInstance(); auto& store2 = bolt::ChatStore::getInstance(); - + BOLT_ASSERT_EQ(&store1, &store2); } BOLT_TEST(ChatStore, DefaultState) { auto& store = bolt::ChatStore::getInstance(); - + BOLT_ASSERT_FALSE(store.getChatStarted()); BOLT_ASSERT_TRUE(store.getShowChat()); BOLT_ASSERT_FALSE(store.getAborted()); @@ -149,30 +149,30 @@ BOLT_TEST(ChatStore, DefaultState) { BOLT_TEST(ChatStore, SetChatStarted) { auto& store = bolt::ChatStore::getInstance(); - + store.setChatStarted(true); BOLT_ASSERT_TRUE(store.getChatStarted()); - + store.setChatStarted(false); BOLT_ASSERT_FALSE(store.getChatStarted()); } BOLT_TEST(ChatStore, SetShowChat) { auto& store = bolt::ChatStore::getInstance(); - + store.setShowChat(false); BOLT_ASSERT_FALSE(store.getShowChat()); - + store.setShowChat(true); BOLT_ASSERT_TRUE(store.getShowChat()); } BOLT_TEST(ChatStore, AddMessage) { auto& store = bolt::ChatStore::getInstance(); - + bolt::SimpleChatMessage msg{"user", "Hello world"}; store.addMessage(msg); - + auto messages = store.getMessages(); BOLT_ASSERT_EQ(1, messages.size()); BOLT_ASSERT_EQ("user", messages[0].sender); @@ -184,36 +184,36 @@ BOLT_TEST(ChatStore, AddMessage) { BOLT_TEST(EditorStore, SingletonInstance) { auto& store1 = bolt::EditorStore::getInstance(); auto& store2 = bolt::EditorStore::getInstance(); - + BOLT_ASSERT_EQ(&store1, &store2); } BOLT_TEST(EditorStore, SetAndGetDocument) { auto& store = bolt::EditorStore::getInstance(); - + bolt::EditorDocument doc; doc.value = "int main() { return 0; }"; doc.filePath = "/path/to/file.cpp"; doc.scroll = {10, 5}; doc.cursor = {42, std::nullopt}; - + store.setDocument("/path/to/file.cpp", doc); - + // Note: EditorStore doesn't have a getDocument method in the header, // so we'll test with getCurrentDocument if selectedFile is set } BOLT_TEST(EditorStore, UpdateScrollPosition) { auto& store = bolt::EditorStore::getInstance(); - + bolt::EditorDocument doc; doc.value = "test content"; doc.filePath = "/test.txt"; - doc.scroll = {0, 0}; // Initialize scroll position - + doc.scroll = {0, 0}; // Initialize scroll position + store.setDocument("/test.txt", doc); store.updateScrollPosition("/test.txt", 15, 20); - + // The method exists and should execute without throwing BOLT_ASSERT_TRUE(true); } @@ -223,43 +223,43 @@ BOLT_TEST(EditorStore, UpdateScrollPosition) { BOLT_TEST(WorkbenchStore, SingletonInstance) { auto& store1 = bolt::WorkbenchStore::getInstance(); auto& store2 = bolt::WorkbenchStore::getInstance(); - + BOLT_ASSERT_EQ(&store1, &store2); } BOLT_TEST(WorkbenchStore, DefaultState) { auto& store = bolt::WorkbenchStore::getInstance(); - + BOLT_ASSERT_FALSE(store.getShowWorkbench()); BOLT_ASSERT_EQ("code", store.getCurrentView()); } BOLT_TEST(WorkbenchStore, SetShowWorkbench) { auto& store = bolt::WorkbenchStore::getInstance(); - + store.setShowWorkbench(true); BOLT_ASSERT_TRUE(store.getShowWorkbench()); - + store.setShowWorkbench(false); BOLT_ASSERT_FALSE(store.getShowWorkbench()); } BOLT_TEST(WorkbenchStore, SetCurrentView) { auto& store = bolt::WorkbenchStore::getInstance(); - + store.setCurrentView("terminal"); BOLT_ASSERT_EQ("terminal", store.getCurrentView()); - + store.setCurrentView("debug"); BOLT_ASSERT_EQ("debug", store.getCurrentView()); } BOLT_TEST(WorkbenchStore, ToggleTerminal) { auto& store = bolt::WorkbenchStore::getInstance(); - + store.toggleTerminal(true); store.toggleTerminal(false); - + // Method should execute without throwing BOLT_ASSERT_TRUE(true); } @@ -269,13 +269,13 @@ BOLT_TEST(WorkbenchStore, ToggleTerminal) { BOLT_TEST(MessageHandler, SingletonInstance) { auto& handler1 = bolt::MessageHandler::getInstance(); auto& handler2 = bolt::MessageHandler::getInstance(); - + BOLT_ASSERT_EQ(&handler1, &handler2); } BOLT_TEST(MessageHandler, Initialize) { auto& handler = bolt::MessageHandler::getInstance(); - + // Should not throw handler.initialize(); BOLT_ASSERT_TRUE(true); @@ -284,9 +284,9 @@ BOLT_TEST(MessageHandler, Initialize) { BOLT_TEST(MessageHandler, PushMessage) { auto& handler = bolt::MessageHandler::getInstance(); handler.initialize(); - + bolt::Message msg(bolt::MessageType::Chat, "Test message"); - + // Should not throw handler.pushMessage(msg); BOLT_ASSERT_TRUE(true); @@ -295,13 +295,13 @@ BOLT_TEST(MessageHandler, PushMessage) { BOLT_TEST(MessageHandler, ProcessMessages) { auto& handler = bolt::MessageHandler::getInstance(); handler.initialize(); - + bolt::Message msg1(bolt::MessageType::Chat, "Hello"); bolt::Message msg2(bolt::MessageType::System, "System message"); - + handler.pushMessage(msg1); handler.pushMessage(msg2); - + // Should not throw handler.processMessages(); BOLT_ASSERT_TRUE(true); @@ -311,14 +311,14 @@ BOLT_TEST(MessageHandler, ProcessMessages) { BOLT_TEST(Message, DefaultConstructor) { bolt::Message msg; - + BOLT_ASSERT(bolt::MessageType::System == msg.type); BOLT_ASSERT_EQ("", msg.content); } BOLT_TEST(Message, ParameterizedConstructor) { bolt::Message msg(bolt::MessageType::Command, "save file"); - + BOLT_ASSERT(bolt::MessageType::Command == msg.type); BOLT_ASSERT_EQ("save file", msg.content); } @@ -347,7 +347,7 @@ BOLT_TEST(StringUtils, CountVowels) { BOLT_ASSERT_EQ(5, StringUtils::countVowels("aeiou")); BOLT_ASSERT_EQ(5, StringUtils::countVowels("AEIOU")); BOLT_ASSERT_EQ(2, StringUtils::countVowels("hello")); - BOLT_ASSERT_EQ(5, StringUtils::countVowels("beautiful")); // b-e-a-u-t-i-f-u-l = e,a,u,i,u = 5 vowels + BOLT_ASSERT_EQ(5, StringUtils::countVowels("beautiful")); // b-e-a-u-t-i-f-u-l = e,a,u,i,u = 5 vowels } // ===== Code Folding Tests ===== @@ -369,10 +369,10 @@ BOLT_TEST(CodeFolding, SingletonInstance) { BOLT_TEST(CodeFolding, AddFoldRange) { auto& folding = bolt::CodeFolding::getInstance(); folding.addFoldRange("/test/file.cpp", 5, 15); - + auto ranges = folding.getFoldingRanges("/test/file.cpp"); BOLT_ASSERT_TRUE(ranges.size() >= 1); - + // Find our added range bool found = false; for (const auto& range : ranges) { @@ -388,7 +388,7 @@ BOLT_TEST(CodeFolding, AddFoldRange) { BOLT_TEST(CodeFolding, ToggleFold) { auto& folding = bolt::CodeFolding::getInstance(); folding.addFoldRange("/test/toggle.cpp", 8, 12); - + // Initially not folded auto ranges = folding.getFoldingRanges("/test/toggle.cpp"); bool initiallyFolded = false; @@ -398,11 +398,11 @@ BOLT_TEST(CodeFolding, ToggleFold) { break; } } - + // Toggle fold folding.toggleFold("/test/toggle.cpp", 10); ranges = folding.getFoldingRanges("/test/toggle.cpp"); - + bool afterToggle = false; for (const auto& range : ranges) { if (range.startLine == 8 && range.endLine == 12) { @@ -410,18 +410,19 @@ BOLT_TEST(CodeFolding, ToggleFold) { break; } } - + BOLT_ASSERT_NE(initiallyFolded, afterToggle); } BOLT_TEST(CodeFoldingDetector, SimpleBraceDetection) { - std::string code = "int main() {\n" - " return 0;\n" - "}\n"; - + std::string code = + "int main() {\n" + " return 0;\n" + "}\n"; + auto ranges = bolt::CodeFoldingDetector::detectFoldableRanges(code); BOLT_ASSERT_TRUE(ranges.size() >= 1); - + // Find the main function fold bool found = false; for (const auto& range : ranges) { @@ -450,13 +451,13 @@ BOLT_TEST(CodeFoldingManager, ManagerSingleton) { BOLT_TEST(CodeFoldingManager, EnableDisableFolding) { auto& manager = bolt::CodeFoldingManager::getInstance(); - + manager.setFoldingEnabled(true); BOLT_ASSERT_TRUE(manager.isFoldingEnabled()); - + manager.setFoldingEnabled(false); BOLT_ASSERT_FALSE(manager.isFoldingEnabled()); - + // Restore default state manager.setFoldingEnabled(true); } @@ -464,11 +465,12 @@ BOLT_TEST(CodeFoldingManager, EnableDisableFolding) { BOLT_TEST(CodeFoldingManager, UpdateFoldingRanges) { auto& manager = bolt::CodeFoldingManager::getInstance(); manager.setFoldingEnabled(true); - - std::string code = "void test() {\n" - " int x = 1;\n" - "}\n"; - + + std::string code = + "void test() {\n" + " int x = 1;\n" + "}\n"; + manager.updateFoldingRanges("/test/manager.cpp", code); auto ranges = manager.getFoldingRanges("/test/manager.cpp"); BOLT_ASSERT_TRUE(ranges.size() >= 1); @@ -482,29 +484,30 @@ BOLT_TEST(IntegratedEditor, EditorSingleton) { BOLT_TEST(IntegratedEditor, OpenDocumentWithFolding) { auto& editor = bolt::IntegratedEditor::getInstance(); - - std::string code = "class TestClass {\n" - "public:\n" - " void method() {\n" - " // code here\n" - " }\n" - "}\n"; - + + std::string code = + "class TestClass {\n" + "public:\n" + " void method() {\n" + " // code here\n" + " }\n" + "}\n"; + editor.openDocument("/test/integrated.cpp", code); - + auto ranges = editor.getFoldingRanges("/test/integrated.cpp"); BOLT_ASSERT_TRUE(ranges.size() >= 1); } BOLT_TEST(IntegratedEditor, FoldingEnabled) { auto& editor = bolt::IntegratedEditor::getInstance(); - + editor.setFoldingEnabled(true); BOLT_ASSERT_TRUE(editor.isFoldingEnabled()); - + editor.setFoldingEnabled(false); BOLT_ASSERT_FALSE(editor.isFoldingEnabled()); - + // Restore default editor.setFoldingEnabled(true); -} \ No newline at end of file +} diff --git a/test/test_code_analyzer.cpp b/test/test_code_analyzer.cpp index dc156dcc..42de144d 100644 --- a/test/test_code_analyzer.cpp +++ b/test/test_code_analyzer.cpp @@ -1,20 +1,21 @@ +#include +#include + #include "bolt/core/code_analyzer.hpp" #include "bolt/test_framework.hpp" -#include -#include using namespace bolt; TEST_CASE("ComplexityAnalyzer basic functionality") { ComplexityAnalyzer analyzer; - + SECTION("supported extensions") { auto extensions = analyzer.getSupportedExtensions(); REQUIRE(!extensions.empty()); REQUIRE(std::find(extensions.begin(), extensions.end(), ".cpp") != extensions.end()); REQUIRE(std::find(extensions.begin(), extensions.end(), ".hpp") != extensions.end()); } - + SECTION("analyze simple code") { std::string simpleCode = R"( #include @@ -28,15 +29,15 @@ class SimpleClass { void method() {} }; )"; - + auto issues = analyzer.analyzeFile("test.cpp", simpleCode); auto metrics = analyzer.getMetrics("test.cpp", simpleCode); - - REQUIRE(metrics.functionCount == 2); // simpleFunction + method + + REQUIRE(metrics.functionCount == 2); // simpleFunction + method REQUIRE(metrics.classCount == 1); REQUIRE(metrics.linesOfCode > 0); } - + SECTION("detect high complexity") { std::string complexCode = R"( void complexFunction(int x) { @@ -60,13 +61,13 @@ void complexFunction(int x) { } } )"; - + auto issues = analyzer.analyzeFile("complex.cpp", complexCode); auto metrics = analyzer.getMetrics("complex.cpp", complexCode); - + REQUIRE(metrics.cyclomaticComplexity > 10); REQUIRE(metrics.nestingDepth > 4); - + // Should have complexity warnings bool hasComplexityIssue = false; for (const auto& issue : issues) { @@ -81,7 +82,7 @@ void complexFunction(int x) { TEST_CASE("SecurityAnalyzer functionality") { SecurityAnalyzer analyzer; - + SECTION("detect unsafe functions") { std::string unsafeCode = R"( #include @@ -94,9 +95,9 @@ void unsafeFunction() { system("rm -rf /"); } )"; - + auto issues = analyzer.analyzeFile("unsafe.cpp", unsafeCode); - + bool hasSecurityIssue = false; for (const auto& issue : issues) { if (issue.category == AnalysisCategory::SECURITY) { @@ -106,7 +107,7 @@ void unsafeFunction() { } REQUIRE(hasSecurityIssue); } - + SECTION("detect potential memory leaks") { std::string leakyCode = R"( void leakyFunction() { @@ -116,10 +117,10 @@ void leakyFunction() { // ptr2 is never deleted - potential leak } )"; - + auto issues = analyzer.analyzeFile("leaky.cpp", leakyCode); auto metrics = analyzer.getMetrics("leaky.cpp", leakyCode); - + // Should detect potential memory leak REQUIRE(metrics.customMetrics.count("memory_leak_risks") > 0); } @@ -127,7 +128,7 @@ void leakyFunction() { TEST_CASE("DependencyAnalyzer functionality") { DependencyAnalyzer analyzer; - + SECTION("extract includes") { std::string codeWithIncludes = R"( #include @@ -137,13 +138,13 @@ TEST_CASE("DependencyAnalyzer functionality") { void function() {} )"; - + auto issues = analyzer.analyzeFile("test.cpp", codeWithIncludes); auto metrics = analyzer.getMetrics("test.cpp", codeWithIncludes); - + REQUIRE(metrics.customMetrics["include_count"] == 4); } - + SECTION("detect too many dependencies") { std::string manyIncludes = R"( #include @@ -170,13 +171,12 @@ void function() {} void function() {} )"; - + auto issues = analyzer.analyzeFile("many_deps.cpp", manyIncludes); - + bool hasDependencyIssue = false; for (const auto& issue : issues) { - if (issue.category == AnalysisCategory::DEPENDENCIES && - issue.id == "TOO_MANY_DEPENDENCIES") { + if (issue.category == AnalysisCategory::DEPENDENCIES && issue.id == "TOO_MANY_DEPENDENCIES") { hasDependencyIssue = true; break; } @@ -187,7 +187,7 @@ void function() {} TEST_CASE("PerformanceAnalyzer functionality") { PerformanceAnalyzer analyzer; - + SECTION("detect performance issues") { std::string slowCode = R"( void inefficientFunction() { @@ -205,9 +205,9 @@ void inefficientFunction() { } } )"; - + auto issues = analyzer.analyzeFile("slow.cpp", slowCode); - + bool hasPerformanceIssue = false; for (const auto& issue : issues) { if (issue.category == AnalysisCategory::PERFORMANCE) { @@ -221,19 +221,19 @@ void inefficientFunction() { TEST_CASE("CodeAnalyzer integration") { CodeAnalyzer analyzer; - + SECTION("register and manage analyzers") { auto analyzers = analyzer.getRegisteredAnalyzers(); - REQUIRE(analyzers.size() >= 4); // Default analyzers - + REQUIRE(analyzers.size() >= 4); // Default analyzers + // Test enabling/disabling analyzer.enableAnalyzer("SecurityAnalyzer", false); REQUIRE(!analyzer.isAnalyzerEnabled("SecurityAnalyzer")); - + analyzer.enableAnalyzer("SecurityAnalyzer", true); REQUIRE(analyzer.isAnalyzerEnabled("SecurityAnalyzer")); } - + SECTION("analyze file with multiple issues") { std::string problematicCode = R"( #include @@ -254,70 +254,70 @@ void problematicFunction(int x) { } } )"; - + // Create temporary file std::string tempFile = "/tmp/test_problematic.cpp"; std::ofstream file(tempFile); file << problematicCode; file.close(); - + auto result = analyzer.analyzeFile(tempFile); - + REQUIRE(!result.issues.empty()); REQUIRE(result.analysisTimeMs > 0); - + // Should have issues from multiple categories bool hasComplexity = result.getIssueCount(AnalysisCategory::COMPLEXITY) > 0; bool hasSecurity = result.getIssueCount(AnalysisCategory::SECURITY) > 0; bool hasPerformance = result.getIssueCount(AnalysisCategory::PERFORMANCE) > 0; - + REQUIRE(hasComplexity || hasSecurity || hasPerformance); - + // Cleanup std::filesystem::remove(tempFile); } - + SECTION("export results") { std::string simpleCode = "void test() {}"; - + std::string tempFile = "/tmp/test_simple.cpp"; std::ofstream file(tempFile); file << simpleCode; file.close(); - + auto result = analyzer.analyzeFile(tempFile); - + // Test JSON export std::string jsonOutput = analyzer.generateReport(result, "json"); REQUIRE(jsonOutput.find("projectPath") != std::string::npos); REQUIRE(jsonOutput.find("totalIssues") != std::string::npos); - + // Test text export std::string textOutput = analyzer.generateReport(result, "text"); REQUIRE(textOutput.find("Code Analysis Report") != std::string::npos); - + // Cleanup std::filesystem::remove(tempFile); } - + SECTION("project analysis") { // Create temporary project std::string projectPath = "/tmp/test_project"; std::filesystem::create_directories(projectPath); - + std::ofstream main_cpp(projectPath + "/main.cpp"); main_cpp << "int main() { return 0; }"; main_cpp.close(); - + std::ofstream utils_hpp(projectPath + "/utils.hpp"); utils_hpp << "#ifndef UTILS_HPP\n#define UTILS_HPP\nvoid util();\n#endif"; utils_hpp.close(); - + auto result = analyzer.analyzeProject(projectPath); - + REQUIRE(result.fileMetrics.size() >= 1); REQUIRE(result.analysisTimeMs > 0); - + // Cleanup std::filesystem::remove_all(projectPath); } @@ -325,7 +325,7 @@ void problematicFunction(int x) { TEST_CASE("RefactoringSuggestionEngine functionality") { RefactoringSuggestionEngine engine; - + SECTION("suggest extract method") { std::string longFunction = R"( void veryLongFunction() { @@ -338,9 +338,9 @@ void veryLongFunction() { std::cout << "Very long function" << std::endl; } )"; - + auto suggestions = engine.generateSuggestionsForFile("long.cpp", longFunction); - + bool hasExtractMethodSuggestion = false; for (const auto& suggestion : suggestions) { if (suggestion.title.find("Extract method") != std::string::npos) { @@ -352,7 +352,7 @@ void veryLongFunction() { } REQUIRE(hasExtractMethodSuggestion); } - + SECTION("suggest reduce complexity") { std::string nestedCode = R"( void nestedFunction() { @@ -365,9 +365,9 @@ void nestedFunction() { } } )"; - + auto suggestions = engine.generateSuggestionsForFile("nested.cpp", nestedCode); - + bool hasComplexitySuggestion = false; for (const auto& suggestion : suggestions) { if (suggestion.title.find("complexity") != std::string::npos) { @@ -377,7 +377,7 @@ void nestedFunction() { } REQUIRE(hasComplexitySuggestion); } - + SECTION("detect code duplication") { std::string duplicatedCode = R"( void function1() { @@ -392,14 +392,14 @@ void function1() { int z = x + y; } )"; - + auto suggestions = engine.generateSuggestionsForFile("dup.cpp", duplicatedCode); - + bool hasDuplicationSuggestion = false; for (const auto& suggestion : suggestions) { if (suggestion.title.find("duplication") != std::string::npos) { hasDuplicationSuggestion = true; - REQUIRE(suggestion.confidenceScore > 0.8); // High confidence for exact duplicates + REQUIRE(suggestion.confidenceScore > 0.8); // High confidence for exact duplicates break; } } @@ -409,39 +409,39 @@ void function1() { TEST_CASE("AnalysisResult utility functions") { AnalysisResult result; - + // Add some test issues AnalysisIssue issue1("TEST1", "Test issue 1", AnalysisSeverity::ERROR, AnalysisCategory::SECURITY); issue1.filePath = "file1.cpp"; - + AnalysisIssue issue2("TEST2", "Test issue 2", AnalysisSeverity::WARNING, AnalysisCategory::PERFORMANCE); issue2.filePath = "file1.cpp"; - + AnalysisIssue issue3("TEST3", "Test issue 3", AnalysisSeverity::ERROR, AnalysisCategory::COMPLEXITY); issue3.filePath = "file2.cpp"; - + result.issues = {issue1, issue2, issue3}; - + SECTION("count by severity") { REQUIRE(result.getIssueCount(AnalysisSeverity::ERROR) == 2); REQUIRE(result.getIssueCount(AnalysisSeverity::WARNING) == 1); REQUIRE(result.getIssueCount(AnalysisSeverity::INFO) == 0); } - + SECTION("count by category") { REQUIRE(result.getIssueCount(AnalysisCategory::SECURITY) == 1); REQUIRE(result.getIssueCount(AnalysisCategory::PERFORMANCE) == 1); REQUIRE(result.getIssueCount(AnalysisCategory::COMPLEXITY) == 1); REQUIRE(result.getIssueCount(AnalysisCategory::MAINTAINABILITY) == 0); } - + SECTION("get issues for file") { auto file1Issues = result.getIssuesForFile("file1.cpp"); auto file2Issues = result.getIssuesForFile("file2.cpp"); auto nonexistentIssues = result.getIssuesForFile("nonexistent.cpp"); - + REQUIRE(file1Issues.size() == 2); REQUIRE(file2Issues.size() == 1); REQUIRE(nonexistentIssues.size() == 0); } -} \ No newline at end of file +} diff --git a/test/test_code_folding.cpp b/test/test_code_folding.cpp index 71f5bfd8..1691eb41 100644 --- a/test/test_code_folding.cpp +++ b/test/test_code_folding.cpp @@ -1,21 +1,22 @@ -#include "bolt/test_framework.hpp" +#include + #include "bolt/editor/code_folding.hpp" #include "bolt/editor/code_folding_detector.hpp" #include "bolt/editor/code_folding_manager.hpp" #include "bolt/editor/integrated_editor.hpp" -#include +#include "bolt/test_framework.hpp" namespace bolt { namespace test { // Helper assertion macros for comparisons -#define BOLT_ASSERT_GE(a, b) \ - do { \ - if (!((a) >= (b))) { \ - std::stringstream ss; \ - ss << "Expected " << (a) << " >= " << (b); \ +#define BOLT_ASSERT_GE(a, b) \ + do { \ + if (!((a) >= (b))) { \ + std::stringstream ss; \ + ss << "Expected " << (a) << " >= " << (b); \ throw bolt::test::TestFailure(ss.str(), __FILE__, __LINE__); \ - } \ + } \ } while (0) // Test fold range creation @@ -66,9 +67,10 @@ BOLT_TEST(CodeFolding, ToggleFold) { // Code Folding Detector tests BOLT_TEST(CodeFoldingDetector, SimpleBraceDetection) { - std::string code = "int main() {\n" - " return 0;\n" - "}\n"; + std::string code = + "int main() {\n" + " return 0;\n" + "}\n"; auto ranges = CodeFoldingDetector::detectFoldableRanges(code); BOLT_ASSERT_GE(ranges.size(), static_cast(1)); @@ -78,17 +80,18 @@ BOLT_TEST(CodeFoldingDetector, SimpleBraceDetection) { } BOLT_TEST(CodeFoldingDetector, NestedBraces) { - std::string code = "class Test {\n" - "public:\n" - " void func() {\n" - " if (true) {\n" - " return;\n" - " }\n" - " }\n" - "}\n"; + std::string code = + "class Test {\n" + "public:\n" + " void func() {\n" + " if (true) {\n" + " return;\n" + " }\n" + " }\n" + "}\n"; auto ranges = CodeFoldingDetector::detectFoldableRanges(code); - BOLT_ASSERT_GE(ranges.size(), static_cast(3)); // Class, function, if statement + BOLT_ASSERT_GE(ranges.size(), static_cast(3)); // Class, function, if statement } BOLT_TEST(CodeFoldingDetector, FoldableRegionDetection) { @@ -119,9 +122,10 @@ BOLT_TEST(CodeFoldingManager, UpdateFoldingRanges) { auto& manager = CodeFoldingManager::getInstance(); manager.setFoldingEnabled(true); - std::string code = "void test() {\n" - " int x = 1;\n" - "}\n"; + std::string code = + "void test() {\n" + " int x = 1;\n" + "}\n"; manager.updateFoldingRanges("/test/manager_cf.cpp", code); auto ranges = manager.getFoldingRanges("/test/manager_cf.cpp"); @@ -132,9 +136,10 @@ BOLT_TEST(CodeFoldingManager, ToggleFold) { auto& manager = CodeFoldingManager::getInstance(); manager.setFoldingEnabled(true); - std::string code = "int func() {\n" - " return 42;\n" - "}\n"; + std::string code = + "int func() {\n" + " return 42;\n" + "}\n"; manager.updateFoldingRanges("/test/toggle_mgr_cf.cpp", code); @@ -161,12 +166,13 @@ BOLT_TEST(IntegratedEditor, Singleton) { BOLT_TEST(IntegratedEditor, OpenDocumentWithFolding) { auto& editor = IntegratedEditor::getInstance(); - std::string code = "class TestClass {\n" - "public:\n" - " void method() {\n" - " // code here\n" - " }\n" - "}\n"; + std::string code = + "class TestClass {\n" + "public:\n" + " void method() {\n" + " // code here\n" + " }\n" + "}\n"; editor.openDocument("/test/integrated_cf.cpp", code); @@ -178,9 +184,10 @@ BOLT_TEST(IntegratedEditor, FoldingOperations) { auto& editor = IntegratedEditor::getInstance(); editor.setFoldingEnabled(true); - std::string code = "namespace test {\n" - " int value = 100;\n" - "}\n"; + std::string code = + "namespace test {\n" + " int value = 100;\n" + "}\n"; editor.openDocument("/test/operations_cf.cpp", code); @@ -203,9 +210,10 @@ BOLT_TEST(IntegratedEditor, UpdateContentRefolding) { auto& editor = IntegratedEditor::getInstance(); std::string originalCode = "int x = 1;\n"; - std::string newCode = "struct Data {\n" - " int value;\n" - "};\n"; + std::string newCode = + "struct Data {\n" + " int value;\n" + "};\n"; editor.openDocument("/test/update_cf.cpp", originalCode); auto originalRanges = editor.getFoldingRanges("/test/update_cf.cpp"); @@ -217,8 +225,8 @@ BOLT_TEST(IntegratedEditor, UpdateContentRefolding) { BOLT_ASSERT_GE(newRanges.size(), static_cast(1)); } -} // namespace test -} // namespace bolt +} // namespace test +} // namespace bolt int main() { return bolt::test::TestSuite::getInstance().runAllTests(); diff --git a/test/test_collaboration.cpp b/test/test_collaboration.cpp index 204271ba..9f1b60b2 100644 --- a/test/test_collaboration.cpp +++ b/test/test_collaboration.cpp @@ -1,53 +1,54 @@ -#include #include -#include #include +#include +#include + +#include "bolt/collaboration/collaborative_editor_integration.hpp" +#include "bolt/collaboration/collaborative_session.hpp" #include "bolt/collaboration/document_operation.hpp" #include "bolt/collaboration/operational_transform.hpp" -#include "bolt/collaboration/collaborative_session.hpp" -#include "bolt/collaboration/collaborative_editor_integration.hpp" using namespace bolt::collaboration; using namespace std::chrono_literals; void testDocumentOperation() { std::cout << "[Collaboration] DocumentOperation Tests\n"; - + // Test basic operation creation Position pos(1, 5); DocumentOperation insertOp(OperationType::INSERT, "user1", pos, "hello"); - + assert(insertOp.getType() == OperationType::INSERT); assert(insertOp.getUserId() == "user1"); assert(insertOp.getPosition() == pos); assert(insertOp.getContent() == "hello"); std::cout << " Basic operation creation ... PASS\n"; - + // Test operation serialization std::string serialized = insertOp.serialize(); assert(!serialized.empty()); assert(serialized.find("\"type\":0") != std::string::npos); assert(serialized.find("\"userId\":\"user1\"") != std::string::npos); std::cout << " Operation serialization ... PASS\n"; - + // Test operation deserialization auto deserializedOp = DocumentOperation::deserialize(serialized); assert(deserializedOp->getType() == OperationType::INSERT); assert(deserializedOp->getUserId() == "user1"); assert(deserializedOp->getContent() == "hello"); std::cout << " Operation deserialization ... PASS\n"; - + // Test inverse operation auto inverseOp = insertOp.createInverse(); assert(inverseOp->getType() == OperationType::DELETE); assert(inverseOp->getContent() == "hello"); std::cout << " Inverse operation ... PASS\n"; - + // Test operation application std::vector lines = {"line1", "line2", "line3"}; Position insertPos(1, 2); DocumentOperation op(OperationType::INSERT, "user1", insertPos, "XXX"); - + bool success = op.apply(lines); assert(success); (void)success; @@ -57,32 +58,32 @@ void testDocumentOperation() { void testOperationalTransform() { std::cout << "[Collaboration] Operational Transform Tests\n"; - + // Test concurrent inserts at same position Position pos(0, 5); DocumentOperation opA(OperationType::INSERT, "userA", pos, "A"); DocumentOperation opB(OperationType::INSERT, "userB", pos, "B"); - + auto transformedA = OperationalTransform::transform(opA, opB); - + // After B is applied, A should be adjusted - assert(transformedA->getPosition().character == 6); // Moved past B's insertion + assert(transformedA->getPosition().character == 6); // Moved past B's insertion std::cout << " Concurrent inserts transformation ... PASS\n"; - + // Test insert vs delete conflict DocumentOperation deleteOp(OperationType::DELETE, "userA", Position(0, 3), "abc"); DocumentOperation insertOp(OperationType::INSERT, "userB", Position(0, 5), "XYZ"); - + auto transformedInsert = OperationalTransform::transform(insertOp, deleteOp); // Delete at pos 3 of "abc" (len 3) covers chars 3-5, insert at 5 is inside deleted range // Insert collapses to delete start position (3) - assert(transformedInsert->getPosition().character == 3); // Collapsed to delete start + assert(transformedInsert->getPosition().character == 3); // Collapsed to delete start std::cout << " Insert vs delete transformation ... PASS\n"; - + // Test same user operations (no transformation) DocumentOperation sameUserOp1(OperationType::INSERT, "user1", pos, "A"); DocumentOperation sameUserOp2(OperationType::INSERT, "user1", pos, "B"); - + auto noTransform = OperationalTransform::transform(sameUserOp1, sameUserOp2); assert(noTransform->getPosition() == sameUserOp1.getPosition()); std::cout << " Same user operations ... PASS\n"; @@ -90,9 +91,9 @@ void testOperationalTransform() { void testCollaborativeSession() { std::cout << "[Collaboration] Collaborative Session Tests\n"; - + auto& session = CollaborativeSession::getInstance(); - + // Test document creation bool created = session.createDocument("test_doc", "Initial content"); assert(created); @@ -107,12 +108,12 @@ void testCollaborativeSession() { assert(joined); (void)joined; std::cout << " User joining ... PASS\n"; - + // Test getting active users auto users = session.getActiveUsers("test_doc"); assert(users.size() == 2); std::cout << " Active users retrieval ... PASS\n"; - + // Test operation application DocumentOperation op(OperationType::INSERT, "user1", Position(0, 7), " - modified"); bool applied = session.applyOperation(op, "test_doc"); @@ -147,20 +148,20 @@ void testCollaborativeSession() { void testEditorIntegration() { std::cout << "[Collaboration] Editor Integration Tests\n"; - + auto& integration = CollaborativeEditorIntegration::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); - + // Create a test document in editor store bolt::EditorDocument testDoc; testDoc.filePath = "/test/collaborative_file.cpp"; testDoc.value = "int main() {\n return 0;\n}"; - testDoc.scroll = {0, 0}; // Initialize scroll position - testDoc.cursor = {0, std::nullopt}; // Initialize cursor - testDoc.foldingRanges.clear(); // Initialize folding ranges - + testDoc.scroll = {0, 0}; // Initialize scroll position + testDoc.cursor = {0, std::nullopt}; // Initialize cursor + testDoc.foldingRanges.clear(); // Initialize folding ranges + editorStore.setDocument(testDoc.filePath, testDoc); - + // Test collaboration stats before initialization auto stats = integration.getStats(); assert(!stats.isServerRunning); @@ -181,15 +182,15 @@ void testEditorIntegration() { // Test cursor position update (should be no-op without collaboration) bool updated = integration.updateCursorPosition(testDoc.filePath, Position(1, 10)); - assert(updated); // Should return true even if it's a no-op + assert(updated); // Should return true even if it's a no-op (void)updated; std::cout << " Cursor position update ... PASS\n"; - + // Test remote cursors (should be empty without collaboration) auto cursors = integration.getRemoteCursors(testDoc.filePath); assert(cursors.empty()); std::cout << " Remote cursors check ... PASS\n"; - + // Test enabling collaboration on non-existent document (should fail) bool enabledFake = integration.enableCollaboration("/non/existent/file.cpp"); assert(!enabledFake); @@ -199,47 +200,44 @@ void testEditorIntegration() { void testConcurrentOperations() { std::cout << "[Collaboration] Concurrent Operations Tests\n"; - + auto& session = CollaborativeSession::getInstance(); - + // Create test document session.createDocument("concurrent_test", "abcdefghijk"); session.joinDocument("userA", "User A", "concurrent_test"); session.joinDocument("userB", "User B", "concurrent_test"); - + // Create concurrent operations std::vector> operations; - operations.push_back(std::make_unique( - OperationType::INSERT, "userA", Position(0, 5), "XXX")); - operations.push_back(std::make_unique( - OperationType::INSERT, "userB", Position(0, 3), "YYY")); - operations.push_back(std::make_unique( - OperationType::DELETE, "userA", Position(0, 7), "gh")); - + operations.push_back(std::make_unique(OperationType::INSERT, "userA", Position(0, 5), "XXX")); + operations.push_back(std::make_unique(OperationType::INSERT, "userB", Position(0, 3), "YYY")); + operations.push_back(std::make_unique(OperationType::DELETE, "userA", Position(0, 7), "gh")); + // Apply operations for (const auto& op : operations) { session.applyOperation(*op, "concurrent_test"); } - + std::string finalContent = session.getDocumentContent("concurrent_test"); assert(!finalContent.empty()); std::cout << " Final content: " << finalContent << "\n"; std::cout << " Concurrent operations application ... PASS\n"; - + // Clean up session.removeDocument("concurrent_test"); } void testPositionConversion() { std::cout << "[Collaboration] Position Conversion Tests\n"; - + std::vector lines = {"hello", "world", "test"}; - + // Test linear conversion Position pos(1, 2); size_t linear = pos.toLinear(lines); - assert(linear == 8); // "hello\n" (6) + "wo" (2) = 8 - + assert(linear == 8); // "hello\n" (6) + "wo" (2) = 8 + Position converted = Position::fromLinear(linear, lines); assert(converted == pos); (void)converted; // Suppress unused variable warning in release builds @@ -257,7 +255,7 @@ void testPositionConversion() { int main() { std::cout << "Bolt C++ Collaborative Editing Test Suite\n"; std::cout << "==========================================\n"; - + try { testDocumentOperation(); testOperationalTransform(); @@ -265,11 +263,11 @@ int main() { testCollaborativeSession(); testConcurrentOperations(); testEditorIntegration(); - + std::cout << "\n==========================================\n"; std::cout << "All collaborative editing tests passed!\n"; std::cout << "Collaborative editing implementation is ready.\n"; - + return 0; } catch (const std::exception& e) { std::cerr << "Test failed with exception: " << e.what() << std::endl; @@ -278,4 +276,4 @@ int main() { std::cerr << "Test failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test/test_e2e.cpp b/test/test_e2e.cpp index 2aff45fc..fdff63a5 100644 --- a/test/test_e2e.cpp +++ b/test/test_e2e.cpp @@ -5,29 +5,29 @@ * Comprehensive E2E tests covering complete workflows and system integration. */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include -#include -#include #include +#include +#include #include +#include "bolt/bolt.hpp" +#include "bolt/collaboration/operational_transform.hpp" +#include "bolt/core/chat_store.hpp" +#include "bolt/core/editor_store.hpp" +#include "bolt/core/logging.hpp" +#include "bolt/core/memory_manager.hpp" +#include "bolt/core/plugin_system.hpp" +#include "bolt/core/workbench_store.hpp" +#include "bolt/editor/code_folding.hpp" +#include "bolt/editor/cursor_manager.hpp" +#include "bolt/editor/keyboard_shortcuts.hpp" +#include "bolt/editor/split_view_manager.hpp" +#include "bolt/editor/tab_bar.hpp" +#include "bolt/editor/theme_system.hpp" +#include "bolt/network/websocket_server.hpp" +#include "bolt/test_framework.hpp" + using namespace bolt::test; // ============================================ @@ -115,7 +115,8 @@ BOLT_TEST(E2E_Workflow, ChatAndEditorIntegration) { // Add messages simulating AI code generation chatStore.addMessage(sessionId, "user", "Generate a hello world function"); - chatStore.addMessage(sessionId, "assistant", "Here's a C++ function:\n```cpp\nvoid hello() { std::cout << \"Hello!\"; }\n```"); + chatStore.addMessage(sessionId, "assistant", + "Here's a C++ function:\n```cpp\nvoid hello() { std::cout << \"Hello!\"; }\n```"); // Open editor with generated code auto fileId = editorStore.createFile("generated.cpp"); @@ -156,7 +157,7 @@ BOLT_TEST(E2E_Memory, LargeFileHandling) { // Verify content was stored auto content = editorStore.getContent(fileId); BOLT_ASSERT(!content.empty()); - BOLT_ASSERT(content.size() > 100000); // Should be > 100KB + BOLT_ASSERT(content.size() > 100000); // Should be > 100KB // Clean up and verify memory is released editorStore.closeFile(fileId); @@ -216,7 +217,7 @@ class MyClass { folding.foldAll(); folding.unfoldAll(); - BOLT_ASSERT(true); // Workflow completed successfully + BOLT_ASSERT(true); // Workflow completed successfully } BOLT_TEST(E2E_Editor, MultiCursorEditing) { @@ -250,9 +251,7 @@ BOLT_TEST(E2E_Editor, KeyboardShortcutExecution) { bool actionExecuted = false; // Register a custom shortcut - shortcuts.registerShortcut("Ctrl+Shift+T", "Test Action", [&]() { - actionExecuted = true; - }); + shortcuts.registerShortcut("Ctrl+Shift+T", "Test Action", [&]() { actionExecuted = true; }); // Execute the shortcut shortcuts.executeShortcut("Ctrl+Shift+T"); @@ -381,13 +380,9 @@ BOLT_TEST(E2E_Plugin, PluginEventSystem) { int eventCount = 0; // Subscribe to plugin events - pluginSystem.onPluginLoaded([&](const std::string& name) { - eventCount++; - }); + pluginSystem.onPluginLoaded([&](const std::string& name) { eventCount++; }); - pluginSystem.onPluginUnloaded([&](const std::string& name) { - eventCount++; - }); + pluginSystem.onPluginUnloaded([&](const std::string& name) { eventCount++; }); // Register and load a plugin bolt::PluginInfo plugin; @@ -454,7 +449,7 @@ BOLT_TEST(E2E_Collaboration, OperationalTransformBasic) { // Create concurrent operations auto op1 = ot.createInsertOperation(5, ", Beautiful"); - auto op2 = ot.createDeleteOperation(6, 5); // Delete "World" + auto op2 = ot.createDeleteOperation(6, 5); // Delete "World" // Transform operations auto transformed = ot.transform(op1, op2); @@ -488,8 +483,7 @@ BOLT_TEST(E2E_Collaboration, ConcurrentEditSimulation) { // Verify final state BOLT_ASSERT(!result.empty()); - BOLT_ASSERT(result.find("// Test function") != std::string::npos || - result.find("42") != std::string::npos); + BOLT_ASSERT(result.find("// Test function") != std::string::npos || result.find("42") != std::string::npos); } // ============================================ @@ -500,7 +494,7 @@ BOLT_TEST(E2E_Network, WebSocketServerStartStop) { bolt::WebSocketServer server; // Configure server - server.setPort(0); // Use any available port + server.setPort(0); // Use any available port server.setMaxConnections(10); // Start server @@ -579,15 +573,15 @@ BOLT_TEST(E2E_ErrorHandling, GracefulDegradation) { // Try to access non-existent file auto content = editorStore.getContent("nonexistent_id"); - BOLT_ASSERT(content.empty()); // Should return empty, not crash + BOLT_ASSERT(content.empty()); // Should return empty, not crash // Try to close non-existent file bool closed = editorStore.closeFile("nonexistent_id"); - BOLT_ASSERT(!closed); // Should return false, not crash + BOLT_ASSERT(!closed); // Should return false, not crash // Try to save non-existent file bool saved = editorStore.saveFile("nonexistent_id"); - BOLT_ASSERT(!saved); // Should return false, not crash + BOLT_ASSERT(!saved); // Should return false, not crash } BOLT_TEST(E2E_ErrorHandling, InvalidInputHandling) { diff --git a/test/test_gguf_loader.cpp b/test/test_gguf_loader.cpp index b9c0f82e..337dc1ff 100644 --- a/test/test_gguf_loader.cpp +++ b/test/test_gguf_loader.cpp @@ -1,7 +1,8 @@ +#include +#include + #include "bolt/ai/gguf_loader.hpp" #include "bolt/test/test_framework.hpp" -#include -#include using namespace bolt; @@ -24,7 +25,7 @@ BOLT_TEST(GGUFLoader, MetadataAccess) { // This test would require a real GGUF file // For now, just verify the API works GGUFLoader loader("test.gguf"); - + // These should not crash even with no file loaded BOLT_ASSERT_FALSE(loader.hasMetadata("test.key")); BOLT_ASSERT_EQUAL(loader.getMetadataString("test.key", "default"), std::string("default")); @@ -34,7 +35,7 @@ BOLT_TEST(GGUFLoader, MetadataAccess) { // Test tensor access BOLT_TEST(GGUFLoader, TensorAccess) { GGUFLoader loader("test.gguf"); - + // Should not crash with no file loaded BOLT_ASSERT_FALSE(loader.hasTensor("test.tensor")); BOLT_ASSERT_EQUAL(loader.getTensorInfo("test.tensor"), nullptr); @@ -44,7 +45,7 @@ BOLT_TEST(GGUFLoader, TensorAccess) { // Test model information extraction BOLT_TEST(GGUFLoader, ModelInformation) { GGUFLoader loader("test.gguf"); - + // Should return 0 for unloaded model BOLT_ASSERT_EQUAL(loader.getNumLayers(), 0); BOLT_ASSERT_EQUAL(loader.getEmbedDim(), 0); @@ -54,9 +55,9 @@ BOLT_TEST(GGUFLoader, ModelInformation) { int main() { std::cout << "Running GGUF Loader tests..." << std::endl; - + // Note: Full integration tests with real GGUF files should be added // when test models are available - + return bolt::test::run_all_tests(); } diff --git a/test/test_git_integration.cpp b/test/test_git_integration.cpp index 8b40ee83..de8e1c63 100644 --- a/test/test_git_integration.cpp +++ b/test/test_git_integration.cpp @@ -1,11 +1,11 @@ -#include #include -#include -#include +#include #include #include +#include +#include #include -#include +#include #include "bolt/git/git.hpp" @@ -13,120 +13,120 @@ * Simple test framework for Git integration */ class GitIntegrationTest { -public: + public: static void runAllTests() { std::cout << "Running Git Integration Tests...\n"; - + testGitRepositoryDetection(); testGitFileStatus(); testGitBranchInfo(); testGitIntegrationManager(); - + std::cout << "All Git integration tests passed!\n"; } -private: + private: static void testGitRepositoryDetection() { std::cout << "Testing Git repository detection...\n"; - + // Test with current repository (should be a Git repo) std::string currentDir = std::filesystem::current_path().string(); bolt::git::GitRepository repo(currentDir); - + // This project should be a Git repository assert(repo.isGitRepository()); - + // Get repository root std::string root = repo.getRepositoryRoot(); assert(!root.empty()); std::cout << "Repository root: " << root << "\n"; - + // Get current branch auto branch = repo.getCurrentBranch(); if (branch) { std::cout << "Current branch: " << *branch << "\n"; } - + std::cout << "โœ“ Git repository detection test passed\n"; } - + static void testGitFileStatus() { std::cout << "Testing Git file status...\n"; - + std::string currentDir = std::filesystem::current_path().string(); bolt::git::GitRepository repo(currentDir); - + if (repo.isGitRepository()) { auto allFiles = repo.getFileStatus(); std::cout << "Found " << allFiles.size() << " files with Git status\n"; - + // Print first few files as examples for (size_t i = 0; i < std::min(size_t(5), allFiles.size()); ++i) { const auto& file = allFiles[i]; std::cout << " " << file.filePath << " - Status: " << static_cast(file.status) << "\n"; } - + // Test checking if repository has uncommitted changes bool hasChanges = repo.hasUncommittedChanges(); std::cout << "Has uncommitted changes: " << (hasChanges ? "yes" : "no") << "\n"; } - + std::cout << "โœ“ Git file status test passed\n"; } - + static void testGitBranchInfo() { std::cout << "Testing Git branch information...\n"; - + std::string currentDir = std::filesystem::current_path().string(); bolt::git::GitRepository repo(currentDir); - + if (repo.isGitRepository()) { auto branches = repo.getBranches(); std::cout << "Found " << branches.size() << " branches\n"; - + for (const auto& branch : branches) { - std::cout << " " << branch.name - << (branch.isCurrent ? " (current)" : "") - << (branch.isRemote ? " (remote)" : "") << "\n"; + std::cout << " " << branch.name << (branch.isCurrent ? " (current)" : "") + << (branch.isRemote ? " (remote)" : "") << "\n"; } - + // Test remote status auto remoteStatus = repo.getRemoteStatus(); if (remoteStatus.hasRemote) { - std::cout << "Remote status - Ahead: " << remoteStatus.ahead - << ", Behind: " << remoteStatus.behind << "\n"; + std::cout << "Remote status - Ahead: " << remoteStatus.ahead << ", Behind: " << remoteStatus.behind + << "\n"; } else { std::cout << "No remote repository configured\n"; } } - + std::cout << "โœ“ Git branch info test passed\n"; } - + static void testGitIntegrationManager() { std::cout << "Testing Git integration manager...\n"; - + auto& gitIntegration = bolt::git::GitIntegration::getInstance(); - + std::string currentDir = std::filesystem::current_path().string(); bool initialized = gitIntegration.initialize(currentDir); - + if (initialized) { std::cout << "Git integration initialized successfully\n"; - + // Test callbacks bool callbackReceived = false; - gitIntegration.setStatusUpdateCallback([&callbackReceived](const std::vector& files) { - std::cout << "Status update callback received with " << files.size() << " files\n"; - callbackReceived = true; - }); - + gitIntegration.setStatusUpdateCallback( + [&callbackReceived](const std::vector& files) { + std::cout << "Status update callback received with " << files.size() << " files\n"; + callbackReceived = true; + }); + // Trigger a status refresh gitIntegration.refreshStatus(); - + // Give some time for async operations std::this_thread::sleep_for(std::chrono::milliseconds(100)); - + // Test repository info auto repoInfo = gitIntegration.getRepositoryInfo(); std::cout << "Repository info:\n"; @@ -136,18 +136,18 @@ class GitIntegrationTest { std::cout << " Staged files: " << repoInfo.stagedFiles << "\n"; std::cout << " Untracked files: " << repoInfo.untrackedFiles << "\n"; std::cout << " Is clean: " << (repoInfo.isClean ? "yes" : "no") << "\n"; - + // Test branch status auto branchStatus = gitIntegration.getBranchStatus(); std::cout << "Branch status:\n"; std::cout << " Current: " << branchStatus.currentBranch << "\n"; std::cout << " Has uncommitted changes: " << (branchStatus.hasUncommittedChanges ? "yes" : "no") << "\n"; - + gitIntegration.shutdown(); } else { std::cout << "Git integration could not be initialized (not a Git repository)\n"; } - + std::cout << "โœ“ Git integration manager test passed\n"; } }; @@ -164,4 +164,4 @@ int main() { std::cerr << "Test failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test/test_gpu_acceleration.cpp b/test/test_gpu_acceleration.cpp index e94a40e5..6b89f041 100644 --- a/test/test_gpu_acceleration.cpp +++ b/test/test_gpu_acceleration.cpp @@ -1,16 +1,17 @@ #include + #include "bolt/ai/gpu_acceleration.hpp" #include "bolt/core/logging.hpp" using namespace bolt::ai; class GPUAccelerationTest : public ::testing::Test { -protected: + protected: void SetUp() override { // Initialize logging bolt::LogManager::configureConsoleLogging(); } - + void TearDown() override { // Clean up GPU manager if initialized auto& gpuManager = GPUAccelerationManager::getInstance(); @@ -23,22 +24,18 @@ class GPUAccelerationTest : public ::testing::Test { TEST_F(GPUAccelerationTest, GPUUtilityFunctions) { // Test GPU availability check bool gpuAvailable = gpu_utils::isGPUAccelerationAvailable(); - EXPECT_TRUE(gpuAvailable || !gpuAvailable); // Should complete without error - + EXPECT_TRUE(gpuAvailable || !gpuAvailable); // Should complete without error + // Test recommended config GPUConfig config = gpu_utils::getRecommendedGPUConfig(); - EXPECT_TRUE(config.preferredBackend == GPUBackendType::CPU || - config.preferredBackend == GPUBackendType::CUDA || - config.preferredBackend == GPUBackendType::OpenCL || - config.preferredBackend == GPUBackendType::Vulkan); - + EXPECT_TRUE(config.preferredBackend == GPUBackendType::CPU || config.preferredBackend == GPUBackendType::CUDA || + config.preferredBackend == GPUBackendType::OpenCL || config.preferredBackend == GPUBackendType::Vulkan); + // Test backend benchmarking GPUBackendType bestBackend = gpu_utils::benchmarkGPUBackends(); - EXPECT_TRUE(bestBackend == GPUBackendType::CPU || - bestBackend == GPUBackendType::CUDA || - bestBackend == GPUBackendType::OpenCL || - bestBackend == GPUBackendType::Vulkan); - + EXPECT_TRUE(bestBackend == GPUBackendType::CPU || bestBackend == GPUBackendType::CUDA || + bestBackend == GPUBackendType::OpenCL || bestBackend == GPUBackendType::Vulkan); + // Test memory estimation size_t memReq = gpu_utils::estimateModelMemoryRequirements("/tmp/mock_model.gguf"); EXPECT_GT(memReq, 0); @@ -46,24 +43,24 @@ TEST_F(GPUAccelerationTest, GPUUtilityFunctions) { TEST_F(GPUAccelerationTest, GPUManagerInitialization) { auto& gpuManager = GPUAccelerationManager::getInstance(); - + // Test initialization GPUConfig config; config.preferredBackend = GPUBackendType::CPU; config.enableAutomaticFallback = true; - + bool initialized = gpuManager.initialize(config); EXPECT_TRUE(initialized); EXPECT_TRUE(gpuManager.isInitialized()); - + // Test re-initialization (should warn but succeed) bool reinit = gpuManager.initialize(config); EXPECT_TRUE(reinit); - + // Test device detection auto devices = gpuManager.detectAvailableDevices(); - EXPECT_GE(devices.size(), 1); // At least CPU should be available - + EXPECT_GE(devices.size(), 1); // At least CPU should be available + // Test that CPU device is present bool cpuFound = false; for (const auto& device : devices) { @@ -73,19 +70,19 @@ TEST_F(GPUAccelerationTest, GPUManagerInitialization) { } } EXPECT_TRUE(cpuFound); - + // Test current device auto currentDevice = gpuManager.getCurrentDevice(); EXPECT_FALSE(currentDevice.name.empty()); - + // Test config management GPUConfig newConfig = config; newConfig.enableMemoryOptimization = false; gpuManager.updateConfig(newConfig); - + auto retrievedConfig = gpuManager.getConfig(); EXPECT_FALSE(retrievedConfig.enableMemoryOptimization); - + // Test shutdown gpuManager.shutdown(); EXPECT_FALSE(gpuManager.isInitialized()); @@ -93,46 +90,46 @@ TEST_F(GPUAccelerationTest, GPUManagerInitialization) { TEST_F(GPUAccelerationTest, DeviceSelection) { auto& gpuManager = GPUAccelerationManager::getInstance(); - + GPUConfig config; config.preferredBackend = GPUBackendType::CPU; - + EXPECT_TRUE(gpuManager.initialize(config)); - + // Test selecting CPU backend (should always work) bool cpuSelected = gpuManager.selectDevice(GPUBackendType::CPU, 0); EXPECT_TRUE(cpuSelected); EXPECT_EQ(gpuManager.getCurrentBackendType(), GPUBackendType::CPU); - + // Test selecting non-existent backends (should fail gracefully) bool cudaSelected = gpuManager.selectDevice(GPUBackendType::CUDA, 0); // This may succeed or fail depending on system - test should not crash - + bool openclSelected = gpuManager.selectDevice(GPUBackendType::OpenCL, 0); // This may succeed or fail depending on system - test should not crash - + bool vulkanSelected = gpuManager.selectDevice(GPUBackendType::Vulkan, 0); // This may succeed or fail depending on system - test should not crash } TEST_F(GPUAccelerationTest, MemoryManager) { auto& gpuManager = GPUAccelerationManager::getInstance(); - + GPUConfig config; config.preferredBackend = GPUBackendType::CPU; - + EXPECT_TRUE(gpuManager.initialize(config)); - + auto& memManager = gpuManager.getMemoryManager(); - + // Test initial memory state size_t initialUsed = memManager.getUsedMemory(); EXPECT_GE(initialUsed, 0); - + // Test memory operations (without actual allocation for now) memManager.optimizeMemoryUsage(); // Should not crash memManager.defragmentMemory(); // Should not crash - + // Memory usage should not have changed significantly size_t afterOptimization = memManager.getUsedMemory(); EXPECT_EQ(initialUsed, afterOptimization); @@ -140,19 +137,19 @@ TEST_F(GPUAccelerationTest, MemoryManager) { TEST_F(GPUAccelerationTest, PerformanceStats) { auto& gpuManager = GPUAccelerationManager::getInstance(); - + GPUConfig config; config.preferredBackend = GPUBackendType::CPU; - + EXPECT_TRUE(gpuManager.initialize(config)); - + // Test initial stats auto stats = gpuManager.getPerformanceStats(); EXPECT_EQ(stats.totalComputeOps, 0); EXPECT_EQ(stats.totalComputeTime, 0.0); EXPECT_EQ(stats.totalMemoryTransfers, 0); EXPECT_EQ(stats.totalTransferTime, 0.0); - + // Reset stats (should not change anything as they're already zero) gpuManager.resetPerformanceStats(); auto resetStats = gpuManager.getPerformanceStats(); @@ -163,28 +160,28 @@ TEST_F(GPUAccelerationTest, GPUAcceleratedModel) { GPUConfig config; config.preferredBackend = GPUBackendType::CPU; config.enableAutomaticFallback = true; - + std::string mockModelPath = "/tmp/mock_model.gguf"; - + // Test model creation GPUAcceleratedModel model(mockModelPath, config); - + // Model should be created but not loaded (no actual file) EXPECT_FALSE(model.isLoaded()); - + // Test configuration model.setMaxContextSize(1024); model.setThreadCount(2); model.enableGPUOffloading(true); - + // Test text generation (should handle unloaded model gracefully) std::string result = model.generate("test prompt", 10); - EXPECT_TRUE(result.empty()); // Should return empty string for unloaded model - + EXPECT_TRUE(result.empty()); // Should return empty string for unloaded model + // Test embedding generation (should handle unloaded model gracefully) auto embedding = model.generateEmbedding("test input"); - EXPECT_TRUE(embedding.empty()); // Should return empty vector for unloaded model - + EXPECT_TRUE(embedding.empty()); // Should return empty vector for unloaded model + // Test performance stats auto stats = model.getPerformanceStats(); // Stats should be accessible even if model is not loaded @@ -194,32 +191,30 @@ TEST_F(GPUAccelerationTest, GPUAccelerationException) { // Test exception creation and retrieval GPUBackendType failedBackend = GPUBackendType::CUDA; std::string message = "Test GPU error"; - + GPUAccelerationException exception(message, failedBackend); - + EXPECT_EQ(std::string(exception.what()), message); EXPECT_EQ(exception.getFailedBackend(), failedBackend); } TEST_F(GPUAccelerationTest, BackendTypeString) { auto& gpuManager = GPUAccelerationManager::getInstance(); - + // Test initialization to access private methods through the manager GPUConfig config; config.preferredBackend = GPUBackendType::CPU; EXPECT_TRUE(gpuManager.initialize(config)); - + // Test device detection which internally uses backendTypeToString auto devices = gpuManager.detectAvailableDevices(); EXPECT_GE(devices.size(), 1); - + // Verify that each device has a valid backend type for (const auto& device : devices) { - EXPECT_TRUE(device.backendType == GPUBackendType::CPU || - device.backendType == GPUBackendType::CUDA || - device.backendType == GPUBackendType::OpenCL || - device.backendType == GPUBackendType::Vulkan || - device.backendType == GPUBackendType::Metal); + EXPECT_TRUE(device.backendType == GPUBackendType::CPU || device.backendType == GPUBackendType::CUDA || + device.backendType == GPUBackendType::OpenCL || device.backendType == GPUBackendType::Vulkan || + device.backendType == GPUBackendType::Metal); } } @@ -233,17 +228,17 @@ TEST_F(GPUAccelerationTest, GPUConfig) { EXPECT_TRUE(defaultConfig.enableMemoryOptimization); EXPECT_TRUE(defaultConfig.enableAsynchronousCompute); EXPECT_GE(defaultConfig.fallbackBackends.size(), 1); - + // Test custom configuration GPUConfig customConfig; customConfig.preferredBackend = GPUBackendType::OpenCL; customConfig.preferredDeviceId = 1; customConfig.enableAutomaticFallback = false; - customConfig.minMemoryRequirement = 512 * 1024 * 1024; // 512MB + customConfig.minMemoryRequirement = 512 * 1024 * 1024; // 512MB customConfig.enableMemoryOptimization = false; customConfig.enableAsynchronousCompute = false; customConfig.fallbackBackends = {GPUBackendType::CPU}; - + EXPECT_EQ(customConfig.preferredBackend, GPUBackendType::OpenCL); EXPECT_EQ(customConfig.preferredDeviceId, 1); EXPECT_FALSE(customConfig.enableAutomaticFallback); @@ -258,33 +253,33 @@ TEST_F(GPUAccelerationTest, GPUConfig) { TEST_F(GPUAccelerationTest, IntegrationTest) { // Get recommended configuration GPUConfig config = gpu_utils::getRecommendedGPUConfig(); - + // Initialize manager auto& gpuManager = GPUAccelerationManager::getInstance(); EXPECT_TRUE(gpuManager.initialize(config)); - + // Detect and verify devices auto devices = gpuManager.detectAvailableDevices(); EXPECT_GE(devices.size(), 1); - + // Create a model with GPU acceleration std::string mockModelPath = "/tmp/integration_test_model.gguf"; GPUAcceleratedModel model(mockModelPath, config); - + // Test that the model was created successfully // (even though it won't load due to missing file) EXPECT_FALSE(model.isLoaded()); - + // Verify performance stats are accessible auto stats = model.getPerformanceStats(); EXPECT_EQ(stats.totalComputeOps, 0); - + // Test memory management auto& memManager = gpuManager.getMemoryManager(); size_t usedMemory = memManager.getUsedMemory(); EXPECT_GE(usedMemory, 0); - + // Clean shutdown gpuManager.shutdown(); EXPECT_FALSE(gpuManager.isInitialized()); -} \ No newline at end of file +} diff --git a/test/test_integration.cpp b/test/test_integration.cpp index 10937039..f2b7f528 100644 --- a/test/test_integration.cpp +++ b/test/test_integration.cpp @@ -1,16 +1,17 @@ -#include "bolt/test_framework.hpp" +#include +#include +#include + #include "bolt/bolt.hpp" -#include "bolt/core/memory_manager.hpp" #include "bolt/core/chat_store.hpp" #include "bolt/core/editor_store.hpp" -#include "bolt/core/workbench_store.hpp" +#include "bolt/core/memory_manager.hpp" #include "bolt/core/message_handler.hpp" +#include "bolt/core/workbench_store.hpp" #include "bolt/editor/code_folding.hpp" #include "bolt/editor/code_folding_manager.hpp" #include "bolt/editor/integrated_editor.hpp" -#include -#include -#include +#include "bolt/test_framework.hpp" using namespace bolt::test; @@ -20,23 +21,23 @@ void resetStoreStates() { (void)bolt::EditorStore::getInstance(); // Access singleton but don't store auto& workbenchStore = bolt::WorkbenchStore::getInstance(); auto& memManager = bolt::MemoryManager::getInstance(); - + // Note: EditorStore doesn't have a clear method, but documents will be overwritten // The test should handle document limits by not exceeding MAX_OPEN_DOCUMENTS (50) - + // Reset chat store chatStore.setChatStarted(false); chatStore.setShowChat(true); chatStore.setAborted(false); - + // Clear any existing messages by getting a reference and clearing it // Since getMessages() returns const reference, we need to work with the store's API // We'll add a large number of dummy messages and then reset - + // Reset workbench store workbenchStore.setShowWorkbench(false); workbenchStore.setCurrentView("code"); - + // Reset memory manager (use forceReset to avoid allocation check) memManager.forceReset(); } @@ -45,59 +46,59 @@ void resetStoreStates() { BOLT_TEST(Integration, BoltAppInitialization) { resetStoreStates(); - + // Test that BoltApp can be initialized and basic state is correct auto& app = bolt::BoltApp::getInstance(); - + // Should not throw during initialization app.initialize(); - + // Verify that core stores are accessible after initialization (void)bolt::ChatStore::getInstance(); (void)bolt::EditorStore::getInstance(); (void)bolt::WorkbenchStore::getInstance(); - BOLT_ASSERT_TRUE(true); // If we get here, initialization worked + BOLT_ASSERT_TRUE(true); // If we get here, initialization worked } BOLT_TEST(Integration, MultiStoreInteractions) { resetStoreStates(); - + // Test interactions between Chat, Editor, and Workbench stores auto& chatStore = bolt::ChatStore::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); auto& workbenchStore = bolt::WorkbenchStore::getInstance(); - + // Start a chat session chatStore.setChatStarted(true); chatStore.setShowChat(true); - + // Add a chat message about editing a file bolt::SimpleChatMessage msg{"user", "Please help me edit main.cpp"}; chatStore.addMessage(msg); - + // Switch workbench to show editor workbenchStore.setShowWorkbench(true); workbenchStore.setCurrentView("code"); - + // Open a document in editor bolt::EditorDocument doc; doc.value = "int main() {\n return 0;\n}"; doc.filePath = "/workspace/main.cpp"; doc.scroll = {0, 0}; doc.cursor = {0, std::nullopt}; - + editorStore.setDocument("/workspace/main.cpp", doc); - + // Verify states are consistent BOLT_ASSERT_TRUE(chatStore.getChatStarted()); BOLT_ASSERT_TRUE(chatStore.getShowChat()); BOLT_ASSERT_TRUE(workbenchStore.getShowWorkbench()); BOLT_ASSERT_EQ("code", workbenchStore.getCurrentView()); - + auto messages = chatStore.getMessages(); - BOLT_ASSERT_TRUE(messages.size() >= 1); // At least our message should be there - + BOLT_ASSERT_TRUE(messages.size() >= 1); // At least our message should be there + // Find our specific message bool foundMessage = false; for (const auto& message : messages) { @@ -113,12 +114,12 @@ BOLT_TEST(Integration, CodeFoldingEditorIntegration) { // Test integration between code folding and editor systems auto& editor = bolt::IntegratedEditor::getInstance(); auto& manager = bolt::CodeFoldingManager::getInstance(); - + // Enable folding manager.setFoldingEnabled(true); editor.setFoldingEnabled(true); - - std::string complexCode = + + std::string complexCode = "class TestClass {\n" "public:\n" " void method1() {\n" @@ -132,17 +133,17 @@ BOLT_TEST(Integration, CodeFoldingEditorIntegration) { " }\n" " }\n" "};\n"; - + // Open document with folding editor.openDocument("/test/complex.cpp", complexCode); - + // Verify folding ranges are detected auto ranges = editor.getFoldingRanges("/test/complex.cpp"); - BOLT_ASSERT_TRUE(ranges.size() >= 3); // Class, method1, method2 at minimum - + BOLT_ASSERT_TRUE(ranges.size() >= 3); // Class, method1, method2 at minimum + // Test folding a range - editor.toggleFold("/test/complex.cpp", 3); // Should fold the if block - + editor.toggleFold("/test/complex.cpp", 3); // Should fold the if block + // Verify fold state changed auto updatedRanges = editor.getFoldingRanges("/test/complex.cpp"); bool foundFoldedRange = false; @@ -157,68 +158,68 @@ BOLT_TEST(Integration, CodeFoldingEditorIntegration) { BOLT_TEST(Integration, MessageHandlerWorkflow) { resetStoreStates(); - + // Test end-to-end message handling workflow auto& handler = bolt::MessageHandler::getInstance(); auto& chatStore = bolt::ChatStore::getInstance(); - + handler.initialize(); - + // Start with clean chat state chatStore.setChatStarted(false); - + // Simulate user starting a chat bolt::Message startMsg(bolt::MessageType::Chat, "Hello, I need help"); handler.pushMessage(startMsg); - + // Process messages handler.processMessages(); - + // Note: The current message handler implementation doesn't automatically // change chat store state, so we manually set it to simulate the workflow chatStore.setChatStarted(true); - + // Simulate system response bolt::Message sysMsg(bolt::MessageType::System, "Chat session initialized"); handler.pushMessage(sysMsg); - + // Process system message handler.processMessages(); - + // Verify chat is now active BOLT_ASSERT_TRUE(chatStore.getChatStarted()); - + // Add more complex command bolt::Message cmdMsg(bolt::MessageType::Command, "open file main.cpp"); handler.pushMessage(cmdMsg); handler.processMessages(); - - BOLT_ASSERT_TRUE(true); // If we reach here, workflow completed + + BOLT_ASSERT_TRUE(true); // If we reach here, workflow completed } BOLT_TEST(Integration, MemoryManagerUnderLoad) { resetStoreStates(); - + // Test memory management during complex operations auto& memManager = bolt::MemoryManager::getInstance(); auto& chatStore = bolt::ChatStore::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); - + // Count existing messages size_t initialMessageCount = chatStore.getMessages().size(); - + // Simulate heavy usage scenario std::vector allocations; - + // Allocate memory for simulated operations (limit to 40 to stay under MAX_OPEN_DOCUMENTS=50) for (int i = 0; i < 40; i++) { - void* ptr = memManager.allocate(1024 + i * 10); // Variable sizes + void* ptr = memManager.allocate(1024 + i * 10); // Variable sizes allocations.push_back(ptr); - + // Add chat messages bolt::SimpleChatMessage msg{"user", "Message " + std::to_string(i)}; chatStore.addMessage(msg); - + // Create editor documents bolt::EditorDocument doc; doc.value = "Content for document " + std::to_string(i); @@ -227,40 +228,40 @@ BOLT_TEST(Integration, MemoryManagerUnderLoad) { doc.cursor = {0, std::nullopt}; editorStore.setDocument(doc.filePath, doc); } - + size_t peakUsage = memManager.getPeakUsage(); - BOLT_ASSERT_TRUE(peakUsage > 40 * 1024); // Should have allocated significant memory - + BOLT_ASSERT_TRUE(peakUsage > 40 * 1024); // Should have allocated significant memory + auto messages = chatStore.getMessages(); BOLT_ASSERT_EQ(initialMessageCount + 40, messages.size()); - + // Clean up memory for (void* ptr : allocations) { memManager.deallocate(ptr); } - + size_t finalUsage = memManager.getCurrentUsage(); - BOLT_ASSERT_TRUE(finalUsage < peakUsage); // Memory should be freed + BOLT_ASSERT_TRUE(finalUsage < peakUsage); // Memory should be freed } BOLT_TEST(Integration, EditorDocumentLifecycle) { resetStoreStates(); - + // Test complete lifecycle of editor document with multiple components auto& editor = bolt::IntegratedEditor::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); auto& workbenchStore = bolt::WorkbenchStore::getInstance(); auto& foldingManager = bolt::CodeFoldingManager::getInstance(); - + // Enable folding foldingManager.setFoldingEnabled(true); editor.setFoldingEnabled(true); - + // Set up workbench for editing workbenchStore.setShowWorkbench(true); workbenchStore.setCurrentView("code"); - - std::string documentContent = + + std::string documentContent = "// C++ File\n" "#include \n" "\n" @@ -272,36 +273,36 @@ BOLT_TEST(Integration, EditorDocumentLifecycle) { " Calculator calc;\n" " return 0;\n" "}\n"; - + const std::string filePath = "/workspace/calculator.cpp"; - + // 1. Open document editor.openDocument(filePath, documentContent); - + // 2. Verify basic integration - editor and workbench state BOLT_ASSERT_TRUE(workbenchStore.getShowWorkbench()); BOLT_ASSERT_EQ("code", workbenchStore.getCurrentView()); - + // 3. Modify document through editor store bolt::EditorDocument doc; doc.value = documentContent + "\n// Modified"; doc.filePath = filePath; doc.scroll = {10, 5}; doc.cursor = {20, std::nullopt}; - + editorStore.setDocument(filePath, doc); - + // 4. Update scroll position - tests editor store integration editorStore.updateScrollPosition(filePath, 15, 8); - - // 5. Verify folding is enabled and working + + // 5. Verify folding is enabled and working BOLT_ASSERT_TRUE(editor.isFoldingEnabled()); BOLT_ASSERT_TRUE(foldingManager.isFoldingEnabled()); - + // 6. Test updating document content through integrated editor std::string newContent = documentContent + "\n// Added by integrated editor"; editor.updateDocumentContent(filePath, newContent); - + // 7. Verify workbench state is still correct after all operations BOLT_ASSERT_TRUE(workbenchStore.getShowWorkbench()); BOLT_ASSERT_EQ("code", workbenchStore.getCurrentView()); @@ -309,35 +310,35 @@ BOLT_TEST(Integration, EditorDocumentLifecycle) { BOLT_TEST(Integration, ChatEditorWorkflow) { resetStoreStates(); - + // Test realistic workflow: user asks for help with code, editor opens file auto& chatStore = bolt::ChatStore::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); auto& workbenchStore = bolt::WorkbenchStore::getInstance(); auto& messageHandler = bolt::MessageHandler::getInstance(); - + messageHandler.initialize(); - + // Count initial messages size_t initialMessageCount = chatStore.getMessages().size(); - + // 1. User starts chat asking for help chatStore.setChatStarted(true); chatStore.setShowChat(true); - + bolt::SimpleChatMessage userMsg{"user", "I need help debugging this C++ function"}; chatStore.addMessage(userMsg); - + // 2. System responds and suggests opening file bolt::SimpleChatMessage assistantMsg{"assistant", "I'd be happy to help! Let me open the file for you."}; chatStore.addMessage(assistantMsg); - + // 3. Switch to code view workbenchStore.setShowWorkbench(true); workbenchStore.setCurrentView("code"); - + // 4. Open problematic code file - std::string buggyCode = + std::string buggyCode = "#include \n" "\n" "int fibonacci(int n) {\n" @@ -352,43 +353,43 @@ BOLT_TEST(Integration, ChatEditorWorkflow) { " std::cout << fibonacci(10) << std::endl;\n" " return 0;\n" "}\n"; - + bolt::EditorDocument doc; doc.value = buggyCode; doc.filePath = "/workspace/fibonacci.cpp"; doc.scroll = {0, 0}; - doc.cursor = {7, std::nullopt}; // Position at the buggy line - + doc.cursor = {7, std::nullopt}; // Position at the buggy line + editorStore.setDocument("/workspace/fibonacci.cpp", doc); - + // 5. Assistant provides feedback in chat bolt::SimpleChatMessage feedbackMsg{"assistant", "I found the issue! Line 8 is missing a 'return' statement."}; chatStore.addMessage(feedbackMsg); - + // 6. Verify the complete workflow state auto messages = chatStore.getMessages(); BOLT_ASSERT_EQ(initialMessageCount + 3, messages.size()); BOLT_ASSERT_TRUE(chatStore.getChatStarted()); BOLT_ASSERT_TRUE(workbenchStore.getShowWorkbench()); BOLT_ASSERT_EQ("code", workbenchStore.getCurrentView()); - + // 7. Verify code is properly loaded BOLT_ASSERT_TRUE(buggyCode.find("fibonacci(n-1) + fibonacci(n-2);") != std::string::npos); - + // 8. User fixes the code std::string fixedCode = buggyCode; size_t pos = fixedCode.find("fibonacci(n-1) + fibonacci(n-2);"); if (pos != std::string::npos) { fixedCode.replace(pos, 32, "return fibonacci(n-1) + fibonacci(n-2);"); } - + doc.value = fixedCode; editorStore.setDocument("/workspace/fibonacci.cpp", doc); - + // 9. Confirm fix in chat bolt::SimpleChatMessage confirmMsg{"user", "Thanks! I added the return statement and it works now."}; chatStore.addMessage(confirmMsg); - + auto finalMessages = chatStore.getMessages(); BOLT_ASSERT_EQ(initialMessageCount + 4, finalMessages.size()); BOLT_ASSERT_TRUE(fixedCode.find("return fibonacci(n-1) + fibonacci(n-2);") != std::string::npos); @@ -396,72 +397,69 @@ BOLT_TEST(Integration, ChatEditorWorkflow) { BOLT_TEST(Integration, MultithreadedOperations) { resetStoreStates(); - + // Test that core components work correctly under simulated concurrent access // Simplified version to avoid segfaults auto& memManager = bolt::MemoryManager::getInstance(); auto& chatStore = bolt::ChatStore::getInstance(); - + // Count initial messages size_t initialMessageCount = chatStore.getMessages().size(); - + // Simulate sequential operations that would happen in a multi-threaded environment // but execute them sequentially to avoid race conditions in the test std::vector allocations; - const int totalOperations = 20; // Reduced for stability - + const int totalOperations = 20; // Reduced for stability + for (int i = 0; i < totalOperations; i++) { // Memory operations void* ptr = memManager.allocate(512 + i * 10); allocations.push_back(ptr); - + // Chat operations - bolt::SimpleChatMessage msg{ - "thread_sim", - "Message " + std::to_string(i) + " from simulated thread operation" - }; + bolt::SimpleChatMessage msg{"thread_sim", "Message " + std::to_string(i) + " from simulated thread operation"}; chatStore.addMessage(msg); - + // Simulate work std::this_thread::sleep_for(std::chrono::microseconds(1)); } - + // Verify operations completed successfully auto messages = chatStore.getMessages(); BOLT_ASSERT_EQ(initialMessageCount + totalOperations, messages.size()); - + // Clean up allocations for (void* ptr : allocations) { memManager.deallocate(ptr); } - + // Memory should be mostly freed size_t finalUsage = memManager.getCurrentUsage(); size_t peakUsage = memManager.getPeakUsage(); - BOLT_ASSERT_TRUE(peakUsage > 0); // Should have tracked peak usage - BOLT_ASSERT_TRUE(finalUsage <= peakUsage); // Current should not exceed peak + BOLT_ASSERT_TRUE(peakUsage > 0); // Should have tracked peak usage + BOLT_ASSERT_TRUE(finalUsage <= peakUsage); // Current should not exceed peak } BOLT_TEST(Integration, SystemShutdownCleanup) { resetStoreStates(); - + // Test proper cleanup during system shutdown simulation auto& memManager = bolt::MemoryManager::getInstance(); auto& chatStore = bolt::ChatStore::getInstance(); auto& editorStore = bolt::EditorStore::getInstance(); auto& workbenchStore = bolt::WorkbenchStore::getInstance(); auto& messageHandler = bolt::MessageHandler::getInstance(); - + // Count initial state size_t initialMessageCount = chatStore.getMessages().size(); - + // Create active chat session chatStore.setChatStarted(true); for (int i = 0; i < 10; i++) { bolt::SimpleChatMessage msg{"user", "Test message " + std::to_string(i)}; chatStore.addMessage(msg); } - + // Create multiple editor documents for (int i = 0; i < 5; i++) { bolt::EditorDocument doc; @@ -469,30 +467,30 @@ BOLT_TEST(Integration, SystemShutdownCleanup) { doc.filePath = "/test/file" + std::to_string(i) + ".cpp"; editorStore.setDocument(doc.filePath, doc); } - + // Set workbench state workbenchStore.setShowWorkbench(true); workbenchStore.setCurrentView("terminal"); - + // Initialize message handler with some messages messageHandler.initialize(); for (int i = 0; i < 5; i++) { bolt::Message msg(bolt::MessageType::System, "System message " + std::to_string(i)); messageHandler.pushMessage(msg); } - + // Verify everything is set up BOLT_ASSERT_TRUE(chatStore.getChatStarted()); BOLT_ASSERT_EQ(initialMessageCount + 10, chatStore.getMessages().size()); BOLT_ASSERT_TRUE(workbenchStore.getShowWorkbench()); - + // Simulate shutdown cleanup // In a real scenario, this would be handled by destructors // Here we just verify current state is consistent - + size_t currentUsage = memManager.getCurrentUsage(); size_t peakUsage = memManager.getPeakUsage(); - + BOLT_ASSERT_TRUE(peakUsage >= currentUsage); - BOLT_ASSERT_TRUE(true); // If we reach here, shutdown simulation passed -} \ No newline at end of file + BOLT_ASSERT_TRUE(true); // If we reach here, shutdown simulation passed +} diff --git a/test/test_keyboard_shortcuts.cpp b/test/test_keyboard_shortcuts.cpp index 733e323d..53256540 100644 --- a/test/test_keyboard_shortcuts.cpp +++ b/test/test_keyboard_shortcuts.cpp @@ -1,13 +1,14 @@ #include #include #include + #include "bolt/editor/keyboard_shortcuts.hpp" using namespace bolt; void test_key_combination_parsing() { std::cout << "[KeyboardShortcuts] KeyCombinationParsing ... "; - + // Test basic key parsing auto combo1 = KeyCombination::fromString("Ctrl+S"); assert(combo1.ctrl == true); @@ -16,7 +17,7 @@ void test_key_combination_parsing() { assert(combo1.meta == false); assert(combo1.key == "S"); assert(combo1.toString() == "Ctrl+S"); - + // Test complex combination auto combo2 = KeyCombination::fromString("Ctrl+Shift+Alt+F1"); assert(combo2.ctrl == true); @@ -25,7 +26,7 @@ void test_key_combination_parsing() { assert(combo2.meta == false); assert(combo2.key == "F1"); assert(combo2.toString() == "Ctrl+Shift+Alt+F1"); - + // Test single key auto combo3 = KeyCombination::fromString("Escape"); assert(combo3.ctrl == false); @@ -34,100 +35,104 @@ void test_key_combination_parsing() { assert(combo3.meta == false); assert(combo3.key == "Escape"); assert(combo3.toString() == "Escape"); - + // Test validity assert(combo1.isValid()); assert(combo2.isValid()); assert(combo3.isValid()); - + KeyCombination empty; assert(!empty.isValid()); - + std::cout << "PASS" << std::endl; } void test_shortcut_registration() { std::cout << "[KeyboardShortcuts] ShortcutRegistration ... "; - + KeyboardShortcuts& mgr = KeyboardShortcuts::getInstance(); - + bool executed = false; - + // Register a shortcut - bool registered = mgr.registerShortcut("Ctrl+T", "test", [&executed]() { executed = true; }, - ShortcutContext::Editor, "Test command"); - assert(registered); (void)registered; - + bool registered = mgr.registerShortcut( + "Ctrl+T", "test", [&executed]() { executed = true; }, ShortcutContext::Editor, "Test command"); + assert(registered); + (void)registered; + // Check if shortcut exists KeyCombination combo = KeyCombination::fromString("Ctrl+T"); assert(mgr.hasShortcut(combo, ShortcutContext::Editor)); - + // Execute shortcut bool result = mgr.executeShortcut("Ctrl+T", ShortcutContext::Editor); - assert(result); (void)result; - assert(executed); (void)executed; - + assert(result); + (void)result; + assert(executed); + (void)executed; + // Unregister shortcut bool unreg = mgr.unregisterShortcut("Ctrl+T", "test", ShortcutContext::Editor); - assert(unreg); (void)unreg; + assert(unreg); + (void)unreg; assert(!mgr.hasShortcut(combo, ShortcutContext::Editor)); - + std::cout << "PASS" << std::endl; } void test_context_management() { std::cout << "[KeyboardShortcuts] ContextManagement ... "; - + auto& mgr = KeyboardShortcuts::getInstance(); - + // Test initial context assert(mgr.getActiveContext() == ShortcutContext::Global); - + // Set context mgr.setActiveContext(ShortcutContext::Editor); assert(mgr.getActiveContext() == ShortcutContext::Editor); - + // Test context stack mgr.pushContext(ShortcutContext::Search); assert(mgr.getActiveContext() == ShortcutContext::Search); - + mgr.popContext(); assert(mgr.getActiveContext() == ShortcutContext::Editor); - + // Register shortcuts in different contexts bool executed1 = false, executed2 = false; - mgr.registerShortcut("F1", "help1", [&executed1]() { executed1 = true; }, - ShortcutContext::Editor, "Editor help"); - mgr.registerShortcut("F1", "help2", [&executed2]() { executed2 = true; }, - ShortcutContext::Search, "Search help"); - + mgr.registerShortcut( + "F1", "help1", [&executed1]() { executed1 = true; }, ShortcutContext::Editor, "Editor help"); + mgr.registerShortcut( + "F1", "help2", [&executed2]() { executed2 = true; }, ShortcutContext::Search, "Search help"); + // Execute in editor context mgr.setActiveContext(ShortcutContext::Editor); assert(mgr.executeShortcut("F1", ShortcutContext::Editor)); assert(executed1 && !executed2); - + // Execute in search context executed1 = executed2 = false; mgr.setActiveContext(ShortcutContext::Search); assert(mgr.executeShortcut("F1", ShortcutContext::Search)); assert(!executed1 && executed2); - + std::cout << "PASS" << std::endl; } void test_shortcut_discovery() { std::cout << "[KeyboardShortcuts] ShortcutDiscovery ... "; - + auto& mgr = KeyboardShortcuts::getInstance(); - + // Register test shortcuts - mgr.registerShortcut("Ctrl+K", "command1", []() {}, - ShortcutContext::Editor, "Command 1"); - mgr.registerShortcut("Ctrl+L", "command2", []() {}, - ShortcutContext::Editor, "Command 2"); - mgr.registerShortcut("Ctrl+K", "command3", []() {}, - ShortcutContext::Search, "Command 3"); - + mgr.registerShortcut( + "Ctrl+K", "command1", []() {}, ShortcutContext::Editor, "Command 1"); + mgr.registerShortcut( + "Ctrl+L", "command2", []() {}, ShortcutContext::Editor, "Command 2"); + mgr.registerShortcut( + "Ctrl+K", "command3", []() {}, ShortcutContext::Search, "Command 3"); + // Test finding by context auto editorShortcuts = mgr.getShortcutsForContext(ShortcutContext::Editor); size_t editorCount = 0; @@ -137,12 +142,12 @@ void test_shortcut_discovery() { } } assert(editorCount >= 2); - + // Test finding by command auto command1Shortcuts = mgr.findShortcutsByCommand("command1"); assert(!command1Shortcuts.empty()); assert(command1Shortcuts[0].command == "command1"); - + // Test finding by key auto ctrlKShortcuts = mgr.findShortcutsByKey("Ctrl+K"); size_t ctrlKCount = 0; @@ -152,100 +157,100 @@ void test_shortcut_discovery() { } } assert(ctrlKCount >= 2); - + std::cout << "PASS" << std::endl; } void test_help_system() { std::cout << "[KeyboardShortcuts] HelpSystem ... "; - + auto& mgr = KeyboardShortcuts::getInstance(); - + // Register test shortcut with description - mgr.registerShortcut("Ctrl+H", "testHelp", []() {}, - ShortcutContext::Editor, "Test help command"); - + mgr.registerShortcut( + "Ctrl+H", "testHelp", []() {}, ShortcutContext::Editor, "Test help command"); + // Get help text std::string helpText = mgr.getHelpText(ShortcutContext::Editor); assert(!helpText.empty()); assert(helpText.find("Test help command") != std::string::npos); - + // Get shortcut description std::string description = mgr.getShortcutDescription("Ctrl+H", ShortcutContext::Editor); assert(description == "Test help command"); - + std::cout << "PASS" << std::endl; } void test_enable_disable() { std::cout << "[KeyboardShortcuts] EnableDisable ... "; - + auto& mgr = KeyboardShortcuts::getInstance(); - + bool executed = false; - mgr.registerShortcut("Ctrl+E", "testEnable", [&executed]() { executed = true; }, - ShortcutContext::Global, "Test enable"); - + mgr.registerShortcut( + "Ctrl+E", "testEnable", [&executed]() { executed = true; }, ShortcutContext::Global, "Test enable"); + // Test enabled state assert(mgr.isEnabled()); assert(mgr.executeShortcut("Ctrl+E", ShortcutContext::Global)); assert(executed); - + // Test disabled state executed = false; mgr.setEnabled(false); assert(!mgr.isEnabled()); assert(!mgr.executeShortcut("Ctrl+E", ShortcutContext::Global)); assert(!executed); - + // Re-enable mgr.setEnabled(true); assert(mgr.executeShortcut("Ctrl+E", ShortcutContext::Global)); assert(executed); - + std::cout << "PASS" << std::endl; } void test_conflict_detection() { std::cout << "[KeyboardShortcuts] ConflictDetection ... "; - + KeyboardShortcuts& mgr = KeyboardShortcuts::getInstance(); (void)mgr; - + // Register initial shortcut - assert(mgr.registerShortcut("Ctrl+R", "command1", []() {}, - ShortcutContext::Editor, "Command 1")); - + assert(mgr.registerShortcut( + "Ctrl+R", "command1", []() {}, ShortcutContext::Editor, "Command 1")); + // Try to register conflicting shortcut (same key combination and context, different command) - assert(!mgr.registerShortcut("Ctrl+R", "command2", []() {}, - ShortcutContext::Editor, "Command 2")); - + assert(!mgr.registerShortcut( + "Ctrl+R", "command2", []() {}, ShortcutContext::Editor, "Command 2")); + // Register same key combination in different context should succeed - assert(mgr.registerShortcut("Ctrl+R", "command3", []() {}, - ShortcutContext::Search, "Command 3")); - + assert(mgr.registerShortcut( + "Ctrl+R", "command3", []() {}, ShortcutContext::Search, "Command 3")); + // Register same command with same key should succeed (overwrite) - assert(mgr.registerShortcut("Ctrl+R", "command1", []() {}, - ShortcutContext::Editor, "Updated Command 1")); - + assert(mgr.registerShortcut( + "Ctrl+R", "command1", []() {}, ShortcutContext::Editor, "Updated Command 1")); + std::cout << "PASS" << std::endl; } void test_default_shortcuts() { std::cout << "[KeyboardShortcuts] DefaultShortcuts ... "; - + auto& mgr = KeyboardShortcuts::getInstance(); - + // Initialize default shortcuts mgr.initDefaultShortcuts(); - + // Check if some default shortcuts exist auto globalShortcuts = mgr.getShortcutsForContext(ShortcutContext::Global); auto editorShortcuts = mgr.getShortcutsForContext(ShortcutContext::Editor); - + assert(!globalShortcuts.empty()); assert(!editorShortcuts.empty()); - + // Check for specific default shortcuts auto ctrlSShortcuts = mgr.findShortcutsByKey("Ctrl+S"); bool hasSave = false; @@ -255,8 +260,9 @@ void test_default_shortcuts() { break; } } - assert(hasSave); (void)hasSave; - + assert(hasSave); + (void)hasSave; + auto ctrlZShortcuts = mgr.findShortcutsByKey("Ctrl+Z"); bool hasUndo = false; for (const auto& info : ctrlZShortcuts) { @@ -265,15 +271,16 @@ void test_default_shortcuts() { break; } } - assert(hasUndo); (void)hasUndo; - + assert(hasUndo); + (void)hasUndo; + std::cout << "PASS" << std::endl; } int main() { std::cout << "Running Keyboard Shortcuts Tests" << std::endl; std::cout << "=================================" << std::endl; - + try { test_key_combination_parsing(); test_shortcut_registration(); @@ -283,13 +290,12 @@ int main() { test_enable_disable(); test_conflict_detection(); test_default_shortcuts(); - + std::cout << "\n=== All Keyboard Shortcuts Tests Passed! ===" << std::endl; - } catch (const std::exception& e) { std::cerr << "Test failed with exception: " << e.what() << std::endl; return 1; } - + return 0; } diff --git a/test/test_koboldcpp_provider.cpp b/test/test_koboldcpp_provider.cpp index e7fad6f5..3c08602f 100644 --- a/test/test_koboldcpp_provider.cpp +++ b/test/test_koboldcpp_provider.cpp @@ -11,13 +11,14 @@ * Path D (cpp-e2e-test-gen) applied to the koboldcpp integration. */ -#include "bolt/ai/koboldcpp_provider.hpp" -#include "bolt/test_framework.hpp" -#include -#include +#include #include #include -#include +#include +#include + +#include "bolt/ai/koboldcpp_provider.hpp" +#include "bolt/test_framework.hpp" using namespace bolt::ai; @@ -327,12 +328,10 @@ BOLT_TEST(KoboldCppChat, ChatWithSystemPrompt) { BOLT_TEST(KoboldCppChat, ChatWithMultipleMessages) { KoboldCppProvider provider("http://127.0.0.1:59999"); - std::vector> messages = { - {"system", "You are helpful."}, - {"user", "What is C++?"}, - {"assistant", "C++ is a programming language."}, - {"user", "Tell me more."} - }; + std::vector> messages = {{"system", "You are helpful."}, + {"user", "What is C++?"}, + {"assistant", "C++ is a programming language."}, + {"user", "Tell me more."}}; auto response = provider.chat(messages); BOLT_ASSERT(response.success == false || response.success == true); } @@ -354,9 +353,7 @@ BOLT_TEST(KoboldCppStreaming, StreamCompleteNoServer) { BOLT_TEST(KoboldCppStreaming, StreamChatNoServer) { KoboldCppProvider provider("http://127.0.0.1:59999"); - bool result = provider.chat_streaming("Hello", [](const std::string& token) { - return true; - }); + bool result = provider.chat_streaming("Hello", [](const std::string& token) { return true; }); BOLT_ASSERT(!result); } @@ -366,8 +363,7 @@ BOLT_TEST(KoboldCppStreaming, StreamChatNoServer) { BOLT_TEST(KoboldCppInterface, ImplementsAICompletionProvider) { // Verify KoboldCppProvider can be used as AICompletionProvider - std::unique_ptr provider = - std::make_unique(); + std::unique_ptr provider = std::make_unique(); BOLT_ASSERT(provider != nullptr); BOLT_ASSERT(!provider->isReady()); } @@ -381,8 +377,7 @@ BOLT_TEST(KoboldCppInterface, InitializeReturnsBool) { } BOLT_TEST(KoboldCppInterface, ShutdownViaInterface) { - std::unique_ptr provider = - std::make_unique(); + std::unique_ptr provider = std::make_unique(); provider->shutdown(); BOLT_ASSERT(!provider->isReady()); } @@ -396,7 +391,7 @@ BOLT_TEST(KoboldCppInterface, GenerateCompletionsViaInterface) { ctx.cursorPosition = 45; ctx.language = "cpp"; auto results = provider->generateCompletions(ctx, "std::cout"); - BOLT_ASSERT(results.empty()); // No server, so empty + BOLT_ASSERT(results.empty()); // No server, so empty } // โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• diff --git a/test/test_lsp.cpp b/test/test_lsp.cpp index ad72d2bb..9bfd622d 100644 --- a/test/test_lsp.cpp +++ b/test/test_lsp.cpp @@ -3,15 +3,15 @@ * @brief Unit tests for LSP (Language Server Protocol) components */ -#include -#include -#include -#include -#include - +#include #include #include -#include + +#include "bolt/editor/lsp_json_rpc.hpp" +#include "bolt/lsp/lsp_client.hpp" +#include "bolt/lsp/lsp_server.hpp" +#include "bolt/lsp/lsp_types.hpp" +#include "bolt/test_framework.hpp" using namespace bolt::test; @@ -263,9 +263,7 @@ BOLT_TEST(LSPServer, NotificationHandling) { int notificationCount = 0; - server.onNotification("textDocument/didChange", [&](const std::string& params) { - notificationCount++; - }); + server.onNotification("textDocument/didChange", [&](const std::string& params) { notificationCount++; }); // Send notification server.handleNotification("textDocument/didChange", "{}"); @@ -284,8 +282,7 @@ BOLT_TEST(LSPProtocol, InitializeRequest) { auto initParams = client.createInitializeParams("/home/user/project"); BOLT_ASSERT(!initParams.empty()); - BOLT_ASSERT(initParams.find("rootUri") != std::string::npos || - initParams.find("rootPath") != std::string::npos); + BOLT_ASSERT(initParams.find("rootUri") != std::string::npos || initParams.find("rootPath") != std::string::npos); } BOLT_TEST(LSPProtocol, CompletionRequest) { @@ -368,19 +365,15 @@ BOLT_TEST(LSPDiagnostics, DiagnosticFiltering) { for (int i = 0; i < 10; i++) { bolt::lsp::Diagnostic diag; - diag.severity = (i % 2 == 0) ? - bolt::lsp::DiagnosticSeverity::Error : - bolt::lsp::DiagnosticSeverity::Warning; + diag.severity = (i % 2 == 0) ? bolt::lsp::DiagnosticSeverity::Error : bolt::lsp::DiagnosticSeverity::Warning; diag.message = "Diagnostic " + std::to_string(i); collection.add("file:///test.cpp", diag); } - auto errors = collection.getByServerity("file:///test.cpp", - bolt::lsp::DiagnosticSeverity::Error); + auto errors = collection.getByServerity("file:///test.cpp", bolt::lsp::DiagnosticSeverity::Error); BOLT_ASSERT_EQ(5u, errors.size()); - auto warnings = collection.getByServerity("file:///test.cpp", - bolt::lsp::DiagnosticSeverity::Warning); + auto warnings = collection.getByServerity("file:///test.cpp", bolt::lsp::DiagnosticSeverity::Warning); BOLT_ASSERT_EQ(5u, warnings.size()); } diff --git a/test/test_memory_leak_detector.cpp b/test/test_memory_leak_detector.cpp index 5f37ecac..3c4d15a4 100644 --- a/test/test_memory_leak_detector.cpp +++ b/test/test_memory_leak_detector.cpp @@ -1,27 +1,28 @@ -#include "bolt/test_framework.hpp" -#include "bolt/core/memory_leak_detector.hpp" #include +#include "bolt/core/memory_leak_detector.hpp" +#include "bolt/test_framework.hpp" + using namespace bolt::test; // ===== Memory Leak Detector Tests ===== BOLT_TEST(MemoryLeakDetector, BasicTracking) { auto& detector = bolt::MemoryLeakDetector::getInstance(); - detector.clear(); // Start fresh - + detector.clear(); // Start fresh + // Allocate and track void* ptr1 = malloc(1024); TRACK_ALLOCATION(ptr1, 1024, "test"); - + BOLT_ASSERT(detector.hasLeaks()); BOLT_ASSERT_EQ(1, detector.getLeakCount()); BOLT_ASSERT_EQ(1024, detector.getLeakedBytes()); - + // Untrack and free UNTRACK_ALLOCATION(ptr1); free(ptr1); - + BOLT_ASSERT(!detector.hasLeaks()); BOLT_ASSERT_EQ(0, detector.getLeakCount()); } @@ -29,51 +30,51 @@ BOLT_TEST(MemoryLeakDetector, BasicTracking) { BOLT_TEST(MemoryLeakDetector, MultipleAllocations) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + void* ptr1 = malloc(512); void* ptr2 = malloc(1024); void* ptr3 = malloc(2048); - + TRACK_ALLOCATION(ptr1, 512, "buffers"); TRACK_ALLOCATION(ptr2, 1024, "network"); TRACK_ALLOCATION(ptr3, 2048, "buffers"); - + BOLT_ASSERT_EQ(3, detector.getLeakCount()); BOLT_ASSERT_EQ(3584, detector.getLeakedBytes()); - + // Free one allocation UNTRACK_ALLOCATION(ptr2); free(ptr2); - + BOLT_ASSERT_EQ(2, detector.getLeakCount()); BOLT_ASSERT_EQ(2560, detector.getLeakedBytes()); - + // Free remaining UNTRACK_ALLOCATION(ptr1); UNTRACK_ALLOCATION(ptr3); free(ptr1); free(ptr3); - + BOLT_ASSERT(!detector.hasLeaks()); } BOLT_TEST(MemoryLeakDetector, Categorization) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + void* ptr1 = malloc(1024); void* ptr2 = malloc(2048); void* ptr3 = malloc(512); - + TRACK_ALLOCATION(ptr1, 1024, "network"); TRACK_ALLOCATION(ptr2, 2048, "buffers"); TRACK_ALLOCATION(ptr3, 512, "network"); - + auto stats = detector.getStats(); - + BOLT_ASSERT_EQ(1536, stats.leaksByCategory["network"]); BOLT_ASSERT_EQ(2048, stats.leaksByCategory["buffers"]); - + // Cleanup UNTRACK_ALLOCATION(ptr1); UNTRACK_ALLOCATION(ptr2); @@ -86,22 +87,22 @@ BOLT_TEST(MemoryLeakDetector, Categorization) { BOLT_TEST(MemoryLeakDetector, ReportGeneration) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // No leaks std::string report = detector.generateReport(); BOLT_ASSERT(report.find("No memory leaks detected") != std::string::npos); - + // With leaks void* ptr = malloc(1024); TRACK_ALLOCATION(ptr, 1024, "test"); - + report = detector.generateReport(); BOLT_ASSERT(report.find("Memory leaks detected") != std::string::npos); BOLT_ASSERT(report.find("Total leaks: 1") != std::string::npos); - + std::string summary = detector.generateSummary(); BOLT_ASSERT(summary.find("1 leaks") != std::string::npos); - + // Cleanup UNTRACK_ALLOCATION(ptr); free(ptr); @@ -111,24 +112,24 @@ BOLT_TEST(MemoryLeakDetector, PeakUsageTracking) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); detector.resetStats(); - + void* ptr1 = malloc(1024); TRACK_ALLOCATION(ptr1, 1024, "test"); - + void* ptr2 = malloc(2048); TRACK_ALLOCATION(ptr2, 2048, "test"); - + auto stats = detector.getStats(); BOLT_ASSERT_EQ(3072, stats.peakMemoryUsage); - + // Free one UNTRACK_ALLOCATION(ptr1); free(ptr1); - + stats = detector.getStats(); - BOLT_ASSERT_EQ(3072, stats.peakMemoryUsage); // Peak should remain + BOLT_ASSERT_EQ(3072, stats.peakMemoryUsage); // Peak should remain BOLT_ASSERT_EQ(2048, stats.currentMemoryUsage); - + // Cleanup UNTRACK_ALLOCATION(ptr2); free(ptr2); @@ -137,18 +138,18 @@ BOLT_TEST(MemoryLeakDetector, PeakUsageTracking) { BOLT_TEST(MemoryLeakDetector, EnableDisable) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + detector.setEnabled(false); BOLT_ASSERT(!detector.isEnabled()); - + void* ptr = malloc(1024); TRACK_ALLOCATION(ptr, 1024, "test"); - + // Should not be tracked when disabled BOLT_ASSERT(!detector.hasLeaks()); - + free(ptr); - + detector.setEnabled(true); BOLT_ASSERT(detector.isEnabled()); } diff --git a/test/test_minimap.cpp b/test/test_minimap.cpp index bbb494f9..ea3db5dc 100644 --- a/test/test_minimap.cpp +++ b/test/test_minimap.cpp @@ -1,8 +1,9 @@ -#include "bolt/test_framework.hpp" +#include +#include + #include "bolt/editor/minimap.hpp" #include "bolt/editor/minimap_ui.hpp" -#include -#include +#include "bolt/test_framework.hpp" using namespace bolt::test; @@ -23,13 +24,13 @@ std::vector createTestDocument() { return lines; } -} +} // namespace // ===== Minimap Component Tests ===== BOLT_TEST(Minimap, BasicCreation) { bolt::Minimap minimap; - + BOLT_ASSERT(!minimap.hasDocument()); BOLT_ASSERT_EQ(0, minimap.getTotalLines()); BOLT_ASSERT(minimap.isEnabled()); @@ -39,9 +40,9 @@ BOLT_TEST(Minimap, ConfigCreation) { bolt::Minimap::MinimapConfig config; config.width = 80; config.height = 30; - + bolt::Minimap minimap(config); - + BOLT_ASSERT_EQ(80, minimap.getConfig().width); BOLT_ASSERT_EQ(30, minimap.getConfig().height); BOLT_ASSERT(minimap.isEnabled()); @@ -50,9 +51,9 @@ BOLT_TEST(Minimap, ConfigCreation) { BOLT_TEST(Minimap, DocumentLoading) { bolt::Minimap minimap; auto testDoc = createTestDocument(); - + minimap.setDocument("/test/file.cpp", testDoc); - + BOLT_ASSERT(minimap.hasDocument()); BOLT_ASSERT_EQ("/test/file.cpp", minimap.getDocumentPath()); BOLT_ASSERT_EQ(testDoc.size(), minimap.getTotalLines()); @@ -62,15 +63,15 @@ BOLT_TEST(Minimap, ViewportUpdate) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + bolt::Minimap::ViewportInfo viewport; viewport.startLine = 10; viewport.endLine = 30; viewport.currentLine = 20; viewport.totalLines = testDoc.size(); - + minimap.updateViewport(viewport); - + auto retrievedViewport = minimap.getViewport(); BOLT_ASSERT_EQ(10, retrievedViewport.startLine); BOLT_ASSERT_EQ(30, retrievedViewport.endLine); @@ -81,15 +82,15 @@ BOLT_TEST(Minimap, Navigation) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + // Test position to line mapping size_t line = minimap.getLineFromPosition(10, 5); BOLT_ASSERT(line < testDoc.size()); - + // Test line to position mapping auto [x, y] = minimap.getPositionFromLine(50); BOLT_ASSERT(y < minimap.getConfig().height); - + // Test scroll to line minimap.scrollToLine(50); auto viewport = minimap.getViewport(); @@ -100,9 +101,9 @@ BOLT_TEST(Minimap, Rendering) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + auto rendered = minimap.render(); - + BOLT_ASSERT_EQ(minimap.getConfig().height, rendered.size()); for (const auto& line : rendered) { BOLT_ASSERT_EQ(minimap.getConfig().width, line.length()); @@ -112,7 +113,7 @@ BOLT_TEST(Minimap, Rendering) { BOLT_TEST(MinimapUI, BasicCreation) { bolt::Minimap minimap; bolt::MinimapUI ui(minimap); - + BOLT_ASSERT(ui.isVisible()); BOLT_ASSERT(ui.getRequiredWidth() > 0); BOLT_ASSERT(ui.getRequiredHeight() > 0); @@ -120,14 +121,14 @@ BOLT_TEST(MinimapUI, BasicCreation) { BOLT_TEST(MinimapUI, ConfiguredCreation) { bolt::Minimap minimap; - + bolt::MinimapUI::UIConfig config; config.showBorder = true; config.showTitle = true; config.title = "Test Minimap"; - + bolt::MinimapUI ui(minimap, config); - + BOLT_ASSERT_EQ("Test Minimap", ui.getConfig().title); BOLT_ASSERT(ui.getConfig().showBorder); BOLT_ASSERT(ui.getConfig().showTitle); @@ -137,22 +138,22 @@ BOLT_TEST(MinimapUI, SizeCalculation) { bolt::Minimap::MinimapConfig minimapConfig; minimapConfig.width = 50; minimapConfig.height = 20; - + bolt::Minimap minimap(minimapConfig); - + bolt::MinimapUI::UIConfig uiConfig; uiConfig.showBorder = true; uiConfig.showTitle = true; uiConfig.showScrollIndicator = true; - + bolt::MinimapUI ui(minimap, uiConfig); - + // Width should include borders (2 chars) BOLT_ASSERT_EQ(52, ui.getRequiredWidth()); - + // Height should include title, borders, and scroll indicator BOLT_ASSERT_EQ(24, ui.getRequiredHeight()); - + BOLT_ASSERT(ui.fitsInArea(60, 30)); BOLT_ASSERT(!ui.fitsInArea(50, 20)); } @@ -161,21 +162,21 @@ BOLT_TEST(MinimapUI, Rendering) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + bolt::MinimapUI ui(minimap); auto rendered = ui.render(); - + BOLT_ASSERT(rendered.size() > 0); - + // Test with borders and title bolt::MinimapUI::UIConfig config; config.showBorder = true; config.showTitle = true; config.title = "Test"; - + bolt::MinimapUI uiWithBorder(minimap, config); auto borderedRender = uiWithBorder.render(); - + // With borders and title, we should have at least as many lines as the basic render BOLT_ASSERT(borderedRender.size() >= rendered.size()); } @@ -184,21 +185,21 @@ BOLT_TEST(MinimapUI, NavigationCallback) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + bolt::MinimapUI ui(minimap); - + size_t callbackLine = 0; bool callbackCalled = false; - + ui.setNavigationCallback([&](size_t line) { callbackLine = line; callbackCalled = true; }); - + // Simulate click that should trigger navigation bolt::MinimapUI::Position pos{0, 0, 50, 20}; ui.setPosition(pos); - + bool handled = ui.handleClick(10, 10); BOLT_ASSERT(handled); BOLT_ASSERT(callbackCalled); @@ -209,18 +210,18 @@ BOLT_TEST(Minimap, DisableEnable) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + BOLT_ASSERT(minimap.isEnabled()); - + minimap.setEnabled(false); BOLT_ASSERT(!minimap.isEnabled()); - + auto rendered = minimap.render(); // Should render empty when disabled for (const auto& line : rendered) { BOLT_ASSERT_EQ(std::string(minimap.getConfig().width, ' '), line); } - + minimap.setEnabled(true); BOLT_ASSERT(minimap.isEnabled()); } @@ -229,15 +230,15 @@ BOLT_TEST(Minimap, ScrollPercentage) { bolt::Minimap minimap; auto testDoc = createTestDocument(); minimap.setDocument("/test/file.cpp", testDoc); - + // Scroll to top minimap.scrollToLine(0); BOLT_ASSERT_EQ(0.0, minimap.getScrollPercentage()); - + // Scroll to middle minimap.scrollToLine(testDoc.size() / 2); double midPercent = minimap.getScrollPercentage(); BOLT_ASSERT(midPercent >= 0.0); - + // Note: Don't test upper bound as scroll percentage calculation may vary -} \ No newline at end of file +} diff --git a/test/test_model_loading.cpp b/test/test_model_loading.cpp index 68ea8ce5..00d9ad74 100644 --- a/test/test_model_loading.cpp +++ b/test/test_model_loading.cpp @@ -1,8 +1,9 @@ -#include "bolt/ai/gguf_loader.hpp" +#include +#include + #include "bolt/ai/bpe_tokenizer.hpp" +#include "bolt/ai/gguf_loader.hpp" #include "bolt/ai/rwkv_wrapper.hpp" -#include -#include using namespace bolt; @@ -11,17 +12,15 @@ int main(int argc, char** argv) { std::cout << "RWKV Model Loading Test" << std::endl; std::cout << "========================================" << std::endl; std::cout << std::endl; - + // Find model file - std::vector model_paths = { - "test/data/models/rwkv-4-pile-169m-q4_0.gguf", - "../test/data/models/rwkv-4-pile-169m-q4_0.gguf", - "../../test/data/models/rwkv-4-pile-169m-q4_0.gguf" - }; - + std::vector model_paths = {"test/data/models/rwkv-4-pile-169m-q4_0.gguf", + "../test/data/models/rwkv-4-pile-169m-q4_0.gguf", + "../../test/data/models/rwkv-4-pile-169m-q4_0.gguf"}; + std::string model_path; bool found = false; - + for (const auto& path : model_paths) { if (std::filesystem::exists(path)) { model_path = path; @@ -29,7 +28,7 @@ int main(int argc, char** argv) { break; } } - + if (!found) { std::cerr << "โŒ Model file not found!" << std::endl; std::cerr << "Searched paths:" << std::endl; @@ -40,54 +39,54 @@ int main(int argc, char** argv) { std::cerr << "Please run: scripts/download_rwkv_model.py" << std::endl; return 1; } - + std::cout << "โœ“ Found model: " << model_path << std::endl; auto size_mb = std::filesystem::file_size(model_path) / (1024.0 * 1024.0); std::cout << " Size: " << size_mb << " MB" << std::endl; std::cout << std::endl; - + // Test 1: GGUF Loader std::cout << "Test 1: GGUF Loader" << std::endl; std::cout << "----------------------------------------" << std::endl; - + try { GGUFLoader loader(model_path); - + if (!loader.load()) { std::cerr << "โŒ Failed to load GGUF file" << std::endl; std::cerr << "Error: " << loader.getError() << std::endl; return 1; } - + std::cout << "โœ“ GGUF file loaded successfully" << std::endl; std::cout << " Version: " << loader.getVersion() << std::endl; std::cout << " Architecture: " << loader.getArchitecture() << std::endl; std::cout << " Tensor count: " << loader.getTensorCount() << std::endl; std::cout << " Metadata count: " << loader.getMetadataCount() << std::endl; - + int n_layers = loader.getNumLayers(); int n_embd = loader.getEmbedDim(); int n_vocab = loader.getVocabSize(); - + std::cout << " Layers: " << n_layers << std::endl; std::cout << " Embedding dim: " << n_embd << std::endl; std::cout << " Vocabulary size: " << n_vocab << std::endl; std::cout << std::endl; - + if (n_layers == 0 || n_embd == 0 || n_vocab == 0) { std::cerr << "โš  Warning: Some model parameters are zero" << std::endl; std::cerr << "This might be an older GGML format (not GGUF)" << std::endl; std::cerr << "The file magic number should be GGUF (0x46554747)" << std::endl; std::cout << std::endl; } - + // Test 2: Tokenizer std::cout << "Test 2: BPE Tokenizer" << std::endl; std::cout << "----------------------------------------" << std::endl; - + auto tokens = loader.getMetadataStringArray("tokenizer.ggml.tokens"); auto scores = loader.getMetadataFloatArray("tokenizer.ggml.scores"); - + if (tokens.empty()) { std::cerr << "โš  No tokenizer vocabulary found in model" << std::endl; std::cerr << "This is expected for older GGML format files" << std::endl; @@ -97,49 +96,48 @@ int main(int argc, char** argv) { if (tokenizer.loadVocabulary(tokens, scores)) { std::cout << "โœ“ Tokenizer loaded successfully" << std::endl; std::cout << " Vocabulary size: " << tokenizer.getVocabSize() << std::endl; - + // Test encoding/decoding std::string test_text = "Hello, world!"; auto encoded = tokenizer.encode(test_text); auto decoded = tokenizer.decode(encoded); - + std::cout << " Test text: \"" << test_text << "\"" << std::endl; std::cout << " Encoded: " << encoded.size() << " tokens" << std::endl; std::cout << " Decoded: \"" << decoded << "\"" << std::endl; std::cout << std::endl; } } - } catch (const std::exception& e) { std::cerr << "โŒ Exception: " << e.what() << std::endl; return 1; } - + // Test 3: RWKV Wrapper Integration std::cout << "Test 3: RWKV Wrapper Integration" << std::endl; std::cout << "----------------------------------------" << std::endl; - + try { auto& wrapper = RWKVWrapper::getInstance(); - + std::cout << "Initializing RWKV model..." << std::endl; wrapper.initialize(model_path, 512); // 512 MB context - + if (wrapper.isInitialized()) { std::cout << "โœ“ RWKV model initialized successfully" << std::endl; std::cout << " Layers: " << wrapper.getNumLayers() << std::endl; std::cout << " Embedding dim: " << wrapper.getEmbedDim() << std::endl; std::cout << std::endl; - + // Test generation (if model is properly loaded) if (wrapper.getNumLayers() > 0) { std::cout << "Test 4: Text Generation" << std::endl; std::cout << "----------------------------------------" << std::endl; - + std::string prompt = "The"; std::cout << "Prompt: \"" << prompt << "\"" << std::endl; std::cout << "Generating 5 tokens..." << std::endl; - + try { std::string generated = wrapper.generate(prompt, 5); std::cout << "โœ“ Generated: \"" << generated << "\"" << std::endl; @@ -152,17 +150,16 @@ int main(int argc, char** argv) { std::cerr << "โŒ RWKV model initialization failed" << std::endl; return 1; } - } catch (const std::exception& e) { std::cerr << "โŒ Exception during RWKV initialization: " << e.what() << std::endl; std::cerr << "This might be due to format incompatibility" << std::endl; return 1; } - + std::cout << std::endl; std::cout << "========================================" << std::endl; std::cout << "โœ“ All tests completed" << std::endl; std::cout << "========================================" << std::endl; - + return 0; } diff --git a/test/test_multi_cursor.cpp b/test/test_multi_cursor.cpp index a089d518..7cb529e5 100644 --- a/test/test_multi_cursor.cpp +++ b/test/test_multi_cursor.cpp @@ -1,6 +1,7 @@ #include #include #include + #include "bolt/editor/cursor_manager.hpp" #include "bolt/editor/integrated_editor.hpp" @@ -8,40 +9,40 @@ using namespace bolt; void test_multi_cursor_basic() { std::cout << "[MultiCursor] BasicOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); - + // Clear any existing cursors manager.clearCursors(); - + // Test adding cursors manager.addCursor(0, 0); manager.addCursor(1, 5); manager.addCursor(2, 10); - + auto cursors = manager.getCursors(); assert(cursors.size() == 3); assert(manager.getCursorCount() == 3); assert(manager.hasCursors()); - + // Test cursor positions assert(cursors[0].line == 0 && cursors[0].column == 0); assert(cursors[1].line == 1 && cursors[1].column == 5); assert(cursors[2].line == 2 && cursors[2].column == 10); - + std::cout << "PASS" << std::endl; } void test_multi_cursor_selection() { std::cout << "[MultiCursor] SelectionOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Test cursor with selection Selection selection{1, 5, 1, 10}; manager.addCursorWithSelection(1, 5, selection); - + auto cursors = manager.getCursors(); assert(cursors.size() == 1); assert(cursors[0].selection.hasSelection()); @@ -49,182 +50,186 @@ void test_multi_cursor_selection() { assert(cursors[0].selection.startColumn == 5); assert(cursors[0].selection.endLine == 1); assert(cursors[0].selection.endColumn == 10); - + // Test clear selections manager.clearAllSelections(); cursors = manager.getCursors(); assert(!cursors[0].selection.hasSelection()); - + std::cout << "PASS" << std::endl; } void test_multi_cursor_movement() { std::cout << "[MultiCursor] MovementOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add multiple cursors manager.addCursor(5, 10); manager.addCursor(10, 20); - + // Test moving cursors manager.moveCursors(2, 3); - + auto cursors = manager.getCursors(); assert(cursors[0].line == 7 && cursors[0].column == 13); assert(cursors[1].line == 12 && cursors[1].column == 23); - + // Test moving with negative values (should not go below 0) manager.moveCursors(-10, -20); cursors = manager.getCursors(); assert(cursors[0].line == 0 && cursors[0].column == 0); assert(cursors[1].line == 2 && cursors[1].column == 3); - + std::cout << "PASS" << std::endl; } void test_multi_cursor_primary() { std::cout << "[MultiCursor] PrimaryCursorOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add cursors manager.addCursor(1, 1); manager.addCursor(2, 2); manager.addCursor(3, 3); - + // Test primary cursor manager.setPrimaryCursor(1); auto primary = manager.getPrimaryCursor(); assert(primary.line == 2 && primary.column == 2); - + // Test primary cursor with invalid index manager.setPrimaryCursor(10); primary = manager.getPrimaryCursor(); // Should return default cursor when index is out of bounds assert(primary.line == 0 && primary.column == 0); - + std::cout << "PASS" << std::endl; } void test_multi_cursor_text_operations() { std::cout << "[MultiCursor] TextOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add cursors manager.addCursor(0, 5); manager.addCursor(1, 10); - + // Test text insertion (simplified) manager.insertTextAtCursors("Hello"); auto cursors = manager.getCursors(); - + // Check that both cursors moved by text length (order may be different due to sorting) bool mcFoundFirst = false, mcFoundSecond = false; for (const auto& cursor : cursors) { - if (cursor.line == 0 && cursor.column == 10) mcFoundFirst = true; // 5 + 5 - if (cursor.line == 1 && cursor.column == 15) mcFoundSecond = true; // 10 + 5 + if (cursor.line == 0 && cursor.column == 10) + mcFoundFirst = true; // 5 + 5 + if (cursor.line == 1 && cursor.column == 15) + mcFoundSecond = true; // 10 + 5 } assert(mcFoundFirst && mcFoundSecond); - (void)mcFoundFirst; (void)mcFoundSecond; - + (void)mcFoundFirst; + (void)mcFoundSecond; + // Test deletion manager.deleteAtCursors(); cursors = manager.getCursors(); - + // Check that both cursors moved back by 1 bool delFoundFirst = false, delFoundSecond = false; for (const auto& cursor : cursors) { - if (cursor.line == 0 && cursor.column == 9) delFoundFirst = true; // 10 - 1 - if (cursor.line == 1 && cursor.column == 14) delFoundSecond = true; // 15 - 1 + if (cursor.line == 0 && cursor.column == 9) + delFoundFirst = true; // 10 - 1 + if (cursor.line == 1 && cursor.column == 14) + delFoundSecond = true; // 15 - 1 } assert(delFoundFirst && delFoundSecond); - (void)delFoundFirst; (void)delFoundSecond; - + (void)delFoundFirst; + (void)delFoundSecond; + std::cout << "PASS" << std::endl; } void test_multi_cursor_removal() { std::cout << "[MultiCursor] RemovalOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add cursors manager.addCursor(1, 1); manager.addCursor(2, 2); manager.addCursor(3, 3); - + assert(manager.getCursorCount() == 3); - + // Remove specific cursor manager.removeCursor(2, 2); assert(manager.getCursorCount() == 2); - + auto cursors = manager.getCursors(); - assert((cursors[0].line == 1 && cursors[0].column == 1) || - (cursors[1].line == 1 && cursors[1].column == 1)); - assert((cursors[0].line == 3 && cursors[0].column == 3) || - (cursors[1].line == 3 && cursors[1].column == 3)); - + assert((cursors[0].line == 1 && cursors[0].column == 1) || (cursors[1].line == 1 && cursors[1].column == 1)); + assert((cursors[0].line == 3 && cursors[0].column == 3) || (cursors[1].line == 3 && cursors[1].column == 3)); + // Clear all cursors manager.clearCursors(); assert(manager.getCursorCount() == 0); assert(!manager.hasCursors()); - + std::cout << "PASS" << std::endl; } void test_integrated_editor_multi_cursor() { std::cout << "[IntegratedEditor] MultiCursorIntegration ... "; - + IntegratedEditor& editor = IntegratedEditor::getInstance(); - + // Test adding cursors through editor editor.addCursorAtPosition(0, 0); editor.addCursorAtPosition(1, 5); - + assert(editor.getCursorCount() == 2); - + auto cursors = editor.getAllCursors(); assert(cursors.size() == 2); - + // Test clearing extra cursors editor.clearExtraCursors(); assert(editor.getCursorCount() == 1); - + std::cout << "PASS" << std::endl; } void test_multi_cursor_find_operations() { std::cout << "[MultiCursor] FindOperations ... "; - + CursorManager& manager = CursorManager::getInstance(); manager.clearCursors(); - + // Add initial cursor manager.addCursor(0, 0); - + // Test find next occurrence (simplified implementation) manager.findNextOccurrence("test", "some document content"); assert(manager.getCursorCount() >= 1); - + // Test select all occurrences manager.selectAllOccurrences("test", "document content"); // Should have multiple cursors from selectAllOccurrences assert(manager.getCursorCount() > 1); - + std::cout << "PASS" << std::endl; } int main() { std::cout << "Multi-Cursor Editing Tests" << std::endl; std::cout << "=========================" << std::endl; - + try { test_multi_cursor_basic(); test_multi_cursor_selection(); @@ -234,11 +239,11 @@ int main() { test_multi_cursor_removal(); test_integrated_editor_multi_cursor(); test_multi_cursor_find_operations(); - + std::cout << std::endl << "All multi-cursor tests passed!" << std::endl; return 0; } catch (const std::exception& e) { std::cerr << "Test failed with exception: " << e.what() << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test/test_runner.cpp b/test/test_runner.cpp index 4fe366ce..f9cdb188 100644 --- a/test/test_runner.cpp +++ b/test/test_runner.cpp @@ -1,14 +1,15 @@ -#include "bolt/test_framework.hpp" #include #include +#include "bolt/test_framework.hpp" + int main(int argc, char* argv[]) { using namespace bolt::test; - + std::string suite_name = ""; bool list_tests = false; bool verbose = true; - + // Parse command line arguments for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; @@ -37,16 +38,16 @@ int main(int argc, char* argv[]) { suite_name = arg; } } - + auto& testSuite = TestSuite::getInstance(); - + if (list_tests) { testSuite.listTests(); return 0; } - + int failed_tests = 0; - + if (suite_name.empty()) { if (verbose) { std::cout << "Bolt C++ Unit Test Runner" << std::endl; @@ -60,6 +61,6 @@ int main(int argc, char* argv[]) { } failed_tests = testSuite.runTestsInSuite(suite_name, verbose); } - + return failed_tests; -} \ No newline at end of file +} diff --git a/test/test_rwkv_integration.cpp b/test/test_rwkv_integration.cpp index e32ffbaf..1062ba78 100644 --- a/test/test_rwkv_integration.cpp +++ b/test/test_rwkv_integration.cpp @@ -1,7 +1,8 @@ +#include +#include + #include "bolt/ai/rwkv_wrapper.hpp" #include "bolt/test/test_framework.hpp" -#include -#include using namespace bolt; @@ -14,7 +15,7 @@ BOLT_TEST(RWKVIntegration, BasicInitialization) { // Test RWKV with nonexistent model BOLT_TEST(RWKVIntegration, NonexistentModel) { auto& wrapper = RWKVWrapper::getInstance(); - + try { wrapper.initialize("nonexistent_model.gguf", 512); BOLT_FAIL("Should have thrown an exception"); @@ -28,16 +29,12 @@ BOLT_TEST(RWKVIntegration, NonexistentModel) { // Test RWKV with real model (if available) BOLT_TEST(RWKVIntegration, RealModelLoading) { // Check if test model exists - std::vector test_model_paths = { - "test/data/rwkv-4-pile-169m.gguf", - "test/data/rwkv-5-world-0.1b.gguf", - "../models/rwkv-test.gguf", - "/tmp/rwkv-test.gguf" - }; - + std::vector test_model_paths = {"test/data/rwkv-4-pile-169m.gguf", "test/data/rwkv-5-world-0.1b.gguf", + "../models/rwkv-test.gguf", "/tmp/rwkv-test.gguf"}; + std::string model_path; bool found = false; - + for (const auto& path : test_model_paths) { if (std::filesystem::exists(path)) { model_path = path; @@ -45,30 +42,29 @@ BOLT_TEST(RWKVIntegration, RealModelLoading) { break; } } - + if (!found) { std::cout << "No test model found, skipping real model test" << std::endl; std::cout << "To run this test, download a small RWKV model to one of:" << std::endl; for (const auto& path : test_model_paths) { std::cout << " - " << path << std::endl; } - return; // Skip test + return; // Skip test } - + std::cout << "Testing with model: " << model_path << std::endl; - + try { auto& wrapper = RWKVWrapper::getInstance(); wrapper.initialize(model_path, 1024); - + BOLT_ASSERT_TRUE(wrapper.isInitialized()); BOLT_ASSERT_GT(wrapper.getNumLayers(), 0); BOLT_ASSERT_GT(wrapper.getEmbedDim(), 0); - + std::cout << "Model loaded successfully!" << std::endl; std::cout << " Layers: " << wrapper.getNumLayers() << std::endl; std::cout << " Embedding dim: " << wrapper.getEmbedDim() << std::endl; - } catch (const std::exception& e) { std::cerr << "Failed to load model: " << e.what() << std::endl; BOLT_FAIL("Model loading failed"); @@ -78,22 +74,21 @@ BOLT_TEST(RWKVIntegration, RealModelLoading) { // Test text generation (if model is available) BOLT_TEST(RWKVIntegration, TextGeneration) { auto& wrapper = RWKVWrapper::getInstance(); - + if (!wrapper.isInitialized()) { std::cout << "Model not initialized, skipping generation test" << std::endl; return; } - + try { std::string prompt = "Hello"; std::string generated = wrapper.generate(prompt, 10); - + std::cout << "Prompt: " << prompt << std::endl; std::cout << "Generated: " << generated << std::endl; - + // Just verify it doesn't crash and returns something BOLT_ASSERT_TRUE(true); - } catch (const std::exception& e) { std::cerr << "Generation failed: " << e.what() << std::endl; // Don't fail the test if generation has issues - implementation is still in progress @@ -105,6 +100,6 @@ int main() { std::cout << "Running RWKV Integration tests..." << std::endl; std::cout << "Note: Some tests require a real RWKV model file" << std::endl; std::cout << std::endl; - + return bolt::test::run_all_tests(); } diff --git a/test/test_sanitizer_integration.cpp b/test/test_sanitizer_integration.cpp index f3277bab..b30bdf62 100644 --- a/test/test_sanitizer_integration.cpp +++ b/test/test_sanitizer_integration.cpp @@ -3,12 +3,13 @@ * @brief Integration tests for memory leak detection tools with sanitizers */ -#include "bolt/test_framework.hpp" -#include "bolt/core/memory_leak_detector.hpp" -#include "bolt/core/memory_manager.hpp" #include #include +#include "bolt/core/memory_leak_detector.hpp" +#include "bolt/core/memory_manager.hpp" +#include "bolt/test_framework.hpp" + using namespace bolt::test; // ===== Sanitizer Integration Tests ===== @@ -16,40 +17,40 @@ using namespace bolt::test; BOLT_TEST(SanitizerIntegration, BasicAllocationDeallocation) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Allocate and properly free void* ptr = malloc(1024); TRACK_ALLOCATION(ptr, 1024, "test"); - + BOLT_ASSERT(detector.hasLeaks()); - + UNTRACK_ALLOCATION(ptr); free(ptr); - + BOLT_ASSERT(!detector.hasLeaks()); } BOLT_TEST(SanitizerIntegration, MultipleAllocations) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + std::vector allocations; - + // Allocate multiple blocks for (int i = 0; i < 10; ++i) { void* ptr = malloc(128 * (i + 1)); allocations.push_back(ptr); TRACK_ALLOCATION(ptr, 128 * (i + 1), "batch_test"); } - + BOLT_ASSERT_EQ(10, detector.getLeakCount()); - + // Free all blocks for (void* ptr : allocations) { UNTRACK_ALLOCATION(ptr); free(ptr); } - + BOLT_ASSERT(!detector.hasLeaks()); } @@ -57,24 +58,24 @@ BOLT_TEST(SanitizerIntegration, MemoryManagerIntegration) { auto& manager = bolt::MemoryManager::getInstance(); auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Track MemoryManager allocations void* ptr1 = manager.allocate(512); TRACK_ALLOCATION(ptr1, 512, "memory_manager"); - + void* ptr2 = manager.allocate(1024); TRACK_ALLOCATION(ptr2, 1024, "memory_manager"); - + BOLT_ASSERT_EQ(2, detector.getLeakCount()); BOLT_ASSERT_EQ(512 + 1024, manager.getCurrentUsage()); - + // Cleanup UNTRACK_ALLOCATION(ptr1); manager.deallocate(ptr1); - + UNTRACK_ALLOCATION(ptr2); manager.deallocate(ptr2); - + BOLT_ASSERT(!detector.hasLeaks()); BOLT_ASSERT_EQ(0, manager.getCurrentUsage()); } @@ -82,18 +83,18 @@ BOLT_TEST(SanitizerIntegration, MemoryManagerIntegration) { BOLT_TEST(SanitizerIntegration, LeakDetectionReport) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Create a leak void* leaked = malloc(2048); TRACK_ALLOCATION(leaked, 2048, "test_leak"); - + // Generate report std::string report = detector.generateReport(); - + BOLT_ASSERT(report.find("Memory leaks detected") != std::string::npos); BOLT_ASSERT(report.find("test_leak") != std::string::npos); BOLT_ASSERT(report.find("2.00 KB") != std::string::npos); - + // Cleanup UNTRACK_ALLOCATION(leaked); free(leaked); @@ -102,22 +103,22 @@ BOLT_TEST(SanitizerIntegration, LeakDetectionReport) { BOLT_TEST(SanitizerIntegration, CategoryTracking) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Allocate in different categories void* cat1 = malloc(100); TRACK_ALLOCATION(cat1, 100, "category1"); - + void* cat2 = malloc(200); TRACK_ALLOCATION(cat2, 200, "category2"); - + void* cat3 = malloc(300); TRACK_ALLOCATION(cat3, 300, "category1"); - + auto stats = detector.getStats(); - + BOLT_ASSERT_EQ(400, stats.leaksByCategory["category1"]); BOLT_ASSERT_EQ(200, stats.leaksByCategory["category2"]); - + // Cleanup UNTRACK_ALLOCATION(cat1); free(cat1); @@ -155,7 +156,7 @@ BOLT_TEST(SanitizerIntegration, UndefinedBehaviorSanitizerEnabled) { BOLT_TEST(SanitizerIntegration, NoLeaksWithProperCleanup) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); - + // Allocate and immediately clean up for (int i = 0; i < 100; ++i) { void* ptr = malloc(i * 10 + 1); @@ -163,7 +164,7 @@ BOLT_TEST(SanitizerIntegration, NoLeaksWithProperCleanup) { UNTRACK_ALLOCATION(ptr); free(ptr); } - + BOLT_ASSERT(!detector.hasLeaks()); } @@ -172,25 +173,25 @@ BOLT_TEST(SanitizerIntegration, PeakMemoryTracking) { auto& detector = bolt::MemoryLeakDetector::getInstance(); detector.clear(); detector.resetStats(); - + // Allocate increasing amounts void* ptr1 = malloc(1024); TRACK_ALLOCATION(ptr1, 1024, "peak_test"); - + void* ptr2 = malloc(2048); TRACK_ALLOCATION(ptr2, 2048, "peak_test"); - + auto stats = detector.getStats(); BOLT_ASSERT_EQ(3072, stats.peakMemoryUsage); - + // Free first allocation UNTRACK_ALLOCATION(ptr1); free(ptr1); - + stats = detector.getStats(); - BOLT_ASSERT_EQ(3072, stats.peakMemoryUsage); // Peak should remain + BOLT_ASSERT_EQ(3072, stats.peakMemoryUsage); // Peak should remain BOLT_ASSERT_EQ(2048, stats.currentMemoryUsage); - + // Cleanup UNTRACK_ALLOCATION(ptr2); free(ptr2); diff --git a/test/test_split_view.cpp b/test/test_split_view.cpp index b5356127..5bf80d58 100644 --- a/test/test_split_view.cpp +++ b/test/test_split_view.cpp @@ -1,94 +1,95 @@ +#include #include #include #include -#include -#include "bolt/editor/split_view_manager.hpp" + +#include "bolt/core/editor_store.hpp" #include "bolt/editor/editor_pane.hpp" #include "bolt/editor/integrated_editor.hpp" -#include "bolt/core/editor_store.hpp" +#include "bolt/editor/split_view_manager.hpp" using namespace bolt; void test_editor_pane_basic() { std::cout << "[SplitView] EditorPaneBasic ... "; - + EditorPane pane("test_pane_1"); - + assert(pane.getId() == "test_pane_1"); assert(!pane.hasDocument()); assert(!pane.hasFocus()); assert(pane.isVisible()); - + pane.setFocus(true); assert(pane.hasFocus()); - + pane.setFocus(false); assert(!pane.hasFocus()); - + std::cout << "PASS" << std::endl; } void test_split_view_manager_basic() { std::cout << "[SplitView] SplitViewManagerBasic ... "; - + auto& manager = SplitViewManager::getInstance(); - + assert(manager.isEnabled()); assert(manager.getPaneCount() >= 1); - + // Test horizontal split [[maybe_unused]] size_t initialCount = manager.getPaneCount(); auto hPaneId = manager.createHorizontalSplit(); assert(!hPaneId.empty()); assert(manager.getPaneCount() == initialCount + 1); assert(manager.hasSplits()); - + // Test vertical split auto vPaneId = manager.createVerticalSplit(); assert(!vPaneId.empty()); assert(manager.getPaneCount() == initialCount + 2); - + // Verify panes exist assert(manager.getPane(hPaneId) != nullptr); assert(manager.getPane(vPaneId) != nullptr); - + std::cout << "PASS" << std::endl; } void test_integrated_editor_split() { std::cout << "[SplitView] IntegratedEditorSplit ... "; - + auto& editor = IntegratedEditor::getInstance(); - + assert(editor.isSplitViewEnabled()); - + // Create splits std::string hSplit = editor.createHorizontalSplit(); std::string vSplit = editor.createVerticalSplit(); - + assert(!hSplit.empty()); assert(!vSplit.empty()); assert(editor.hasSplits()); - + // Test pane management assert(!editor.getActivePaneId().empty()); assert(editor.getActivePane() != nullptr); - + auto allIds = editor.getAllPaneIds(); assert(allIds.size() >= 3); - + std::cout << "PASS" << std::endl; } int main(int argc, char* argv[]) { std::cout << "Split View Editing Tests" << std::endl; std::cout << "========================" << std::endl; - + try { test_editor_pane_basic(); test_split_view_manager_basic(); test_integrated_editor_split(); - + std::cout << std::endl << "All split view tests passed!" << std::endl; return 0; } catch (const std::exception& e) { @@ -98,4 +99,4 @@ int main(int argc, char* argv[]) { std::cerr << "Test failed with unknown exception" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test/test_tab_bar.cpp b/test/test_tab_bar.cpp index e2f00ac7..50a7328a 100644 --- a/test/test_tab_bar.cpp +++ b/test/test_tab_bar.cpp @@ -1,22 +1,23 @@ -#include "bolt/test_framework.hpp" -#include "bolt/editor/tab_bar.hpp" #include +#include "bolt/editor/tab_bar.hpp" +#include "bolt/test_framework.hpp" + using namespace bolt; // Test basic tab creation BOLT_TEST(TabBar, CreateTab) { TabBar& tabBar = TabBar::getInstance(); - + // Close all tabs first to start fresh tabBar.closeAllTabs(); - + // Create a new tab size_t tabId = tabBar.addTab("/path/to/file1.cpp"); - + BOLT_ASSERT_TRUE(tabId > 0); BOLT_ASSERT_EQ(1u, tabBar.getTabCount()); - + auto tab = tabBar.getTab(tabId); BOLT_ASSERT_TRUE(tab.has_value()); BOLT_ASSERT_EQ("/path/to/file1.cpp", tab->filePath); @@ -29,10 +30,10 @@ BOLT_TEST(TabBar, CreateTab) { BOLT_TEST(TabBar, DuplicateTabPrevention) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tabId1 = tabBar.addTab("/path/to/file.cpp"); size_t tabId2 = tabBar.addTab("/path/to/file.cpp"); - + // Should return the same tab ID BOLT_ASSERT_EQ(tabId1, tabId2); BOLT_ASSERT_EQ(1u, tabBar.getTabCount()); @@ -42,11 +43,11 @@ BOLT_TEST(TabBar, DuplicateTabPrevention) { BOLT_TEST(TabBar, MultipleTabs) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tab1 = tabBar.addTab("/file1.cpp"); size_t tab2 = tabBar.addTab("/file2.cpp"); size_t tab3 = tabBar.addTab("/file3.cpp"); - + BOLT_ASSERT_EQ(3u, tabBar.getTabCount()); BOLT_ASSERT_TRUE(tab1 != tab2); BOLT_ASSERT_TRUE(tab2 != tab3); @@ -56,19 +57,19 @@ BOLT_TEST(TabBar, MultipleTabs) { BOLT_TEST(TabBar, TabActivation) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tab1 = tabBar.addTab("/file1.cpp"); size_t tab2 = tabBar.addTab("/file2.cpp"); - + // tab2 should be active (last added) auto activeTab = tabBar.getActiveTab(); BOLT_ASSERT_TRUE(activeTab.has_value()); BOLT_ASSERT_EQ(tab2, activeTab->id); - + // Activate tab1 bool activated = tabBar.activateTab(tab1); BOLT_ASSERT_TRUE(activated); - + activeTab = tabBar.getActiveTab(); BOLT_ASSERT_TRUE(activeTab.has_value()); BOLT_ASSERT_EQ(tab1, activeTab->id); @@ -84,12 +85,12 @@ BOLT_TEST(TabBar, CloseTab) { (void)tabBar.addTab("/file3.cpp"); BOLT_ASSERT_EQ(3u, tabBar.getTabCount()); - + // Close middle tab bool closed = tabBar.closeTab(tab2); BOLT_ASSERT_TRUE(closed); BOLT_ASSERT_EQ(2u, tabBar.getTabCount()); - + // Verify tab2 is gone auto tab = tabBar.getTab(tab2); BOLT_ASSERT_FALSE(tab.has_value()); @@ -99,10 +100,10 @@ BOLT_TEST(TabBar, CloseTab) { BOLT_TEST(TabBar, CloseByPath) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + tabBar.addTab("/file1.cpp"); tabBar.addTab("/file2.cpp"); - + bool closed = tabBar.closeTabByPath("/file1.cpp"); BOLT_ASSERT_TRUE(closed); BOLT_ASSERT_EQ(1u, tabBar.getTabCount()); @@ -112,26 +113,26 @@ BOLT_TEST(TabBar, CloseByPath) { BOLT_TEST(TabBar, TabNavigation) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tab1 = tabBar.addTab("/file1.cpp"); size_t tab2 = tabBar.addTab("/file2.cpp"); size_t tab3 = tabBar.addTab("/file3.cpp"); - + // Start at tab3 tabBar.activateTab(tab3); - + // Go to next (should wrap to tab1) tabBar.activateNextTab(); auto active = tabBar.getActiveTab(); BOLT_ASSERT_TRUE(active.has_value()); BOLT_ASSERT_EQ(tab1, active->id); - + // Go to previous (should wrap to tab3) tabBar.activatePreviousTab(); active = tabBar.getActiveTab(); BOLT_ASSERT_TRUE(active.has_value()); BOLT_ASSERT_EQ(tab3, active->id); - + // Go to previous (should go to tab2) tabBar.activatePreviousTab(); active = tabBar.getActiveTab(); @@ -143,17 +144,17 @@ BOLT_TEST(TabBar, TabNavigation) { BOLT_TEST(TabBar, DirtyFlag) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tabId = tabBar.addTab("/file.cpp"); auto tab = tabBar.getTab(tabId); - + BOLT_ASSERT_TRUE(tab.has_value()); BOLT_ASSERT_FALSE(tab->isDirty); - + tabBar.setTabDirty(tabId, true); tab = tabBar.getTab(tabId); BOLT_ASSERT_TRUE(tab->isDirty); - + tabBar.setTabDirty(tabId, false); tab = tabBar.getTab(tabId); BOLT_ASSERT_FALSE(tab->isDirty); @@ -169,16 +170,16 @@ BOLT_TEST(TabBar, PinnedTabs) { // Pin tab1 tabBar.setTabPinned(tab1, true); - + // Try to close pinned tab - should fail bool closed = tabBar.closeTab(tab1); BOLT_ASSERT_FALSE(closed); BOLT_ASSERT_EQ(2u, tabBar.getTabCount()); - + // Close all should skip pinned tabs tabBar.closeAllTabs(); BOLT_ASSERT_EQ(1u, tabBar.getTabCount()); - + auto tab = tabBar.getActiveTab(); BOLT_ASSERT_TRUE(tab.has_value()); BOLT_ASSERT_EQ(tab1, tab->id); @@ -196,13 +197,13 @@ BOLT_TEST(TabBar, CloseOtherTabs) { // Pin one tab tabBar.setTabPinned(tab1, true); - + // Close all except tab3 tabBar.closeOtherTabs(tab3); - + // Should have tab1 (pinned) and tab3 (exception) BOLT_ASSERT_EQ(2u, tabBar.getTabCount()); - + auto t1 = tabBar.getTab(tab1); auto t3 = tabBar.getTab(tab3); BOLT_ASSERT_TRUE(t1.has_value()); @@ -213,13 +214,13 @@ BOLT_TEST(TabBar, CloseOtherTabs) { BOLT_TEST(TabBar, GetByPath) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tabId = tabBar.addTab("/my/path/file.cpp"); - + auto tab = tabBar.getTabByPath("/my/path/file.cpp"); BOLT_ASSERT_TRUE(tab.has_value()); BOLT_ASSERT_EQ(tabId, tab->id); - + // Non-existent path tab = tabBar.getTabByPath("/does/not/exist.cpp"); BOLT_ASSERT_FALSE(tab.has_value()); @@ -229,21 +230,21 @@ BOLT_TEST(TabBar, GetByPath) { BOLT_TEST(TabBar, TabReordering) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tab1 = tabBar.addTab("/file1.cpp"); size_t tab2 = tabBar.addTab("/file2.cpp"); size_t tab3 = tabBar.addTab("/file3.cpp"); - + // Get initial order auto tabs = tabBar.getAllTabs(); BOLT_ASSERT_EQ(3u, tabs.size()); BOLT_ASSERT_EQ(tab1, tabs[0].id); BOLT_ASSERT_EQ(tab2, tabs[1].id); BOLT_ASSERT_EQ(tab3, tabs[2].id); - + // Move tab3 to position 0 tabBar.moveTab(tab3, 0); - + tabs = tabBar.getAllTabs(); BOLT_ASSERT_EQ(tab3, tabs[0].id); BOLT_ASSERT_EQ(tab1, tabs[1].id); @@ -254,14 +255,14 @@ BOLT_TEST(TabBar, TabReordering) { BOLT_TEST(TabBar, GetAllTabs) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + tabBar.addTab("/file1.cpp"); tabBar.addTab("/file2.cpp"); tabBar.addTab("/file3.cpp"); - + auto tabs = tabBar.getAllTabs(); BOLT_ASSERT_EQ(3u, tabs.size()); - + BOLT_ASSERT_EQ("/file1.cpp", tabs[0].filePath); BOLT_ASSERT_EQ("/file2.cpp", tabs[1].filePath); BOLT_ASSERT_EQ("/file3.cpp", tabs[2].filePath); @@ -278,10 +279,10 @@ BOLT_TEST(TabBar, CloseActiveTab) { // Activate tab2 tabBar.activateTab(tab2); - + // Close tab2 tabBar.closeTab(tab2); - + // Should activate tab to the left (tab1) auto active = tabBar.getActiveTab(); BOLT_ASSERT_TRUE(active.has_value()); @@ -292,19 +293,19 @@ BOLT_TEST(TabBar, CloseActiveTab) { BOLT_TEST(TabBar, DisplayNameExtraction) { TabBar& tabBar = TabBar::getInstance(); tabBar.closeAllTabs(); - + size_t tab1 = tabBar.addTab("/path/to/my/file.cpp"); size_t tab2 = tabBar.addTab("C:\\Windows\\path\\file.hpp"); size_t tab3 = tabBar.addTab("filename_only.txt"); - + auto t1 = tabBar.getTab(tab1); auto t2 = tabBar.getTab(tab2); auto t3 = tabBar.getTab(tab3); - + BOLT_ASSERT_TRUE(t1.has_value()); BOLT_ASSERT_TRUE(t2.has_value()); BOLT_ASSERT_TRUE(t3.has_value()); - + BOLT_ASSERT_EQ("file.cpp", t1->displayName); BOLT_ASSERT_EQ("file.hpp", t2->displayName); BOLT_ASSERT_EQ("filename_only.txt", t3->displayName); diff --git a/test/test_theme_system.cpp b/test/test_theme_system.cpp index f3cbddae..07c853bc 100644 --- a/test/test_theme_system.cpp +++ b/test/test_theme_system.cpp @@ -1,12 +1,13 @@ -#include -#include #include +#include +#include + #include "bolt/editor/theme_system.hpp" namespace { // Test framework utilities -void runTest(const std::string& testName, void(*testFunc)()) { +void runTest(const std::string& testName, void (*testFunc)()) { try { testFunc(); std::cout << "[PASS] " << testName << std::endl; @@ -24,21 +25,22 @@ void testSingleton() { auto& inst1 = bolt::ThemeSystem::getInstance(); auto& inst2 = bolt::ThemeSystem::getInstance(); assert(&inst1 == &inst2); - (void)inst1; (void)inst2; + (void)inst1; + (void)inst2; } // Test default themes loading void testDefaultThemesLoading() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + // Test that default themes are loaded themeSystem.setTheme("dark"); auto darkColors = themeSystem.getCurrentColors(); assert(darkColors.background == "#1E1E1E"); assert(darkColors.foreground == "#D4D4D4"); assert(darkColors.keyword == "#569CD6"); - + themeSystem.setTheme("light"); auto lightColors = themeSystem.getCurrentColors(); assert(lightColors.background == "#FFFFFF"); @@ -50,7 +52,7 @@ void testDefaultThemesLoading() { void testFontSettings() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + themeSystem.setTheme("dark"); auto fontSettings = themeSystem.getCurrentFontSettings(); assert(fontSettings.family == "Consolas, 'Courier New', monospace"); @@ -61,7 +63,7 @@ void testFontSettings() { // Test custom theme addition void testCustomTheme() { auto& themeSystem = bolt::ThemeSystem::getInstance(); - + bolt::Theme customTheme; customTheme.colors.background = "#222222"; customTheme.colors.foreground = "#EEEEEE"; @@ -69,15 +71,15 @@ void testCustomTheme() { customTheme.fontSettings.family = "Monaco"; customTheme.fontSettings.size = 16; customTheme.fontSettings.lineHeight = 1.6f; - + themeSystem.addTheme("custom", customTheme); themeSystem.setTheme("custom"); - + auto colors = themeSystem.getCurrentColors(); assert(colors.background == "#222222"); assert(colors.foreground == "#EEEEEE"); assert(colors.keyword == "#FF6B6B"); - + auto fontSettings = themeSystem.getCurrentFontSettings(); assert(fontSettings.family == "Monaco"); assert(fontSettings.size == 16); @@ -88,15 +90,15 @@ void testCustomTheme() { void testInvalidTheme() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + // Set to a valid theme first themeSystem.setTheme("dark"); auto validColors = themeSystem.getCurrentColors(); - + // Try to set invalid theme - should remain on previous theme themeSystem.setTheme("nonexistent"); auto currentColors = themeSystem.getCurrentColors(); - + // Should still be using the dark theme assert(currentColors.background == validColors.background); assert(currentColors.foreground == validColors.foreground); @@ -106,17 +108,17 @@ void testInvalidTheme() { void testThemeSwitching() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + // Switch to light theme themeSystem.setTheme("light"); auto lightColors = themeSystem.getCurrentColors(); assert(lightColors.background == "#FFFFFF"); - + // Switch to dark theme themeSystem.setTheme("dark"); auto darkColors = themeSystem.getCurrentColors(); assert(darkColors.background == "#1E1E1E"); - + // Switch back to light themeSystem.setTheme("light"); auto lightColors2 = themeSystem.getCurrentColors(); @@ -127,10 +129,10 @@ void testThemeSwitching() { void testThemeEnumeration() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + auto themes = themeSystem.getAvailableThemes(); - assert(themes.size() >= 2); // At least dark and light - + assert(themes.size() >= 2); // At least dark and light + // Check that dark and light are present assert(std::find(themes.begin(), themes.end(), "dark") != themes.end()); assert(std::find(themes.begin(), themes.end(), "light") != themes.end()); @@ -140,10 +142,10 @@ void testThemeEnumeration() { void testCurrentThemeName() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + themeSystem.setTheme("light"); assert(themeSystem.getCurrentThemeName() == "light"); - + themeSystem.setTheme("dark"); assert(themeSystem.getCurrentThemeName() == "dark"); } @@ -152,7 +154,7 @@ void testCurrentThemeName() { void testThemeExistence() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + assert(themeSystem.hasTheme("dark")); assert(themeSystem.hasTheme("light")); assert(!themeSystem.hasTheme("nonexistent")); @@ -160,10 +162,10 @@ void testThemeExistence() { void testColorSchemeCompleteness() { auto& themeSystem = bolt::ThemeSystem::getInstance(); themeSystem.loadDefaultThemes(); - + themeSystem.setTheme("dark"); auto colors = themeSystem.getCurrentColors(); - + // Ensure all color fields are set assert(!colors.background.empty()); assert(!colors.foreground.empty()); @@ -177,11 +179,11 @@ void testColorSchemeCompleteness() { assert(!colors.function.empty()); } -} // anonymous namespace +} // anonymous namespace int main() { std::cout << "Running Theme System Tests..." << std::endl; - + try { runTest("Singleton Pattern", testSingleton); runTest("Default Themes Loading", testDefaultThemesLoading); @@ -193,11 +195,11 @@ int main() { runTest("Theme Enumeration", testThemeEnumeration); runTest("Current Theme Name", testCurrentThemeName); runTest("Theme Existence Check", testThemeExistence); - + std::cout << "\nโœ… All Theme System tests passed!" << std::endl; return 0; } catch (...) { std::cout << "\nโŒ Some Theme System tests failed!" << std::endl; return 1; } -} \ No newline at end of file +} diff --git a/test/test_widget_framework.cpp b/test/test_widget_framework.cpp index 73da0a23..1054324d 100644 --- a/test/test_widget_framework.cpp +++ b/test/test_widget_framework.cpp @@ -1,31 +1,28 @@ -#include "bolt/gui/widget_framework.hpp" -#include "bolt/gui/widgets.hpp" -#include "bolt/gui/widget_registration.hpp" - #include + #include +#include "bolt/gui/widget_framework.hpp" +#include "bolt/gui/widget_registration.hpp" +#include "bolt/gui/widgets.hpp" + using namespace bolt::gui; class WidgetFrameworkTest : public ::testing::Test { -protected: - void SetUp() override { - WidgetFrameworkInit::initialize(); - } - - void TearDown() override { - WidgetFrameworkInit::shutdown(); - } + protected: + void SetUp() override { WidgetFrameworkInit::initialize(); } + + void TearDown() override { WidgetFrameworkInit::shutdown(); } }; // Widget Framework Core Tests TEST_F(WidgetFrameworkTest, FrameworkInitialization) { EXPECT_TRUE(WidgetFrameworkInit::isInitialized()); - + // Check widget registration auto registeredTypes = WidgetRegistration::getRegisteredTypes(); EXPECT_GT(registeredTypes.size(), 0); - + // Check theme registration auto& themeManager = ThemeManager::getInstance(); auto themeNames = themeManager.getThemeNames(); @@ -35,7 +32,7 @@ TEST_F(WidgetFrameworkTest, FrameworkInitialization) { TEST_F(WidgetFrameworkTest, WidgetCreation) { auto widget = std::make_shared("test_widget"); - + EXPECT_EQ(widget->getId(), "test_widget"); EXPECT_TRUE(widget->isVisible()); EXPECT_TRUE(widget->isEnabled()); @@ -48,18 +45,18 @@ TEST_F(WidgetFrameworkTest, WidgetHierarchy) { auto parent = std::make_shared("parent"); auto child1 = std::make_shared("child1"); auto child2 = std::make_shared("child2"); - + parent->addChild(child1); parent->addChild(child2); - + EXPECT_EQ(parent->getChildren().size(), 2); EXPECT_EQ(child1->getParent(), parent.get()); EXPECT_EQ(child2->getParent(), parent.get()); - + parent->removeChild(child1); EXPECT_EQ(parent->getChildren().size(), 1); EXPECT_EQ(child1->getParent(), nullptr); - + parent->clearChildren(); EXPECT_TRUE(parent->getChildren().empty()); EXPECT_EQ(child2->getParent(), nullptr); @@ -67,36 +64,36 @@ TEST_F(WidgetFrameworkTest, WidgetHierarchy) { TEST_F(WidgetFrameworkTest, WidgetProperties) { auto widget = std::make_shared("test"); - + widget->setProperty("intValue", 42); widget->setProperty("stringValue", std::string("hello")); widget->setProperty("floatValue", 3.14f); - + EXPECT_EQ(widget->getProperty("intValue"), 42); EXPECT_EQ(widget->getProperty("stringValue"), "hello"); EXPECT_FLOAT_EQ(widget->getProperty("floatValue"), 3.14f); - + EXPECT_TRUE(widget->hasProperty("intValue")); EXPECT_FALSE(widget->hasProperty("nonexistent")); - + widget->removeProperty("intValue"); EXPECT_FALSE(widget->hasProperty("intValue")); } TEST_F(WidgetFrameworkTest, WidgetGeometry) { auto widget = std::make_shared("test"); - + widget->setPosition(Position(10.0f, 20.0f)); widget->setSize(Size(100.0f, 50.0f)); - + EXPECT_EQ(widget->getBounds().position.x, 10.0f); EXPECT_EQ(widget->getBounds().position.y, 20.0f); EXPECT_EQ(widget->getBounds().size.width, 100.0f); EXPECT_EQ(widget->getBounds().size.height, 50.0f); - + widget->setMinimumSize(Size(50.0f, 25.0f)); widget->setMaximumSize(Size(200.0f, 100.0f)); - + EXPECT_EQ(widget->getMinimumSize().width, 50.0f); EXPECT_EQ(widget->getMaximumSize().width, 200.0f); } @@ -104,16 +101,16 @@ TEST_F(WidgetFrameworkTest, WidgetGeometry) { // Widget Factory Tests TEST_F(WidgetFrameworkTest, WidgetFactory) { auto& factory = WidgetFactory::getInstance(); - + EXPECT_TRUE(factory.isTypeRegistered("Button")); EXPECT_TRUE(factory.isTypeRegistered("Label")); EXPECT_TRUE(factory.isTypeRegistered("TextInput")); EXPECT_FALSE(factory.isTypeRegistered("NonExistentWidget")); - + auto button = factory.createWidget("Button", "test_button"); EXPECT_TRUE(button != nullptr); EXPECT_EQ(button->getId(), "test_button"); - + auto invalidWidget = factory.createWidget("InvalidType"); EXPECT_TRUE(invalidWidget == nullptr); } @@ -121,12 +118,12 @@ TEST_F(WidgetFrameworkTest, WidgetFactory) { // Container Tests TEST_F(WidgetFrameworkTest, WidgetContainer) { auto container = std::make_shared("container", LayoutType::Vertical); - + EXPECT_EQ(container->getLayoutType(), LayoutType::Vertical); - + container->setLayoutType(LayoutType::Horizontal); EXPECT_EQ(container->getLayoutType(), LayoutType::Horizontal); - + container->setSpacing(10.0f); EXPECT_EQ(container->getSpacing(), 10.0f); } @@ -134,23 +131,21 @@ TEST_F(WidgetFrameworkTest, WidgetContainer) { // Button Tests TEST_F(WidgetFrameworkTest, ButtonWidget) { auto button = std::make_shared